method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
input_keys
return ['input']
@property def input_keys(self) ->List[str]: return ['input']
null
get_propose_prompt
return PromptTemplate(template_format='jinja2', input_variables=[ 'problem_description', 'thoughts', 'n'], output_parser= JSONListOutputParser(), template=dedent( """ You are an intelligent agent that is generating thoughts in a tree of thoughts setting. ...
def get_propose_prompt() ->PromptTemplate: return PromptTemplate(template_format='jinja2', input_variables=[ 'problem_description', 'thoughts', 'n'], output_parser= JSONListOutputParser(), template=dedent( """ You are an intelligent agent that is generating thoughts in a tree...
null
test_messages_to_prompt_dict_with_valid_messages
pytest.importorskip('google.generativeai') result = _messages_to_prompt_dict([SystemMessage(content='Prompt'), HumanMessage(example=True, content='Human example #1'), AIMessage( example=True, content='AI example #1'), HumanMessage(example=True, content='Human example #2'), AIMessage(example=True, content= ...
def test_messages_to_prompt_dict_with_valid_messages() ->None: pytest.importorskip('google.generativeai') result = _messages_to_prompt_dict([SystemMessage(content='Prompt'), HumanMessage(example=True, content='Human example #1'), AIMessage( example=True, content='AI example #1'), HumanMessage(ex...
null
test_create_ticket
"""Test the Create Ticket Call that Creates a Issue/Ticket on JIRA.""" issue_string = ( '{"summary": "Test Summary", "description": "Test Description", "issuetype": {"name": "Bug"}, "project": {"key": "TP"}}' ) jira = JiraAPIWrapper() output = jira.run('create_issue', issue_string) assert 'id' in output assert ...
def test_create_ticket() ->None: """Test the Create Ticket Call that Creates a Issue/Ticket on JIRA.""" issue_string = ( '{"summary": "Test Summary", "description": "Test Description", "issuetype": {"name": "Bug"}, "project": {"key": "TP"}}' ) jira = JiraAPIWrapper() output = jira.run('c...
Test the Create Ticket Call that Creates a Issue/Ticket on JIRA.
test_partial_init_string
"""Test prompt can be initialized with partial variables.""" prefix = 'This is a test about {content}.' suffix = 'Now you try to talk about {new_content}.' examples = [{'question': 'foo', 'answer': 'bar'}, {'question': 'baz', 'answer': 'foo'}] prompt = FewShotPromptTemplate(suffix=suffix, prefix=prefix, input_v...
def test_partial_init_string() ->None: """Test prompt can be initialized with partial variables.""" prefix = 'This is a test about {content}.' suffix = 'Now you try to talk about {new_content}.' examples = [{'question': 'foo', 'answer': 'bar'}, {'question': 'baz', 'answer': 'foo'}] prompt = ...
Test prompt can be initialized with partial variables.
test_get_relevant_documents_with_filter
"""Test end to end construction and MRR search.""" from weaviate import Client texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] client = Client(weaviate_url) retriever = WeaviateHybridSearchRetriever(client=client, index_name= f'LangChain_{uuid4().hex}', text_key='text', attributes...
@pytest.mark.vcr(ignore_localhost=True) def test_get_relevant_documents_with_filter(self, weaviate_url: str) ->None: """Test end to end construction and MRR search.""" from weaviate import Client texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] client = Client(weavi...
Test end to end construction and MRR search.
_import_azure_cognitive_services_AzureCogsSpeech2TextTool
from langchain_community.tools.azure_cognitive_services import AzureCogsSpeech2TextTool return AzureCogsSpeech2TextTool
def _import_azure_cognitive_services_AzureCogsSpeech2TextTool() ->Any: from langchain_community.tools.azure_cognitive_services import AzureCogsSpeech2TextTool return AzureCogsSpeech2TextTool
null
test_qdrant_from_texts_stores_ids
"""Test end to end Qdrant.from_texts stores provided ids.""" from qdrant_client import QdrantClient collection_name = uuid.uuid4().hex with tempfile.TemporaryDirectory() as tmpdir: ids = ['fa38d572-4c31-4579-aedc-1960d79df6df', 'cdc1aa36-d6ab-4fb2-8a94-56674fd27484'] vec_store = Qdrant.from_texts(['abc'...
@pytest.mark.parametrize('batch_size', [1, 64]) @pytest.mark.parametrize('vector_name', [None, 'my-vector']) def test_qdrant_from_texts_stores_ids(batch_size: int, vector_name: Optional[str]) ->None: """Test end to end Qdrant.from_texts stores provided ids.""" from qdrant_client import QdrantClient coll...
Test end to end Qdrant.from_texts stores provided ids.
_create_retry_decorator
from grpc import RpcError min_seconds = 1 max_seconds = 60 return retry(reraise=True, stop=stop_after_attempt(llm.max_retries), wait= wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry =retry_if_exception_type(RpcError), before_sleep=before_sleep_log( logger, logging.WARNING))
def _create_retry_decorator(llm: YandexGPT) ->Callable[[Any], Any]: from grpc import RpcError min_seconds = 1 max_seconds = 60 return retry(reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max= max_seconds), retry=retry_if_excep...
null
make_request
"""Generate text from the model.""" params = params or {} api_key = None if self.nebula_api_key is not None: api_key = self.nebula_api_key.get_secret_value() headers = {'Content-Type': 'application/json', 'ApiKey': f'{api_key}'} body = {'prompt': prompt} for key, value in params.items(): body[key] = value respo...
def make_request(self: Nebula, prompt: str, url: str= f'{DEFAULT_NEBULA_SERVICE_URL}{DEFAULT_NEBULA_SERVICE_PATH}', params: Optional[Dict]=None) ->Any: """Generate text from the model.""" params = params or {} api_key = None if self.nebula_api_key is not None: api_key = self.nebula_api_k...
Generate text from the model.
_astream
raise NotImplementedError()
def _astream(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[AsyncCallbackManagerForLLMRun]=None, ** kwargs: Any) ->AsyncIterator[ChatGenerationChunk]: raise NotImplementedError()
null
_validate_tools
super()._validate_tools(tools) validate_tools_single_input(class_name=cls.__name__, tools=tools)
@classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) ->None: super()._validate_tools(tools) validate_tools_single_input(class_name=cls.__name__, tools=tools)
null
__init__
""" Create an AstraDB cache using a collection for storage. Args (only keyword-arguments accepted): collection_name (str): name of the Astra DB collection to create/use. token (Optional[str]): API token for Astra DB usage. api_endpoint (Optional[str]): full URL to th...
def __init__(self, *, collection_name: str= ASTRA_DB_CACHE_DEFAULT_COLLECTION_NAME, token: Optional[str]=None, api_endpoint: Optional[str]=None, astra_db_client: Optional[Any]=None, namespace: Optional[str]=None): """ Create an AstraDB cache using a collection for storage. Args (only ke...
Create an AstraDB cache using a collection for storage. Args (only keyword-arguments accepted): collection_name (str): name of the Astra DB collection to create/use. token (Optional[str]): API token for Astra DB usage. api_endpoint (Optional[str]): full URL to the API endpoint, such as "https://<DB...
test_chat_openai
"""Test ChatOpenAI wrapper.""" chat = ChatOpenAI(temperature=0.7, base_url=None, organization=None, openai_proxy=None, timeout=10.0, max_retries=3, http_client=None, n=1, max_tokens=10, default_headers=None, default_query=None) message = HumanMessage(content='Hello') response = chat([message]) assert isinstance...
@pytest.mark.scheduled def test_chat_openai() ->None: """Test ChatOpenAI wrapper.""" chat = ChatOpenAI(temperature=0.7, base_url=None, organization=None, openai_proxy=None, timeout=10.0, max_retries=3, http_client=None, n =1, max_tokens=10, default_headers=None, default_query=None) message =...
Test ChatOpenAI wrapper.
test_ddg_search_news_tool
keywords = 'Tesla' tool = DuckDuckGoSearchResults(source='news') result = tool(keywords) print(result) assert len(result.split()) > 20
@pytest.mark.skipif(not ddg_installed(), reason= 'requires duckduckgo-search package') def test_ddg_search_news_tool() ->None: keywords = 'Tesla' tool = DuckDuckGoSearchResults(source='news') result = tool(keywords) print(result) assert len(result.split()) > 20
null
test_run_success_arxiv_identifier
"""Test a query of an arxiv identifier returns the correct answer""" output = api_client.run('1605.08386v1') assert 'Heat-bath random walks with Markov bases' in output
def test_run_success_arxiv_identifier(api_client: ArxivAPIWrapper) ->None: """Test a query of an arxiv identifier returns the correct answer""" output = api_client.run('1605.08386v1') assert 'Heat-bath random walks with Markov bases' in output
Test a query of an arxiv identifier returns the correct answer
embed_documents
""" Make a list of texts into a list of embedding vectors. """ return [self.embed_query(text) for text in texts]
def embed_documents(self, texts: List[str]) ->List[List[float]]: """ Make a list of texts into a list of embedding vectors. """ return [self.embed_query(text) for text in texts]
Make a list of texts into a list of embedding vectors.
similarity_search_with_score
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. """ embedding = self.embedding.embed_query(query) script_query = _de...
def similarity_search_with_score(self, query: str, k: int=4, filter: Optional[dict]=None, **kwargs: Any) ->List[Tuple[Document, float]]: """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. Returns: List of Documents most similar to the query.
warn_once
"""Warn once about the dangers of PythonREPL.""" logger.warning('Python REPL can execute arbitrary code. Use with caution.')
@functools.lru_cache(maxsize=None) def warn_once() ->None: """Warn once about the dangers of PythonREPL.""" logger.warning('Python REPL can execute arbitrary code. Use with caution.')
Warn once about the dangers of PythonREPL.
_llm_type
return 'NIBittensorLLM'
@property def _llm_type(self) ->str: return 'NIBittensorLLM'
null
from_documents
"""Return VectorStore initialized from documents and embeddings.""" texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
@classmethod def from_documents(cls: Type['MockVectorStore'], documents: List[Document], embedding: Embeddings, **kwargs: Any) ->'MockVectorStore': """Return VectorStore initialized from documents and embeddings.""" texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] ...
Return VectorStore initialized from documents and embeddings.
test_chat_prompt_template_with_messages
messages: List[Union[BaseMessagePromptTemplate, BaseMessage] ] = create_messages() + [HumanMessage(content='foo')] chat_prompt_template = ChatPromptTemplate.from_messages(messages) assert sorted(chat_prompt_template.input_variables) == sorted(['context', 'foo', 'bar']) assert len(chat_prompt_template.messages) ...
def test_chat_prompt_template_with_messages() ->None: messages: List[Union[BaseMessagePromptTemplate, BaseMessage] ] = create_messages() + [HumanMessage(content='foo')] chat_prompt_template = ChatPromptTemplate.from_messages(messages) assert sorted(chat_prompt_template.input_variables) == sorted([ ...
null
test_deprecated_function
"""Test deprecated function.""" with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter('always') assert deprecated_function() == 'This is a deprecated function.' assert len(warning_list) == 1 warning = warning_list[0].message assert str(warning ) == 'The function `d...
def test_deprecated_function() ->None: """Test deprecated function.""" with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter('always') assert deprecated_function() == 'This is a deprecated function.' assert len(warning_list) == 1 warning = warning_list[...
Test deprecated function.
from_texts
"""Create an AtlasDB vectorstore from a raw documents. Args: texts (List[str]): The list of texts to ingest. name (str): Name of the project to create. api_key (str): Your nomic API key, embedding (Optional[Embeddings]): Embedding function. Defaults to None. ...
@classmethod def from_texts(cls: Type[AtlasDB], texts: List[str], embedding: Optional[ Embeddings]=None, metadatas: Optional[List[dict]]=None, ids: Optional[ List[str]]=None, name: Optional[str]=None, api_key: Optional[str]=None, description: str='A description for your project', is_public: bool=True, r...
Create an AtlasDB vectorstore from a raw documents. Args: texts (List[str]): The list of texts to ingest. name (str): Name of the project to create. api_key (str): Your nomic API key, embedding (Optional[Embeddings]): Embedding function. Defaults to None. metadatas (Optional[List[dict]]): List of m...
_llm_type
"""Return type of llm.""" return f"aviary-{self.model.replace('/', '-')}"
@property def _llm_type(self) ->str: """Return type of llm.""" return f"aviary-{self.model.replace('/', '-')}"
Return type of llm.
test_pandas_output_parser_col_first_elem
expected_output = {'chicken': 1} actual_output = parser.parse_folder('column:chicken[0]') assert actual_output == expected_output
def test_pandas_output_parser_col_first_elem() ->None: expected_output = {'chicken': 1} actual_output = parser.parse_folder('column:chicken[0]') assert actual_output == expected_output
null
texts_metadatas
return {'texts': ['Test Document' for _ in range(2)], 'metadatas': [{'key': 'value'} for _ in range(2)]}
@pytest.fixture def texts_metadatas() ->Dict[str, Any]: return {'texts': ['Test Document' for _ in range(2)], 'metadatas': [{ 'key': 'value'} for _ in range(2)]}
null
_import_google_scholar
from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper return GoogleScholarAPIWrapper
def _import_google_scholar() ->Any: from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper return GoogleScholarAPIWrapper
null
_dependable_mastodon_import
try: import mastodon except ImportError: raise ImportError( 'Mastodon.py package not found, please install it with `pip install Mastodon.py`' ) return mastodon
def _dependable_mastodon_import() ->mastodon: try: import mastodon except ImportError: raise ImportError( 'Mastodon.py package not found, please install it with `pip install Mastodon.py`' ) return mastodon
null
_import_requests_tool_BaseRequestsTool
from langchain_community.tools.requests.tool import BaseRequestsTool return BaseRequestsTool
def _import_requests_tool_BaseRequestsTool() ->Any: from langchain_community.tools.requests.tool import BaseRequestsTool return BaseRequestsTool
null
on_agent_action
"""Run on agent action."""
def on_agent_action(self, action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: """Run on agent action."""
Run on agent action.
validate_environment
"""Validate that api key and python package exists in environment.""" if values['n'] < 1: raise ValueError('n must be at least 1.') if values['n'] > 1 and values['streaming']: raise ValueError('n must be 1 when streaming.') values['openai_api_key'] = get_from_dict_or_env(values, 'openai_api_key', 'OPENAI_AP...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" if values['n'] < 1: raise ValueError('n must be at least 1.') if values['n'] > 1 and values['streaming']: raise ValueError('n must be 1 when streaming.'...
Validate that api key and python package exists in environment.
delete_documents_with_document_id
"""Delete documents based on their IDs. Args: id_list: List of document IDs. Returns: Whether the deletion was successful or not. """ if id_list is None or len(id_list) == 0: return True from alibabacloud_ha3engine_vector import models delete_doc_list = [] for doc_id...
def delete_documents_with_document_id(self, id_list: List[str]) ->bool: """Delete documents based on their IDs. Args: id_list: List of document IDs. Returns: Whether the deletion was successful or not. """ if id_list is None or len(id_list) == 0: return T...
Delete documents based on their IDs. Args: id_list: List of document IDs. Returns: Whether the deletion was successful or not.
test_simple_action_strlist_w_emb
str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) encoded_str2 = base.stringify_embedding(list(encoded_keyword + str2)) encoded_str3 = base.stringify_embedding(list(encoded_keyword + str3)) expected = [{'a_namespace': encoded_str1}, {'a_namespace': encode...
@pytest.mark.requires('vowpal_wabbit_next') def test_simple_action_strlist_w_emb() ->None: str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) encoded_str2 = base.stringify_embedding(list(encoded_keyword + str2)) encoded_str3 = base....
null
lazy_load
"""Lazily load documents.""" if self.web_path: blob = Blob.from_data(open(self.file_path, 'rb').read(), path=self.web_path ) else: blob = Blob.from_path(self.file_path) yield from self.parser.parse_folder(blob)
def lazy_load(self) ->Iterator[Document]: """Lazily load documents.""" if self.web_path: blob = Blob.from_data(open(self.file_path, 'rb').read(), path=self. web_path) else: blob = Blob.from_path(self.file_path) yield from self.parser.parse_folder(blob)
Lazily load documents.
get_tools
"""Get the tools in the toolkit.""" return [O365SearchEvents(), O365CreateDraftMessage(), O365SearchEmails(), O365SendEvent(), O365SendMessage()]
def get_tools(self) ->List[BaseTool]: """Get the tools in the toolkit.""" return [O365SearchEvents(), O365CreateDraftMessage(), O365SearchEmails( ), O365SendEvent(), O365SendMessage()]
Get the tools in the toolkit.
test_llamacpp_streaming_callback
"""Test that streaming correctly invokes on_llm_new_token callback.""" MAX_TOKENS = 5 OFF_BY_ONE = 1 callback_handler = FakeCallbackHandler() llm = LlamaCpp(model_path=get_model(), callbacks=[callback_handler], verbose=True, max_tokens=MAX_TOKENS) llm("Q: Can you count to 10? A:'1, ") assert callback_handler.llm_st...
def test_llamacpp_streaming_callback() ->None: """Test that streaming correctly invokes on_llm_new_token callback.""" MAX_TOKENS = 5 OFF_BY_ONE = 1 callback_handler = FakeCallbackHandler() llm = LlamaCpp(model_path=get_model(), callbacks=[callback_handler], verbose=True, max_tokens=MAX_TOKEN...
Test that streaming correctly invokes on_llm_new_token callback.
__add__
"""Override the + operator to allow for combining prompt templates.""" if isinstance(other, PromptTemplate): if self.template_format != 'f-string': raise ValueError( 'Adding prompt templates only supported for f-strings.') if other.template_format != 'f-string': raise ValueError( ...
def __add__(self, other: Any) ->PromptTemplate: """Override the + operator to allow for combining prompt templates.""" if isinstance(other, PromptTemplate): if self.template_format != 'f-string': raise ValueError( 'Adding prompt templates only supported for f-strings.') ...
Override the + operator to allow for combining prompt templates.
test_drop
""" Destroy the vector store """ self.vectorstore.drop()
def test_drop(self) ->None: """ Destroy the vector store """ self.vectorstore.drop()
Destroy the vector store
_llm_type
return 'vertexai'
@property def _llm_type(self) ->str: return 'vertexai'
null
test_prompt_invalid_template_format
"""Test initializing a prompt with invalid template format.""" template = 'This is a {foo} test.' input_variables = ['foo'] with pytest.raises(ValueError): PromptTemplate(input_variables=input_variables, template=template, template_format='bar')
def test_prompt_invalid_template_format() ->None: """Test initializing a prompt with invalid template format.""" template = 'This is a {foo} test.' input_variables = ['foo'] with pytest.raises(ValueError): PromptTemplate(input_variables=input_variables, template=template, template_fo...
Test initializing a prompt with invalid template format.
buffer
"""Access chat memory messages.""" return self.chat_memory.messages
@property def buffer(self) ->List[BaseMessage]: """Access chat memory messages.""" return self.chat_memory.messages
Access chat memory messages.
get_table_names
"""Get names of tables available.""" warnings.warn( 'This method is deprecated - please use `get_usable_table_names`.') return self.get_usable_table_names()
def get_table_names(self) ->Iterable[str]: """Get names of tables available.""" warnings.warn( 'This method is deprecated - please use `get_usable_table_names`.') return self.get_usable_table_names()
Get names of tables available.
test_faiss_invalid_normalize_fn
"""Test the similarity search with normalized similarities.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings(), relevance_score_fn=lambda _: 2.0) with pytest.warns(Warning, match='scores must be between'): docsearch.similarity_search_with_relevance_scores('foo', k=1)
@pytest.mark.requires('faiss') def test_faiss_invalid_normalize_fn() ->None: """Test the similarity search with normalized similarities.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings(), relevance_score_fn=lambda _: 2.0) with pytest.warns(Warning, match='scor...
Test the similarity search with normalized similarities.
_import_requests_tool_RequestsPutTool
from langchain_community.tools.requests.tool import RequestsPutTool return RequestsPutTool
def _import_requests_tool_RequestsPutTool() ->Any: from langchain_community.tools.requests.tool import RequestsPutTool return RequestsPutTool
null
headers
return {'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {self.access_token}'}
@property def headers(self) ->Dict[str, str]: return {'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {self.access_token}'}
null
__del__
if hasattr(self, 'temp_file'): self.temp_file.close()
def __del__(self) ->None: if hasattr(self, 'temp_file'): self.temp_file.close()
null
__init__
"""Initialize the loader. Args: file_path: A file, url or s3 path for input file textract_features: Features to be used for extraction, each feature should be passed as a str that conforms to the enum `Textract_Features`, see...
def __init__(self, file_path: str, textract_features: Optional[Sequence[str ]]=None, client: Optional[Any]=None, credentials_profile_name: Optional [str]=None, region_name: Optional[str]=None, endpoint_url: Optional[str ]=None, headers: Optional[Dict]=None) ->None: """Initialize the loader. Arg...
Initialize the loader. Args: file_path: A file, url or s3 path for input file textract_features: Features to be used for extraction, each feature should be passed as a str that conforms to the enum `Textract_Features`, see `amazon-textract-caller` pkg client: b...
lazy_load
""" Lazy load the chat sessions from the iMessage chat.db and yield them in the required format. Yields: ChatSession: Loaded chat session. """ import sqlite3 try: conn = sqlite3.connect(self.db_path) except sqlite3.OperationalError as e: raise ValueError( f""...
def lazy_load(self) ->Iterator[ChatSession]: """ Lazy load the chat sessions from the iMessage chat.db and yield them in the required format. Yields: ChatSession: Loaded chat session. """ import sqlite3 try: conn = sqlite3.connect(self.db_path) except...
Lazy load the chat sessions from the iMessage chat.db and yield them in the required format. Yields: ChatSession: Loaded chat session.
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, chain in enumerate(self.chains): _input = chain.run(_input, callbacks=_run_manager.get_child( f'step_{i + 1}')) ...
def _call(self, inputs: Dict[str, str], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))] ...
null
_get_verbosity
from langchain_core.globals import get_verbose return get_verbose()
def _get_verbosity() ->bool: from langchain_core.globals import get_verbose return get_verbose()
null
_get_relevant_documents
return self.retriever.get_relevant_documents(query, run_manager=run_manager .get_child(), **kwargs)
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any) ->List[Document]: return self.retriever.get_relevant_documents(query, run_manager= run_manager.get_child(), **kwargs)
null
ignore_agent
"""Whether to ignore agent callbacks.""" return self.ignore_agent_
@property def ignore_agent(self) ->bool: """Whether to ignore agent callbacks.""" return self.ignore_agent_
Whether to ignore agent callbacks.
_import_searchapi
from langchain_community.utilities.searchapi import SearchApiAPIWrapper return SearchApiAPIWrapper
def _import_searchapi() ->Any: from langchain_community.utilities.searchapi import SearchApiAPIWrapper return SearchApiAPIWrapper
null
_extract_images_from_page
"""Extract images from page and get the text with RapidOCR.""" if not self.extract_images or '/XObject' not in page['/Resources'].keys(): return '' xObject = page['/Resources']['/XObject'].get_object() images = [] for obj in xObject: if xObject[obj]['/Subtype'] == '/Image': if xObject[obj]['/Filter'][1:...
def _extract_images_from_page(self, page: pypdf._page.PageObject) ->str: """Extract images from page and get the text with RapidOCR.""" if not self.extract_images or '/XObject' not in page['/Resources'].keys(): return '' xObject = page['/Resources']['/XObject'].get_object() images = [] for o...
Extract images from page and get the text with RapidOCR.
test__convert_message_to_dict_system
message = SystemMessage(content='foo') result = _convert_message_to_dict(message) expected_output = {'role': 'system', 'content': 'foo'} assert result == expected_output
def test__convert_message_to_dict_system() ->None: message = SystemMessage(content='foo') result = _convert_message_to_dict(message) expected_output = {'role': 'system', 'content': 'foo'} assert result == expected_output
null
parse_iter
"""Parse the output of an LLM call.""" raise NotImplementedError
def parse_iter(self, text: str) ->Iterator[re.Match]: """Parse the output of an LLM call.""" raise NotImplementedError
Parse the output of an LLM call.
on_chain_error
"""Run when chain errors.""" self.step += 1 self.errors += 1
def on_chain_error(self, error: BaseException, **kwargs: Any) ->None: """Run when chain errors.""" self.step += 1 self.errors += 1
Run when chain errors.
test_edenai_call
"""Test simple call to edenai's speech to text endpoint.""" speech2text = EdenAiSpeechToTextTool(providers=['amazon']) output = speech2text( 'https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3' ) assert speech2text.name == 'edenai_speech_to_text' assert speech2text.feature == 'audio...
def test_edenai_call() ->None: """Test simple call to edenai's speech to text endpoint.""" speech2text = EdenAiSpeechToTextTool(providers=['amazon']) output = speech2text( 'https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3' ) assert speech2text.name == 'eden...
Test simple call to edenai's speech to text endpoint.
test_from_documents
input_docs = [Document(page_content='I have a pen.'), Document(page_content ='Do you have a pen?'), Document(page_content='I have a bag.')] tfidf_retriever = TFIDFRetriever.from_documents(documents=input_docs) assert len(tfidf_retriever.docs) == 3 assert tfidf_retriever.tfidf_array.toarray().shape == (3, 5)
@pytest.mark.requires('sklearn') def test_from_documents() ->None: input_docs = [Document(page_content='I have a pen.'), Document( page_content='Do you have a pen?'), Document(page_content= 'I have a bag.')] tfidf_retriever = TFIDFRetriever.from_documents(documents=input_docs) assert len(tfi...
null
on_chat_model_start
if self.__has_valid_config is False: return try: user_id = _get_user_id(metadata) user_props = _get_user_props(metadata) params = kwargs.get('invocation_params', {}) params.update(serialized.get('kwargs', {})) name = params.get('model') or params.get('model_name') or params.get( 'model_i...
def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[ List[BaseMessage]], *, run_id: UUID, parent_run_id: Union[UUID, None]= None, tags: Union[List[str], None]=None, metadata: Union[Dict[str, Any], None]=None, **kwargs: Any) ->Any: if self.__has_valid_config is False: return ...
null
_get_mock_page_restrictions
return {'read': {'operation': 'read', 'restrictions': {'user': {'results': [], 'start': 0, 'limit': 200, 'size': 0}, 'group': {'results': [], 'start': 0, 'limit': 200, 'size': 0}}, '_expandable': {'content': f'/rest/api/content/{page_id}'}, '_links': {'self': f'{self.CONFLUENCE_URL}/rest/api/content/{pa...
def _get_mock_page_restrictions(self, page_id: str) ->Dict: return {'read': {'operation': 'read', 'restrictions': {'user': { 'results': [], 'start': 0, 'limit': 200, 'size': 0}, 'group': { 'results': [], 'start': 0, 'limit': 200, 'size': 0}}, '_expandable': {'content': f'/rest/api/content/{p...
null
__init__
""" Initialize the object for file processing with Azure Document Intelligence (formerly Form Recognizer). This constructor initializes a DocumentIntelligenceParser object to be used for parsing files using the Azure Document Intelligence API. The load method generates a Documen...
def __init__(self, file_path: str, client: Any, model: str= 'prebuilt-document', headers: Optional[Dict]=None) ->None: """ Initialize the object for file processing with Azure Document Intelligence (formerly Form Recognizer). This constructor initializes a DocumentIntelligenceParser obj...
Initialize the object for file processing with Azure Document Intelligence (formerly Form Recognizer). This constructor initializes a DocumentIntelligenceParser object to be used for parsing files using the Azure Document Intelligence API. The load method generates a Document node including metadata (source blob and p...
__init__
raise ValueError('Deprecated,TinyAsyncGradientEmbeddingClient was removed.')
def __init__(self, *args, **kwargs) ->None: raise ValueError('Deprecated,TinyAsyncGradientEmbeddingClient was removed.' )
null
fake_retriever_v2
return FakeRetrieverV2()
@pytest.fixture def fake_retriever_v2() ->BaseRetriever: return FakeRetrieverV2()
null
_cleanup_unnecessary_items
fields = self.json_result_fields if self.json_result_fields is not None else [] if len(fields) > 0: for k, v in list(d.items()): if isinstance(v, dict): self._cleanup_unnecessary_items(v) if len(v) == 0: del d[k] elif k not in fields: del d[k] if '...
def _cleanup_unnecessary_items(self, d: dict) ->dict: fields = (self.json_result_fields if self.json_result_fields is not None else []) if len(fields) > 0: for k, v in list(d.items()): if isinstance(v, dict): self._cleanup_unnecessary_items(v) if len(v...
null
get_tokens
tiktoken = _import_tiktoken() return len(tiktoken.get_encoding('cl100k_base').encode(text))
def get_tokens(text: str) ->int: tiktoken = _import_tiktoken() return len(tiktoken.get_encoding('cl100k_base').encode(text))
null
retriever
return search.run(query)
def retriever(query): return search.run(query)
null
_similarity_search_with_relevance_scores
"""Return docs and their similarity scores on a scale from 0 to 1.""" score_threshold = kwargs.pop('score_threshold', None) relevance_score_fn = self._select_relevance_score_fn() if relevance_score_fn is None: raise ValueError( 'normalize_score_fn must be provided to ScaNN constructor to normalize scores' ...
def _similarity_search_with_relevance_scores(self, query: str, k: int=4, filter: Optional[Dict[str, Any]]=None, fetch_k: int=20, **kwargs: Any ) ->List[Tuple[Document, float]]: """Return docs and their similarity scores on a scale from 0 to 1.""" score_threshold = kwargs.pop('score_threshold', None) ...
Return docs and their similarity scores on a scale from 0 to 1.
test_json_equality_evaluator_evaluate_strings_custom_operator_equal
def operator(x: dict, y: dict) ->bool: return x['a'] == y['a'] evaluator = JsonEqualityEvaluator(operator=operator) prediction = '{"a": 1, "b": 2}' reference = '{"a": 1, "c": 3}' result = evaluator.evaluate_strings(prediction=prediction, reference=reference) assert result == {'score': True}
def test_json_equality_evaluator_evaluate_strings_custom_operator_equal( ) ->None: def operator(x: dict, y: dict) ->bool: return x['a'] == y['a'] evaluator = JsonEqualityEvaluator(operator=operator) prediction = '{"a": 1, "b": 2}' reference = '{"a": 1, "c": 3}' result = evaluator.evalua...
null
on_llm_start
"""Run when LLM starts.""" self.step += 1 self.llm_starts += 1 self.starts += 1 resp: Dict[str, Any] = {} resp.update({'action': 'on_llm_start'}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) prompt_responses = [] for prompt in prompts: prompt_responses.append(prompt) resp.updat...
def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], ** kwargs: Any) ->None: """Run when LLM starts.""" self.step += 1 self.llm_starts += 1 self.starts += 1 resp: Dict[str, Any] = {} resp.update({'action': 'on_llm_start'}) resp.update(flatten_dict(serialized)) resp....
Run when LLM starts.
_parse_message
return {'role': role, 'text': text}
def _parse_message(role: str, text: str) ->Dict: return {'role': role, 'text': text}
null
_llm_type
return 'vicuna-style'
@property def _llm_type(self) ->str: return 'vicuna-style'
null
_add_newlines_before_ha
new_text = input_text for word in ['Human:', 'Assistant:']: new_text = new_text.replace(word, '\n\n' + word) for i in range(2): new_text = new_text.replace('\n\n\n' + word, '\n\n' + word) return new_text
def _add_newlines_before_ha(input_text: str) ->str: new_text = input_text for word in ['Human:', 'Assistant:']: new_text = new_text.replace(word, '\n\n' + word) for i in range(2): new_text = new_text.replace('\n\n\n' + word, '\n\n' + word) return new_text
null
test_structured_single_str_decorator_no_infer_schema
"""Test functionality with structured arguments parsed as a decorator.""" @tool(infer_schema=False) def unstructured_tool_input(tool_input: str) ->str: """Return the arguments directly.""" assert isinstance(tool_input, str) return f'{tool_input}' assert isinstance(unstructured_tool_input, BaseTool) assert u...
def test_structured_single_str_decorator_no_infer_schema() ->None: """Test functionality with structured arguments parsed as a decorator.""" @tool(infer_schema=False) def unstructured_tool_input(tool_input: str) ->str: """Return the arguments directly.""" assert isinstance(tool_input, str) ...
Test functionality with structured arguments parsed as a decorator.
__init__
"""Initialize with Marqo client.""" try: import marqo except ImportError: raise ImportError( 'Could not import marqo python package. Please install it with `pip install marqo`.' ) if not isinstance(client, marqo.Client): raise ValueError( f'client should be an instance of marqo.Clien...
def __init__(self, client: marqo.Client, index_name: str, add_documents_settings: Optional[Dict[str, Any]]=None, searchable_attributes: Optional[List[str]]=None, page_content_builder: Optional[Callable[[Dict[str, Any]], str]]=None): """Initialize with Marqo client.""" try: import marqo e...
Initialize with Marqo client.
test_fireworks_streaming_stop_words
"""Test streaming tokens with stop words.""" last_token = '' for token in chat.stream("I'm Pickle Rick", stop=[',']): last_token = cast(str, token.content) assert isinstance(token.content, str) assert last_token[-1] == ','
@pytest.mark.scheduled def test_fireworks_streaming_stop_words(chat: ChatFireworks) ->None: """Test streaming tokens with stop words.""" last_token = '' for token in chat.stream("I'm Pickle Rick", stop=[',']): last_token = cast(str, token.content) assert isinstance(token.content, str) as...
Test streaming tokens with stop words.
_results_to_docs
return [doc for doc, _ in _results_to_docs_and_scores(results)]
def _results_to_docs(results: Any) ->List[Document]: return [doc for doc, _ in _results_to_docs_and_scores(results)]
null
_import_playwright_NavigateTool
from langchain_community.tools.playwright import NavigateTool return NavigateTool
def _import_playwright_NavigateTool() ->Any: from langchain_community.tools.playwright import NavigateTool return NavigateTool
null
test_refresh_schema
self.conn.execute( 'CREATE NODE TABLE Person (name STRING, birthDate STRING, PRIMARY KEY(name))' ) self.conn.execute('CREATE REL TABLE ActedIn (FROM Person TO Movie)') self.kuzu_graph.refresh_schema() schema = self.kuzu_graph.get_schema self.assertEqual(schema, EXPECTED_SCHEMA)
def test_refresh_schema(self) ->None: self.conn.execute( 'CREATE NODE TABLE Person (name STRING, birthDate STRING, PRIMARY KEY(name))' ) self.conn.execute('CREATE REL TABLE ActedIn (FROM Person TO Movie)') self.kuzu_graph.refresh_schema() schema = self.kuzu_graph.get_schema self.asse...
null
test_deeplake_with_metadatas
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = DeepLake.from_texts(dataset_path='mem://test_path', texts=texts, embedding=FakeEmbeddings(), metadatas=metadatas) output = docsearch.similarity_search('foo', k=1) assert...
def test_deeplake_with_metadatas() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = DeepLake.from_texts(dataset_path='mem://test_path', texts= texts, embedding=FakeEmbeddings(), metadatas=me...
Test end to end construction and search.
parse
try: expected_keys = ['query', 'filter'] allowed_keys = ['query', 'filter', 'limit'] parsed = parse_and_check_json_markdown(text, expected_keys) if len(parsed['query']) == 0: parsed['query'] = ' ' if parsed['filter'] == 'NO_FILTER' or not parsed['filter']: parsed['filter'] = None ...
def parse(self, text: str) ->StructuredQuery: try: expected_keys = ['query', 'filter'] allowed_keys = ['query', 'filter', 'limit'] parsed = parse_and_check_json_markdown(text, expected_keys) if len(parsed['query']) == 0: parsed['query'] = ' ' if parsed['filter'] =...
null
get_description
template: str = ( 'Useful for when you need to answer questions about {name} and the sources used to construct the answer. Whenever you need information about {description} you should ALWAYS use this. Input should be a fully formed question. Output is a json serialized dictionary with keys `answer` and `sources`. ...
@staticmethod def get_description(name: str, description: str) ->str: template: str = ( 'Useful for when you need to answer questions about {name} and the sources used to construct the answer. Whenever you need information about {description} you should ALWAYS use this. Input should be a fully formed quest...
null
crawl
page = self.page page_element_buffer = self.page_element_buffer start = time.time() page_state_as_text = [] device_pixel_ratio: float = page.evaluate('window.devicePixelRatio') if platform == 'darwin' and device_pixel_ratio == 1: device_pixel_ratio = 2 win_upper_bound: float = page.evaluate('window.pageYOffset') wi...
def crawl(self) ->List[str]: page = self.page page_element_buffer = self.page_element_buffer start = time.time() page_state_as_text = [] device_pixel_ratio: float = page.evaluate('window.devicePixelRatio') if platform == 'darwin' and device_pixel_ratio == 1: device_pixel_ratio = 2 wi...
null
format_prompt
"""Create Prompt Value."""
@abstractmethod def format_prompt(self, **kwargs: Any) ->PromptValue: """Create Prompt Value."""
Create Prompt Value.
parse_pull_requests
""" Extracts title and number from each Issue and puts them in a dictionary Parameters: issues(List[Issue]): A list of Github Issue objects Returns: List[dict]: A dictionary of issue titles and numbers """ parsed = [] for pr in pull_requests: parsed.append({'t...
def parse_pull_requests(self, pull_requests: List[PullRequest]) ->List[dict]: """ Extracts title and number from each Issue and puts them in a dictionary Parameters: issues(List[Issue]): A list of Github Issue objects Returns: List[dict]: A dictionary of issue titles ...
Extracts title and number from each Issue and puts them in a dictionary Parameters: issues(List[Issue]): A list of Github Issue objects Returns: List[dict]: A dictionary of issue titles and numbers
_embed_documents
"""Embed search docs.""" if isinstance(self._embedding, Embeddings): return self._embedding.embed_documents(list(texts)) return [self._embedding(t) for t in texts]
def _embed_documents(self, texts: Iterable[str]) ->List[List[float]]: """Embed search docs.""" if isinstance(self._embedding, Embeddings): return self._embedding.embed_documents(list(texts)) return [self._embedding(t) for t in texts]
Embed search docs.
test_run_success
responses.add(responses.POST, api_client.outline_instance_url + api_client. outline_search_endpoint, json=OUTLINE_SUCCESS_RESPONSE, status=200) docs = api_client.run('Testing') assert_docs(docs, all_meta=False)
@responses.activate def test_run_success(api_client: OutlineAPIWrapper) ->None: responses.add(responses.POST, api_client.outline_instance_url + api_client.outline_search_endpoint, json=OUTLINE_SUCCESS_RESPONSE, status=200) docs = api_client.run('Testing') assert_docs(docs, all_meta=False)
null
test_eval_chain
"""Test a simple eval chain.""" example = {'query': "What's my name", 'answer': 'John Doe'} prediction = {'result': 'John Doe'} fake_qa_eval_chain = QAEvalChain.from_llm(FakeLLM()) outputs = fake_qa_eval_chain.evaluate([example, example], [prediction, prediction]) assert outputs[0] == outputs[1] assert fake_qa_eval...
@pytest.mark.skipif(sys.platform.startswith('win'), reason= 'Test not supported on Windows') def test_eval_chain() ->None: """Test a simple eval chain.""" example = {'query': "What's my name", 'answer': 'John Doe'} prediction = {'result': 'John Doe'} fake_qa_eval_chain = QAEvalChain.from_llm(FakeLLM...
Test a simple eval chain.
test_qdrant_max_marginal_relevance_search
"""Test end to end construction and MRR search.""" from qdrant_client import models filter = models.Filter(must=[models.FieldCondition(key= f'{metadata_payload_key}.page', match=models.MatchValue(value=2))]) texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = Qdrant.from_t...
@pytest.mark.parametrize('batch_size', [1, 64]) @pytest.mark.parametrize('content_payload_key', [Qdrant.CONTENT_KEY, 'test_content']) @pytest.mark.parametrize('metadata_payload_key', [Qdrant.METADATA_KEY, 'test_metadata']) @pytest.mark.parametrize('vector_name', [None, 'my-vector']) def test_qdrant_max_marginal...
Test end to end construction and MRR search.
_load_vector_db_qa
if 'vectorstore' in kwargs: vectorstore = kwargs.pop('vectorstore') else: raise ValueError('`vectorstore` must be present.') if 'combine_documents_chain' in config: combine_documents_chain_config = config.pop('combine_documents_chain') combine_documents_chain = load_chain_from_config( combine_do...
def _load_vector_db_qa(config: dict, **kwargs: Any) ->VectorDBQA: if 'vectorstore' in kwargs: vectorstore = kwargs.pop('vectorstore') else: raise ValueError('`vectorstore` must be present.') if 'combine_documents_chain' in config: combine_documents_chain_config = config.pop('combine_...
null
_generate
should_stream = stream if stream is not None else self.streaming if should_stream: stream_iter = self._stream(messages, stop=stop, run_manager=run_manager, **kwargs) return generate_from_stream(stream_iter) payload = self._build_payload(messages) response = self._client.chat(payload) return self._create...
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, stream: Optional[bool]=None, **kwargs: Any) ->ChatResult: should_stream = stream if stream is not None else self.streaming if should_stream: stream_iter = self....
null
_delete_all
"""Delete all records in the table.""" while True: r = self._client.data().query(self._table_name, payload={'columns': ['id']} ) if r.status_code != 200: raise Exception(f'Error running query: {r.status_code} {r}') ids = [rec['id'] for rec in r['records']] if len(ids) == 0: break...
def _delete_all(self) ->None: """Delete all records in the table.""" while True: r = self._client.data().query(self._table_name, payload={'columns': ['id']}) if r.status_code != 200: raise Exception(f'Error running query: {r.status_code} {r}') ids = [rec['id'] for...
Delete all records in the table.
is_llm
"""Check if the language model is a LLM. Args: llm: Language model to check. Returns: True if the language model is a BaseLLM model, False otherwise. """ return isinstance(llm, BaseLLM)
def is_llm(llm: BaseLanguageModel) ->bool: """Check if the language model is a LLM. Args: llm: Language model to check. Returns: True if the language model is a BaseLLM model, False otherwise. """ return isinstance(llm, BaseLLM)
Check if the language model is a LLM. Args: llm: Language model to check. Returns: True if the language model is a BaseLLM model, False otherwise.
message_chunk_to_message
if not isinstance(chunk, BaseMessageChunk): return chunk return chunk.__class__.__mro__[1](**{k: v for k, v in chunk.__dict__.items( ) if k != 'type'})
def message_chunk_to_message(chunk: BaseMessageChunk) ->BaseMessage: if not isinstance(chunk, BaseMessageChunk): return chunk return chunk.__class__.__mro__[1](**{k: v for k, v in chunk.__dict__. items() if k != 'type'})
null
max_marginal_relevance_search
"""Perform a search and return results that are reordered by MMR. Args: query (str): The text being searched. k (int, optional): How many results to give. Defaults to 4. fetch_k (int, optional): Total results to select k from. Defaults to 20. lamb...
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, param: Optional[dict]=None, expr: Optional[ str]=None, timeout: Optional[int]=None, **kwargs: Any) ->List[Document]: """Perform a search and return results that are reordered by MMR. Args: ...
Perform a search and return results that are reordered by MMR. Args: query (str): The text being searched. k (int, optional): How many results to give. Defaults to 4. fetch_k (int, optional): Total results to select k from. Defaults to 20. lambda_mult: Number between 0 and 1 that determines the...
__del__
"""Ensure the client streaming connection is properly shutdown""" self.client.close()
def __del__(self): """Ensure the client streaming connection is properly shutdown""" self.client.close()
Ensure the client streaming connection is properly shutdown
modify_serialized_iterative
"""Utility to modify the serialized field of a list of runs dictionaries. removes any keys that match the exact_keys and any keys that contain any of the partial_keys. recursively moves the dictionaries under the kwargs key to the top level. changes the "id" field to a string "_kind" fie...
def modify_serialized_iterative(self, runs: List[Dict[str, Any]], exact_keys: Tuple[str, ...]=(), partial_keys: Tuple[str, ...]=()) ->List[ Dict[str, Any]]: """Utility to modify the serialized field of a list of runs dictionaries. removes any keys that match the exact_keys and any keys that contain ...
Utility to modify the serialized field of a list of runs dictionaries. removes any keys that match the exact_keys and any keys that contain any of the partial_keys. recursively moves the dictionaries under the kwargs key to the top level. changes the "id" field to a string "_kind" field that tells WBTraceTree how to vi...
remove_html_tags
from bs4 import BeautifulSoup soup = BeautifulSoup(html_string, 'html.parser') return soup.get_text()
def remove_html_tags(self, html_string: str) ->str: from bs4 import BeautifulSoup soup = BeautifulSoup(html_string, 'html.parser') return soup.get_text()
null
__init__
"""Initialize callback handler.""" super().__init__() self.model_id = model_id self.model_version = model_version self.space_key = SPACE_KEY self.api_key = API_KEY self.prompt_records: List[str] = [] self.response_records: List[str] = [] self.prediction_ids: List[str] = [] self.pred_timestamps: List[int] = [] self.resp...
def __init__(self, model_id: Optional[str]=None, model_version: Optional[ str]=None, SPACE_KEY: Optional[str]=None, API_KEY: Optional[str]=None ) ->None: """Initialize callback handler.""" super().__init__() self.model_id = model_id self.model_version = model_version self.space_key = SPACE_K...
Initialize callback handler.