method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
index
"""Create the mapping for the Elasticsearch index.""" return {'mappings': {'properties': {vector_query_field: {'type': 'dense_vector', 'dims': dims_length, 'index': False}}}}
def index(self, dims_length: Union[int, None], vector_query_field: str, similarity: Union[DistanceStrategy, None]) ->Dict: """Create the mapping for the Elasticsearch index.""" return {'mappings': {'properties': {vector_query_field: {'type': 'dense_vector', 'dims': dims_length, 'index': False}}}}
Create the mapping for the Elasticsearch index.
test_runnable_branch_init
"""Verify that runnable branch gets initialized properly.""" add = RunnableLambda(lambda x: x + 1) condition = RunnableLambda(lambda x: x > 0) with pytest.raises(ValueError): RunnableBranch((condition, add)) with pytest.raises(ValueError): RunnableBranch(condition)
def test_runnable_branch_init() ->None: """Verify that runnable branch gets initialized properly.""" add = RunnableLambda(lambda x: x + 1) condition = RunnableLambda(lambda x: x > 0) with pytest.raises(ValueError): RunnableBranch((condition, add)) with pytest.raises(ValueError): Runn...
Verify that runnable branch gets initialized properly.
validate_environment
"""Validate that python package exists in environment.""" try: from duckduckgo_search import DDGS except ImportError: raise ImportError( 'Could not import duckduckgo-search python package. Please install it with `pip install -U duckduckgo-search`.' ) return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that python package exists in environment.""" try: from duckduckgo_search import DDGS except ImportError: raise ImportError( 'Could not import duckduckgo-search python package. Please install it wit...
Validate that python package exists in environment.
get_format_instructions
"""Instructions on how the LLM output should be formatted.""" raise NotImplementedError
def get_format_instructions(self) ->str: """Instructions on how the LLM output should be formatted.""" raise NotImplementedError
Instructions on how the LLM output should be formatted.
validate_environment
"""Validate that api key and python package exists in environment.""" values['eas_service_url'] = get_from_dict_or_env(values, 'eas_service_url', 'EAS_SERVICE_URL') values['eas_service_token'] = get_from_dict_or_env(values, 'eas_service_token', 'EAS_SERVICE_TOKEN') return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" values['eas_service_url'] = get_from_dict_or_env(values, 'eas_service_url', 'EAS_SERVICE_URL') values['eas_service_token'] = get_from_dict_or_env(values, ...
Validate that api key and python package exists in environment.
test__convert_delta_to_message_assistant
delta = {'role': 'assistant', 'content': 'foo'} result = _convert_delta_to_message_chunk(delta, AIMessageChunk) expected_output = AIMessageChunk(content='foo') assert result == expected_output
def test__convert_delta_to_message_assistant() ->None: delta = {'role': 'assistant', 'content': 'foo'} result = _convert_delta_to_message_chunk(delta, AIMessageChunk) expected_output = AIMessageChunk(content='foo') assert result == expected_output
null
similarity_search
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of Documents to fet...
def similarity_search(self, query: str, k: int=4, filter: Optional[Dict[str, Any]]=None, fetch_k: int=20, **kwargs: Any) ->List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. ...
Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of Documents to fetch before filtering. Defaults...
validate_environment
"""Validate that api key and python package exists in environment.""" values['dashscope_api_key'] = get_from_dict_or_env(values, 'dashscope_api_key', 'DASHSCOPE_API_KEY') try: import dashscope except ImportError: raise ImportError( 'Could not import dashscope python package. Please install it with `...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" values['dashscope_api_key'] = get_from_dict_or_env(values, 'dashscope_api_key', 'DASHSCOPE_API_KEY') try: import dashscope except ImportError: ...
Validate that api key and python package exists in environment.
max_marginal_relevance_search_by_vector
"""Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: embedding: Embedding to look up documents similar to. fetch_k: Number of Documents to fetch to pass t...
def max_marginal_relevance_search_by_vector(self, embedding: List[float], k: int=4, fetch_k: int=20, lambda_mult: float=0.5, **kwargs: Any) ->List[ Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity ...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: embedding: Embedding to look up documents similar to. fetch_k: Number of Documents to fetch to pass to MMR algorithm. k: Number of Documents...
_retrieve_ref
components = path.split('/') if components[0] != '#': raise ValueError( 'ref paths are expected to be URI fragments, meaning they should start with #.' ) out = schema for component in components[1:]: if component.isdigit(): out = out[int(component)] else: out = out[component]...
def _retrieve_ref(path: str, schema: dict) ->dict: components = path.split('/') if components[0] != '#': raise ValueError( 'ref paths are expected to be URI fragments, meaning they should start with #.' ) out = schema for component in components[1:]: if component....
null
test_pairwise_embedding_distance_eval_chain_chebyshev_distance
"""Test the chebyshev distance.""" from scipy.spatial.distance import chebyshev pairwise_embedding_distance_eval_chain.distance_metric = (EmbeddingDistance .CHEBYSHEV) result = pairwise_embedding_distance_eval_chain._compute_score(np.array( vectors)) expected = chebyshev(*vectors) assert np.isclose(result, expe...
@pytest.mark.requires('scipy') def test_pairwise_embedding_distance_eval_chain_chebyshev_distance( pairwise_embedding_distance_eval_chain: PairwiseEmbeddingDistanceEvalChain, vectors: Tuple[np.ndarray, np.ndarray] ) ->None: """Test the chebyshev distance.""" from scipy.spatial.distance import chebys...
Test the chebyshev distance.
batch
if not inputs: return [] config = get_config_list(config, len(inputs)) max_concurrency = config[0].get('max_concurrency') if max_concurrency is None: try: llm_result = self.generate_prompt([self._convert_input(input) for input in inputs], callbacks=[c.get('callbacks') for c in config ...
def batch(self, inputs: List[LanguageModelInput], config: Optional[Union[ RunnableConfig, List[RunnableConfig]]]=None, *, return_exceptions: bool =False, **kwargs: Any) ->List[str]: if not inputs: return [] config = get_config_list(config, len(inputs)) max_concurrency = config[0].get('max_co...
null
test_news_loader
loader = NewsURLLoader([get_random_news_url()]) docs = loader.load() assert docs[0] is not None assert hasattr(docs[0], 'page_content') assert hasattr(docs[0], 'metadata') metadata = docs[0].metadata assert 'title' in metadata assert 'link' in metadata assert 'authors' in metadata assert 'language' in metadata assert '...
def test_news_loader() ->None: loader = NewsURLLoader([get_random_news_url()]) docs = loader.load() assert docs[0] is not None assert hasattr(docs[0], 'page_content') assert hasattr(docs[0], 'metadata') metadata = docs[0].metadata assert 'title' in metadata assert 'link' in metadata ...
null
test_litellm_streaming_callback
"""Test that streaming correctly invokes on_llm_new_token callback.""" callback_handler = FakeCallbackHandler() callback_manager = CallbackManager([callback_handler]) chat = ChatLiteLLM(model='test', streaming=True, callback_manager= callback_manager, verbose=True) message = HumanMessage(content='Write me a sentenc...
def test_litellm_streaming_callback() ->None: """Test that streaming correctly invokes on_llm_new_token callback.""" callback_handler = FakeCallbackHandler() callback_manager = CallbackManager([callback_handler]) chat = ChatLiteLLM(model='test', streaming=True, callback_manager= callback_manager...
Test that streaming correctly invokes on_llm_new_token callback.
_import_deeplake
from langchain_community.vectorstores.deeplake import DeepLake return DeepLake
def _import_deeplake() ->Any: from langchain_community.vectorstores.deeplake import DeepLake return DeepLake
null
load_llm
"""Load LLM from file.""" if isinstance(file, str): file_path = Path(file) else: file_path = file if file_path.suffix == '.json': with open(file_path) as f: config = json.load(f) elif file_path.suffix == '.yaml': with open(file_path, 'r') as f: config = yaml.safe_load(f) else: raise ...
def load_llm(file: Union[str, Path]) ->BaseLLM: """Load LLM from file.""" if isinstance(file, str): file_path = Path(file) else: file_path = file if file_path.suffix == '.json': with open(file_path) as f: config = json.load(f) elif file_path.suffix == '.yaml': ...
Load LLM from file.
test_serialize_openai_llm
llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello', callbacks=[LangChainTracer()]) llm.temperature = 0.7 assert dumps(llm, pretty=True) == snapshot
@pytest.mark.requires('openai') def test_serialize_openai_llm(snapshot: Any) ->None: llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello', callbacks=[LangChainTracer()]) llm.temperature = 0.7 assert dumps(llm, pretty=True) == snapshot
null
create_extraction_chain
"""Creates a chain that extracts information from a passage. Args: schema: The schema of the entities to extract. llm: The language model to use. prompt: The prompt to use for extraction. verbose: Whether to run in verbose mode. In verbose mode, some intermediate logs wi...
def create_extraction_chain(schema: dict, llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate]=None, tags: Optional[List[str]]=None, verbose: bool=False) ->Chain: """Creates a chain that extracts information from a passage. Args: schema: The schema of the entities to extract. ll...
Creates a chain that extracts information from a passage. Args: schema: The schema of the entities to extract. llm: The language model to use. prompt: The prompt to use for extraction. verbose: Whether to run in verbose mode. In verbose mode, some intermediate logs will be printed to the consol...
_get_root_referenced_request_body
"""Get the root request Body or err.""" from openapi_pydantic import Reference request_body = self._get_referenced_request_body(ref) while isinstance(request_body, Reference): request_body = self._get_referenced_request_body(request_body) return request_body
def _get_root_referenced_request_body(self, ref: Reference) ->Optional[ RequestBody]: """Get the root request Body or err.""" from openapi_pydantic import Reference request_body = self._get_referenced_request_body(ref) while isinstance(request_body, Reference): request_body = self._get_refer...
Get the root request Body or err.
_format_chat_history
buffer = [] for human, ai in chat_history: buffer.append(HumanMessage(content=human)) buffer.append(AIMessage(content=ai)) return buffer
def _format_chat_history(chat_history: List[Tuple[str, str]]) ->List: buffer = [] for human, ai in chat_history: buffer.append(HumanMessage(content=human)) buffer.append(AIMessage(content=ai)) return buffer
null
get_num_tokens_anthropic
"""Get the number of tokens in a string of text.""" client = _get_anthropic_client() return client.count_tokens(text=text)
def get_num_tokens_anthropic(text: str) ->int: """Get the number of tokens in a string of text.""" client = _get_anthropic_client() return client.count_tokens(text=text)
Get the number of tokens in a string of text.
add_texts
""" Add text to the collection. Args: texts: An iterable that contains the text to be added. metadatas: An optional list of dictionaries, each dictionary contains the metadata associated with a text. timeout: Optional timeout, in seconds. batc...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, timeout: Optional[int]=None, batch_size: int=1000, **kwargs: Any ) ->List[str]: """ Add text to the collection. Args: texts: An iterable that contains the text to be added. metadatas: An...
Add text to the collection. Args: texts: An iterable that contains the text to be added. metadatas: An optional list of dictionaries, each dictionary contains the metadata associated with a text. timeout: Optional timeout, in seconds. batch_size: The number of texts inserted in each batch, defaults...
get_executor_for_config
"""Get an executor for a config. Args: config (RunnableConfig): The config. Yields: Generator[Executor, None, None]: The executor. """ config = config or {} with ContextThreadPoolExecutor(max_workers=config.get('max_concurrency') ) as executor: yield executor
@contextmanager def get_executor_for_config(config: Optional[RunnableConfig]) ->Generator[ Executor, None, None]: """Get an executor for a config. Args: config (RunnableConfig): The config. Yields: Generator[Executor, None, None]: The executor. """ config = config or {} wit...
Get an executor for a config. Args: config (RunnableConfig): The config. Yields: Generator[Executor, None, None]: The executor.
cache_embeddings
"""Create a cache backed embeddings.""" store = InMemoryStore() embeddings = MockEmbeddings() return CacheBackedEmbeddings.from_bytes_store(embeddings, store, namespace= 'test_namespace')
@pytest.fixture def cache_embeddings() ->CacheBackedEmbeddings: """Create a cache backed embeddings.""" store = InMemoryStore() embeddings = MockEmbeddings() return CacheBackedEmbeddings.from_bytes_store(embeddings, store, namespace='test_namespace')
Create a cache backed embeddings.
_chain_type
return 'chat-vector-db'
@property def _chain_type(self) ->str: return 'chat-vector-db'
null
__init__
"""Initialize with Lance DB connection""" try: import lancedb except ImportError: raise ImportError( 'Could not import lancedb python package. Please install it with `pip install lancedb`.' ) if not isinstance(connection, lancedb.db.LanceTable): raise ValueError( 'connection should b...
def __init__(self, connection: Any, embedding: Embeddings, vector_key: Optional[str]='vector', id_key: Optional[str]='id', text_key: Optional[ str]='text'): """Initialize with Lance DB connection""" try: import lancedb except ImportError: raise ImportError( 'Could not imp...
Initialize with Lance DB connection
on_retry_common
self.retries += 1
def on_retry_common(self) ->None: self.retries += 1
null
lookup_with_id
""" Look up based on prompt and llm_string. If there are hits, return (document_id, cached_entry) for the top hit """ prompt_embedding: List[float] = self._get_embedding(text=prompt) llm_string_hash = _hash(llm_string) hit = self.collection.vector_find_one(vector=prompt_embedding, filter={ '...
def lookup_with_id(self, prompt: str, llm_string: str) ->Optional[Tuple[str, RETURN_VAL_TYPE]]: """ Look up based on prompt and llm_string. If there are hits, return (document_id, cached_entry) for the top hit """ prompt_embedding: List[float] = self._get_embedding(text=prompt) l...
Look up based on prompt and llm_string. If there are hits, return (document_id, cached_entry) for the top hit
on_llm_start
"""Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. prompts (List[str]): The list of prompts. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: List[CallbackManagerForLLMRun]: A callback manager for...
def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], ** kwargs: Any) ->List[CallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. prompts (List[str]): The list of prompts. run_id (UUID, opt...
Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. prompts (List[str]): The list of prompts. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: List[CallbackManagerForLLMRun]: A callback manager for each prompt as an LLM run.
_call
return self.client(pipeline=self.pipeline_ref, prompt=prompt, stop=stop, ** kwargs)
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: return self.client(pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs)
null
output_parser
"""Output parser for testing.""" return BashOutputParser()
@pytest.fixture def output_parser() ->BashOutputParser: """Output parser for testing.""" return BashOutputParser()
Output parser for testing.
_call_after_predict_before_llm
import numpy as np prob_sum = sum(prob for _, prob in prediction) probabilities = [(prob / prob_sum) for _, prob in prediction] sampled_index = np.random.choice(len(prediction), p=probabilities) sampled_ap = prediction[sampled_index] sampled_action = sampled_ap[0] sampled_prob = sampled_ap[1] selected = PickBestSelecte...
def _call_after_predict_before_llm(self, inputs: Dict[str, Any], event: PickBestEvent, prediction: List[Tuple[int, float]]) ->Tuple[Dict[str, Any], PickBestEvent]: import numpy as np prob_sum = sum(prob for _, prob in prediction) probabilities = [(prob / prob_sum) for _, prob in prediction] samp...
null
test_llamacpp_streaming
"""Test streaming tokens from LlamaCpp.""" model_path = get_model() llm = LlamaCpp(model_path=model_path, max_tokens=10) generator = llm.stream("Q: How do you say 'hello' in German? A:'", stop=["'"]) stream_results_string = '' assert isinstance(generator, Generator) for chunk in generator: assert not isinstance(chu...
def test_llamacpp_streaming() ->None: """Test streaming tokens from LlamaCpp.""" model_path = get_model() llm = LlamaCpp(model_path=model_path, max_tokens=10) generator = llm.stream("Q: How do you say 'hello' in German? A:'", stop =["'"]) stream_results_string = '' assert isinstance(gene...
Test streaming tokens from LlamaCpp.
from_llm
"""Create a `LabeledCriteriaEvalChain` instance from an llm and criteria. Parameters ---------- llm : BaseLanguageModel The language model to use for evaluation. criteria : CRITERIA_TYPE - default=None for "helpfulness" The criteria to evaluate the runs against. ...
@classmethod def from_llm(cls, llm: BaseLanguageModel, criteria: Optional[CRITERIA_TYPE] =None, *, prompt: Optional[BasePromptTemplate]=None, **kwargs: Any ) ->CriteriaEvalChain: """Create a `LabeledCriteriaEvalChain` instance from an llm and criteria. Parameters ---------- llm : Ba...
Create a `LabeledCriteriaEvalChain` instance from an llm and criteria. Parameters ---------- llm : BaseLanguageModel The language model to use for evaluation. criteria : CRITERIA_TYPE - default=None for "helpfulness" The criteria to evaluate the runs against. It can be: - a mapping of a criterion name...
add_texts
"""Insert documents into the instance.. Args: texts: The text segments to be inserted into the vector storage, should not be empty. metadatas: Metadata information. Returns: id_list: List of document IDs. """ def _upsert(push_doc_list: List[Dict])...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, **kwargs: Any) ->List[str]: """Insert documents into the instance.. Args: texts: The text segments to be inserted into the vector storage, should not be empty. metadatas: Metadata inform...
Insert documents into the instance.. Args: texts: The text segments to be inserted into the vector storage, should not be empty. metadatas: Metadata information. Returns: id_list: List of document IDs.
register_configure_hook
"""Register a configure hook. Args: context_var (ContextVar[Optional[Any]]): The context variable. inheritable (bool): Whether the context variable is inheritable. handle_class (Optional[Type[BaseCallbackHandler]], optional): The callback handler class. Defaults to None. e...
def register_configure_hook(context_var: ContextVar[Optional[Any]], inheritable: bool, handle_class: Optional[Type[BaseCallbackHandler]]= None, env_var: Optional[str]=None) ->None: """Register a configure hook. Args: context_var (ContextVar[Optional[Any]]): The context variable. inherit...
Register a configure hook. Args: context_var (ContextVar[Optional[Any]]): The context variable. inheritable (bool): Whether the context variable is inheritable. handle_class (Optional[Type[BaseCallbackHandler]], optional): The callback handler class. Defaults to None. env_var (Optional[str], opti...
from_documents
texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) return cls.from_texts(texts=texts, tfidf_params=tfidf_params, metadatas= metadatas, **kwargs)
@classmethod def from_documents(cls, documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]]=None, **kwargs: Any) ->TFIDFRetriever: texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) return cls.from_texts(texts=texts, tfidf_params=tfidf_params, metadatas =met...
null
_end_trace
"""End a trace for a run.""" if not run.parent_run_id: self._persist_run(run) else: parent_run = self.run_map.get(str(run.parent_run_id)) if parent_run is None: logger.debug(f'Parent run with UUID {run.parent_run_id} not found.') elif run.child_execution_order is not None and parent_run.child_ex...
def _end_trace(self, run: Run) ->None: """End a trace for a run.""" if not run.parent_run_id: self._persist_run(run) else: parent_run = self.run_map.get(str(run.parent_run_id)) if parent_run is None: logger.debug(f'Parent run with UUID {run.parent_run_id} not found.' ...
End a trace for a run.
test_few_shot_chat_message_prompt_template
"""Tests for few shot chat message template.""" examples = [{'input': '2+2', 'output': '4'}, {'input': '2+3', 'output': '5'}] example_prompt = ChatPromptTemplate.from_messages([ HumanMessagePromptTemplate.from_template('{input}'), AIMessagePromptTemplate.from_template('{output}')]) few_shot_prompt = FewShotChat...
def test_few_shot_chat_message_prompt_template() ->None: """Tests for few shot chat message template.""" examples = [{'input': '2+2', 'output': '4'}, {'input': '2+3', 'output': '5'}] example_prompt = ChatPromptTemplate.from_messages([ HumanMessagePromptTemplate.from_template('{input}'), ...
Tests for few shot chat message template.
test_create
""" Create a vector with vector index 'v' of dimension 10 and 'v:text' to hold text and metadatas author and category """ metadata_str = 'author char(32), category char(16)' self.vectorstore.create(metadata_str, 1024) podstore = self.pod + '.' + self.store js = self.vectorstore.run(f'desc {podst...
def test_create(self) ->None: """ Create a vector with vector index 'v' of dimension 10 and 'v:text' to hold text and metadatas author and category """ metadata_str = 'author char(32), category char(16)' self.vectorstore.create(metadata_str, 1024) podstore = self.pod + '.' + self...
Create a vector with vector index 'v' of dimension 10 and 'v:text' to hold text and metadatas author and category
load
"""Load data into document objects.""" docs = [] try: with open(self.file_path, newline='', encoding=self.encoding) as csvfile: docs = self.__read_file(csvfile) except UnicodeDecodeError as e: if self.autodetect_encoding: detected_encodings = detect_file_encodings(self.file_path) for enc...
def load(self) ->List[Document]: """Load data into document objects.""" docs = [] try: with open(self.file_path, newline='', encoding=self.encoding ) as csvfile: docs = self.__read_file(csvfile) except UnicodeDecodeError as e: if self.autodetect_encoding: ...
Load data into document objects.
from_texts
""" Return VectorStore initialized from texts and embeddings. Hologres connection string is required "Either pass it as a parameter or set the HOLOGRES_CONNECTION_STRING environment variable. Create the connection string by calling HologresVector.connection_string_from_db...
@classmethod def from_texts(cls: Type[Hologres], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, ndims: int=ADA_TOKEN_COUNT, table_name: str=_LANGCHAIN_DEFAULT_TABLE_NAME, ids: Optional[List[str]] =None, pre_delete_table: bool=False, **kwargs: Any) ->Hologres: """ ...
Return VectorStore initialized from texts and embeddings. Hologres connection string is required "Either pass it as a parameter or set the HOLOGRES_CONNECTION_STRING environment variable. Create the connection string by calling HologresVector.connection_string_from_db_params
__str__
"""Return the query syntax for a RedisText filter expression.""" if not self._value: return '*' return self.OPERATOR_MAP[self._operator] % (self._field, self._value)
def __str__(self) ->str: """Return the query syntax for a RedisText filter expression.""" if not self._value: return '*' return self.OPERATOR_MAP[self._operator] % (self._field, self._value)
Return the query syntax for a RedisText filter expression.
mock_lakefs_client_no_presign_local
with patch('langchain_community.document_loaders.lakefs.LakeFSClient' ) as mock_lakefs_client: mock_lakefs_client.return_value.ls_objects.return_value = [( 'path_bla.txt', 'local:///physical_address_bla')] mock_lakefs_client.return_value.is_presign_supported.return_value = False yield mock_lakef...
@pytest.fixture def mock_lakefs_client_no_presign_local() ->Any: with patch('langchain_community.document_loaders.lakefs.LakeFSClient' ) as mock_lakefs_client: mock_lakefs_client.return_value.ls_objects.return_value = [( 'path_bla.txt', 'local:///physical_address_bla')] (mock_lak...
null
save_context
"""Nothing should be saved or changed""" pass
def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) ->None: """Nothing should be saved or changed""" pass
Nothing should be saved or changed
test_chat_google_palm_multiple_completions
"""Test Google PaLM Chat API wrapper with multiple completions.""" chat = ChatGooglePalm(n=5, temperature=1.0) message = HumanMessage(content='Hello') response = chat._generate([message]) assert isinstance(response, ChatResult) assert len(response.generations) == 5 for generation in response.generations: assert isi...
def test_chat_google_palm_multiple_completions() ->None: """Test Google PaLM Chat API wrapper with multiple completions.""" chat = ChatGooglePalm(n=5, temperature=1.0) message = HumanMessage(content='Hello') response = chat._generate([message]) assert isinstance(response, ChatResult) assert len(...
Test Google PaLM Chat API wrapper with multiple completions.
create
...
@overload @staticmethod def create(messages: Sequence[Dict[str, Any]], *, provider: str= 'ChatOpenAI', stream: Literal[False]=False, **kwargs: Any ) ->ChatCompletions: ...
null
embed_documents
"""Call out to LocalAI's embedding endpoint for embedding search docs. Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk size specified by the class. Returns: List of embeddings, one for ea...
def embed_documents(self, texts: List[str], chunk_size: Optional[int]=0 ) ->List[List[float]]: """Call out to LocalAI's embedding endpoint for embedding search docs. Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk si...
Call out to LocalAI's embedding endpoint for embedding search docs. Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk size specified by the class. Returns: List of embeddings, one for each text.
_to_chat_prompt
"""Convert a list of messages into a prompt format expected by wrapped LLM.""" if not messages: raise ValueError('at least one HumanMessage must be provided') if not isinstance(messages[0], SystemMessage): messages = [self.system_message] + messages if not isinstance(messages[1], HumanMessage): raise ValueE...
def _to_chat_prompt(self, messages: List[BaseMessage]) ->str: """Convert a list of messages into a prompt format expected by wrapped LLM.""" if not messages: raise ValueError('at least one HumanMessage must be provided') if not isinstance(messages[0], SystemMessage): messages = [self.system_...
Convert a list of messages into a prompt format expected by wrapped LLM.
get_structured_schema
"""Returns the structured schema of the Graph""" return self.structured_schema
@property def get_structured_schema(self) ->Dict[str, Any]: """Returns the structured schema of the Graph""" return self.structured_schema
Returns the structured schema of the Graph
_run_persistent
""" Runs commands in a persistent environment and returns the output. Args: command: the command to execute """ pexpect = self._lazy_import_pexpect() if self.process is None: raise ValueError('Process not initialized') self.process.sendline(command) self.process.expect(s...
def _run_persistent(self, command: str) ->str: """ Runs commands in a persistent environment and returns the output. Args: command: the command to execute """ pexpect = self._lazy_import_pexpect() if self.process is None: raise ValueError('Process not ini...
Runs commands in a persistent environment and returns the output. Args: command: the command to execute
OutputType
"""The type of the output of this runnable as a type annotation.""" func = getattr(self, 'func', None) or getattr(self, 'afunc') try: sig = inspect.signature(func) if sig.return_annotation != inspect.Signature.empty: if getattr(sig.return_annotation, '__origin__', None) in (collections .abc....
@property def OutputType(self) ->Any: """The type of the output of this runnable as a type annotation.""" func = getattr(self, 'func', None) or getattr(self, 'afunc') try: sig = inspect.signature(func) if sig.return_annotation != inspect.Signature.empty: if getattr(sig.return_ann...
The type of the output of this runnable as a type annotation.
_call
"""Call the IBM watsonx.ai inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. run_manager: Optional callback manager. Returns: The string generated by the model. Example: ...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call the IBM watsonx.ai inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when g...
Call the IBM watsonx.ai inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. run_manager: Optional callback manager. Returns: The string generated by the model. Example: .. code-block:: python response = watsonx_llm("...
_process_page_content
"""Process the page content based on dedupe.""" if self.dedupe: return page.dedupe_chars().extract_text(**self.text_kwargs) return page.extract_text(**self.text_kwargs)
def _process_page_content(self, page: pdfplumber.page.Page) ->str: """Process the page content based on dedupe.""" if self.dedupe: return page.dedupe_chars().extract_text(**self.text_kwargs) return page.extract_text(**self.text_kwargs)
Process the page content based on dedupe.
test_messages_to_prompt_dict_raises_with_misplaced_system_message
pytest.importorskip('google.generativeai') with pytest.raises(ChatGooglePalmError) as e: _messages_to_prompt_dict([HumanMessage(content='Real human message'), SystemMessage(content='Prompt')]) assert 'System message must be first' in str(e)
def test_messages_to_prompt_dict_raises_with_misplaced_system_message() ->None: pytest.importorskip('google.generativeai') with pytest.raises(ChatGooglePalmError) as e: _messages_to_prompt_dict([HumanMessage(content='Real human message' ), SystemMessage(content='Prompt')]) assert 'System...
null
validate_channel_or_videoIds_is_set
"""Validate that either folder_id or document_ids is set, but not both.""" if not values.get('channel_name') and not values.get('video_ids'): raise ValueError('Must specify either channel_name or video_ids') return values
@root_validator def validate_channel_or_videoIds_is_set(cls, values: Dict[str, Any]) ->Dict[ str, Any]: """Validate that either folder_id or document_ids is set, but not both.""" if not values.get('channel_name') and not values.get('video_ids'): raise ValueError('Must specify either channel_name or ...
Validate that either folder_id or document_ids is set, but not both.
__getattr__
try: return self[name] except KeyError: raise AttributeError(f"'EvalError' object has no attribute '{name}'")
def __getattr__(self, name: str) ->Any: try: return self[name] except KeyError: raise AttributeError(f"'EvalError' object has no attribute '{name}'")
null
get_return_intermediate_steps
"""For backwards compatibility.""" if 'return_refine_steps' in values: values['return_intermediate_steps'] = values['return_refine_steps'] del values['return_refine_steps'] return values
@root_validator(pre=True) def get_return_intermediate_steps(cls, values: Dict) ->Dict: """For backwards compatibility.""" if 'return_refine_steps' in values: values['return_intermediate_steps'] = values['return_refine_steps'] del values['return_refine_steps'] return values
For backwards compatibility.
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
get_summary
"""Return a descriptive summary of the agent.""" current_time = datetime.now() if now is None else now since_refresh = (current_time - self.last_refreshed).seconds if not self.summary or since_refresh >= self.summary_refresh_seconds or force_refresh: self.summary = self._compute_agent_summary() self.last_refres...
def get_summary(self, force_refresh: bool=False, now: Optional[datetime]=None ) ->str: """Return a descriptive summary of the agent.""" current_time = datetime.now() if now is None else now since_refresh = (current_time - self.last_refreshed).seconds if (not self.summary or since_refresh >= self.sum...
Return a descriptive summary of the agent.
_diff
return jsonpatch.make_patch(prev, next).patch
def _diff(self, prev: Optional[Any], next: Any) ->Any: return jsonpatch.make_patch(prev, next).patch
null
get_prompt
"""Generates a prompt string. It includes various constraints, commands, resources, and performance evaluations. Returns: str: The generated prompt string. """ prompt_generator = PromptGenerator() prompt_generator.add_constraint( '~4000 word limit for short term memory. Your short term memory ...
def get_prompt(tools: List[BaseTool]) ->str: """Generates a prompt string. It includes various constraints, commands, resources, and performance evaluations. Returns: str: The generated prompt string. """ prompt_generator = PromptGenerator() prompt_generator.add_constraint( '~4...
Generates a prompt string. It includes various constraints, commands, resources, and performance evaluations. Returns: str: The generated prompt string.
test_xml_output_parser_fail
"""Test XMLOutputParser where complete output is not in XML format.""" xml_parser = XMLOutputParser() with pytest.raises(ValueError) as e: xml_parser.parse_folder(result) assert 'Could not parse output' in str(e)
@pytest.mark.parametrize('result', ['foo></foo>', '<foo></foo', 'foo></foo', 'foofoo']) def test_xml_output_parser_fail(result: str) ->None: """Test XMLOutputParser where complete output is not in XML format.""" xml_parser = XMLOutputParser() with pytest.raises(ValueError) as e: xml_parser.parse...
Test XMLOutputParser where complete output is not in XML format.
_identifying_params
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return {**{'endpoint_url': self.endpoint_url}, **{'model_kwargs': _model_kwargs}}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return {**{'endpoint_url': self.endpoint_url}, **{'model_kwargs': _model_kwargs}}
Get the identifying parameters.
format
return self.format_prompt(**kwargs).to_string()
def format(self, **kwargs: Any) ->str: return self.format_prompt(**kwargs).to_string()
null
_llm_type
"""Return type of llm.""" return 'cerebriumai'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'cerebriumai'
Return type of llm.
test_sim_search
"""Test end to end construction and simple similarity search.""" texts = ['foo', 'bar', 'baz'] in_memory_vec_store = DocArrayInMemorySearch.from_texts(texts=texts, embedding=FakeEmbeddings(), metric=metric) output = in_memory_vec_store.similarity_search('foo', k=1) assert output == [Document(page_content='foo')]
@pytest.mark.parametrize('metric', ['cosine_sim', 'euclidean_dist', 'sqeuclidean_dist']) def test_sim_search(metric: str, texts: List[str]) ->None: """Test end to end construction and simple similarity search.""" texts = ['foo', 'bar', 'baz'] in_memory_vec_store = DocArrayInMemorySearch.from_texts(texts...
Test end to end construction and simple similarity search.
_on_tool_end
crumbs = self.get_breadcrumbs(run) if run.outputs: self.function_callback( f"{get_colored_text('[tool/end]', color='blue')} " + get_bolded_text( f"""[{crumbs}] [{elapsed(run)}] Exiting Tool run with output: """) + f'"{run.outputs[\'output\'].strip()}"')
def _on_tool_end(self, run: Run) ->None: crumbs = self.get_breadcrumbs(run) if run.outputs: self.function_callback( f"{get_colored_text('[tool/end]', color='blue')} " + get_bolded_text( f"""[{crumbs}] [{elapsed(run)}] Exiting Tool run with output: """ ) + ...
null
__init__
""" Initializes the GoogleSpeechToTextLoader. Args: project_id: Google Cloud Project ID. file_path: A Google Cloud Storage URI or a local file path. location: Speech-to-Text recognizer location. recognizer_id: Speech-to-Text recognizer id. con...
def __init__(self, project_id: str, file_path: str, location: str= 'us-central1', recognizer_id: str='_', config: Optional[ RecognitionConfig]=None, config_mask: Optional[FieldMask]=None): """ Initializes the GoogleSpeechToTextLoader. Args: project_id: Google Cloud Project ID. ...
Initializes the GoogleSpeechToTextLoader. Args: project_id: Google Cloud Project ID. file_path: A Google Cloud Storage URI or a local file path. location: Speech-to-Text recognizer location. recognizer_id: Speech-to-Text recognizer id. config: Recognition options and features. For more info...
test_visit_operation_or
op = Operation(operator=Operator.OR, arguments=[Comparison(comparator= Comparator.EQ, attribute='foo', value=2), Comparison(comparator= Comparator.EQ, attribute='bar', value='baz')]) expected = {'bool': {'should': [{'term': {'metadata.foo': 2}}, {'term': { 'metadata.bar.keyword': 'baz'}}]}} actual = DEFAULT...
def test_visit_operation_or() ->None: op = Operation(operator=Operator.OR, arguments=[Comparison(comparator= Comparator.EQ, attribute='foo', value=2), Comparison(comparator= Comparator.EQ, attribute='bar', value='baz')]) expected = {'bool': {'should': [{'term': {'metadata.foo': 2}}, {'term': ...
null
test_md_header_text_splitter_preserve_headers_1
"""Test markdown splitter by header: Preserve Headers.""" markdown_document = """# Foo ## Bat Hi this is Jim Hi Joe ## Baz # Bar This is Alice This is Bob""" headers_to_split_on = [('#', 'Header 1')] markdown_splitter = MarkdownHeaderTextSplitter(headers_to_split_on= headers_to_split_on, strip_headers=Fa...
def test_md_header_text_splitter_preserve_headers_1() ->None: """Test markdown splitter by header: Preserve Headers.""" markdown_document = """# Foo ## Bat Hi this is Jim Hi Joe ## Baz # Bar This is Alice This is Bob""" headers_to_split_on = [('#', 'Header 1')] markdown_splitter = MarkdownHea...
Test markdown splitter by header: Preserve Headers.
__or__
"""Compose this runnable with another object to create a RunnableSequence.""" return RunnableSequence(self, coerce_to_runnable(other))
def __or__(self, other: Union[Runnable[Any, Other], Callable[[Any], Other], Callable[[Iterator[Any]], Iterator[Other]], Mapping[str, Union[Runnable [Any, Other], Callable[[Any], Other], Any]]]) ->RunnableSerializable[ Input, Other]: """Compose this runnable with another object to create a RunnableSequen...
Compose this runnable with another object to create a RunnableSequence.
test_example_id_assignment_threadsafe
"""Test that example assigned at callback start/end is honored.""" example_ids = {} def mock_create_run(**kwargs: Any) ->Any: example_ids[kwargs.get('id')] = kwargs.get('reference_example_id') return unittest.mock.MagicMock() client = unittest.mock.MagicMock(spec=Client) client.create_run = mock_create_run trac...
def test_example_id_assignment_threadsafe() ->None: """Test that example assigned at callback start/end is honored.""" example_ids = {} def mock_create_run(**kwargs: Any) ->Any: example_ids[kwargs.get('id')] = kwargs.get('reference_example_id') return unittest.mock.MagicMock() client = ...
Test that example assigned at callback start/end is honored.
__init__
""" Args: repo_path: The path to the Git repository. clone_url: Optional. The URL to clone the repository from. branch: Optional. The branch to load files from. Defaults to `main`. file_filter: Optional. A function that takes a file path and returns ...
def __init__(self, repo_path: str, clone_url: Optional[str]=None, branch: Optional[str]='main', file_filter: Optional[Callable[[str], bool]]=None): """ Args: repo_path: The path to the Git repository. clone_url: Optional. The URL to clone the repository from. branch:...
Args: repo_path: The path to the Git repository. clone_url: Optional. The URL to clone the repository from. branch: Optional. The branch to load files from. Defaults to `main`. file_filter: Optional. A function that takes a file path and returns a boolean indicating whether to load the file. Defau...
_llm_type
"""Return type of chat model.""" return 'konko-chat'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'konko-chat'
Return type of chat model.
llm_prefix
"""Prefix to append the llm call with.""" return 'Thought:'
@property def llm_prefix(self) ->str: """Prefix to append the llm call with.""" return 'Thought:'
Prefix to append the llm call with.
delete
del self.store[key]
def delete(self, key: str) ->None: del self.store[key]
null
test_pgvector_delete_docs
"""Add and delete documents.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = PGVector.from_texts(texts=texts, collection_name= 'test_collection_filter', embedding=FakeEmbeddingsWithAdaDimension(), metadatas=metadatas, ids=['1', '2', '3'], connection_string=...
def test_pgvector_delete_docs() ->None: """Add and delete documents.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = PGVector.from_texts(texts=texts, collection_name= 'test_collection_filter', embedding=FakeEmbeddingsWithAdaDimension( ...
Add and delete documents.
_create_chat_result
generations = [] for res in response['choices']: message = _convert_dict_to_message(res['message']) gen = ChatGeneration(message=message, generation_info=dict( finish_reason=res.get('finish_reason'))) generations.append(gen) return ChatResult(generations=generations)
def _create_chat_result(self, response: Mapping[str, Any]) ->ChatResult: generations = [] for res in response['choices']: message = _convert_dict_to_message(res['message']) gen = ChatGeneration(message=message, generation_info=dict( finish_reason=res.get('finish_reason'))) ge...
null
test_saving_loading_llm
"""Test saving/loading an Cohere LLM.""" llm = Cohere(max_tokens=10) llm.save(file_path=tmp_path / 'cohere.yaml') loaded_llm = load_llm(tmp_path / 'cohere.yaml') assert_llm_equality(llm, loaded_llm)
def test_saving_loading_llm(tmp_path: Path) ->None: """Test saving/loading an Cohere LLM.""" llm = Cohere(max_tokens=10) llm.save(file_path=tmp_path / 'cohere.yaml') loaded_llm = load_llm(tmp_path / 'cohere.yaml') assert_llm_equality(llm, loaded_llm)
Test saving/loading an Cohere LLM.
_identifying_params
"""Get the identifying parameters.""" return {**{'endpoint_url': self.endpoint_url}, **{'model_kwargs': self. model_kwargs}}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {**{'endpoint_url': self.endpoint_url}, **{'model_kwargs': self. model_kwargs}}
Get the identifying parameters.
on_text
"""Run on arbitrary text."""
def on_text(self, text: str, **kwargs: Any) ->None: """Run on arbitrary text."""
Run on arbitrary text.
execute_task
"""Execute a task.""" context = self._get_top_tasks(query=objective, k=k) return self.execution_chain.run(objective=objective, context='\n'.join( context), task=task, **kwargs)
def execute_task(self, objective: str, task: str, k: int=5, **kwargs: Any ) ->str: """Execute a task.""" context = self._get_top_tasks(query=objective, k=k) return self.execution_chain.run(objective=objective, context='\n'.join( context), task=task, **kwargs)
Execute a task.
from_es_connection
""" Instantiate embeddings from an existing Elasticsearch connection. This method provides a way to create an instance of the ElasticsearchEmbeddings class using an existing Elasticsearch connection. The connection object is used to create an MlClient, which is then used to initialize t...
@classmethod def from_es_connection(cls, model_id: str, es_connection: Elasticsearch, input_field: str='text_field') ->ElasticsearchEmbeddings: """ Instantiate embeddings from an existing Elasticsearch connection. This method provides a way to create an instance of the ElasticsearchEmbeddings ...
Instantiate embeddings from an existing Elasticsearch connection. This method provides a way to create an instance of the ElasticsearchEmbeddings class using an existing Elasticsearch connection. The connection object is used to create an MlClient, which is then used to initialize the ElasticsearchEmbeddings instance....
test_sequential_overlapping_inputs
"""Test error is raised when input variables are overlapping.""" chain_1 = FakeChain(input_variables=['foo'], output_variables=['bar', 'test']) chain_2 = FakeChain(input_variables=['bar'], output_variables=['baz']) with pytest.raises(ValueError): SequentialChain(chains=[chain_1, chain_2], input_variables=['foo', 't...
def test_sequential_overlapping_inputs() ->None: """Test error is raised when input variables are overlapping.""" chain_1 = FakeChain(input_variables=['foo'], output_variables=['bar', 'test']) chain_2 = FakeChain(input_variables=['bar'], output_variables=['baz']) with pytest.raises(ValueError): ...
Test error is raised when input variables are overlapping.
_run
return 'foo'
def _run(self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] =None, **kwargs: Any) ->str: return 'foo'
null
test_tiledb_vector_sim
"""Test vector similarity.""" texts = ['foo', 'bar', 'baz'] docsearch = TileDB.from_texts(texts=texts, embedding= ConsistentFakeEmbeddings(), index_uri=f'{str(tmp_path)}/flat', index_type='FLAT') query_vec = FakeEmbeddings().embed_query(text='foo') output = docsearch.similarity_search_by_vector(query_vec, k=1) ...
@pytest.mark.requires('tiledb-vector-search') def test_tiledb_vector_sim(tmp_path: Path) ->None: """Test vector similarity.""" texts = ['foo', 'bar', 'baz'] docsearch = TileDB.from_texts(texts=texts, embedding= ConsistentFakeEmbeddings(), index_uri=f'{str(tmp_path)}/flat', index_type='FLAT')...
Test vector similarity.
_get_dataforseo_api_search
return DataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))
def _get_dataforseo_api_search(**kwargs: Any) ->BaseTool: return DataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))
null
convert_prompt
return self._wrap_prompt(prompt.to_string())
def convert_prompt(self, prompt: PromptValue) ->str: return self._wrap_prompt(prompt.to_string())
null
load_memory_variables
if self.return_messages: return {self.memory_key: self.chat_memory.messages} else: return {self.memory_key: get_buffer_string(self.chat_memory.messages)}
def load_memory_variables(self, values: Dict[str, Any]) ->Dict[str, Any]: if self.return_messages: return {self.memory_key: self.chat_memory.messages} else: return {self.memory_key: get_buffer_string(self.chat_memory.messages)}
null
list_files_in_main_branch
""" Fetches all files in the main branch of the repo. Returns: str: A plaintext report containing the paths and names of the files. """ files: List[str] = [] try: contents = self.github_repo_instance.get_contents('', ref=self. github_base_branch) for content in conte...
def list_files_in_main_branch(self) ->str: """ Fetches all files in the main branch of the repo. Returns: str: A plaintext report containing the paths and names of the files. """ files: List[str] = [] try: contents = self.github_repo_instance.get_contents('', ref...
Fetches all files in the main branch of the repo. Returns: str: A plaintext report containing the paths and names of the files.
add_the_end
return text + 'THE END!'
def add_the_end(text: str) ->str: return text + 'THE END!'
null
test_few_shot_chat_message_prompt_template_with_selector
"""Tests for few shot chat message template with an example selector.""" examples = [{'input': '2+2', 'output': '4'}, {'input': '2+3', 'output': '5'}] example_selector = AsIsSelector(examples) example_prompt = ChatPromptTemplate.from_messages([ HumanMessagePromptTemplate.from_template('{input}'), AIMessagePromp...
def test_few_shot_chat_message_prompt_template_with_selector() ->None: """Tests for few shot chat message template with an example selector.""" examples = [{'input': '2+2', 'output': '4'}, {'input': '2+3', 'output': '5'}] example_selector = AsIsSelector(examples) example_prompt = ChatPromptTempl...
Tests for few shot chat message template with an example selector.
input_keys
"""Expect input keys. :meta private: """ return self.input_variables
@property def input_keys(self) ->List[str]: """Expect input keys. :meta private: """ return self.input_variables
Expect input keys. :meta private:
test_singlestoredb_from_existing
"""Test adding a new document""" table_name = 'test_singlestoredb_from_existing' drop(table_name) SingleStoreDB.from_texts(texts, NormilizedFakeEmbeddings(), table_name= table_name, host=TEST_SINGLESTOREDB_URL) docsearch2 = SingleStoreDB(NormilizedFakeEmbeddings(), table_name= 'test_singlestoredb_from_existing'...
@pytest.mark.skipif(not singlestoredb_installed, reason= 'singlestoredb not installed') def test_singlestoredb_from_existing(texts: List[str]) ->None: """Test adding a new document""" table_name = 'test_singlestoredb_from_existing' drop(table_name) SingleStoreDB.from_texts(texts, NormilizedFakeEmbed...
Test adding a new document
_embedding_func
""" Generate embeddings for the given texts using the Elasticsearch model. Args: texts (List[str]): A list of text strings to generate embeddings for. Returns: List[List[float]]: A list of embeddings, one for each text in the input list. """ resp...
def _embedding_func(self, texts: List[str]) ->List[List[float]]: """ Generate embeddings for the given texts using the Elasticsearch model. Args: texts (List[str]): A list of text strings to generate embeddings for. Returns: List[List[float]]: A list of embeddings, ...
Generate embeddings for the given texts using the Elasticsearch model. Args: texts (List[str]): A list of text strings to generate embeddings for. Returns: List[List[float]]: A list of embeddings, one for each text in the input list.
simplify_code
import esprima tree = esprima.parseScript(self.code, loc=True) simplified_lines = self.source_lines[:] for node in tree.body: if isinstance(node, (esprima.nodes.FunctionDeclaration, esprima.nodes. ClassDeclaration)): start = node.loc.start.line - 1 simplified_lines[start] = f'// Code for: {s...
def simplify_code(self) ->str: import esprima tree = esprima.parseScript(self.code, loc=True) simplified_lines = self.source_lines[:] for node in tree.body: if isinstance(node, (esprima.nodes.FunctionDeclaration, esprima. nodes.ClassDeclaration)): start = node.loc.start.l...
null
_llm_type
"""Return type of llm.""" return 'fake_list'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'fake_list'
Return type of llm.
test__filter_similar_embeddings
threshold = 0.79 embedded_docs = [[1.0, 2.0], [1.0, 2.0], [2.0, 1.0], [2.0, 0.5], [0.0, 0.0]] expected = [1, 3, 4] actual = _filter_similar_embeddings(embedded_docs, cosine_similarity, threshold ) assert expected == actual
def test__filter_similar_embeddings() ->None: threshold = 0.79 embedded_docs = [[1.0, 2.0], [1.0, 2.0], [2.0, 1.0], [2.0, 0.5], [0.0, 0.0] ] expected = [1, 3, 4] actual = _filter_similar_embeddings(embedded_docs, cosine_similarity, threshold) assert expected == actual
null
yield_blobs
"""A lazy loader for raw data represented by LangChain's Blob object. Returns: A generator over blobs """
@abstractmethod def yield_blobs(self) ->Iterable[Blob]: """A lazy loader for raw data represented by LangChain's Blob object. Returns: A generator over blobs """
A lazy loader for raw data represented by LangChain's Blob object. Returns: A generator over blobs