id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
21,701 | import collections
import glob
import json
import logging
import math
import multiprocessing
import os
import pickle
import torch
from functools import partial
from typing import Tuple, List, Dict, Iterable, Optional
from torch import Tensor as T
from tqdm import tqdm
from dpr.utils.data_utils import Tensorizer, read_s... | Finds the best answer span for the extractive Q&A model |
21,702 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(console)
def convert_jsonl_to_qas_... | null |
21,703 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
def tokenize(text):
doc = nlp(text)
return [token.text.lower() for token in doc]
def normalize(text):
"""Resolve different type of unicode encodings."""
... | Check if a document contains an answer string. |
21,704 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(console)
class NQTableParser(object... | null |
21,705 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(console)
class NQTableParser(object... | null |
21,706 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(console)
def parse_qa_csv_file(loca... | null |
21,707 | import collections
import csv
import json
import logging
import re
import unicodedata
import jsonlines
import spacy as spacy
from typing import List, Dict
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(console)
def convert_train_jsonl_t... | null |
21,708 | import collections
import logging
import string
import unicodedata
from multiprocessing import Pool as ProcessPool
import regex as re
from functools import partial
from typing import Tuple, List, Dict
from dpr.data.retriever_data import TableChunk
from dpr.utils.tokenizers import SimpleTokenizer
def _normalize_answer(s... | null |
21,709 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,710 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,711 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,712 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,713 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,714 | import collections
import csv
import glob
import logging
import os
import random
from typing import Dict, List, Tuple
import hydra
import jsonlines
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor as T
from dpr.data.tables import Table
from dpr.utils.data_utils import read_data_... | null |
21,715 | import logging
import numpy as np
import os
import random
import socket
import torch
from omegaconf import DictConfig
The provided code snippet includes necessary dependencies for implementing the `set_cfg_params_from_state` function. Write a Python function `def set_cfg_params_from_state(state: dict, cfg: DictConfig)... | Overrides some of the encoder config parameters from a give state object |
21,716 | import logging
import numpy as np
import os
import random
import socket
import torch
from omegaconf import DictConfig
The provided code snippet includes necessary dependencies for implementing the `get_encoder_params_state_from_cfg` function. Write a Python function `def get_encoder_params_state_from_cfg(cfg: DictConf... | Selects the param values to be saved in a checkpoint, so that a trained model can be used for downstream tasks without the need to specify these parameter again :return: Dict of params to memorize in a checkpoint |
21,717 | import logging
import numpy as np
import os
import random
import socket
import torch
from omegaconf import DictConfig
def set_seed(args):
seed = args.seed
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(seed) | null |
21,718 | import logging
import numpy as np
import os
import random
import socket
import torch
from omegaconf import DictConfig
logger = logging.getLogger()
The provided code snippet includes necessary dependencies for implementing the `setup_cfg_gpu` function. Write a Python function `def setup_cfg_gpu(cfg)` to solve the follo... | Setup params for CUDA, GPU & distributed training |
21,719 | import logging
import numpy as np
import os
import random
import socket
import torch
from omegaconf import DictConfig
def setup_logger(logger):
logger.setLevel(logging.INFO)
if logger.hasHandlers():
logger.handlers.clear()
log_formatter = logging.Formatter(
"[%(thread)s] %(asctime)s [%(leve... | null |
21,720 | import logging
from typing import Tuple
import torch
from torch import Tensor as T
from torch import nn
from transformers.modeling_bert import BertConfig, BertModel
from transformers.optimization import AdamW
from transformers.tokenization_bert import BertTokenizer
from transformers.tokenization_roberta import RobertaT... | null |
21,721 | import logging
from typing import Tuple
import torch
from torch import Tensor as T
from torch import nn
from transformers.modeling_bert import BertConfig, BertModel
from transformers.optimization import AdamW
from transformers.tokenization_bert import BertTokenizer
from transformers.tokenization_roberta import RobertaT... | null |
21,722 | import logging
from typing import Tuple
import torch
from pytext.models.representations.transformer_sentence_encoder import TransformerSentenceEncoder
from pytext.optimizer.optimizers import AdamW
from torch import Tensor as T
from torch import nn
from .biencoder import BiEncoder
def get_optimizer(model: nn.Module, lea... | null |
21,723 | import logging
from typing import Tuple
import torch
from pytext.models.representations.transformer_sentence_encoder import TransformerSentenceEncoder
from pytext.optimizer.optimizers import AdamW
from torch import Tensor as T
from torch import nn
from .biencoder import BiEncoder
def get_pytext_bert_base_cfg():
cf... | null |
21,724 | import collections
import logging
import random
from typing import Tuple, List
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import BiEncoderSample
from dpr.utils.data_utils import Tensorizer
from dpr.utils.model_utils imp... | calculates q->ctx scores for every row in ctx_vector :param q_vector: :param ctx_vector: :return: |
21,725 | import collections
import logging
import random
from typing import Tuple, List
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import BiEncoderSample
from dpr.utils.data_utils import Tensorizer
from dpr.utils.model_utils imp... | null |
21,726 | import logging
from typing import Tuple
from fairseq.models.roberta.hub_interface import RobertaHubInterface
from fairseq.models.roberta.model import RobertaModel as FaiseqRobertaModel
from fairseq.optim.adam import FairseqAdam
from torch import Tensor as T
from torch import nn
from dpr.models.hf_models import get_robe... | null |
21,727 | import collections
import logging
from typing import List
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor as T
from torch.nn import CrossEntropyLoss
from dpr.data.reader_data import ReaderSample, ReaderPassage
from dpr.utils.model_utils import init_weights
def _calc_mml(loss_tensor):
... | null |
21,728 | import collections
import logging
from typing import List
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor as T
from torch.nn import CrossEntropyLoss
from dpr.data.reader_data import ReaderSample, ReaderPassage
from dpr.utils.model_utils import init_weights
logger = logging.getLogger()
Rea... | Creates a reader batch instance out of a list of ReaderSample-s :param pad_token_id: id of the padding token :param samples: list of samples to create the batch for :param passages_per_question: amount of passages for every question in a batch :param max_length: max model input sequence length :param max_n_answers: max... |
21,729 | import json
import logging
import pickle
import random
import itertools
import math
import torch
from torch import Tensor as T
from typing import List, Iterator, Callable, Tuple
logger = logging.getLogger()
def read_serialized_data_from_files(paths: List[str]) -> List:
results = []
for i, path in enumerate(pat... | null |
21,730 | import json
import logging
import pickle
import random
import itertools
import math
import torch
from torch import Tensor as T
from typing import List, Iterator, Callable, Tuple
logger = logging.getLogger()
def read_data_from_json_files(paths: List[str]) -> List:
results = []
for i, path in enumerate(paths):
... | null |
21,731 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
def setup_for_distributed_mode(
model: nn.Module,
optimizer: torch.optim.Optimizer,
device... | null |
21,732 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
def move_to_cuda(sample):
if len(sample) == 0:
return {}
def _move_to_cuda(maybe_tens... | null |
21,733 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
The provided code snippet includes necessary dependencies for implementing the `get_schedule_linear` f... | Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period. |
21,734 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
def init_weights(modules: List):
for module in modules:
if isinstance(module, (nn.Linear, ... | null |
21,735 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
def get_model_obj(model: nn.Module):
return model.module if hasattr(model, "module") else model | null |
21,736 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
logger = logging.getLogger()
def get_model_file(args, file_prefix) -> str:
if args.model_file and ... | null |
21,737 | import collections
import glob
import logging
import os
from typing import List
import torch
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.serialization import default_restore_location
logger = logging.getLogger()
CheckpointState = collections.namedtuple(
"CheckpointState",
[
... | null |
21,738 | import glob
import json
import logging
import pickle
import time
from typing import List, Tuple, Dict, Iterator
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import RepTokenSelector
from dpr.data.q... | null |
21,739 | import glob
import json
import logging
import pickle
import time
from typing import List, Tuple, Dict, Iterator
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import RepTokenSelector
from dpr.data.q... | null |
21,740 | import glob
import json
import logging
import pickle
import time
from typing import List, Tuple, Dict, Iterator
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import RepTokenSelector
from dpr.data.q... | null |
21,741 | import glob
import json
import logging
import pickle
import time
from typing import List, Tuple, Dict, Iterator
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import RepTokenSelector
from dpr.data.q... | null |
21,742 | import glob
import json
import logging
import pickle
import time
from typing import List, Tuple, Dict, Iterator
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.data.biencoder_data import RepTokenSelector
from dpr.data.q... | null |
21,743 | import logging
import math
import os
import pathlib
import pickle
from typing import List, Tuple
import hydra
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
from torch import nn
from dpr.data.biencoder_data import BiEncoderPassage
from dpr.models import init_biencoder_components
from dpr.op... | null |
21,744 | import sys
import statistics
from collections import Counter
def load_reference(path_to_reference):
"""Load Reference reference relevant passages
Args:path_to_reference (str): path to a file to load.
Returns:qids_to_relevant_passageids (dict): dictionary mapping from query_id (int) to relevant passages (lis... | Compute MRR metric Args: p_path_to_reference_file (str): path to reference file. Reference file should contain lines in the following format: QUERYID\tPASSAGEID Where PASSAGEID is a relevant passage for a query. Note QUERYID can repeat on different lines with different PASSAGEIDs p_path_to_candidate_file (str): path to... |
21,745 | import argparse
import glob
import os
import re
import subprocess
from distutils.dir_util import copy_tree
from typing import List
from bs4 import BeautifulSoup
from packaging import version
The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `d... | Setup and parse command line arguments for using the script |
21,746 | import argparse
import glob
import os
import re
import subprocess
from distutils.dir_util import copy_tree
from typing import List
from bs4 import BeautifulSoup
from packaging import version
The provided code snippet includes necessary dependencies for implementing the `create_docs` function. Write a Python function `... | Run the sphinx command to create the docs from src into dest. :param src: the source directory for docs :type src: str :param dest: the destination directory for docs :type dest: str |
21,747 | import argparse
import glob
import os
import re
import subprocess
from distutils.dir_util import copy_tree
from typing import List
from bs4 import BeautifulSoup
from packaging import version
def _get_docs_folders(dest: str) -> List[str]:
folders = os.listdir(dest)
return folders
def _get_latest_folder(folders: ... | Run any extra packaging commands to prep the docs for release. Ex: copies the latest version to the root so if a version isn't specified will load. :param dest: the destination directory the docs were built in :type dest: str |
21,748 | import argparse
import os
import re
from typing import Dict
import numpy as np
import tensorflow
import torch
import torchvision.transforms as transforms
from PIL import Image
from sparseml.keras.datasets import ImageNetDataset, SplitsTransforms
from sparseml.keras.models import ModelRegistry as KRModelRegistry
from sp... | null |
21,749 | import argparse
import os
import re
from typing import Dict
import numpy as np
import tensorflow
import torch
import torchvision.transforms as transforms
from PIL import Image
from sparseml.keras.datasets import ImageNetDataset, SplitsTransforms
from sparseml.keras.models import ModelRegistry as KRModelRegistry
from sp... | Verify the converted models using ImageNet's data pipeline in Pytorch Assumption: the validation pipeline is enhanced with the following permutation class my_permuter: def __call__(self, img): return img.permute(1, 2, 0) to fit into the default data format "channels_last" by Keras |
21,750 | import argparse
import os
import re
from typing import Dict
import numpy as np
import tensorflow
import torch
import torchvision.transforms as transforms
from PIL import Image
from sparseml.keras.datasets import ImageNetDataset, SplitsTransforms
from sparseml.keras.models import ModelRegistry as KRModelRegistry
from sp... | null |
21,751 | import argparse
import glob
import os
import sys
from typing import List, NamedTuple
QUALITY_COMMAND = "quality"
STYLE_COMMAND = "style"
The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args()` to solve the following problem:
Setup... | Setup and parse command line arguments for using the script |
21,752 | import argparse
import glob
import os
import sys
from typing import List, NamedTuple
def _get_files(patterns: List[str]) -> List[str]:
files = []
for pattern in patterns:
for file in glob.glob(pattern, recursive=True):
files.append(os.path.abspath(os.path.expanduser(file)))
files.sort()
... | Run a quality check across all files in the given glob patterns. This checks to make sure all matching files have the NM copyright present. If any do not, it will list them out and exit with an error. :param patterns: The glob file patterns to run quality check on |
21,753 | import argparse
import glob
import os
import sys
from typing import List, NamedTuple
def _get_files(patterns: List[str]) -> List[str]:
files = []
for pattern in patterns:
for file in glob.glob(pattern, recursive=True):
files.append(os.path.abspath(os.path.expanduser(file)))
files.sort()
... | Run a style application across all files in the given glob patterns. This checks to make sure all matching files have the NM copyright present. If any do not, it will append the copyright to above the file after any already contained headers such as shebang lines. :param patterns: The glob file patterns to run quality ... |
21,754 | import codecs
import os
import re
from typing import List
import setuptools
from setuptools import find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
def parse_requirements(file_name: str) -> List[str]:
with open(file_name) as f:
return [
require.strip() for requi... | null |
21,755 | import codecs
import os
import re
from typing import List
import setuptools
from setuptools import find_packages
def read(*parts):
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
r... | null |
21,756 | import streamlit as st
from PIL import Image
import os
import io
import base64
from io import BytesIO
import requests
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase, ObjectBase
from gptcache.adapter import openai
from gptcache.processor.pre import get_prompt
from gptcach... | null |
21,757 | import streamlit as st
from PIL import Image
import os
import io
import base64
from io import BytesIO
import requests
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase, ObjectBase
from gptcache.adapter import openai
from gptcache.processor.pre import get_prompt
from gptcach... | null |
21,758 | import streamlit as st
import os
import uuid
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase, ObjectBase
from gptcache.adapter import openai
from gptcache.processor.pre import get_file_name
from gptcache.embedding import Data2VecAudio
from gptcache.similarity_evaluation.d... | null |
21,759 | import streamlit as st
import os
import uuid
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase, ObjectBase
from gptcache.adapter import openai
from gptcache.processor.pre import get_file_name
from gptcache.embedding import Data2VecAudio
from gptcache.similarity_evaluation.d... | null |
21,760 | from gptcache import cache
from gptcache.session import Session
from gptcache.adapter import openai
class Session:
"""
Session for gptcache. Session can isolate the context of each connection, and can also filter the results after recall,
and if not satisfied will re-request rather than return the cache re... | null |
21,761 | from gptcache import cache
from gptcache.session import Session
from gptcache.adapter import openai
class Session:
"""
Session for gptcache. Session can isolate the context of each connection, and can also filter the results after recall,
and if not satisfied will re-request rather than return the cache re... | null |
21,762 | from gptcache import cache, Config, Cache
from gptcache.adapter.api import put, get, init_similar_cache
from gptcache.processor.post import nop
from gptcache.processor.pre import get_prompt
def put(prompt: str, data: Any, **kwargs) -> None:
"""put api, put qa pair information to GPTCache
Please make sure that ... | null |
21,763 | from gptcache import cache, Config, Cache
from gptcache.adapter.api import put, get, init_similar_cache
from gptcache.processor.post import nop
from gptcache.processor.pre import get_prompt
def put(prompt: str, data: Any, **kwargs) -> None:
"""put api, put qa pair information to GPTCache
Please make sure that ... | null |
21,764 | import os
from langchain import Cohere
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage
from gptcache.adapter.langchain_models import LangChainLLMs
from gptcache import cache
from gptcache.processor.pre import get_prompt
from gptcache.adapter.langc... | null |
21,765 | import os
from langchain import Cohere
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage
from gptcache.adapter.langchain_models import LangChainLLMs
from gptcache import cache
from gptcache.processor.pre import get_prompt
from gptcache.adapter.langc... | null |
21,766 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.embedding import Onnx as EmbeddingOnnx
from gptcache.similarity_evaluation import OnnxModelEvaluation
import openai
def OnnxModelEvaluation(model="GPTCache/albert-duplicate... | null |
21,767 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.similarity_evaluation.exact_match import ExactMatchEvaluation
import openai
class ExactMatchEvaluation(SimilarityEvaluation):
"""Using exact metric to evaluate sentences pair similarity.
This evaluator is used to directly compare tw... | null |
21,768 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager import get_data_manager, VectorBase
from gptcache.similarity_evaluation import SequenceMatchEvaluation
from gptcache.processor.pre import concat_all_queries
from gptcache.embedding import Onnx
from gptcache import Config
import openai... | null |
21,769 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager import get_data_manager, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.embedding import Onnx
import openai
class SearchDistanceEvaluation(SimilarityEvaluation):
"""Using sea... | null |
21,770 | import argparse
import gradio as gr
from gptcache import cache
from gptcache.processor.pre import get_image, get_image_question
from gptcache.embedding import Timm
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.manager.factory import manager_factory
from gptcache.adapter.mini... | null |
21,771 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager.factory import get_data_manager
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.embedding import Onnx
import openai
def g... | null |
21,772 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.embedding.string import to_embeddings as string_embedding
import openai
def run():
cache.init(embedding_func=string_embedding)
cache.set_openai_key()
answer = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
... | null |
21,773 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager.factory import get_data_manager
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.embedding import PaddleNLP
import openai
... | null |
21,774 | from gptcache.adapter import openai
from gptcache import cache
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
import numpy as np
d = 8
def mock_embeddings(data, **kwargs):
return np.random.random((d, )).astype('float3... | null |
21,775 | import time
from gptcache.adapter.llama_cpp import Llama
from gptcache.manager import manager_factory
from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.processor.pre import get_prompt
class Llama(llama_cpp.Llama):
"""llama.cpp wrapper
You should have the llama-cpp-python library... | null |
21,776 | import time
from gptcache.adapter.llama_cpp import Llama
from gptcache.manager import manager_factory
from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.processor.pre import get_prompt
class Llama(llama_cpp.Llama):
def __call__(
self,
prompt: str,
... | null |
21,777 | import os
import time
import openai
from gptcache import cache
from gptcache.adapter import openai
from gptcache import cache
from gptcache.adapter import openai
from gptcache.embedding import Onnx
from gptcache.manager import get_data_manager, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistan... | null |
21,778 | import os
import time
from gptcache.manager import get_data_manager, VectorBase
from gptcache import cache, Cache
from gptcache.embedding import Onnx
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.adapter import openai
def cache_init():
dir_name, _ = os.path.split(os.pat... | null |
21,779 | import os
import time
from gptcache.manager import get_data_manager, VectorBase
from gptcache import cache, Cache
from gptcache.embedding import Onnx
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.adapter import openai
def response_text(openai_resp):
return openai_resp['c... | null |
21,780 | import os
import time
from gptcache.manager import get_data_manager, VectorBase
from gptcache import cache, Cache
from gptcache.embedding import Onnx
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.adapter import openai
import openai
def stream_request():
for _ in range(... | null |
21,781 | import os
import time
from gptcache.manager import get_data_manager, VectorBase
from gptcache import cache, Cache
from gptcache.embedding import Onnx
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
from gptcache.adapter import openai
def response_text(openai_resp):
return openai_resp['c... | null |
21,782 | import os
from langchain import Cohere
from langchain.llms import OpenAI
from gptcache.adapter.langchain_models import LangChainLLMs
from gptcache import cache, Cache
from gptcache.processor.pre import get_prompt
OpenAI.api_key = os.getenv("OPENAI_API_KEY")
Cohere.cohere_api_key = os.getenv("COHERE_API_KEY")
class Lan... | null |
21,783 | import time
from langchain import OpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.schema import Document
from gptcache import cache
from gptcache.adapter.api import init_similar_cache
from gptcache.adapter.langchain_models import LangChainLLMs
def get_content_func(data, **_):
re... | null |
21,784 | import time
import torch
from transformers import pipeline
from gptcache.processor.pre import get_inputs
from gptcache.manager import manager_factory
from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.adapter.dolly import Dolly
def get_inputs(data: Dict[str, Any], **_: Dict[str, Any]):
""... | null |
21,785 | import time
import torch
from transformers import pipeline
from gptcache.processor.pre import get_inputs
from gptcache.manager import manager_factory
from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.adapter.dolly import Dolly
def get_inputs(data: Dict[str, Any], **_: Dict[str, Any]):
""... | null |
21,786 | import os
from gptcache.manager import get_data_manager
from gptcache.adapter import openai
from gptcache import cache
import openai
def run():
dir_name, _ = os.path.split(os.path.abspath(__file__))
data_file = dir_name + '/data_map.txt'
data_manager = get_data_manager(data_path=data_file, max_size=10)
... | null |
21,787 | import os
import numpy as np
from gptcache import cache
from gptcache.adapter import openai
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
d = 8
def mock_embeddings(data, **kwargs):
return np.random.random((d, )).asty... | null |
21,788 | import numpy as np
from gptcache import cache
from gptcache.adapter import openai
from gptcache.manager import CacheBase, VectorBase, get_data_manager
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
d = 8
def mock_embeddings(data, **kwargs):
return np.random.random((d, )).astype('float3... | null |
21,789 | from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.manager.eviction import EvictionBase
from gptcache.manager import get_data_manager, CacheBase, VectorBase, manager_factory
def Onnx(model="GPTCache/paraphrase-albert-onnx"):
return onnx.Onnx(model)
def EvictionBase(name: str, **kwargs):
... | This example shows how to create a data manager with a mongo as a scalar storage, faiss vector base, and redis eviction base. This type of configuration can be used to scale GPTCache horizontally. Where keys will be maintained in redis key-value store instead of in-memory. The eviction of the keys will be handled based... |
21,790 | from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.manager.eviction import EvictionBase
from gptcache.manager import get_data_manager, CacheBase, VectorBase, manager_factory
def Onnx(model="GPTCache/paraphrase-albert-onnx"):
return onnx.Onnx(model)
def EvictionBase(name: str, **kwargs):
... | Note: Since, `RedisScalarStorage` can be configured to internally handle the ttl of the keys and their eviction. In this scenario, `no_op_eviction` is used as the eviction base. It will not add any keys or update their ttls. This example shows how to create a data manager with a redis as a scalar storage, as well as ev... |
21,791 | from gptcache import Cache
from gptcache.embedding import Onnx
from gptcache.manager.eviction import EvictionBase
from gptcache.manager import get_data_manager, CacheBase, VectorBase, manager_factory
def Onnx(model="GPTCache/paraphrase-albert-onnx"):
return onnx.Onnx(model)
def manager_factory_example():
onnx... | null |
21,792 | import os
import time
from gptcache import cache
from gptcache.adapter import openai
from gptcache.embedding import Onnx
from gptcache.manager import manager_factory
from gptcache.processor.context import SummarizationContextProcess
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation
def respon... | null |
21,793 | import os
import time
from gptcache import cache
from gptcache.adapter import openai
from gptcache.embedding import Onnx
from gptcache.manager import manager_factory
from gptcache.processor.context import SelectiveContextProcess
from gptcache.similarity_evaluation import SearchDistanceEvaluation
from gptcache.utils imp... | null |
21,794 | import json
import os
import time
from gptcache.adapter import openai
from gptcache import cache, Config
from gptcache.manager import get_data_manager, CacheBase, VectorBase
from gptcache.similarity_evaluation.onnx import OnnxModelEvaluation
from gptcache.embedding import Onnx as EmbeddingOnnx
from gptcache.similarity_... | null |
21,795 | import re
import string
from typing import Dict, Any
The provided code snippet includes necessary dependencies for implementing the `last_content` function. Write a Python function `def last_content(data: Dict[str, Any], **_: Dict[str, Any]) -> Any` to solve the following problem:
get the last content of the message l... | get the last content of the message list :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import last_content content = last_content({"messages": [{"content": "foo1"}, {"content": "foo2"}]}) # content = "foo2" |
21,796 | import re
import string
from typing import Dict, Any
The provided code snippet includes necessary dependencies for implementing the `last_content_without_prompt` function. Write a Python function `def last_content_without_prompt(data: Dict[str, Any], **params: Dict[str, Any]) -> Any` to solve the following problem:
ge... | get the last content of the message list without prompts content :param data: the user llm request data :type data: Dict[str, Any] :param params: the special gptcache params, like prompts param in the cache object :type params: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import last_conte... |
21,797 | import re
import string
from typing import Dict, Any
def _get_pattern_value(pattern_str: str, value_str: str):
literal_text_arr = []
field_name_arr = []
for literal_text, field_name, _, _ in string.Formatter().parse(pattern_str):
literal_text_arr.append(literal_text)
if field_name is not Non... | get the last content's template values of the message list without template content. When considering a cache agent or chain, the majority of the content consists of template content, while the essential information is simply a list of parameters within the template. In this way, the cache key is composed of a string m... |
21,798 | import re
import string
from typing import Dict, Any
The provided code snippet includes necessary dependencies for implementing the `all_content` function. Write a Python function `def all_content(data: Dict[str, Any], **_: Dict[str, Any]) -> Any` to solve the following problem:
get all content of the message list :pa... | get all content of the message list :param data: the user llm request data :type data: Dict[str, Any] :Example: .. code-block:: python from gptcache.processor.pre import all_content content = all_content( {"messages": [{"content": "foo1"}, {"content": "foo2"}]} ) # content = "foo1\\nfoo2" |
21,799 | import re
import string
from typing import Dict, Any
The provided code snippet includes necessary dependencies for implementing the `get_file_bytes` function. Write a Python function `def get_file_bytes(data: Dict[str, Any], **_: Dict[str, Any]) -> bytes` to solve the following problem:
get the file bytes of the llm r... | get the file bytes of the llm request params :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_file_bytes content = get_file_bytes({"file": open("test.txt", "rb")}) |
21,800 | import re
import string
from typing import Dict, Any
The provided code snippet includes necessary dependencies for implementing the `get_input_str` function. Write a Python function `def get_input_str(data: Dict[str, Any], **_: Dict[str, Any]) -> str` to solve the following problem:
get the image and question str of t... | get the image and question str of the llm request params :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_input_str content = get_input_str({"input": {"image": open("test.png", "rb"), "question": "foo"}}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.