method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
configurable_alternatives
from langchain_core.runnables.configurable import RunnableConfigurableAlternatives return RunnableConfigurableAlternatives(which=which, default=self, alternatives=kwargs, default_key=default_key, prefix_keys=prefix_keys)
def configurable_alternatives(self, which: ConfigurableField, *, default_key: str='default', prefix_keys: bool=False, **kwargs: Union[ Runnable[Input, Output], Callable[[], Runnable[Input, Output]]] ) ->RunnableSerializable[Input, Output]: from langchain_core.runnables.configurable import RunnableConfig...
null
as_import_path
"""Path of the file as a LangChain import exclude langchain top namespace.""" if isinstance(file, str): file = Path(file) path = get_relative_path(file, relative_to=relative_to) if file.is_file(): path = path[:-len(file.suffix)] import_path = path.replace(SEPARATOR, '.') if suffix: import_path += '.' + suff...
def as_import_path(file: Union[Path, str], *, suffix: Optional[str]=None, relative_to: Path=PACKAGE_DIR) ->str: """Path of the file as a LangChain import exclude langchain top namespace.""" if isinstance(file, str): file = Path(file) path = get_relative_path(file, relative_to=relative_to) if...
Path of the file as a LangChain import exclude langchain top namespace.
on_chat_model_start
assert all(isinstance(m, BaseMessage) for m in chain(*messages)) self.on_chat_model_start_common()
def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[ List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: assert all(isinstance(m, BaseMessage) for m in chain(*messages)) self.on_chat_model_start_common()
null
_convert_message_to_dict
"""Converts message to a dict according to role""" content = cast(str, message.content) if isinstance(message, HumanMessage): return {'role': 'user', 'content': ContentFormatterBase. escape_special_characters(content)} elif isinstance(message, AIMessage): return {'role': 'assistant', 'content': ContentF...
@staticmethod def _convert_message_to_dict(message: BaseMessage) ->Dict: """Converts message to a dict according to role""" content = cast(str, message.content) if isinstance(message, HumanMessage): return {'role': 'user', 'content': ContentFormatterBase. escape_special_characters(conten...
Converts message to a dict according to role
_alias
self.write(t.name) if t.asname: self.write(' as ' + t.asname)
def _alias(self, t): self.write(t.name) if t.asname: self.write(' as ' + t.asname)
null
setUp
self.loader = CubeSemanticLoader(cube_api_url='http://example.com', cube_api_token='test_token')
def setUp(self) ->None: self.loader = CubeSemanticLoader(cube_api_url='http://example.com', cube_api_token='test_token')
null
lookup
"""Look up based on prompt and llm_string."""
@abstractmethod def lookup(self, prompt: str, llm_string: str) ->Optional[RETURN_VAL_TYPE]: """Look up based on prompt and llm_string."""
Look up based on prompt and llm_string.
_identifying_params
"""Get the identifying parameters.""" return {**{'model_name': self.model_name}, **self._default_params}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {**{'model_name': self.model_name}, **self._default_params}
Get the identifying parameters.
_stream_response_to_generation_chunk
"""Convert a stream response to a generation chunk.""" if not stream_response['choices']: return GenerationChunk(text='') return GenerationChunk(text=stream_response['choices'][0]['text'], generation_info=dict(finish_reason=stream_response['choices'][0].get( 'finish_reason', None), logprobs=stream_response[...
def _stream_response_to_generation_chunk(stream_response: Dict[str, Any] ) ->GenerationChunk: """Convert a stream response to a generation chunk.""" if not stream_response['choices']: return GenerationChunk(text='') return GenerationChunk(text=stream_response['choices'][0]['text'], gener...
Convert a stream response to a generation chunk.
text
return RedisText(field)
@staticmethod def text(field: str) ->'RedisText': return RedisText(field)
null
test_transform_keeps_order
bs_transformer = BeautifulSoupTransformer() multiple_tags_html = ( '<h1>First heading.</h1><p>First paragraph.</p><h1>Second heading.</h1><p>Second paragraph.</p>' ) documents = [Document(page_content=multiple_tags_html)] docs_transformed_p_then_h1 = bs_transformer.transform_documents(documents, tags_to_ext...
@pytest.mark.requires('bs4') def test_transform_keeps_order() ->None: bs_transformer = BeautifulSoupTransformer() multiple_tags_html = ( '<h1>First heading.</h1><p>First paragraph.</p><h1>Second heading.</h1><p>Second paragraph.</p>' ) documents = [Document(page_content=multiple_tags_html)] ...
null
_invocation_params
params = self._default_params if self.model_kwargs: params.update(self.model_kwargs) if self.stop_sequences is not None and stop_sequences is not None: raise ValueError('`stop` found in both the input and default params.') elif self.stop_sequences is not None: params['stop'] = self.stop_sequences else: ...
def _invocation_params(self, stop_sequences: Optional[List[str]], **kwargs: Any ) ->dict: params = self._default_params if self.model_kwargs: params.update(self.model_kwargs) if self.stop_sequences is not None and stop_sequences is not None: raise ValueError('`stop` found in both the inp...
null
test_awadb_add_texts
"""Test end to end adding of texts.""" texts = ['foo', 'bar', 'baz'] docsearch = AwaDB.from_texts(table_name='test_awadb', texts=texts, embedding=FakeEmbeddings()) docsearch.add_texts(['foo']) output = docsearch.similarity_search('foo', k=2) assert output == [Document(page_content='foo'), Document(page_content='foo...
def test_awadb_add_texts() ->None: """Test end to end adding of texts.""" texts = ['foo', 'bar', 'baz'] docsearch = AwaDB.from_texts(table_name='test_awadb', texts=texts, embedding=FakeEmbeddings()) docsearch.add_texts(['foo']) output = docsearch.similarity_search('foo', k=2) assert outp...
Test end to end adding of texts.
test_openai_callback_agent
from langchain.agents import AgentType, initialize_agent, load_tools llm = OpenAI(temperature=0) tools = load_tools(['serpapi', 'llm-math'], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType. ZERO_SHOT_REACT_DESCRIPTION, verbose=True) with get_openai_callback() as cb: agent.run( "Who is Oliv...
def test_openai_callback_agent() ->None: from langchain.agents import AgentType, initialize_agent, load_tools llm = OpenAI(temperature=0) tools = load_tools(['serpapi', 'llm-math'], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType. ZERO_SHOT_REACT_DESCRIPTION, verbose=True) with...
null
__init__
"""Initialize with bilibili url. Args: video_urls: List of bilibili urls. """ self.video_urls = video_urls
def __init__(self, video_urls: List[str]): """Initialize with bilibili url. Args: video_urls: List of bilibili urls. """ self.video_urls = video_urls
Initialize with bilibili url. Args: video_urls: List of bilibili urls.
save_local
"""Save ScaNN index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. """ path = Path(folder_path) scann_path = path / '{index_name}.scann'.format(index_name=index_name) scann_path.mkdir(exist_ok...
def save_local(self, folder_path: str, index_name: str='index') ->None: """Save ScaNN index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. """ path = Path(folder_path) scann_path =...
Save ScaNN index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to.
similarity_search_by_vector
"""The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text query. min_score: the score of similar documents to the text query Returns: The k most similar d...
def similarity_search_by_vector(self, embedding: List[float], k: int= DEFAULT_TOPN, **kwargs: Any) ->List[Document]: """The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text que...
The most k similar documents and scores of the specified query. Args: embeddings: embedding vector of the query. k: The k most similar documents to the text query. min_score: the score of similar documents to the text query Returns: The k most similar documents to the specified text query. 0 is diss...
_get_memories_until_limit
"""Reduce the number of tokens in the documents.""" result = [] for doc in self.memory_retriever.memory_stream[::-1]: if consumed_tokens >= self.max_tokens_limit: break consumed_tokens += self.llm.get_num_tokens(doc.page_content) if consumed_tokens < self.max_tokens_limit: result.append(doc)...
def _get_memories_until_limit(self, consumed_tokens: int) ->str: """Reduce the number of tokens in the documents.""" result = [] for doc in self.memory_retriever.memory_stream[::-1]: if consumed_tokens >= self.max_tokens_limit: break consumed_tokens += self.llm.get_num_tokens(doc...
Reduce the number of tokens in the documents.
test_pdfminer_loader
"""Test PDFMiner loader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PDFMinerLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__).parent.parent / 'examples/layout-parser-paper.pdf' loader = PDFMinerLoader(str(file_path)) docs = loader.load() assert...
def test_pdfminer_loader() ->None: """Test PDFMiner loader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PDFMinerLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__ ).parent.parent / 'examples/layout-parser-paper.pdf'...
Test PDFMiner loader.
_import_tongyi
from langchain_community.llms.tongyi import Tongyi return Tongyi
def _import_tongyi() ->Any: from langchain_community.llms.tongyi import Tongyi return Tongyi
null
test_confluence_loader_initialization
ConfluenceLoader(self.CONFLUENCE_URL, username=self.MOCK_USERNAME, api_key= self.MOCK_API_TOKEN) mock_confluence.assert_called_once_with(url=self.CONFLUENCE_URL, username= 'user@gmail.com', password='api_token', cloud=True)
def test_confluence_loader_initialization(self, mock_confluence: MagicMock ) ->None: ConfluenceLoader(self.CONFLUENCE_URL, username=self.MOCK_USERNAME, api_key=self.MOCK_API_TOKEN) mock_confluence.assert_called_once_with(url=self.CONFLUENCE_URL, username='user@gmail.com', password='api_token...
null
raise_deprecation
"""Raise deprecation warning if callback_manager is used.""" if values.get('callback_manager') is not None: warnings.warn( 'callback_manager is deprecated. Please use callbacks instead.', DeprecationWarning) values['callbacks'] = values.pop('callback_manager', None) return values
@root_validator() def raise_deprecation(cls, values: Dict) ->Dict: """Raise deprecation warning if callback_manager is used.""" if values.get('callback_manager') is not None: warnings.warn( 'callback_manager is deprecated. Please use callbacks instead.', DeprecationWarning) ...
Raise deprecation warning if callback_manager is used.
_import_baiducloud_vector_search
from langchain_community.vectorstores.baiducloud_vector_search import BESVectorStore return BESVectorStore
def _import_baiducloud_vector_search() ->Any: from langchain_community.vectorstores.baiducloud_vector_search import BESVectorStore return BESVectorStore
null
_response_to_result
"""Converts a PaLM API response into a LangChain ChatResult.""" llm_output = {} if response.prompt_feedback: try: prompt_feedback = type(response.prompt_feedback).to_dict(response. prompt_feedback, use_integers_for_enums=False) llm_output['prompt_feedback'] = prompt_feedback except E...
def _response_to_result(response: genai.types.GenerateContentResponse, ai_msg_t: Type[BaseMessage]=AIMessage, human_msg_t: Type[BaseMessage]= HumanMessage, chat_msg_t: Type[BaseMessage]=ChatMessage, generation_t: Type[ChatGeneration]=ChatGeneration) ->ChatResult: """Converts a PaLM API response into a L...
Converts a PaLM API response into a LangChain ChatResult.
_identifying_params
return self._default_params
@property def _identifying_params(self) ->Dict[str, Any]: return self._default_params
null
_import_playwright_ClickTool
from langchain_community.tools.playwright import ClickTool return ClickTool
def _import_playwright_ClickTool() ->Any: from langchain_community.tools.playwright import ClickTool return ClickTool
null
load
"""Load documents.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load documents.""" return list(self.lazy_load())
Load documents.
test_results
"""Test that call gives the correct answer.""" search = BingSearchAPIWrapper() results = search.results("Obama's first name", num_results=5) result_contents = '\n'.join(f"{result['title']}: {result['snippet']}" for result in results) assert 'Barack Hussein Obama' in result_contents
def test_results() ->None: """Test that call gives the correct answer.""" search = BingSearchAPIWrapper() results = search.results("Obama's first name", num_results=5) result_contents = '\n'.join(f"{result['title']}: {result['snippet']}" for result in results) assert 'Barack Hussein Obama' i...
Test that call gives the correct answer.
_is_delta_sync_index
"""Return True if the index is a delta-sync index.""" return self.index_type == 'DELTA_SYNC'
def _is_delta_sync_index(self) ->bool: """Return True if the index is a delta-sync index.""" return self.index_type == 'DELTA_SYNC'
Return True if the index is a delta-sync index.
main
pass
@app.callback() def main(version: bool=typer.Option(False, '--version', '-v', help= 'Print the current CLI version.', callback=version_callback, is_eager=True) ): pass
null
__init__
self._commands: List[str] = [] self.output = output
def __init__(self, output: str='') ->None: self._commands: List[str] = [] self.output = output
null
yield_keys
"""Yield keys in the store.""" if prefix: pattern = self._get_prefixed_key(prefix) else: pattern = self._get_prefixed_key('*') scan_iter = cast(Iterator[bytes], self.client.scan_iter(match=pattern)) for key in scan_iter: decoded_key = key.decode('utf-8') if self.namespace: relative_key = decoded...
def yield_keys(self, *, prefix: Optional[str]=None) ->Iterator[str]: """Yield keys in the store.""" if prefix: pattern = self._get_prefixed_key(prefix) else: pattern = self._get_prefixed_key('*') scan_iter = cast(Iterator[bytes], self.client.scan_iter(match=pattern)) for key in scan_...
Yield keys in the store.
update_with_delayed_score
""" Updates the learned policy with the score provided. Will raise an error if selection_scorer is set, and force_score=True was not provided during the method call """ if self._can_use_selection_scorer() and not force_score: raise RuntimeError( 'The selection scorer is set, and forc...
def update_with_delayed_score(self, score: float, chain_response: Dict[str, Any], force_score: bool=False) ->None: """ Updates the learned policy with the score provided. Will raise an error if selection_scorer is set, and force_score=True was not provided during the method call """ ...
Updates the learned policy with the score provided. Will raise an error if selection_scorer is set, and force_score=True was not provided during the method call
wrong_output_format
assert 'foo' in inputs assert 'baz' in inputs return 'hehe'
def wrong_output_format(inputs: dict) ->str: assert 'foo' in inputs assert 'baz' in inputs return 'hehe'
null
test_non_zero_distance
eval_chain = StringDistanceEvalChain(distance=distance, normalize_score= normalize_score) prediction = 'I like to eat apples.' reference = 'I like apples.' result = eval_chain.evaluate_strings(prediction=prediction, reference=reference ) assert 'score' in result assert 0 < result['score'] if normalize_score: ...
@pytest.mark.requires('rapidfuzz') @pytest.mark.parametrize('distance', valid_distances) @pytest.mark.parametrize('normalize_score', [True, False]) def test_non_zero_distance(distance: StringDistance, normalize_score: bool ) ->None: eval_chain = StringDistanceEvalChain(distance=distance, normalize_score ...
null
_permute
"""Sort texts in ascending order, and delivers a lambda expr, which can sort a same length list https://github.com/UKPLab/sentence-transformers/blob/ c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156 Args: texts (List[str]): _descript...
@staticmethod def _permute(texts: List[str], sorter: Callable=len) ->Tuple[List[str], Callable]: """Sort texts in ascending order, and delivers a lambda expr, which can sort a same length list https://github.com/UKPLab/sentence-transformers/blob/ c5f93f70eca933c78695c5bc686ceda59651ae3b/...
Sort texts in ascending order, and delivers a lambda expr, which can sort a same length list https://github.com/UKPLab/sentence-transformers/blob/ c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156 Args: texts (List[str]): _description_ sorter (Callable, optional): _desc...
__init__
super().__init__() self.file_path = path if isinstance(path, Path) else Path(path)
def __init__(self, path: Union[Path, str]) ->None: super().__init__() self.file_path = path if isinstance(path, Path) else Path(path)
null
aggregate_lines_to_chunks
"""Combine lines with common metadata into chunks Args: lines: Line of text / associated header metadata """ aggregated_chunks: List[LineType] = [] for line in lines: if aggregated_chunks and aggregated_chunks[-1]['metadata'] == line[ 'metadata']: aggregated_chunks[-1]['c...
def aggregate_lines_to_chunks(self, lines: List[LineType]) ->List[Document]: """Combine lines with common metadata into chunks Args: lines: Line of text / associated header metadata """ aggregated_chunks: List[LineType] = [] for line in lines: if aggregated_chunks and agg...
Combine lines with common metadata into chunks Args: lines: Line of text / associated header metadata
_identifying_params
"""Get the identifying parameters.""" return {'base_url': self.base_url, **{}, **self._default_params}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {'base_url': self.base_url, **{}, **self._default_params}
Get the identifying parameters.
similarity_search_with_relevance_scores
"""Perform similarity retrieval based on text with scores. Args: query: Vectorize text for retrieval.,should not be empty. k: top n. search_filter: Additional filtering conditions. Returns: document_list: List of documents. """ embedding: List[floa...
def similarity_search_with_relevance_scores(self, query: str, k: int=4, search_filter: Optional[dict]=None, **kwargs: Any) ->List[Tuple[ Document, float]]: """Perform similarity retrieval based on text with scores. Args: query: Vectorize text for retrieval.,should not be empty. ...
Perform similarity retrieval based on text with scores. Args: query: Vectorize text for retrieval.,should not be empty. k: top n. search_filter: Additional filtering conditions. Returns: document_list: List of documents.
create_client
try: from zep_python import ZepClient except ImportError: raise ImportError( 'Could not import zep-python package. Please install it with `pip install zep-python`.' ) values['zep_client'] = values.get('zep_client', ZepClient(base_url=values[ 'url'], api_key=values.get('api_key'))) return val...
@root_validator(pre=True) def create_client(cls, values: dict) ->dict: try: from zep_python import ZepClient except ImportError: raise ImportError( 'Could not import zep-python package. Please install it with `pip install zep-python`.' ) values['zep_client'] = values....
null
similarity_search
vector = self._embedding.embed_query(query) return self.similarity_search_by_vector(vector, k=k, filter=filter, **kwargs)
def similarity_search(self, query: str, k: int=4, filter: Optional[Dict[str, Any]]=None, **kwargs: Any) ->List[Document]: vector = self._embedding.embed_query(query) return self.similarity_search_by_vector(vector, k=k, filter=filter, ** kwargs)
null
add_texts
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of unique IDs. refresh_indices: bool to refresh El...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, ids: Optional[List[str]]=None, refresh_indices: bool=True, ** kwargs: Any) ->List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the ve...
Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of unique IDs. refresh_indices: bool to refresh ElasticSearch indices Returns: List of i...
_llm_type
"""Return type of chat model.""" return 'chat-anthropic-messages'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'chat-anthropic-messages'
Return type of chat model.
on_llm_end
self.saved_things['generation'] = args[0]
def on_llm_end(self, *args: Any, **kwargs: Any) ->Any: self.saved_things['generation'] = args[0]
null
test_formatting
result = convert_messages_to_prompt_anthropic(messages) assert result == expected
@pytest.mark.parametrize(('messages', 'expected'), [([HumanMessage(content= 'Hello')], """ Human: Hello Assistant:"""), ([HumanMessage(content= 'Hello'), AIMessage(content='Answer:')], """ Human: Hello Assistant: Answer:"""), ([SystemMessage(content= "You're an assistant"), HumanMessage(content='Hel...
null
test_explicitly_no_scorer
llm, PROMPT = setup() chain = pick_best_chain.PickBest.from_llm(llm=llm, prompt=PROMPT, selection_scorer=None, feature_embedder=pick_best_chain. PickBestFeatureEmbedder(auto_embed=False, model=MockEncoder())) response = chain.run(User=rl_chain.BasedOn('Context'), action=rl_chain. ToSelectFrom(['0', '1', '2'...
@pytest.mark.requires('vowpal_wabbit_next', 'sentence_transformers') def test_explicitly_no_scorer() ->None: llm, PROMPT = setup() chain = pick_best_chain.PickBest.from_llm(llm=llm, prompt=PROMPT, selection_scorer=None, feature_embedder=pick_best_chain. PickBestFeatureEmbedder(auto_embed=False, ...
null
test_continue_on_failure_true
"""Test exception is not raised when continue_on_failure=True.""" loader = NewsURLLoader(['badurl.foobar']) loader.load()
def test_continue_on_failure_true() ->None: """Test exception is not raised when continue_on_failure=True.""" loader = NewsURLLoader(['badurl.foobar']) loader.load()
Test exception is not raised when continue_on_failure=True.
as_bytes_io
"""Read data as a byte stream.""" if isinstance(self.data, bytes): yield BytesIO(self.data) elif self.data is None and self.path: with open(str(self.path), 'rb') as f: yield f else: raise NotImplementedError(f'Unable to convert blob {self}')
@contextlib.contextmanager def as_bytes_io(self) ->Generator[Union[BytesIO, BufferedReader], None, None]: """Read data as a byte stream.""" if isinstance(self.data, bytes): yield BytesIO(self.data) elif self.data is None and self.path: with open(str(self.path), 'rb') as f: yield ...
Read data as a byte stream.
combine_embeddings
"""Combine embeddings into final embeddings.""" return list(np.array(embeddings).mean(axis=0))
def combine_embeddings(self, embeddings: List[List[float]]) ->List[float]: """Combine embeddings into final embeddings.""" return list(np.array(embeddings).mean(axis=0))
Combine embeddings into final embeddings.
embed_query
"""Call out to Clarifai's embedding models. Args: text: The text to embed. Returns: Embeddings for the text. """ try: from clarifai.client.model import Model except ImportError: raise ImportError( 'Could not import clarifai python package. Please install...
def embed_query(self, text: str) ->List[float]: """Call out to Clarifai's embedding models. Args: text: The text to embed. Returns: Embeddings for the text. """ try: from clarifai.client.model import Model except ImportError: raise ImportErro...
Call out to Clarifai's embedding models. Args: text: The text to embed. Returns: Embeddings for the text.
test_conversation_chain_errors_bad_variable
"""Test that conversation chain raise error with bad variable.""" llm = FakeLLM() prompt = PromptTemplate(input_variables=['foo'], template='{foo}') memory = ConversationBufferMemory(memory_key='foo') with pytest.raises(ValueError): ConversationChain(llm=llm, prompt=prompt, memory=memory, input_key='foo')
def test_conversation_chain_errors_bad_variable() ->None: """Test that conversation chain raise error with bad variable.""" llm = FakeLLM() prompt = PromptTemplate(input_variables=['foo'], template='{foo}') memory = ConversationBufferMemory(memory_key='foo') with pytest.raises(ValueError): C...
Test that conversation chain raise error with bad variable.
_import_tair
from langchain_community.vectorstores.tair import Tair return Tair
def _import_tair() ->Any: from langchain_community.vectorstores.tair import Tair return Tair
null
_prepare_query
new_query, new_kwargs = (self.structured_query_translator. visit_structured_query(structured_query)) if structured_query.limit is not None: new_kwargs['k'] = structured_query.limit if self.use_original_query: new_query = query search_kwargs = {**self.search_kwargs, **new_kwargs} return new_query, search_kwa...
def _prepare_query(self, query: str, structured_query: StructuredQuery ) ->Tuple[str, Dict[str, Any]]: new_query, new_kwargs = (self.structured_query_translator. visit_structured_query(structured_query)) if structured_query.limit is not None: new_kwargs['k'] = structured_query.limit if s...
null
format_tool_to_openai_function
"""Format tool into the OpenAI function API.""" if tool.args_schema: return convert_pydantic_to_openai_function(tool.args_schema, name=tool. name, description=tool.description) else: return {'name': tool.name, 'description': tool.description, 'parameters': {'properties': {'__arg1': {'title': '__...
def format_tool_to_openai_function(tool: BaseTool) ->FunctionDescription: """Format tool into the OpenAI function API.""" if tool.args_schema: return convert_pydantic_to_openai_function(tool.args_schema, name= tool.name, description=tool.description) else: return {'name': tool.na...
Format tool into the OpenAI function API.
_parse_response
if len(response) == 1: result = self._parse_json(response[0]) else: for entry in response: if entry.get('provider') == 'eden-ai': result = self._parse_json(entry) return result
def _parse_response(self, response: list) ->str: if len(response) == 1: result = self._parse_json(response[0]) else: for entry in response: if entry.get('provider') == 'eden-ai': result = self._parse_json(entry) return result
null
aggregate_elements_to_chunks
"""Combine elements with common metadata into chunks Args: elements: HTML element content with associated identifying info and metadata """ aggregated_chunks: List[ElementType] = [] for element in elements: if aggregated_chunks and aggregated_chunks[-1]['metadata'] == element[ '...
def aggregate_elements_to_chunks(self, elements: List[ElementType]) ->List[ Document]: """Combine elements with common metadata into chunks Args: elements: HTML element content with associated identifying info and metadata """ aggregated_chunks: List[ElementType] = [] for el...
Combine elements with common metadata into chunks Args: elements: HTML element content with associated identifying info and metadata
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
test_not_an_ai
err = f'Expected an AI message got {str(SystemMessage)}' with pytest.raises(TypeError, match=err): _parse_ai_message(SystemMessage(content='x'))
def test_not_an_ai(self) ->None: err = f'Expected an AI message got {str(SystemMessage)}' with pytest.raises(TypeError, match=err): _parse_ai_message(SystemMessage(content='x'))
null
test_duckdb_loader_metadata_columns
"""Test DuckDB loader.""" loader = DuckDBLoader('SELECT 1 AS a, 2 AS b', page_content_columns=['a'], metadata_columns=['b']) docs = loader.load() assert len(docs) == 1 assert docs[0].page_content == 'a: 1' assert docs[0].metadata == {'b': 2}
@unittest.skipIf(not duckdb_installed, 'duckdb not installed') def test_duckdb_loader_metadata_columns() ->None: """Test DuckDB loader.""" loader = DuckDBLoader('SELECT 1 AS a, 2 AS b', page_content_columns=[ 'a'], metadata_columns=['b']) docs = loader.load() assert len(docs) == 1 assert doc...
Test DuckDB loader.
_import_spark_sql_tool_ListSparkSQLTool
from langchain_community.tools.spark_sql.tool import ListSparkSQLTool return ListSparkSQLTool
def _import_spark_sql_tool_ListSparkSQLTool() ->Any: from langchain_community.tools.spark_sql.tool import ListSparkSQLTool return ListSparkSQLTool
null
_stream
message_dicts = self._create_message_dicts(messages) default_chunk_class = AIMessageChunk params = {'model': self.model, 'messages': message_dicts, 'stream': True, **self.model_kwargs, **kwargs} for chunk in completion_with_retry(self, self.use_retry, run_manager= run_manager, stop=stop, **params): choice =...
def _stream(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->Iterator[ChatGenerationChunk]: message_dicts = self._create_message_dicts(messages) default_chunk_class = AIMessageChunk params = {'model': self.mod...
null
test_qdrant_similarity_search_filters_with_qdrant_filters
"""Test end to end construction and search.""" from qdrant_client.http import models as rest texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i, 'details': {'page': i + 1, 'pages': [i + 2, -1]}} for i in range(len(texts))] docsearch = Qdrant.from_texts(texts, ConsistentFakeEmbeddings(), metadatas= metadatas,...
@pytest.mark.parametrize('vector_name', [None, 'my-vector']) def test_qdrant_similarity_search_filters_with_qdrant_filters(vector_name: Optional[str]) ->None: """Test end to end construction and search.""" from qdrant_client.http import models as rest texts = ['foo', 'bar', 'baz'] metadatas = [{'pag...
Test end to end construction and search.
from_texts
"""Create ClickHouse wrapper with existing texts Args: embedding_function (Embeddings): Function to extract text embedding texts (Iterable[str]): List or tuple of strings to be added config (ClickHouseSettings, Optional): ClickHouse configuration text_ids (Option...
@classmethod def from_texts(cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]]=None, config: Optional[ ClickhouseSettings]=None, text_ids: Optional[Iterable[str]]=None, batch_size: int=32, **kwargs: Any) ->Clickhouse: """Create ClickHouse wrapper with existing texts ...
Create ClickHouse wrapper with existing texts Args: embedding_function (Embeddings): Function to extract text embedding texts (Iterable[str]): List or tuple of strings to be added config (ClickHouseSettings, Optional): ClickHouse configuration text_ids (Optional[Iterable], optional): IDs for the texts....
__init__
"""Init the pipeline with an auxiliary function. The load function must be in global scope to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function. """ super().__init__(**kwargs) try: import runhouse as rh exce...
def __init__(self, **kwargs: Any): """Init the pipeline with an auxiliary function. The load function must be in global scope to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function. """ super().__init__(**...
Init the pipeline with an auxiliary function. The load function must be in global scope to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function.
test_deeplakewith_persistence
"""Test end to end construction and search, with persistence.""" import deeplake dataset_path = './tests/persist_dir' if deeplake.exists(dataset_path): deeplake.delete(dataset_path) texts = ['foo', 'bar', 'baz'] docsearch = DeepLake.from_texts(dataset_path=dataset_path, texts=texts, embedding=FakeEmbeddings()) ...
def test_deeplakewith_persistence() ->None: """Test end to end construction and search, with persistence.""" import deeplake dataset_path = './tests/persist_dir' if deeplake.exists(dataset_path): deeplake.delete(dataset_path) texts = ['foo', 'bar', 'baz'] docsearch = DeepLake.from_texts(...
Test end to end construction and search, with persistence.
_sync_request_embed
response = requests.post(**self._kwargs_post_request(model=model, texts= batch_texts)) if response.status_code != 200: raise Exception( f'Infinity returned an unexpected response with status {response.status_code}: {response.text}' ) return [e['embedding'] for e in response.json()['data']]
def _sync_request_embed(self, model: str, batch_texts: List[str]) ->List[List [float]]: response = requests.post(**self._kwargs_post_request(model=model, texts =batch_texts)) if response.status_code != 200: raise Exception( f'Infinity returned an unexpected response with status {...
null
test_load_uses_page_content_column_to_create_document_text
sample_data_frame = sample_data_frame.rename(mapping={'text': 'dummy_test_column'}) loader = PolarsDataFrameLoader(sample_data_frame, page_content_column= 'dummy_test_column') docs = loader.load() assert docs[0].page_content == 'Hello' assert docs[1].page_content == 'World'
def test_load_uses_page_content_column_to_create_document_text( sample_data_frame: pl.DataFrame) ->None: sample_data_frame = sample_data_frame.rename(mapping={'text': 'dummy_test_column'}) loader = PolarsDataFrameLoader(sample_data_frame, page_content_column= 'dummy_test_column') docs = ...
null
weighted_reciprocal_rank
""" Perform weighted Reciprocal Rank Fusion on multiple rank lists. You can find more details about RRF here: https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf Args: doc_lists: A list of rank lists, where each rank list contains unique items. Returns: ...
def weighted_reciprocal_rank(self, doc_lists: List[List[Document]]) ->List[ Document]: """ Perform weighted Reciprocal Rank Fusion on multiple rank lists. You can find more details about RRF here: https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf Args: doc_li...
Perform weighted Reciprocal Rank Fusion on multiple rank lists. You can find more details about RRF here: https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf Args: doc_lists: A list of rank lists, where each rank list contains unique items. Returns: list: The final aggregated list of items sorted by the...
test_figma_file_loader
"""Test Figma file loader.""" loader = FigmaFileLoader(ACCESS_TOKEN, IDS, KEY) docs = loader.load() assert len(docs) == 1
def test_figma_file_loader() ->None: """Test Figma file loader.""" loader = FigmaFileLoader(ACCESS_TOKEN, IDS, KEY) docs = loader.load() assert len(docs) == 1
Test Figma file loader.
observation_prefix
"""Prefix to append the observation with.""" return 'Observation: '
@property def observation_prefix(self) ->str: """Prefix to append the observation with.""" return 'Observation: '
Prefix to append the observation with.
__exit__
self.close()
def __exit__(self, exception_type: Any, exception_value: Any, traceback: Any ) ->None: self.close()
null
test_loading_few_shot_prompt_from_yaml
"""Test loading few shot prompt from yaml.""" with change_directory(EXAMPLE_DIR): prompt = load_prompt('few_shot_prompt.yaml') expected_prompt = FewShotPromptTemplate(input_variables=['adjective'], prefix='Write antonyms for the following words.', example_prompt= PromptTemplate(input_variables=[...
def test_loading_few_shot_prompt_from_yaml() ->None: """Test loading few shot prompt from yaml.""" with change_directory(EXAMPLE_DIR): prompt = load_prompt('few_shot_prompt.yaml') expected_prompt = FewShotPromptTemplate(input_variables=[ 'adjective'], prefix='Write antonyms for the f...
Test loading few shot prompt from yaml.
on_tool_start
"""Do nothing when tool starts.""" pass
def on_tool_start(self, serialized: Dict[str, Any], input_str: str, ** kwargs: Any) ->None: """Do nothing when tool starts.""" pass
Do nothing when tool starts.
on_agent_action
"""Run on agent action.""" self.step += 1 self.tool_starts += 1 self.starts += 1 tool = action.tool tool_input = str(action.tool_input) log = action.log resp = self._init_resp() resp.update({'action': 'on_agent_action', 'log': log, 'tool': tool}) resp.update(self.get_custom_callback_meta()) if self.stream_logs: sel...
def on_agent_action(self, action: AgentAction, **kwargs: Any) ->Any: """Run on agent action.""" self.step += 1 self.tool_starts += 1 self.starts += 1 tool = action.tool tool_input = str(action.tool_input) log = action.log resp = self._init_resp() resp.update({'action': 'on_agent_acti...
Run on agent action.
merge_chat_runs
"""Merge chat runs together. A chat run is a sequence of messages from the same sender. Args: chat_sessions: A list of chat sessions. Returns: A list of chat sessions with merged chat runs. """ for chat_session in chat_sessions: yield merge_chat_runs_in_session(chat_session)
def merge_chat_runs(chat_sessions: Iterable[ChatSession]) ->Iterator[ ChatSession]: """Merge chat runs together. A chat run is a sequence of messages from the same sender. Args: chat_sessions: A list of chat sessions. Returns: A list of chat sessions with merged chat runs. """...
Merge chat runs together. A chat run is a sequence of messages from the same sender. Args: chat_sessions: A list of chat sessions. Returns: A list of chat sessions with merged chat runs.
ignore_agent
"""Whether to ignore agent callbacks.""" return False
@property def ignore_agent(self) ->bool: """Whether to ignore agent callbacks.""" return False
Whether to ignore agent callbacks.
_call
"""Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python ...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use...
Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = hf("Tell me a joke.")
vectara3
vectara3: Vectara = Vectara() texts = [ """ The way Grounded Generation with Vectara works is we only use valid responses from your data relative to the search query. This dramatically reduces hallucinations in Vectara's responses. You can try it out on your own on our newly launc...
@pytest.fixture(scope='function') def vectara3(): vectara3: Vectara = Vectara() texts = [ """ The way Grounded Generation with Vectara works is we only use valid responses from your data relative to the search query. This dramatically reduces hallucinations in Vectara's respons...
null
_Call
self.dispatch(t.func) self.write('(') comma = False for e in t.args: if comma: self.write(', ') else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(', ') else: comma = True self.dispatch(e) self.write(')')
def _Call(self, t): self.dispatch(t.func) self.write('(') comma = False for e in t.args: if comma: self.write(', ') else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(', ') else: comma ...
null
process_output
""" Uses regex to remove the command from the output Args: output: a process' output string command: the executed command """ pattern = re.escape(command) + '\\s*\\n' output = re.sub(pattern, '', output, count=1) return output.strip()
def process_output(self, output: str, command: str) ->str: """ Uses regex to remove the command from the output Args: output: a process' output string command: the executed command """ pattern = re.escape(command) + '\\s*\\n' output = re.sub(pattern, '', outp...
Uses regex to remove the command from the output Args: output: a process' output string command: the executed command
on_agent_action
self.on_agent_action_common()
def on_agent_action(self, *args: Any, **kwargs: Any) ->Any: self.on_agent_action_common()
null
from_function
"""Initialize tool from a function.""" if func is None and coroutine is None: raise ValueError('Function and/or coroutine must be provided') return cls(name=name, func=func, coroutine=coroutine, description= description, return_direct=return_direct, args_schema=args_schema, **kwargs )
@classmethod def from_function(cls, func: Optional[Callable], name: str, description: str, return_direct: bool=False, args_schema: Optional[Type[BaseModel]]= None, coroutine: Optional[Callable[..., Awaitable[Any]]]=None, **kwargs: Any) ->Tool: """Initialize tool from a function.""" if func is None a...
Initialize tool from a function.
get_title
return self.DocumentTitle or ''
def get_title(self) ->str: return self.DocumentTitle or ''
null
add_texts
"""Run more texts through the embeddings and add to the retriever. Args: texts: Iterable of strings to add to the retriever. refresh_indices: bool to refresh ElasticSearch indices Returns: List of ids from adding the texts into the retriever. """ try: fr...
def add_texts(self, texts: Iterable[str], refresh_indices: bool=True) ->List[ str]: """Run more texts through the embeddings and add to the retriever. Args: texts: Iterable of strings to add to the retriever. refresh_indices: bool to refresh ElasticSearch indices Return...
Run more texts through the embeddings and add to the retriever. Args: texts: Iterable of strings to add to the retriever. refresh_indices: bool to refresh ElasticSearch indices Returns: List of ids from adding the texts into the retriever.
from_texts
"""Return Marqo initialized from texts. Note that Marqo does not need embeddings, we retain the parameter to adhere to the Liskov substitution principle. This is a quick way to get started with marqo - simply provide your texts and metadatas and this will create an instance of the data ...
@classmethod def from_texts(cls, texts: List[str], embedding: Any=None, metadatas: Optional[List[dict]]=None, index_name: str='', url: str= 'http://localhost:8882', api_key: str='', add_documents_settings: Optional[Dict[str, Any]]=None, searchable_attributes: Optional[List[str ]]=None, page_content_buil...
Return Marqo initialized from texts. Note that Marqo does not need embeddings, we retain the parameter to adhere to the Liskov substitution principle. This is a quick way to get started with marqo - simply provide your texts and metadatas and this will create an instance of the data store and index the provided data. ...
_parse_response
formatted_list: list = [] if len(response) == 1: self._parse_json_multilevel(response[0]['extracted_data'][0], formatted_list) else: for entry in response: if entry.get('provider') == 'eden-ai': self._parse_json_multilevel(entry['extracted_data'][0], formatted_list) r...
def _parse_response(self, response: list) ->str: formatted_list: list = [] if len(response) == 1: self._parse_json_multilevel(response[0]['extracted_data'][0], formatted_list) else: for entry in response: if entry.get('provider') == 'eden-ai': self._pa...
null
validate_environment
"""Validate that open_clip and torch libraries are installed.""" try: import open_clip model_name = values.get('model_name', cls.__fields__['model_name'].default) checkpoint = values.get('checkpoint', cls.__fields__['checkpoint'].default) model, _, preprocess = open_clip.create_model_and_transforms(mode...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that open_clip and torch libraries are installed.""" try: import open_clip model_name = values.get('model_name', cls.__fields__['model_name']. default) checkpoint = values.get('checkpoint', cls....
Validate that open_clip and torch libraries are installed.
test_call
"""Test that call gives correct answer.""" search = SearchApiAPIWrapper() output = search.run('What is the capital of Lithuania?') assert 'Vilnius' in output
def test_call() ->None: """Test that call gives correct answer.""" search = SearchApiAPIWrapper() output = search.run('What is the capital of Lithuania?') assert 'Vilnius' in output
Test that call gives correct answer.
compress_documents
"""Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs(self.embeddings, stateful_documents) embedded_query = self.embeddings.embed_query(query) similarity = self.similarity_fn([embedd...
def compress_documents(self, documents: Sequence[Document], query: str, callbacks: Optional[Callbacks]=None) ->Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from...
Filter documents based on similarity of their embeddings to the query.
similarity_search_by_vector
raise NotImplementedError
def similarity_search_by_vector(self, embedding: List[float], k: int=4, ** kwargs: Any) ->List[Document]: raise NotImplementedError
null
_resolve_schema_references
""" Resolves the $ref keys in a JSON schema object using the provided definitions. """ if isinstance(schema, list): for i, item in enumerate(schema): schema[i] = _resolve_schema_references(item, definitions) elif isinstance(schema, dict): if '$ref' in schema: ref_key = schema.pop('$ref')...
def _resolve_schema_references(schema: Any, definitions: Dict[str, Any]) ->Any: """ Resolves the $ref keys in a JSON schema object using the provided definitions. """ if isinstance(schema, list): for i, item in enumerate(schema): schema[i] = _resolve_schema_references(item, definitio...
Resolves the $ref keys in a JSON schema object using the provided definitions.
embed_documents
return [self._get_embedding() for _ in texts]
def embed_documents(self, texts: List[str]) ->List[List[float]]: return [self._get_embedding() for _ in texts]
null
_parse_json
result = [] label_info = [] for found_obj in json_data['items']: label_str = f"{found_obj['label']} - Confidence {found_obj['confidence']}" x_min = found_obj.get('x_min') x_max = found_obj.get('x_max') y_min = found_obj.get('y_min') y_max = found_obj.get('y_max') if self.show_positions and all([...
def _parse_json(self, json_data: dict) ->str: result = [] label_info = [] for found_obj in json_data['items']: label_str = ( f"{found_obj['label']} - Confidence {found_obj['confidence']}") x_min = found_obj.get('x_min') x_max = found_obj.get('x_max') y_min = found...
null
_import_slack_send_message
from langchain_community.tools.slack.send_message import SlackSendMessage return SlackSendMessage
def _import_slack_send_message() ->Any: from langchain_community.tools.slack.send_message import SlackSendMessage return SlackSendMessage
null
_get_mock_quip_loader
quip_loader = QuipLoader(self.API_URL, access_token=self.ACCESS_TOKEN, request_timeout=60) quip_loader.quip_client = mock_quip return quip_loader
def _get_mock_quip_loader(self, mock_quip: MagicMock) ->QuipLoader: quip_loader = QuipLoader(self.API_URL, access_token=self.ACCESS_TOKEN, request_timeout=60) quip_loader.quip_client = mock_quip return quip_loader
null
nested_element
"""Get nested element from path.""" if len(path) == 0: return AddableDict({elem.tag: elem.text}) else: return AddableDict({path[0]: [nested_element(path[1:], elem)]})
def nested_element(path: List[str], elem: ET.Element) ->Any: """Get nested element from path.""" if len(path) == 0: return AddableDict({elem.tag: elem.text}) else: return AddableDict({path[0]: [nested_element(path[1:], elem)]})
Get nested element from path.
from_texts
"""Create Rockset wrapper with existing texts. This is intended as a quicker way to get started. """ assert client is not None, 'Rockset Client cannot be None' assert collection_name, 'Collection name cannot be empty' assert text_key, 'Text key name cannot be empty' assert embedding_key, 'Embedding key ...
@classmethod def from_texts(cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, client: Any=None, collection_name: str='', text_key: str='', embedding_key: str='', ids: Optional[List[str]]=None, batch_size: int=32, **kwargs: Any) ->Rockset: """Create Rockset wrapper with ...
Create Rockset wrapper with existing texts. This is intended as a quicker way to get started.
_get_language_model
if isinstance(llm_like, BaseLanguageModel): return llm_like elif isinstance(llm_like, RunnableBinding): return _get_language_model(llm_like.bound) elif isinstance(llm_like, RunnableWithFallbacks): return _get_language_model(llm_like.runnable) elif isinstance(llm_like, (RunnableBranch, DynamicRunnable)): ...
def _get_language_model(llm_like: Runnable) ->BaseLanguageModel: if isinstance(llm_like, BaseLanguageModel): return llm_like elif isinstance(llm_like, RunnableBinding): return _get_language_model(llm_like.bound) elif isinstance(llm_like, RunnableWithFallbacks): return _get_language_m...
null
on_agent_action
"""Run on agent action.""" self.metrics['step'] += 1 self.metrics['tool_starts'] += 1 self.metrics['starts'] += 1 tool_starts = self.metrics['tool_starts'] resp: Dict[str, Any] = {} resp.update({'action': 'on_agent_action', 'tool': action.tool, 'tool_input': action.tool_input, 'log': action.log}) resp.update(self.m...
def on_agent_action(self, action: AgentAction, **kwargs: Any) ->Any: """Run on agent action.""" self.metrics['step'] += 1 self.metrics['tool_starts'] += 1 self.metrics['starts'] += 1 tool_starts = self.metrics['tool_starts'] resp: Dict[str, Any] = {} resp.update({'action': 'on_agent_action',...
Run on agent action.