method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_import_vearch
from langchain_community.vectorstores.vearch import Vearch return Vearch
def _import_vearch() ->Any: from langchain_community.vectorstores.vearch import Vearch return Vearch
null
test_writer_call
"""Test valid call to Writer.""" llm = Writer() output = llm('Say foo:') assert isinstance(output, str)
def test_writer_call() ->None: """Test valid call to Writer.""" llm = Writer() output = llm('Say foo:') assert isinstance(output, str)
Test valid call to Writer.
validate_environment
"""Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env(values, 'cohere_api_key', 'COHERE_API_KEY') max_retries = values.get('max_retries') request_timeout = values.get('request_timeout') try: import cohere client_name = values['user_agent'] values['cl...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env(values, 'cohere_api_key', 'COHERE_API_KEY') max_retries = values.get('max_retries') request_timeout = values.get('requ...
Validate that api key and python package exists in environment.
load
brave_client = BraveSearchWrapper(api_key=self.api_key, search_kwargs=self. search_kwargs) return brave_client.download_documents(self.query)
def load(self) ->List[Document]: brave_client = BraveSearchWrapper(api_key=self.api_key, search_kwargs= self.search_kwargs) return brave_client.download_documents(self.query)
null
new_persist_run_single
time.sleep(0.01) old_persist_run_single(run)
def new_persist_run_single(run: Run) ->None: time.sleep(0.01) old_persist_run_single(run)
null
_import_merriam_webster
from langchain_community.utilities.merriam_webster import MerriamWebsterAPIWrapper return MerriamWebsterAPIWrapper
def _import_merriam_webster() ->Any: from langchain_community.utilities.merriam_webster import MerriamWebsterAPIWrapper return MerriamWebsterAPIWrapper
null
_import_scenexplain_tool
from langchain_community.tools.scenexplain.tool import SceneXplainTool return SceneXplainTool
def _import_scenexplain_tool() ->Any: from langchain_community.tools.scenexplain.tool import SceneXplainTool return SceneXplainTool
null
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
_import_opensearch_vector_search
from langchain_community.vectorstores.opensearch_vector_search import OpenSearchVectorSearch return OpenSearchVectorSearch
def _import_opensearch_vector_search() ->Any: from langchain_community.vectorstores.opensearch_vector_search import OpenSearchVectorSearch return OpenSearchVectorSearch
null
_identifying_params
kwargs = self.llm_kwargs or {} return {**self.client.client_pool.get_current_client().get_model_params(), **kwargs}
@property def _identifying_params(self) ->Mapping[str, Any]: kwargs = self.llm_kwargs or {} return {**self.client.client_pool.get_current_client().get_model_params (), **kwargs}
null
plan
"""Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ agent_scratchpad = format_to_openai_function_messages(intermediate_...
def plan(self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks=None, with_functions: bool=True, **kwargs: Any) ->Union[ AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observatio...
Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use.
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() url = inputs[self.input_url_key] browser_content = inputs[self.input_browser_content_key] llm_cmd = self.llm_chain.predict(objective=self.objective, url=url[:100], previous_command=self.previous_command, browser_content=browser_content ...
def _call(self, inputs: Dict[str, str], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() url = inputs[self.input_url_key] browser_content = inputs[self.input_browser_content_key] llm_cmd = self.llm_...
null
test_from_texts
input_texts = ['I have a pen.', 'Do you have a pen?', 'I have a bag.'] tfidf_retriever = TFIDFRetriever.from_texts(texts=input_texts) assert len(tfidf_retriever.docs) == 3 assert tfidf_retriever.tfidf_array.toarray().shape == (3, 5)
@pytest.mark.requires('sklearn') def test_from_texts() ->None: input_texts = ['I have a pen.', 'Do you have a pen?', 'I have a bag.'] tfidf_retriever = TFIDFRetriever.from_texts(texts=input_texts) assert len(tfidf_retriever.docs) == 3 assert tfidf_retriever.tfidf_array.toarray().shape == (3, 5)
null
load
"""Load weather data for the given locations.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load weather data for the given locations.""" return list(self.lazy_load())
Load weather data for the given locations.
similarity_search
"""Return Elasticsearch documents most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k (int): Number of Documents to fetch to pass to knn num_candidates. filter: Array of Elasticsearch ...
def similarity_search(self, query: str, k: int=4, fetch_k: int=50, filter: Optional[List[dict]]=None, **kwargs: Any) ->List[Document]: """Return Elasticsearch documents most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. De...
Return Elasticsearch documents most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k (int): Number of Documents to fetch to pass to knn num_candidates. filter: Array of Elasticsearch filter clauses to apply to the query. Retu...
set_api_url
if 'api_url' not in values: host = values['host'] endpoint_name = values['endpoint_name'] api_url = f'https://{host}/serving-endpoints/{endpoint_name}/invocations' values['api_url'] = api_url return values
@root_validator(pre=True) def set_api_url(cls, values: Dict[str, Any]) ->Dict[str, Any]: if 'api_url' not in values: host = values['host'] endpoint_name = values['endpoint_name'] api_url = ( f'https://{host}/serving-endpoints/{endpoint_name}/invocations') values['api_url'...
null
test_initialization
loader = AssemblyAIAudioTranscriptLoader(file_path='./testfile.mp3', api_key='api_key') assert loader.file_path == './testfile.mp3' assert loader.transcript_format == TranscriptFormat.TEXT
@pytest.mark.requires('assemblyai') def test_initialization() ->None: loader = AssemblyAIAudioTranscriptLoader(file_path='./testfile.mp3', api_key='api_key') assert loader.file_path == './testfile.mp3' assert loader.transcript_format == TranscriptFormat.TEXT
null
invoke
if isinstance(input, BaseMessage): return self._call_with_config(lambda inner_input: self.parse_result([ ChatGeneration(message=inner_input)]), input, config, run_type='parser' ) else: return self._call_with_config(lambda inner_input: self.parse_result([ Generation(text=inner_input)]), i...
def invoke(self, input: Union[str, BaseMessage], config: Optional[ RunnableConfig]=None) ->T: if isinstance(input, BaseMessage): return self._call_with_config(lambda inner_input: self.parse_result ([ChatGeneration(message=inner_input)]), input, config, run_type='parser') else...
null
_get_len_safe_embeddings
""" Generate length-safe embeddings for a list of texts. This method handles tokenization and embedding generation, respecting the set embedding context length and chunk size. It supports both tiktoken and HuggingFace tokenizer based on the tiktoken_enabled flag. Args: ...
def _get_len_safe_embeddings(self, texts: List[str], *, engine: str, chunk_size: Optional[int]=None) ->List[List[float]]: """ Generate length-safe embeddings for a list of texts. This method handles tokenization and embedding generation, respecting the set embedding context length and c...
Generate length-safe embeddings for a list of texts. This method handles tokenization and embedding generation, respecting the set embedding context length and chunk size. It supports both tiktoken and HuggingFace tokenizer based on the tiktoken_enabled flag. Args: texts (List[str]): A list of texts to embed. ...
select_examples
"""Select which examples to use based on the input lengths.""" inputs = ' '.join(input_variables.values()) remaining_length = self.max_length - self.get_text_length(inputs) i = 0 examples = [] while remaining_length > 0 and i < len(self.examples): new_length = remaining_length - self.example_text_lengths[i] if ...
def select_examples(self, input_variables: Dict[str, str]) ->List[dict]: """Select which examples to use based on the input lengths.""" inputs = ' '.join(input_variables.values()) remaining_length = self.max_length - self.get_text_length(inputs) i = 0 examples = [] while remaining_length > 0 and...
Select which examples to use based on the input lengths.
load
""" Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator - created_at - last_upda...
def load(self) ->List[Document]: """ Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator - creat...
Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator - created_at - last_update_time - closed_time - number of comments - sta...
multi_modal_rag_chain
""" Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process. """ model = ChatGoogleGenerativeAI(model='gemini-pro-vision') chain = {'context': retriever | RunnableLambda(get_resized_im...
def multi_modal_rag_chain(retriever): """ Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process. """ model = ChatGoogleGenerativeAI(model='gemini-pro-vision') chain = {'c...
Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process.
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
test_load_issue_9046
"""Test for the fixed issue 9046""" expected_docs = 3 loader = ArxivLoader(query= 'MetaGPT: Meta Programming for Multi-Agent Collaborative Framework', load_max_docs=expected_docs) docs = loader.load() assert_docs(docs) assert 'MetaGPT' in docs[0].metadata['Title'] loader = ArxivLoader(query= 'MetaGPT - Meta...
@pytest.mark.skip(reason='test could be flaky') def test_load_issue_9046() ->None: """Test for the fixed issue 9046""" expected_docs = 3 loader = ArxivLoader(query= 'MetaGPT: Meta Programming for Multi-Agent Collaborative Framework', load_max_docs=expected_docs) docs = loader.load() ...
Test for the fixed issue 9046
similarity_search
"""Run similarity search with Chroma. Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Document]: List of documents mo...
def similarity_search(self, query: str, k: int=DEFAULT_K, filter: Optional[ Dict[str, str]]=None, **kwargs: Any) ->List[Document]: """Run similarity search with Chroma. Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. ...
Run similarity search with Chroma. Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Document]: List of documents most similar to the query text.
evaluation_name
""" Get the evaluation name. Returns: str: The evaluation name. """ return 'exact_match'
@property def evaluation_name(self) ->str: """ Get the evaluation name. Returns: str: The evaluation name. """ return 'exact_match'
Get the evaluation name. Returns: str: The evaluation name.
test_default_call
"""Test default model(`ERNIE-Bot`) call.""" chat = QianfanChatEndpoint() response = chat(messages=[HumanMessage(content='Hello')]) assert isinstance(response, BaseMessage) assert isinstance(response.content, str)
def test_default_call() ->None: """Test default model(`ERNIE-Bot`) call.""" chat = QianfanChatEndpoint() response = chat(messages=[HumanMessage(content='Hello')]) assert isinstance(response, BaseMessage) assert isinstance(response.content, str)
Test default model(`ERNIE-Bot`) call.
_import_pubmed_tool
from langchain_community.tools.pubmed.tool import PubmedQueryRun return PubmedQueryRun
def _import_pubmed_tool() ->Any: from langchain_community.tools.pubmed.tool import PubmedQueryRun return PubmedQueryRun
null
__key
"""Compute cache key from prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. Returns: str: The cache key. """ return _hash(prompt + llm_string)
def __key(self, prompt: str, llm_string: str) ->str: """Compute cache key from prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. Returns: str: The c...
Compute cache key from prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. Returns: str: The cache key.
on_chain_end
"""Run when chain ends running.""" self.step += 1 self.chain_ends += 1 self.ends += 1 resp: Dict[str, Any] = {} chain_output = ','.join([f'{k}={v}' for k, v in outputs.items()]) resp.update({'action': 'on_chain_end', 'outputs': chain_output}) resp.update(self.get_custom_callback_meta()) self.deck.append(self.markdown_r...
def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) ->None: """Run when chain ends running.""" self.step += 1 self.chain_ends += 1 self.ends += 1 resp: Dict[str, Any] = {} chain_output = ','.join([f'{k}={v}' for k, v in outputs.items()]) resp.update({'action': 'on_chain_end', 'out...
Run when chain ends running.
ddg_installed
try: from duckduckgo_search import DDGS return True except Exception as e: print(f'duckduckgo not installed, skipping test {e}') return False
def ddg_installed() ->bool: try: from duckduckgo_search import DDGS return True except Exception as e: print(f'duckduckgo not installed, skipping test {e}') return False
null
_run_llm_or_chain
""" Run the Chain or language model synchronously. Args: example: The example to run. llm_or_chain_factory: The Chain or language model constructor to run. tags: Optional tags to add to the run. callbacks: Optional callbacks to use during the run. Returns: Union[Lis...
def _run_llm_or_chain(example: Example, config: RunnableConfig, *, llm_or_chain_factory: MCF, input_mapper: Optional[Callable[[Dict], Any] ]=None) ->Union[dict, str, LLMResult, ChatResult]: """ Run the Chain or language model synchronously. Args: example: The example to run. llm_or_...
Run the Chain or language model synchronously. Args: example: The example to run. llm_or_chain_factory: The Chain or language model constructor to run. tags: Optional tags to add to the run. callbacks: Optional callbacks to use during the run. Returns: Union[List[dict], List[str], List[LLMResult],...
_generate_command_string
output = f'{tool.name}: {tool.description}' output += f', args json schema: {json.dumps(tool.args)}' return output
def _generate_command_string(self, tool: BaseTool) ->str: output = f'{tool.name}: {tool.description}' output += f', args json schema: {json.dumps(tool.args)}' return output
null
get
query = f""" SELECT value FROM {self.full_table_name} WHERE key = ? """ cursor = self.conn.execute(query, (key,)) result = cursor.fetchone() if result is not None: value = result[0] return value return default
def get(self, key: str, default: Optional[str]=None) ->Optional[str]: query = f""" SELECT value FROM {self.full_table_name} WHERE key = ? """ cursor = self.conn.execute(query, (key,)) result = cursor.fetchone() if result is not None: value = result[0] ...
null
test_add_ai_message
zep_chat.add_ai_message('test message') zep_chat.zep_client.memory.add_memory.assert_called_once()
@pytest.mark.requires('zep_python') def test_add_ai_message(mocker: MockerFixture, zep_chat: ZepChatMessageHistory ) ->None: zep_chat.add_ai_message('test message') zep_chat.zep_client.memory.add_memory.assert_called_once()
null
_generate_outputs
"""Generate the expected output structure.""" return [grpcclient.InferRequestedOutput('text_output')]
def _generate_outputs(self) ->List[grpcclient.InferRequestedOutput]: """Generate the expected output structure.""" return [grpcclient.InferRequestedOutput('text_output')]
Generate the expected output structure.
_import_bananadev
from langchain_community.llms.bananadev import Banana return Banana
def _import_bananadev() ->Any: from langchain_community.llms.bananadev import Banana return Banana
null
lazy_load
"""Lazy load records from dataframe.""" for row in self.data_frame.iter_rows(named=True): text = row[self.page_content_column] row.pop(self.page_content_column) yield Document(page_content=text, metadata=row)
def lazy_load(self) ->Iterator[Document]: """Lazy load records from dataframe.""" for row in self.data_frame.iter_rows(named=True): text = row[self.page_content_column] row.pop(self.page_content_column) yield Document(page_content=text, metadata=row)
Lazy load records from dataframe.
test_openweathermap_api_wrapper
"""Test that OpenWeatherMapAPIWrapper returns correct data for London, GB.""" weather = OpenWeatherMapAPIWrapper() weather_data = weather.run('London,GB') assert weather_data is not None assert 'London' in weather_data assert 'GB' in weather_data assert 'Detailed status:' in weather_data assert 'Wind speed:' in weather...
def test_openweathermap_api_wrapper() ->None: """Test that OpenWeatherMapAPIWrapper returns correct data for London, GB.""" weather = OpenWeatherMapAPIWrapper() weather_data = weather.run('London,GB') assert weather_data is not None assert 'London' in weather_data assert 'GB' in weather_data ...
Test that OpenWeatherMapAPIWrapper returns correct data for London, GB.
_import_human_tool
from langchain_community.tools.human.tool import HumanInputRun return HumanInputRun
def _import_human_tool() ->Any: from langchain_community.tools.human.tool import HumanInputRun return HumanInputRun
null
clear
self.messages = []
def clear(self) ->None: self.messages = []
null
on_retriever_error
self.on_retriever_error_common()
def on_retriever_error(self, *args: Any, **kwargs: Any) ->Any: self.on_retriever_error_common()
null
test_memory_with_message_store
"""Test the memory with a message store.""" message_history = ElasticsearchChatMessageHistory(** elasticsearch_connection, index=index_name, session_id='test-session') memory = ConversationBufferMemory(memory_key='baz', chat_memory= message_history, return_messages=True) memory.chat_memory.add_ai_message('This ...
def test_memory_with_message_store(self, elasticsearch_connection: dict, index_name: str) ->None: """Test the memory with a message store.""" message_history = ElasticsearchChatMessageHistory(** elasticsearch_connection, index=index_name, session_id='test-session') memory = ConversationBufferMem...
Test the memory with a message store.
fn
if url.endswith('/processing/upload'): return FakeUploadResponse() elif url.endswith('/processing/push'): return FakePushResponse() else: raise Exception('Invalid POST URL')
def fn(url: str, **kwargs: Any) ->Any: if url.endswith('/processing/upload'): return FakeUploadResponse() elif url.endswith('/processing/push'): return FakePushResponse() else: raise Exception('Invalid POST URL')
null
get_tools
"""Get the tools in the toolkit."""
@abstractmethod def get_tools(self) ->List[BaseTool]: """Get the tools in the toolkit."""
Get the tools in the toolkit.
validate_input_variables
dummy_inputs = {input_variable: 'foo' for input_variable in input_variables} super().format(format_string, **dummy_inputs)
def validate_input_variables(self, format_string: str, input_variables: List[str]) ->None: dummy_inputs = {input_variable: 'foo' for input_variable in input_variables } super().format(format_string, **dummy_inputs)
null
load
"""Load toots into documents.""" results: List[Document] = [] for account in self.mastodon_accounts: user = self.api.account_lookup(account) toots = self.api.account_statuses(user.id, only_media=False, pinned= False, exclude_replies=self.exclude_replies, exclude_reblogs=True, limit=self.number_t...
def load(self) ->List[Document]: """Load toots into documents.""" results: List[Document] = [] for account in self.mastodon_accounts: user = self.api.account_lookup(account) toots = self.api.account_statuses(user.id, only_media=False, pinned =False, exclude_replies=self.exclude_r...
Load toots into documents.
__str__
"""Get a string representation of the object for printing.""" cls_name = f'\x1b[1m{self.__class__.__name__}\x1b[0m' return f"""{cls_name} Params: {self._identifying_params}"""
def __str__(self) ->str: """Get a string representation of the object for printing.""" cls_name = f'\x1b[1m{self.__class__.__name__}\x1b[0m' return f'{cls_name}\nParams: {self._identifying_params}'
Get a string representation of the object for printing.
test_tiledb_mmr
texts = ['foo', 'foo', 'fou', 'foy'] docsearch = TileDB.from_texts(texts=texts, embedding= ConsistentFakeEmbeddings(), index_uri=f'{str(tmp_path)}/flat', index_type='FLAT') query_vec = ConsistentFakeEmbeddings().embed_query(text='foo') output = docsearch.max_marginal_relevance_search_with_score_by_vector(query_...
@pytest.mark.requires('tiledb-vector-search') def test_tiledb_mmr(tmp_path: Path) ->None: texts = ['foo', 'foo', 'fou', 'foy'] docsearch = TileDB.from_texts(texts=texts, embedding= ConsistentFakeEmbeddings(), index_uri=f'{str(tmp_path)}/flat', index_type='FLAT') query_vec = ConsistentFakeEmb...
null
_get_invocation_params
"""Get the parameters used to invoke the model FOR THE CALLBACKS.""" return {**self._default_params, **super()._get_invocation_params(stop=stop, **kwargs)}
def _get_invocation_params(self, stop: Optional[List[str]]=None, **kwargs: Any ) ->Dict[str, Any]: """Get the parameters used to invoke the model FOR THE CALLBACKS.""" return {**self._default_params, **super()._get_invocation_params(stop= stop, **kwargs)}
Get the parameters used to invoke the model FOR THE CALLBACKS.
input_keys
"""Return the singular input key. :meta private: """ return [self.input_key]
@property def input_keys(self) ->List[str]: """Return the singular input key. :meta private: """ return [self.input_key]
Return the singular input key. :meta private:
build_extra
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = get_pydantic_field_names(cls) extra = values.get('model_kwargs', {}) values['model_kwargs'] = build_extra_kwargs(extra, values, all_required_field_names) return values
@root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) ->Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = get_pydantic_field_names(cls) extra = values.get('model_kwargs', {}) values['model_kwargs'] = build_extra_kwargs(extra,...
Build extra kwargs from additional params that were passed in.
from_llm
"""Construct the chain from an LLM.""" llm_question_chain = LLMChain(llm=llm, prompt=question_prompt) llm_combine_chain = LLMChain(llm=llm, prompt=combine_prompt) combine_results_chain = StuffDocumentsChain(llm_chain=llm_combine_chain, document_prompt=document_prompt, document_variable_name='summaries') reduce_docu...
@classmethod def from_llm(cls, llm: BaseLanguageModel, document_prompt: BasePromptTemplate=EXAMPLE_PROMPT, question_prompt: BasePromptTemplate= QUESTION_PROMPT, combine_prompt: BasePromptTemplate=COMBINE_PROMPT, ** kwargs: Any) ->BaseQAWithSourcesChain: """Construct the chain from an LLM.""" llm_que...
Construct the chain from an LLM.
accept
"""Accept a visitor. Args: visitor: visitor to accept Returns: result of visiting """ return getattr(visitor, f'visit_{_to_snake_case(self.__class__.__name__)}')( self)
def accept(self, visitor: Visitor) ->Any: """Accept a visitor. Args: visitor: visitor to accept Returns: result of visiting """ return getattr(visitor, f'visit_{_to_snake_case(self.__class__.__name__)}' )(self)
Accept a visitor. Args: visitor: visitor to accept Returns: result of visiting
mock_collection
from zep_python.document import DocumentCollection mock_collection: DocumentCollection = mocker.patch( 'zep_python.document.collections.DocumentCollection', autospec=True) mock_collection.search.return_value = copy.deepcopy(search_results) mock_collection.asearch.return_value = copy.deepcopy(search_results) temp_va...
@pytest.fixture @pytest.mark.requires('zep_python') def mock_collection(mocker: MockerFixture, mock_collection_config: CollectionConfig, search_results: List[Document], search_results_with_query_embedding: Tuple[List[Document], List[float]] ) ->'DocumentCollection': from zep_python.document import Docum...
null
test_parse_with_language_and_spaces
llm_output = """I can use the `foo` tool to achieve the goal. Action: ```json { "action": "foo", "action_input": "bar" } ``` """ action, action_input = get_action_and_input(llm_output) assert action == 'foo' assert action_input == 'bar'
def test_parse_with_language_and_spaces() ->None: llm_output = """I can use the `foo` tool to achieve the goal. Action: ```json { "action": "foo", "action_input": "bar" } ``` """ action, action_input = get_action_and_input(llm_output) assert action == 'foo' ass...
null
test_run_query
"""Test that run gives the correct answer.""" search = api_client.run(query='university', sort='relevance', time_filter= 'all', subreddit='funny', limit=5) assert 'University' in search
@pytest.mark.requires('praw') def test_run_query(api_client: RedditSearchAPIWrapper) ->None: """Test that run gives the correct answer.""" search = api_client.run(query='university', sort='relevance', time_filter='all', subreddit='funny', limit=5) assert 'University' in search
Test that run gives the correct answer.
verify_version
""" Check if the connected Neo4j database version supports vector indexing. Queries the Neo4j database to retrieve its version and compares it against a target version (5.11.0) that is known to support vector indexing. Raises a ValueError if the connected Neo4j version is not su...
def verify_version(self) ->None: """ Check if the connected Neo4j database version supports vector indexing. Queries the Neo4j database to retrieve its version and compares it against a target version (5.11.0) that is known to support vector indexing. Raises a ValueError if the conn...
Check if the connected Neo4j database version supports vector indexing. Queries the Neo4j database to retrieve its version and compares it against a target version (5.11.0) that is known to support vector indexing. Raises a ValueError if the connected Neo4j version is not supported.
test_using_custom_config_specs
"""Test that we can configure which keys should be passed to the session factory.""" def _fake_llm(input: Dict[str, Any]) ->List[BaseMessage]: messages = input['messages'] return [AIMessage(content='you said: ' + '\n'.join(str(m.content) for m in messages if isinstance(m, HumanMessage)))] runnable = Run...
def test_using_custom_config_specs() ->None: """Test that we can configure which keys should be passed to the session factory.""" def _fake_llm(input: Dict[str, Any]) ->List[BaseMessage]: messages = input['messages'] return [AIMessage(content='you said: ' + '\n'.join(str(m.content) for ...
Test that we can configure which keys should be passed to the session factory.
embeddings
return self._embedding_function
@property def embeddings(self) ->Optional[Embeddings]: return self._embedding_function
null
build_extra
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} input = values.pop('input', {}) if input: logger.warning( 'Init param `input` is deprecated, please use `model_kwargs` instead.') extra = {**values.pop('model_kw...
@root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) ->Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__. values()} input = values.pop('input', {}) if input: logger.wa...
Build extra kwargs from additional params that were passed in.
_process_response
text = response['output']['text'] if stop: text = enforce_stop_tokens(text, stop) return text
@staticmethod def _process_response(response: Any, stop: Optional[List[str]]) ->str: text = response['output']['text'] if stop: text = enforce_stop_tokens(text, stop) return text
null
test_indexing_same_content
"""Indexing some content to confirm it gets added only once.""" loader = ToyLoader(documents=[Document(page_content= 'This is a test document.'), Document(page_content= 'This is another document.')]) assert index(loader, record_manager, vector_store) == {'num_added': 2, 'num_deleted': 0, 'num_skipped': 0, '...
def test_indexing_same_content(record_manager: SQLRecordManager, vector_store: InMemoryVectorStore) ->None: """Indexing some content to confirm it gets added only once.""" loader = ToyLoader(documents=[Document(page_content= 'This is a test document.'), Document(page_content= 'This is anothe...
Indexing some content to confirm it gets added only once.
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. k: Number of Documents to return. Defaults to 4...
def max_marginal_relevance_search_by_vector(self, embedding: List[float], k: int=4, fetch_k: int=20, lambda_mult: float=0.5, filter: Optional[dict]= None, namespace: Optional[str]=None, **kwargs: Any) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal r...
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. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch...
test_default_ollama_functions
base_model = OllamaFunctions(model='mistral') self.assertIsInstance(base_model.model, ChatOllama) model = base_model.bind(functions=[{'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'd...
def test_default_ollama_functions(self) ->None: base_model = OllamaFunctions(model='mistral') self.assertIsInstance(base_model.model, ChatOllama) model = base_model.bind(functions=[{'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'t...
null
_texts_to_documents
"""Return list of Documents from list of texts and metadatas.""" if metadatas is None: metadatas = repeat({}) docs = [Document(page_content=text, metadata=metadata) for text, metadata in zip(texts, metadatas)] return docs
@staticmethod def _texts_to_documents(texts: Iterable[str], metadatas: Optional[Iterable[ Dict[Any, Any]]]=None) ->List[Document]: """Return list of Documents from list of texts and metadatas.""" if metadatas is None: metadatas = repeat({}) docs = [Document(page_content=text, metadata=metadata) ...
Return list of Documents from list of texts and metadatas.
completion_with_retry
"""Use tenacity to retry the completion call.""" retry_decorator = create_retry_decorator(llm, max_retries=llm.max_retries, run_manager=run_manager) @retry_decorator def _completion_with_retry(prompt: LanguageModelInput, is_gemini: bool, stream: bool, **kwargs: Any) ->Any: generation_config = kwargs.get('ge...
def completion_with_retry(llm: GooglePalm, prompt: LanguageModelInput, is_gemini: bool=False, stream: bool=False, run_manager: Optional[ CallbackManagerForLLMRun]=None, **kwargs: Any) ->Any: """Use tenacity to retry the completion call.""" retry_decorator = create_retry_decorator(llm, max_retries=llm. ...
Use tenacity to retry the completion call.
__iter__
logger.debug('Initialising AgentExecutorIterator') self.reset() callback_manager = CallbackManager.configure(self.callbacks, self. agent_executor.callbacks, self.agent_executor.verbose, self.tags, self. agent_executor.tags, self.metadata, self.agent_executor.metadata) run_manager = callback_manager.on_chain_sta...
def __iter__(self: 'AgentExecutorIterator') ->Iterator[AddableDict]: logger.debug('Initialising AgentExecutorIterator') self.reset() callback_manager = CallbackManager.configure(self.callbacks, self. agent_executor.callbacks, self.agent_executor.verbose, self.tags, self.agent_executor.tags, ...
null
run_rnn
AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ',:?!' for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens out: Any = None while len(tokens) > 0: out, self.model_state = self.client.forward(tokens[:self....
def run_rnn(self, _tokens: List[str], newline_adj: int=0) ->Any: AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ',:?!' for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens ...
null
test_correct_call
"""Test correct call of fake chain.""" chain = FakeChain() output = chain({'foo': 'bar'}) assert output == {'foo': 'bar', 'bar': 'baz'}
def test_correct_call() ->None: """Test correct call of fake chain.""" chain = FakeChain() output = chain({'foo': 'bar'}) assert output == {'foo': 'bar', 'bar': 'baz'}
Test correct call of fake chain.
input_variables
"""Input variables for this prompt template. Returns: List of input variables. """
@property @abstractmethod def input_variables(self) ->List[str]: """Input variables for this prompt template. Returns: List of input variables. """
Input variables for this prompt template. Returns: List of input variables.
_import_clickhouse_settings
from langchain_community.vectorstores.clickhouse import ClickhouseSettings return ClickhouseSettings
def _import_clickhouse_settings() ->Any: from langchain_community.vectorstores.clickhouse import ClickhouseSettings return ClickhouseSettings
null
test_runnable_context_deadlock
seq: Runnable = {'bar': Context.setter('input') | Context.getter('foo'), 'foo': Context.setter('foo') | Context.getter('input') } | RunnablePassthrough() with pytest.raises(ValueError): seq.invoke('foo')
def test_runnable_context_deadlock() ->None: seq: Runnable = {'bar': Context.setter('input') | Context.getter('foo'), 'foo': Context.setter('foo') | Context.getter('input') } | RunnablePassthrough() with pytest.raises(ValueError): seq.invoke('foo')
null
load
"""Load documents.""" if self.chat_entity is not None: try: import nest_asyncio nest_asyncio.apply() asyncio.run(self.fetch_data_from_telegram()) except ImportError: raise ImportError( """`nest_asyncio` package not found. please install with `pip i...
def load(self) ->List[Document]: """Load documents.""" if self.chat_entity is not None: try: import nest_asyncio nest_asyncio.apply() asyncio.run(self.fetch_data_from_telegram()) except ImportError: raise ImportError( """`nest_async...
Load documents.
_default_params
"""Get the default parameters for calling Javelin AI Gateway API.""" params: Dict[str, Any] = {'gateway_uri': self.gateway_uri, 'route': self. route, 'javelin_api_key': self.javelin_api_key, **self.params.dict() if self.params else {}} return params
@property def _default_params(self) ->Dict[str, Any]: """Get the default parameters for calling Javelin AI Gateway API.""" params: Dict[str, Any] = {'gateway_uri': self.gateway_uri, 'route': self.route, 'javelin_api_key': self.javelin_api_key, **self.params. dict() if self.params else {}} re...
Get the default parameters for calling Javelin AI Gateway API.
_parse_response
"""Take a dict response and condense it's data in a human readable string""" pass
@abstractmethod def _parse_response(self, response: Any) ->str: """Take a dict response and condense it's data in a human readable string""" pass
Take a dict response and condense it's data in a human readable string
on_llm_new_token
"""Run when LLM generates a new token.""" self.step += 1 self.llm_streams += 1 resp = self._init_resp() resp.update({'action': 'on_llm_new_token', 'token': token}) resp.update(self.get_custom_callback_meta()) self.on_llm_token_records.append(resp) self.action_records.append(resp) if self.stream_logs: self.logger.re...
def on_llm_new_token(self, token: str, **kwargs: Any) ->None: """Run when LLM generates a new token.""" self.step += 1 self.llm_streams += 1 resp = self._init_resp() resp.update({'action': 'on_llm_new_token', 'token': token}) resp.update(self.get_custom_callback_meta()) self.on_llm_token_rec...
Run when LLM generates a new token.
last_tool
"""The last tool executed by this thought""" return self._last_tool
@property def last_tool(self) ->Optional[ToolRecord]: """The last tool executed by this thought""" return self._last_tool
The last tool executed by this thought
_is_gemini_model
return 'gemini' in model_name
def _is_gemini_model(model_name: str) ->bool: return 'gemini' in model_name
null
test_configurable_fields_example
fake_chat = FakeListChatModel(responses=['b']).configurable_fields(responses =ConfigurableFieldMultiOption(id='chat_responses', name= 'Chat Responses', options={'hello': 'A good morning to you!', 'bye': 'See you later!', 'helpful': 'How can I help you?'}, default=['hello', 'bye'])) fake_llm = FakeListLL...
def test_configurable_fields_example() ->None: fake_chat = FakeListChatModel(responses=['b']).configurable_fields( responses=ConfigurableFieldMultiOption(id='chat_responses', name= 'Chat Responses', options={'hello': 'A good morning to you!', 'bye': 'See you later!', 'helpful': 'How can I he...
null
fn
return None
def fn(self: Any, **kwargs: Any) ->None: return None
null
transform_documents
"""Translates text documents using doctran.""" try: from doctran import Doctran doctran = Doctran(openai_api_key=self.openai_api_key, openai_model=self .openai_api_model) except ImportError: raise ImportError( 'Install doctran to use this parser. (pip install doctran)') doctran_docs = [doctr...
def transform_documents(self, documents: Sequence[Document], **kwargs: Any ) ->Sequence[Document]: """Translates text documents using doctran.""" try: from doctran import Doctran doctran = Doctran(openai_api_key=self.openai_api_key, openai_model= self.openai_api_model) except...
Translates text documents using doctran.
on_chain_end
"""Print out that we finished a chain.""" print_text(""" > Finished chain.""", end='\n', file=self.file)
def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) ->None: """Print out that we finished a chain.""" print_text('\n\x1b[1m> Finished chain.\x1b[0m', end='\n', file=self.file)
Print out that we finished a chain.
from_schema
"""Recursively populate from an OpenAPI Schema.""" if references_used is None: references_used = [] schema_type = schema.type properties: List[APIRequestBodyProperty] = [] if schema_type == 'object' and schema.properties: schema_type, properties = cls._process_object_schema(schema, spec, references_used...
@classmethod def from_schema(cls, schema: Schema, name: str, required: bool, spec: OpenAPISpec, references_used: Optional[List[str]]=None ) ->'APIRequestBodyProperty': """Recursively populate from an OpenAPI Schema.""" if references_used is None: references_used = [] schema_type = schema.typ...
Recursively populate from an OpenAPI Schema.
test_dereference_refs_missing_ref
schema = {'type': 'object', 'properties': {'first_name': {'$ref': '#/$defs/name'}}, '$defs': {}} with pytest.raises(KeyError): dereference_refs(schema)
def test_dereference_refs_missing_ref() ->None: schema = {'type': 'object', 'properties': {'first_name': {'$ref': '#/$defs/name'}}, '$defs': {}} with pytest.raises(KeyError): dereference_refs(schema)
null
from_texts
"""Return VectorStore initialized from texts and embeddings."""
@classmethod @abstractmethod def from_texts(cls: Type[VST], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, **kwargs: Any) ->VST: """Return VectorStore initialized from texts and embeddings."""
Return VectorStore initialized from texts and embeddings.
test_deanonymizer_mapping
"""Test if deanonymizer mapping is correctly populated""" from langchain_experimental.data_anonymizer import PresidioReversibleAnonymizer anonymizer = PresidioReversibleAnonymizer(analyzed_fields=['PERSON', 'PHONE_NUMBER', 'EMAIL_ADDRESS', 'CREDIT_CARD']) anonymizer.anonymize( 'Hello, my name is John Doe and my...
@pytest.mark.requires('presidio_analyzer', 'presidio_anonymizer', 'faker') def test_deanonymizer_mapping() ->None: """Test if deanonymizer mapping is correctly populated""" from langchain_experimental.data_anonymizer import PresidioReversibleAnonymizer anonymizer = PresidioReversibleAnonymizer(analyzed_fiel...
Test if deanonymizer mapping is correctly populated
_chebyshev_distance
"""Compute the Chebyshev distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: np.floating: The Chebyshev distance. """ return np.max(np.abs(a - b))
@staticmethod def _chebyshev_distance(a: np.ndarray, b: np.ndarray) ->np.floating: """Compute the Chebyshev distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: np.floating: The Chebyshev distance. ...
Compute the Chebyshev distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: np.floating: The Chebyshev distance.
test__collapse_docs_no_metadata
"""Test collapse documents functionality when no metadata.""" docs = [Document(page_content='foo'), Document(page_content='bar'), Document(page_content='baz')] output = collapse_docs(docs, _fake_combine_docs_func) expected_output = Document(page_content='foobarbaz') assert output == expected_output
def test__collapse_docs_no_metadata() ->None: """Test collapse documents functionality when no metadata.""" docs = [Document(page_content='foo'), Document(page_content='bar'), Document(page_content='baz')] output = collapse_docs(docs, _fake_combine_docs_func) expected_output = Document(page_cont...
Test collapse documents functionality when no metadata.
filter_func
return x in include_types if include_types else x not in exclude_types
def filter_func(x: str) ->bool: return x in include_types if include_types else x not in exclude_types
null
lookup
"""Lookup llm generations in cache by prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. Raises: SdkException: Momento service or network error ...
def lookup(self, prompt: str, llm_string: str) ->Optional[RETURN_VAL_TYPE]: """Lookup llm generations in cache by prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. ...
Lookup llm generations in cache by prompt and associated model and settings. Args: prompt (str): The prompt run through the language model. llm_string (str): The language model version and settings. Raises: SdkException: Momento service or network error Returns: Optional[RETURN_VAL_TYPE]: A list of l...
_import_sql_database_tool_ListSQLDatabaseTool
from langchain_community.tools.sql_database.tool import ListSQLDatabaseTool return ListSQLDatabaseTool
def _import_sql_database_tool_ListSQLDatabaseTool() ->Any: from langchain_community.tools.sql_database.tool import ListSQLDatabaseTool return ListSQLDatabaseTool
null
_build_insert_sql
ks = ','.join(column_names) embed_tuple_index = tuple(column_names).index(self.config.column_map[ 'embedding']) _data = [] for n in transac: n = ','.join([(f"'{self.escape_str(str(_n))}'" if idx != embed_tuple_index else f'array<float>{str(_n)}') for idx, _n in enumerate(n)]) _data.append(f'...
def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str] ) ->str: ks = ','.join(column_names) embed_tuple_index = tuple(column_names).index(self.config.column_map[ 'embedding']) _data = [] for n in transac: n = ','.join([(f"'{self.escape_str(str(_n))}'" if idx != ...
null
_call
"""Run the agent.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() objective = inputs['objective'] first_task = inputs.get('first_task', 'Make a todo list') self.add_task({'task_id': 1, 'task_name': first_task}) num_iters = 0 while True: if self.task_list: self.print_task_list(...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: """Run the agent.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() objective = inputs['objective'] first_task = inputs.get('first_task', 'Make a todo list'...
Run the agent.
evaluate
return 'test'
def evaluate(self, page: 'Page', browser: 'Browser', response: 'Response' ) ->str: return 'test'
null
test_messages
from zep_python import Memory, Message, Summary mock_memory: Memory = Memory(summary=Summary(content='summary'), messages=[ Message(content='message', role='ai', metadata={'key': 'value'}), Message(content='message2', role='human', metadata={'key2': 'value2'})]) zep_chat.zep_client.memory.get_memory.return_valu...
@pytest.mark.requires('zep_python') def test_messages(mocker: MockerFixture, zep_chat: ZepChatMessageHistory ) ->None: from zep_python import Memory, Message, Summary mock_memory: Memory = Memory(summary=Summary(content='summary'), messages=[Message(content='message', role='ai', metadata={'key': ...
null
test_pgvector_with_filter_nin_set
"""Test end to end construction and search.""" 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, connection_string=CONNEC...
def test_pgvector_with_filter_nin_set() ->None: """Test end to end construction and search.""" 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=FakeEmbeddingsW...
Test end to end construction and search.
_get_index
"""Return the vector index information if it exists""" from pymilvus import Collection if isinstance(self.col, Collection): for x in self.col.indexes: if x.field_name == self._vector_field: return x.to_dict() return None
def _get_index(self) ->Optional[dict[str, Any]]: """Return the vector index information if it exists""" from pymilvus import Collection if isinstance(self.col, Collection): for x in self.col.indexes: if x.field_name == self._vector_field: return x.to_dict() return Non...
Return the vector index information if it exists
test_chat_invalid_input_variables_missing
messages = [HumanMessagePromptTemplate.from_template('{foo}')] with pytest.raises(ValueError): ChatPromptTemplate(messages=messages, input_variables=[], validate_template=True) assert ChatPromptTemplate(messages=messages, input_variables=[] ).input_variables == ['foo']
def test_chat_invalid_input_variables_missing() ->None: messages = [HumanMessagePromptTemplate.from_template('{foo}')] with pytest.raises(ValueError): ChatPromptTemplate(messages=messages, input_variables=[], validate_template=True) assert ChatPromptTemplate(messages=messages, input_vari...
null
test_quip_loader_load_date_invalid_args
quip_loader = QuipLoader(self.API_URL, access_token=self.ACCESS_TOKEN, request_timeout=60) with pytest.raises(ValueError, match= 'Must specify at least one among `folder_ids`, `thread_ids` or set `include_all`_folders as True' ): quip_loader.load()
def test_quip_loader_load_date_invalid_args(self) ->None: quip_loader = QuipLoader(self.API_URL, access_token=self.ACCESS_TOKEN, request_timeout=60) with pytest.raises(ValueError, match= 'Must specify at least one among `folder_ids`, `thread_ids` or set `include_all`_folders as True' ): ...
null