method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
test_generate
"""Test valid call to qianfan.""" llm = QianfanLLMEndpoint() output = llm.generate(['write a joke']) assert isinstance(output, LLMResult) assert isinstance(output.generations, list)
def test_generate() ->None: """Test valid call to qianfan.""" llm = QianfanLLMEndpoint() output = llm.generate(['write a joke']) assert isinstance(output, LLMResult) assert isinstance(output.generations, list)
Test valid call to qianfan.
vectors
"""Create two random vectors.""" vector_a = np.array([0.5488135, 0.71518937, 0.60276338, 0.54488318, 0.4236548, 0.64589411, 0.43758721, 0.891773, 0.96366276, 0.38344152]) vector_b = np.array([0.79172504, 0.52889492, 0.56804456, 0.92559664, 0.07103606, 0.0871293, 0.0202184, 0.83261985, 0.77815675, 0.87001215])...
@pytest.fixture def vectors() ->Tuple[np.ndarray, np.ndarray]: """Create two random vectors.""" vector_a = np.array([0.5488135, 0.71518937, 0.60276338, 0.54488318, 0.4236548, 0.64589411, 0.43758721, 0.891773, 0.96366276, 0.38344152]) vector_b = np.array([0.79172504, 0.52889492, 0.56804456, 0.925596...
Create two random vectors.
test_api_key_is_string
llm = LLMRailsEmbeddings(api_key='secret-api-key') assert isinstance(llm.api_key, SecretStr)
def test_api_key_is_string() ->None: llm = LLMRailsEmbeddings(api_key='secret-api-key') assert isinstance(llm.api_key, SecretStr)
null
test_similarity_search_with_score_by_vector_with_score_threshold
"""Test vector similarity with score by vector.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings()) index_to_id = docsearch.index_to_docstore_id expected_docstore = InMemoryDocstore({index_to_id[0]: Document(page_content ='foo'), index_to_id[1]: Document(page_content='bar'), index...
@pytest.mark.requires('faiss') def test_similarity_search_with_score_by_vector_with_score_threshold() ->None: """Test vector similarity with score by vector.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings()) index_to_id = docsearch.index_to_docstore_id expected_d...
Test vector similarity with score by vector.
get_client
"""Get the client.""" global _CLIENT if _CLIENT is None: _CLIENT = Client() return _CLIENT
def get_client() ->Client: """Get the client.""" global _CLIENT if _CLIENT is None: _CLIENT = Client() return _CLIENT
Get the client.
create
...
@overload @staticmethod def create(messages: Sequence[Dict[str, Any]], *, provider: str= 'ChatOpenAI', stream: Literal[True], **kwargs: Any) ->Iterable: ...
null
expected_documents
return [Document(page_content= "{'_id': '1', 'address': {'building': '1', 'room': '1'}}", metadata={ 'database': 'sample_restaurants', 'collection': 'restaurants'}), Document(page_content= "{'_id': '2', 'address': {'building': '2', 'room': '2'}}", metadata={ 'database': 'sample_restaurants', 'collec...
@pytest.fixture def expected_documents() ->List[Document]: return [Document(page_content= "{'_id': '1', 'address': {'building': '1', 'room': '1'}}", metadata ={'database': 'sample_restaurants', 'collection': 'restaurants'}), Document(page_content= "{'_id': '2', 'address': {'building'...
null
test_initialization
os.environ['MS_GRAPH_CLIENT_ID'] = 'CLIENT_ID' os.environ['MS_GRAPH_CLIENT_SECRET'] = 'CLIENT_SECRET' loader = OneNoteLoader(notebook_name='test_notebook', section_name= 'test_section', page_title='test_title', access_token='access_token') assert loader.notebook_name == 'test_notebook' assert loader.section_name ==...
def test_initialization() ->None: os.environ['MS_GRAPH_CLIENT_ID'] = 'CLIENT_ID' os.environ['MS_GRAPH_CLIENT_SECRET'] = 'CLIENT_SECRET' loader = OneNoteLoader(notebook_name='test_notebook', section_name= 'test_section', page_title='test_title', access_token='access_token') assert loader.notebook...
null
test_news_loader_with_nlp
loader = NewsURLLoader([get_random_news_url()], nlp=True) docs = loader.load() assert docs[0] is not None assert hasattr(docs[0], 'page_content') assert hasattr(docs[0], 'metadata') metadata = docs[0].metadata assert 'title' in metadata assert 'link' in metadata assert 'authors' in metadata assert 'language' in metadat...
def test_news_loader_with_nlp() ->None: loader = NewsURLLoader([get_random_news_url()], nlp=True) docs = loader.load() assert docs[0] is not None assert hasattr(docs[0], 'page_content') assert hasattr(docs[0], 'metadata') metadata = docs[0].metadata assert 'title' in metadata assert 'lin...
null
_get_verbosity
from langchain.globals import get_verbose return get_verbose()
def _get_verbosity() ->bool: from langchain.globals import get_verbose return get_verbose()
null
jsonf
"""To log the input data as json file artifact.""" with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id=self. mlf_expid): self.mlflow.log_dict(data, f'{filename}.json')
def jsonf(self, data: Dict[str, Any], filename: str) ->None: """To log the input data as json file artifact.""" with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id= self.mlf_expid): self.mlflow.log_dict(data, f'{filename}.json')
To log the input data as json file artifact.
__init__
"""Initializes the `ArgillaCallbackHandler`. Args: dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must exist in advance. If you need help on how to create a `FeedbackDataset` in Argilla, please visit https://docs.argilla.io/en/la...
def __init__(self, dataset_name: str, workspace_name: Optional[str]=None, api_url: Optional[str]=None, api_key: Optional[str]=None) ->None: """Initializes the `ArgillaCallbackHandler`. Args: dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must exist in a...
Initializes the `ArgillaCallbackHandler`. Args: dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must exist in advance. If you need help on how to create a `FeedbackDataset` in Argilla, please visit https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argil...
__init__
if boto3_session: client = boto3_session.resource('dynamodb', endpoint_url=endpoint_url) else: try: import boto3 except ImportError as e: raise ImportError( 'Unable to import boto3, please install with `pip install boto3`.' ) from e if endpoint_url: client...
def __init__(self, table_name: str, session_id: str, endpoint_url: Optional [str]=None, primary_key_name: str='SessionId', key: Optional[Dict[str, str]]=None, boto3_session: Optional[Session]=None, kms_key_id: Optional [str]=None): if boto3_session: client = boto3_session.resource('dynamodb', en...
null
_identifying_params
"""Get the identifying parameters.""" return {'model_id': self.model_id, 'deployment_id': self.deployment_id, 'params': self.params, 'project_id': self.project_id, 'space_id': self. space_id}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {'model_id': self.model_id, 'deployment_id': self.deployment_id, 'params': self.params, 'project_id': self.project_id, 'space_id': self.space_id}
Get the identifying parameters.
drop
""" Helper function: Drop data """ self.client.command( f'DROP TABLE IF EXISTS {self.config.database}.{self.config.table}')
def drop(self) ->None: """ Helper function: Drop data """ self.client.command( f'DROP TABLE IF EXISTS {self.config.database}.{self.config.table}')
Helper function: Drop data
from_texts
"""Return VectorStore initialized from texts and embeddings.""" if not api_key or not db_url: raise ValueError('Xata api_key and db_url must be set.') embeddings = embedding.embed_documents(texts) ids = None docs = cls._texts_to_documents(texts, metadatas) vector_db = cls(api_key=api_key, db_url=db_url, embedding=e...
@classmethod def from_texts(cls: Type['XataVectorStore'], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, api_key: Optional[str ]=None, db_url: Optional[str]=None, table_name: str='vectors', ids: Optional[List[str]]=None, **kwargs: Any) ->'XataVectorStore': """Return Vecto...
Return VectorStore initialized from texts and embeddings.
_llm_type
"""Return type of llm.""" return 'tongyi'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'tongyi'
Return type of llm.
_get_metadata
return {'source': self.file_path}
def _get_metadata(self) ->dict: return {'source': self.file_path}
null
output_keys
"""Output key of bar.""" return self.the_output_keys
@property def output_keys(self) ->List[str]: """Output key of bar.""" return self.the_output_keys
Output key of bar.
test_multiple_agent_actions_observations
intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log= 'Log1'), 'Observation1'), (AgentAction(tool='Tool2', tool_input= 'input2', log='Log2'), 'Observation2'), (AgentAction(tool='Tool3', tool_input='input3', log='Log3'), 'Observation3')] expected_result = """Log1 Observation: Observation...
def test_multiple_agent_actions_observations() ->None: intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log='Log1'), 'Observation1'), (AgentAction(tool='Tool2', tool_input ='input2', log='Log2'), 'Observation2'), (AgentAction(tool='Tool3', tool_input='input3', log='Log3'...
null
_pushField
logger.info(f'Pushing {id} in queue') response = requests.post(self._config['BACKEND'] + '/processing/push', headers={'content-type': 'application/json', 'x-stf-nuakey': 'Bearer ' + self._config['NUA_KEY']}, json=field) if response.status_code != 200: logger.info( f'Error pushing field {id}:{respons...
def _pushField(self, id: str, field: Any) ->str: logger.info(f'Pushing {id} in queue') response = requests.post(self._config['BACKEND'] + '/processing/push', headers={'content-type': 'application/json', 'x-stf-nuakey': 'Bearer ' + self._config['NUA_KEY']}, json=field) if response.status_cod...
null
_process_next_step_output
""" Process the output of the next step, handling AgentFinish and tool return cases. """ logger.debug('Processing output of Agent loop step') if isinstance(next_step_output, AgentFinish): logger.debug( 'Hit AgentFinish: _return -> on_chain_end -> run final output logic') return s...
def _process_next_step_output(self, next_step_output: Union[AgentFinish, List[Tuple[AgentAction, str]]], run_manager: CallbackManagerForChainRun ) ->AddableDict: """ Process the output of the next step, handling AgentFinish and tool return cases. """ logger.debug('Processing outp...
Process the output of the next step, handling AgentFinish and tool return cases.
_import_docarray_hnsw
from langchain_community.vectorstores.docarray import DocArrayHnswSearch return DocArrayHnswSearch
def _import_docarray_hnsw() ->Any: from langchain_community.vectorstores.docarray import DocArrayHnswSearch return DocArrayHnswSearch
null
output_keys
"""Return the singular output key. :meta private: """ return [self.output_key]
@property def output_keys(self) ->List[str]: """Return the singular output key. :meta private: """ return [self.output_key]
Return the singular output key. :meta private:
prep_prompts
"""Prepare prompts from inputs.""" stop = None if 'stop' in inputs: stop = inputs['stop'] selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), 'green') _text = 'Prompt after formatting:\n' + _...
def prep_prompts(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Tuple[PromptValue, Optional[List[str]] ]: """Prepare prompts from inputs.""" stop = None if 'stop' in inputs: stop = inputs['stop'] selected_inputs = {k: inputs[k] for k in self.prom...
Prepare prompts from inputs.
encode
if isinstance(to_encode, str): return [1.0, 2.0] elif isinstance(to_encode, List): return [[1.0, 2.0] for _ in range(len(to_encode))] raise ValueError('Invalid input type for unit test')
def encode(self, to_encode: Any) ->List: if isinstance(to_encode, str): return [1.0, 2.0] elif isinstance(to_encode, List): return [[1.0, 2.0] for _ in range(len(to_encode))] raise ValueError('Invalid input type for unit test')
null
__init__
self.steps = steps
def __init__(self, steps: List[Step]): self.steps = steps
null
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
__call__
"""Interface for the combine_docs method."""
def __call__(self, docs: List[Document], **kwargs: Any) ->str: """Interface for the combine_docs method."""
Interface for the combine_docs method.
_convert_llm_run_to_wb_span
"""Converts a LangChain LLM Run into a W&B Trace Span. :param run: The LangChain LLM Run to convert. :return: The converted W&B Trace Span. """ base_span = self._convert_run_to_wb_span(run) if base_span.attributes is None: base_span.attributes = {} base_span.attributes['llm_output'] = (run.o...
def _convert_llm_run_to_wb_span(self, run: Run) ->'Span': """Converts a LangChain LLM Run into a W&B Trace Span. :param run: The LangChain LLM Run to convert. :return: The converted W&B Trace Span. """ base_span = self._convert_run_to_wb_span(run) if base_span.attributes is None: ...
Converts a LangChain LLM Run into a W&B Trace Span. :param run: The LangChain LLM Run to convert. :return: The converted W&B Trace Span.
_run
"""Use the LLM to check the query.""" return self.llm_chain.predict(query=query, callbacks=run_manager.get_child( ) if run_manager else None)
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] =None) ->str: """Use the LLM to check the query.""" return self.llm_chain.predict(query=query, callbacks=run_manager. get_child() if run_manager else None)
Use the LLM to check the query.
get_output_schema
schema: Dict[str, Any] = {self.output_key: (str, None)} if self.return_intermediate_steps: schema['intermediate_steps'] = List[str], None if self.metadata_keys: schema.update({key: (Any, None) for key in self.metadata_keys}) return create_model('MapRerankOutput', **schema)
def get_output_schema(self, config: Optional[RunnableConfig]=None) ->Type[ BaseModel]: schema: Dict[str, Any] = {self.output_key: (str, None)} if self.return_intermediate_steps: schema['intermediate_steps'] = List[str], None if self.metadata_keys: schema.update({key: (Any, None) for key ...
null
lc_secrets
return {'anyscale_api_key': 'ANYSCALE_API_KEY'}
@property def lc_secrets(self) ->Dict[str, str]: return {'anyscale_api_key': 'ANYSCALE_API_KEY'}
null
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() user_input = inputs[self.input_keys[0]] response = '' for i in range(self.max_iter): _run_manager.on_text(f'Current Response: {response}', color='blue', end ='\n') _input = {'user_input': user_input, 'context': '', 'response': r...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() user_input = inputs[self.input_keys[0]] response = '' for i in range(self.max_iter): _run_manager.on_...
null
test_redis_retriever_distance_threshold
texts = ['foo', 'bar', 'baz'] docsearch = Redis.from_texts(texts, FakeEmbeddings(), redis_url=TEST_REDIS_URL) retriever = docsearch.as_retriever(search_type= 'similarity_distance_threshold', search_kwargs={'k': 3, 'distance_threshold': 0.1}) results = retriever.get_relevant_documents('foo') assert len(results) ...
def test_redis_retriever_distance_threshold() ->None: texts = ['foo', 'bar', 'baz'] docsearch = Redis.from_texts(texts, FakeEmbeddings(), redis_url= TEST_REDIS_URL) retriever = docsearch.as_retriever(search_type= 'similarity_distance_threshold', search_kwargs={'k': 3, 'distance_thres...
null
_similarity_search_with_score_by_vector
"""Return docs most similar to query vector, along with scores""" ret = self._collection.query(embedding, topk=k, filter=filter) if not ret: raise ValueError( f'Fail to query docs by vector, error {self._collection.message}') docs = [] for doc in ret: metadata = doc.fields text = metadata.pop(self._...
def _similarity_search_with_score_by_vector(self, embedding: List[float], k: int=4, filter: Optional[str]=None) ->List[Tuple[Document, float]]: """Return docs most similar to query vector, along with scores""" ret = self._collection.query(embedding, topk=k, filter=filter) if not ret: raise Value...
Return docs most similar to query vector, along with scores
delete
"""Delete by document ID. Args: ids: List of ids to delete. **kwargs: Other keyword arguments that subclasses might use. Returns: Optional[bool]: True if deletion is successful, False otherwise. """ async def _delete(ids: Optional[List[str]], **k...
def delete(self, ids: Optional[List[str]]=None, **kwargs: Any) ->Optional[bool ]: """Delete by document ID. Args: ids: List of ids to delete. **kwargs: Other keyword arguments that subclasses might use. Returns: Optional[bool]: True if deletion is successful...
Delete by document ID. Args: ids: List of ids to delete. **kwargs: Other keyword arguments that subclasses might use. Returns: Optional[bool]: True if deletion is successful, False otherwise.
add_embeddings
"""Add embeddings to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. embeddings: List of list of embedding vectors. metadatas: List of metadatas associated with the texts. kwargs: vectorstore specific parameters """ if ids is ...
def add_embeddings(self, texts: Iterable[str], embeddings: List[List[float] ], metadatas: Optional[List[dict]]=None, ids: Optional[List[str]]=None, **kwargs: Any) ->List[str]: """Add embeddings to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. e...
Add embeddings to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. embeddings: List of list of embedding vectors. metadatas: List of metadatas associated with the texts. kwargs: vectorstore specific parameters
main
name = input('Enter your name: ') obj = MyClass(name) obj.greet()
def main(): name = input('Enter your name: ') obj = MyClass(name) obj.greet()
null
read_and_detect
with open(file_path, 'rb') as f: rawdata = f.read() return cast(List[dict], chardet.detect_all(rawdata))
def read_and_detect(file_path: str) ->List[dict]: with open(file_path, 'rb') as f: rawdata = f.read() return cast(List[dict], chardet.detect_all(rawdata))
null
test_google_generativeai_call
"""Test valid call to Google GenerativeAI text API.""" if model_name: llm = GoogleGenerativeAI(max_output_tokens=10, model=model_name) else: llm = GoogleGenerativeAI(max_output_tokens=10) output = llm('Say foo:') assert isinstance(output, str) assert llm._llm_type == 'google_palm' if model_name and 'gemini' in ...
@pytest.mark.parametrize('model_name', model_names) def test_google_generativeai_call(model_name: str) ->None: """Test valid call to Google GenerativeAI text API.""" if model_name: llm = GoogleGenerativeAI(max_output_tokens=10, model=model_name) else: llm = GoogleGenerativeAI(max_output_toke...
Test valid call to Google GenerativeAI text API.
azure_installed
try: from azure.core.credentials import TokenCredential from azure.identity import DefaultAzureCredential return True except Exception as e: print(f'azure not installed, skipping test {e}') return False
def azure_installed() ->bool: try: from azure.core.credentials import TokenCredential from azure.identity import DefaultAzureCredential return True except Exception as e: print(f'azure not installed, skipping test {e}') return False
null
similarity_search
embedding_vector = self.embedding.embed_query(query) return self.similarity_search_by_vector(embedding_vector, k, filter=filter)
def similarity_search(self, query: str, k: int=4, filter: Optional[Dict[str, str]]=None, **kwargs: Any) ->List[Document]: embedding_vector = self.embedding.embed_query(query) return self.similarity_search_by_vector(embedding_vector, k, filter=filter)
null
_get_message_role
"""Get the role of the message.""" if isinstance(message, ChatMessage): return message.role else: return message.__class__.__name__
def _get_message_role(self, message: BaseMessage) ->str: """Get the role of the message.""" if isinstance(message, ChatMessage): return message.role else: return message.__class__.__name__
Get the role of the message.
validate_prompt
if values['llm_chain'].prompt.output_parser is None: raise ValueError( 'The prompt used by llm_chain is expected to have an output_parser.') return values
@root_validator def validate_prompt(cls, values: Dict) ->Dict: if values['llm_chain'].prompt.output_parser is None: raise ValueError( 'The prompt used by llm_chain is expected to have an output_parser.' ) return values
null
concatenate_rows
"""Combine message information in a readable format ready to be used.""" date = row['date'] sender = row['from'] text = row['text'] return f'{sender} on {date}: {text}\n\n'
def concatenate_rows(row: dict) ->str: """Combine message information in a readable format ready to be used.""" date = row['date'] sender = row['from'] text = row['text'] return f'{sender} on {date}: {text}\n\n'
Combine message information in a readable format ready to be used.
create_prompt
"""Create prompt for this agent. Args: system_message: Message to use as the system message that will be the first in the prompt. extra_prompt_messages: Prompt messages that will be placed between the system message and the new human input. Retur...
@classmethod def create_prompt(cls, system_message: Optional[SystemMessage]= SystemMessage(content='You are a helpful AI assistant.'), extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]]=None ) ->BasePromptTemplate: """Create prompt for this agent. Args: system_message:...
Create prompt for this agent. Args: system_message: Message to use as the system message that will be the first in the prompt. extra_prompt_messages: Prompt messages that will be placed between the system message and the new human input. Returns: A prompt template to pass into this agent.
test_saving_loading_llm
"""Test saving/loading an OpenAI LLM.""" llm = OpenAI(max_tokens=10) llm.save(file_path=tmp_path / 'openai.yaml') loaded_llm = load_llm(tmp_path / 'openai.yaml') assert loaded_llm == llm
def test_saving_loading_llm(tmp_path: Path) ->None: """Test saving/loading an OpenAI LLM.""" llm = OpenAI(max_tokens=10) llm.save(file_path=tmp_path / 'openai.yaml') loaded_llm = load_llm(tmp_path / 'openai.yaml') assert loaded_llm == llm
Test saving/loading an OpenAI LLM.
on_tool_end
"""If not the final action, print out observation.""" if observation_prefix is not None: print_text(f'\n{observation_prefix}', file=self.file) print_text(output, color=color or self.color, file=self.file) if llm_prefix is not None: print_text(f'\n{llm_prefix}', file=self.file)
def on_tool_end(self, output: str, color: Optional[str]=None, observation_prefix: Optional[str]=None, llm_prefix: Optional[str]=None, **kwargs: Any) ->None: """If not the final action, print out observation.""" if observation_prefix is not None: print_text(f'\n{observation_prefix}', file=self.fi...
If not the final action, print out observation.
run
""" Run Outline search and get the document content plus the meta information. Returns: a list of documents. """ results = self._outline_api_query(query[:OUTLINE_MAX_QUERY_LENGTH]) docs = [] for result in results[:self.top_k_results]: if (doc := self._result_to_document(result)): d...
def run(self, query: str) ->List[Document]: """ Run Outline search and get the document content plus the meta information. Returns: a list of documents. """ results = self._outline_api_query(query[:OUTLINE_MAX_QUERY_LENGTH]) docs = [] for result in results[:self.top_k_results]:...
Run Outline search and get the document content plus the meta information. Returns: a list of documents.
_get_openai_client
try: import openai return openai.OpenAI() except ImportError as e: raise ImportError( 'Unable to import openai, please install with `pip install openai`.' ) from e except AttributeError as e: raise AttributeError( 'Please make sure you are using a v1.1-compatible version of opena...
def _get_openai_client() ->openai.OpenAI: try: import openai return openai.OpenAI() except ImportError as e: raise ImportError( 'Unable to import openai, please install with `pip install openai`.' ) from e except AttributeError as e: raise AttributeErr...
null
max_marginal_relevance_search
"""Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 5. ...
def max_marginal_relevance_search(self, query: str, fetch_k: int=50, lambda_mult: float=0.5, **kwargs: Any) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. ...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 5. fetch_k: Number of Documents to fetch to pass t...
_get_relevant_documents
return self.run(query=query)
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) ->List[Document]: return self.run(query=query)
null
get_by_name
return session.query(cls).filter(cls.name == name).first()
@classmethod def get_by_name(cls, session: Session, name: str) ->Optional['CollectionStore' ]: return session.query(cls).filter(cls.name == name).first()
null
_import_pgvector
from langchain_community.vectorstores.pgvector import PGVector return PGVector
def _import_pgvector() ->Any: from langchain_community.vectorstores.pgvector import PGVector return PGVector
null
custom_distance
return 0.5 if a != b else 0.0
def custom_distance(a: str, b: str) ->float: return 0.5 if a != b else 0.0
null
raise_deprecation
if 'llm' in values: warnings.warn( 'Directly instantiating an NatBotChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.' ) if 'llm_chain' not in values and values['llm'] is not None: values['llm_chain'] = LLMChain(llm=values['ll...
@root_validator(pre=True) def raise_deprecation(cls, values: Dict) ->Dict: if 'llm' in values: warnings.warn( 'Directly instantiating an NatBotChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.' ) if 'llm_chain' not...
null
_aggregate_msgs
"""Dig out relevant details of aggregated message""" content_buffer: Dict[str, Any] = dict() content_holder: Dict[Any, Any] = dict() is_stopped = False for msg in msg_list: if 'choices' in msg: msg = msg.get('choices', [{}])[0] is_stopped = msg.get('finish_reason', '') == 'stop' msg = msg.ge...
def _aggregate_msgs(self, msg_list: Sequence[dict]) ->Tuple[dict, bool]: """Dig out relevant details of aggregated message""" content_buffer: Dict[str, Any] = dict() content_holder: Dict[Any, Any] = dict() is_stopped = False for msg in msg_list: if 'choices' in msg: msg = msg.get...
Dig out relevant details of aggregated message
main
print('Hello World!') return 0
def main() ->int: print('Hello World!') return 0
null
on_chain_start
"""Run when chain starts running."""
def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) ->None: """Run when chain starts running."""
Run when chain starts running.
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
_zilliz_from_texts
return Zilliz.from_texts(fake_texts, FakeEmbeddings(), metadatas=metadatas, connection_args={'uri': '', 'user': '', 'password': '', 'secure': True}, drop_old=drop)
def _zilliz_from_texts(metadatas: Optional[List[dict]]=None, drop: bool=True ) ->Zilliz: return Zilliz.from_texts(fake_texts, FakeEmbeddings(), metadatas= metadatas, connection_args={'uri': '', 'user': '', 'password': '', 'secure': True}, drop_old=drop)
null
_get_llm_parameters
if not langchain_asset: return {} try: if hasattr(langchain_asset, 'agent'): llm_parameters = langchain_asset.agent.llm_chain.llm.dict() elif hasattr(langchain_asset, 'llm_chain'): llm_parameters = langchain_asset.llm_chain.llm.dict() elif hasattr(langchain_asset, 'llm'): llm_par...
def _get_llm_parameters(self, langchain_asset: Any=None) ->dict: if not langchain_asset: return {} try: if hasattr(langchain_asset, 'agent'): llm_parameters = langchain_asset.agent.llm_chain.llm.dict() elif hasattr(langchain_asset, 'llm_chain'): llm_parameters = l...
null
_update_run_single
"""Update a run.""" try: run_dict = run.dict() run_dict['tags'] = self._get_tags(run) self.client.update_run(run.id, **run_dict) except Exception as e: log_error_once('patch', e) raise
def _update_run_single(self, run: Run) ->None: """Update a run.""" try: run_dict = run.dict() run_dict['tags'] = self._get_tags(run) self.client.update_run(run.id, **run_dict) except Exception as e: log_error_once('patch', e) raise
Update a run.
test_gpt_router_call
"""Test valid call to GPTRouter.""" anthropic_claude = GPTRouterModel(name='claude-instant-1.2', provider_name= 'anthropic') chat = GPTRouter(models_priority_list=[anthropic_claude]) message = HumanMessage(content='Hello World') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(res...
def test_gpt_router_call() ->None: """Test valid call to GPTRouter.""" anthropic_claude = GPTRouterModel(name='claude-instant-1.2', provider_name='anthropic') chat = GPTRouter(models_priority_list=[anthropic_claude]) message = HumanMessage(content='Hello World') response = chat([message]) ...
Test valid call to GPTRouter.
_make_request
try: import grpc from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import CompletionOptions, Message from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import CompletionRequest from yandex.cloud.ai.fo...
def _make_request(self: YandexGPT, prompt: str) ->str: try: import grpc from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import CompletionOptions, Message from yandex.cloud.ai.foundation_models.v1.foundat...
null
get_entities
"""Extract entities from entity string.""" if entity_str.strip() == 'NONE': return [] else: return [w.strip() for w in entity_str.split(',')]
def get_entities(entity_str: str) ->List[str]: """Extract entities from entity string.""" if entity_str.strip() == 'NONE': return [] else: return [w.strip() for w in entity_str.split(',')]
Extract entities from entity string.
test_load_success_init_args
retriever = ArxivRetriever(load_max_docs=1, load_all_available_meta=True) docs = retriever.get_relevant_documents(query='ChatGPT') assert len(docs) == 1 assert_docs(docs, all_meta=True)
def test_load_success_init_args() ->None: retriever = ArxivRetriever(load_max_docs=1, load_all_available_meta=True) docs = retriever.get_relevant_documents(query='ChatGPT') assert len(docs) == 1 assert_docs(docs, all_meta=True)
null
update
"""Upsert records into the SQLite database.""" if group_ids is None: group_ids = [None] * len(keys) if len(keys) != len(group_ids): raise ValueError( f'Number of keys ({len(keys)}) does not match number of group_ids ({len(group_ids)})' ) update_time = self.get_time() if time_at_least and update_...
def update(self, keys: Sequence[str], *, group_ids: Optional[Sequence[ Optional[str]]]=None, time_at_least: Optional[float]=None) ->None: """Upsert records into the SQLite database.""" if group_ids is None: group_ids = [None] * len(keys) if len(keys) != len(group_ids): raise ValueError( ...
Upsert records into the SQLite database.
momento_cache
from momento import CacheClient, Configurations, CredentialProvider cache_name = f'langchain-test-cache-{random_string()}' client = CacheClient(Configurations.Laptop.v1(), CredentialProvider. from_environment_variable('MOMENTO_API_KEY'), default_ttl=timedelta( seconds=30)) try: llm_cache = MomentoCache(clie...
@pytest.fixture(scope='module') def momento_cache() ->Iterator[MomentoCache]: from momento import CacheClient, Configurations, CredentialProvider cache_name = f'langchain-test-cache-{random_string()}' client = CacheClient(Configurations.Laptop.v1(), CredentialProvider. from_environment_variable('MOM...
null
_get_default_python_repl
return PythonREPL(_globals=globals(), _locals=None)
def _get_default_python_repl() ->PythonREPL: return PythonREPL(_globals=globals(), _locals=None)
null
_load_chunks_for_document
"""Load chunks for a document.""" url = f'{self.api}/docsets/{docset_id}/documents/{document_id}/dgml' response = requests.request('GET', url, headers={'Authorization': f'Bearer {self.access_token}'}, data={}) if response.ok: return self._parse_dgml(content=response.content, document_name= document_name...
def _load_chunks_for_document(self, document_id: str, docset_id: str, document_name: Optional[str]=None, additional_metadata: Optional[ Mapping]=None) ->List[Document]: """Load chunks for a document.""" url = f'{self.api}/docsets/{docset_id}/documents/{document_id}/dgml' response = requests.request(...
Load chunks for a document.
test_spacy_text_splitting_args
"""Test invalid arguments.""" with pytest.raises(ValueError): SpacyTextSplitter(chunk_size=2, chunk_overlap=4)
def test_spacy_text_splitting_args() ->None: """Test invalid arguments.""" with pytest.raises(ValueError): SpacyTextSplitter(chunk_size=2, chunk_overlap=4)
Test invalid arguments.
test_memory_separate_session_ids
"""Test that separate session IDs do not share entries.""" memory1 = ConversationBufferMemory(memory_key='mk1', chat_memory=history1, return_messages=True) memory2 = ConversationBufferMemory(memory_key='mk2', chat_memory=history2, return_messages=True) memory1.chat_memory.add_ai_message('Just saying.') assert m...
@pytest.mark.requires('astrapy') @pytest.mark.skipif(not _has_env_vars(), reason='Missing Astra DB env. vars') def test_memory_separate_session_ids(history1: AstraDBChatMessageHistory, history2: AstraDBChatMessageHistory) ->None: """Test that separate session IDs do not share entries.""" memory1 = Conversat...
Test that separate session IDs do not share entries.
_check_docarray_import
try: import docarray da_version = docarray.__version__.split('.') if int(da_version[0]) == 0 and int(da_version[1]) <= 31: raise ImportError( f'To use the DocArrayHnswSearch VectorStore the docarray version >=0.32.0 is expected, received: {docarray.__version__}.To upgrade, please run: `p...
def _check_docarray_import() ->None: try: import docarray da_version = docarray.__version__.split('.') if int(da_version[0]) == 0 and int(da_version[1]) <= 31: raise ImportError( f'To use the DocArrayHnswSearch VectorStore the docarray version >=0.32.0 is expected...
null
transform_serialized
"""Transforms the serialized field of a run dictionary to be compatible with WBTraceTree. :param serialized: The serialized field of a run dictionary. :return: The transformed serialized field. """ serialized = handle_id_and_kwargs(serialized, root=True) serialized = ...
def transform_serialized(serialized: Dict[str, Any]) ->Dict[str, Any]: """Transforms the serialized field of a run dictionary to be compatible with WBTraceTree. :param serialized: The serialized field of a run dictionary. :return: The transformed serialized field. ...
Transforms the serialized field of a run dictionary to be compatible with WBTraceTree. :param serialized: The serialized field of a run dictionary. :return: The transformed serialized field.
test_init_fail_no_embedding
index = mock_index(index_details) with pytest.raises(ValueError) as ex: DatabricksVectorSearch(index, text_column=DEFAULT_TEXT_COLUMN) assert '`embedding` is required for this index.' in str(ex.value)
@pytest.mark.requires('databricks', 'databricks.vector_search') @pytest.mark.parametrize('index_details', [ DELTA_SYNC_INDEX_SELF_MANAGED_EMBEDDINGS, DIRECT_ACCESS_INDEX]) def test_init_fail_no_embedding(index_details: dict) ->None: index = mock_index(index_details) with pytest.raises(ValueError) as ex: ...
null
load
"""Load LarkSuite (FeiShu) document.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load LarkSuite (FeiShu) document.""" return list(self.lazy_load())
Load LarkSuite (FeiShu) document.
on_llm_end
pd = import_pandas() from arize.utils.types import EmbeddingColumnNames, Environments, ModelTypes, Schema if response.llm_output and 'token_usage' in response.llm_output: self.prompt_tokens = response.llm_output['token_usage'].get('prompt_tokens' , 0) self.total_tokens = response.llm_output['token_usage...
def on_llm_end(self, response: LLMResult, **kwargs: Any) ->None: pd = import_pandas() from arize.utils.types import EmbeddingColumnNames, Environments, ModelTypes, Schema if response.llm_output and 'token_usage' in response.llm_output: self.prompt_tokens = response.llm_output['token_usage'].get( ...
null
get_format_instructions
"""Returns formatting instructions for the given output parser.""" return FORMAT_INSTRUCTIONS
def get_format_instructions(self) ->str: """Returns formatting instructions for the given output parser.""" return FORMAT_INSTRUCTIONS
Returns formatting instructions for the given output parser.
similarity_search
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(query, k, ...
def similarity_search(self, query: str, k: int=4, filter: Optional[dict]= None, **kwargs: Any) ->List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: ...
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.
test_zilliz
"""Test end to end construction and search.""" docsearch = _zilliz_from_texts() output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo')]
def test_zilliz() ->None: """Test end to end construction and search.""" docsearch = _zilliz_from_texts() output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo')]
Test end to end construction and search.
load
"""Load documents.""" p = Path(self.path) if not p.exists(): raise FileNotFoundError(f"Directory not found: '{self.path}'") if not p.is_dir(): raise ValueError(f"Expected directory, got file: '{self.path}'") docs: List[Document] = [] items = list(p.rglob(self.glob) if self.recursive else p.glob(self.glob)) if s...
def load(self) ->List[Document]: """Load documents.""" p = Path(self.path) if not p.exists(): raise FileNotFoundError(f"Directory not found: '{self.path}'") if not p.is_dir(): raise ValueError(f"Expected directory, got file: '{self.path}'") docs: List[Document] = [] items = list(...
Load documents.
_on_llm_end
"""Process the LLM Run."""
def _on_llm_end(self, run: Run) ->None: """Process the LLM Run."""
Process the LLM Run.
update
"""Update cache based on prompt and llm_string.""" self._cache[prompt, llm_string] = return_val
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE ) ->None: """Update cache based on prompt and llm_string.""" self._cache[prompt, llm_string] = return_val
Update cache based on prompt and llm_string.
_reduce_tokens_below_limit
num_docs = len(docs) if self.reduce_k_below_max_tokens and isinstance(self. combine_documents_chain, StuffDocumentsChain): tokens = [self.combine_documents_chain.llm_chain._get_num_tokens(doc. page_content) for doc in docs] token_count = sum(tokens[:num_docs]) while token_count > self.max_tokens...
def _reduce_tokens_below_limit(self, docs: List[Document]) ->List[Document]: num_docs = len(docs) if self.reduce_k_below_max_tokens and isinstance(self. combine_documents_chain, StuffDocumentsChain): tokens = [self.combine_documents_chain.llm_chain._get_num_tokens( doc.page_content) ...
null
test_docugami_initialization
"""Test correct initialization in remote mode.""" DocugamiLoader(access_token='test', docset_id='123')
def test_docugami_initialization() ->None: """Test correct initialization in remote mode.""" DocugamiLoader(access_token='test', docset_id='123')
Test correct initialization in remote mode.
test_narrative_chain
"""Test narrative chain returns the three main elements of the causal narrative as a pydantic object. """ narrative_chain = NarrativeChain.from_univariate_prompt(llm=self.fake_llm) output = narrative_chain( 'jan has three times the number of pets as marcia. marcia has two more pets than cindy.if cin...
def test_narrative_chain(self) ->None: """Test narrative chain returns the three main elements of the causal narrative as a pydantic object. """ narrative_chain = NarrativeChain.from_univariate_prompt(llm=self.fake_llm) output = narrative_chain( 'jan has three times the number of pet...
Test narrative chain returns the three main elements of the causal narrative as a pydantic object.
test_add_texts
retriever.add_texts(['hello world', 'foo bar', 'baz qux'], [{'a': 1}, {'b': 2}, {'c': 3}]) assert retriever.client.count(retriever.collection_name, exact=True).count == 3 retriever.add_texts(['hello world', 'foo bar', 'baz qux']) assert retriever.client.count(retriever.collection_name, exact=True).count == 6
def test_add_texts(retriever: QdrantSparseVectorRetriever) ->None: retriever.add_texts(['hello world', 'foo bar', 'baz qux'], [{'a': 1}, { 'b': 2}, {'c': 3}]) assert retriever.client.count(retriever.collection_name, exact=True ).count == 3 retriever.add_texts(['hello world', 'foo bar', 'baz ...
null
example_jinja2_prompt
example_template = '{{ word }}: {{ antonym }}' examples = [{'word': 'happy', 'antonym': 'sad'}, {'word': 'tall', 'antonym': 'short'}] return PromptTemplate(input_variables=['word', 'antonym'], template= example_template, template_format='jinja2'), examples
@pytest.fixture() @pytest.mark.requires('jinja2') def example_jinja2_prompt() ->Tuple[PromptTemplate, List[Dict[str, str]]]: example_template = '{{ word }}: {{ antonym }}' examples = [{'word': 'happy', 'antonym': 'sad'}, {'word': 'tall', 'antonym': 'short'}] return PromptTemplate(input_variables=['w...
null
get_format_instructions
examples = comma_list(_generate_random_datetime_strings(self.format)) return f"""Write a datetime string that matches the following pattern: '{self.format}'. Examples: {examples} Return ONLY this string, no other words!"""
def get_format_instructions(self) ->str: examples = comma_list(_generate_random_datetime_strings(self.format)) return f"""Write a datetime string that matches the following pattern: '{self.format}'. Examples: {examples} Return ONLY this string, no other words!"""
null
invoke
"""Invoke assistant. Args: input: Runnable input dict that can have: content: User message when starting a new run. thread_id: Existing thread to use. run_id: Existing run to use. Should only be supplied when providing the tool out...
def invoke(self, input: dict, config: Optional[RunnableConfig]=None ) ->OutputType: """Invoke assistant. Args: input: Runnable input dict that can have: content: User message when starting a new run. thread_id: Existing thread to use. run_id: ...
Invoke assistant. Args: input: Runnable input dict that can have: content: User message when starting a new run. thread_id: Existing thread to use. run_id: Existing run to use. Should only be supplied when providing the tool output for a required action after an initial invocati...
parse
try: expected_keys = ['destination', 'next_inputs'] parsed = parse_and_check_json_markdown(text, expected_keys) if not isinstance(parsed['destination'], str): raise ValueError("Expected 'destination' to be a string.") if not isinstance(parsed['next_inputs'], self.next_inputs_type): raise...
def parse(self, text: str) ->Dict[str, Any]: try: expected_keys = ['destination', 'next_inputs'] parsed = parse_and_check_json_markdown(text, expected_keys) if not isinstance(parsed['destination'], str): raise ValueError("Expected 'destination' to be a string.") if not is...
null
test_chat_bedrock
"""Test BedrockChat wrapper.""" system = SystemMessage(content='You are a helpful assistant.') human = HumanMessage(content='Hello') response = chat([system, human]) assert isinstance(response, BaseMessage) assert isinstance(response.content, str)
@pytest.mark.scheduled def test_chat_bedrock(chat: BedrockChat) ->None: """Test BedrockChat wrapper.""" system = SystemMessage(content='You are a helpful assistant.') human = HumanMessage(content='Hello') response = chat([system, human]) assert isinstance(response, BaseMessage) assert isinstance...
Test BedrockChat wrapper.
_import_pai_eas_endpoint
from langchain_community.llms.pai_eas_endpoint import PaiEasEndpoint return PaiEasEndpoint
def _import_pai_eas_endpoint() ->Any: from langchain_community.llms.pai_eas_endpoint import PaiEasEndpoint return PaiEasEndpoint
null
_generate
message_dicts = self._create_message_dicts(messages) params = {'model': self.model, 'messages': message_dicts, **self. model_kwargs, **kwargs} response = completion_with_retry(self, self.use_retry, run_manager= run_manager, stop=stop, **params) return self._create_chat_result(response)
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->ChatResult: message_dicts = self._create_message_dicts(messages) params = {'model': self.model, 'messages': message_dicts, **self. model_kwarg...
null
_strremoveprefix
"""str.removeprefix() is only available in Python 3.9+.""" return s.replace(prefix, '', 1) if s.startswith(prefix) else s
def _strremoveprefix(s: str, prefix: str) ->str: """str.removeprefix() is only available in Python 3.9+.""" return s.replace(prefix, '', 1) if s.startswith(prefix) else s
str.removeprefix() is only available in Python 3.9+.
test_input_dict
runnable = RunnableLambda(lambda input: 'you said: ' + '\n'.join(str(m. content) for m in input['messages'] if isinstance(m, HumanMessage))) get_session_history = _get_get_session_history() with_history = RunnableWithMessageHistory(runnable, get_session_history, input_messages_key='messages') config: RunnableCo...
def test_input_dict() ->None: runnable = RunnableLambda(lambda input: 'you said: ' + '\n'.join(str(m. content) for m in input['messages'] if isinstance(m, HumanMessage))) get_session_history = _get_get_session_history() with_history = RunnableWithMessageHistory(runnable, get_session_history, ...
null
_call
"""Call out to a ChatGLM LLM 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 a ChatGLM LLM inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use whe...
Call out to a ChatGLM LLM 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 = chatglm_llm("Who are you?")
on_tool_end
"""Do nothing when tool ends.""" pass
def on_tool_end(self, output: str, observation_prefix: Optional[str]=None, llm_prefix: Optional[str]=None, **kwargs: Any) ->None: """Do nothing when tool ends.""" pass
Do nothing when tool ends.