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]) return vector_a, vector_b
@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.92559664, 0.07103606, 0.0871293, 0.0202184, 0.83261985, 0.77815675, 0.87001215]) return vector_a, vector_b
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_to_id[2]: Document(page_content='baz')}) assert docsearch.docstore.__dict__ == expected_docstore.__dict__ query_vec = FakeEmbeddings().embed_query(text='foo') output = docsearch.similarity_search_with_score_by_vector(query_vec, k=2, score_threshold=0.2) assert len(output) == 1 assert output[0][0] == Document(page_content='foo') assert output[0][1] < 0.2
@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_docstore = InMemoryDocstore({index_to_id[0]: Document( page_content='foo'), index_to_id[1]: Document(page_content='bar'), index_to_id[2]: Document(page_content='baz')}) assert docsearch.docstore.__dict__ == expected_docstore.__dict__ query_vec = FakeEmbeddings().embed_query(text='foo') output = docsearch.similarity_search_with_score_by_vector(query_vec, k= 2, score_threshold=0.2) assert len(output) == 1 assert output[0][0] == Document(page_content='foo') assert output[0][1] < 0.2
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', 'collection': 'restaurants'})]
@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': '2', 'room': '2'}}", metadata ={'database': 'sample_restaurants', 'collection': 'restaurants'})]
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 == 'test_section' assert loader.page_title == 'test_title' assert loader.access_token == 'access_token' assert loader._headers == {'Authorization': 'Bearer access_token'}
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_name == 'test_notebook' assert loader.section_name == 'test_section' assert loader.page_title == 'test_title' assert loader.access_token == 'access_token' assert loader._headers == {'Authorization': 'Bearer access_token'}
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 metadata assert 'description' in metadata assert 'publish_date' in metadata assert 'keywords' in metadata assert 'summary' in metadata
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 'link' in metadata assert 'authors' in metadata assert 'language' in metadata assert 'description' in metadata assert 'publish_date' in metadata assert 'keywords' in metadata assert 'summary' in metadata
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/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html. workspace_name: name of the workspace in Argilla where the specified `FeedbackDataset` lives in. Defaults to `None`, which means that the default workspace will be used. api_url: URL of the Argilla Server that we want to use, and where the `FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `ARGILLA_API_KEY` environment variable or the default will be used. Raises: ImportError: if the `argilla` package is not installed. ConnectionError: if the connection to Argilla fails. FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails. """ super().__init__() try: import argilla as rg self.ARGILLA_VERSION = rg.__version__ except ImportError: raise ImportError( 'To use the Argilla callback manager you need to have the `argilla` Python package installed. Please install it with `pip install argilla`' ) if parse(self.ARGILLA_VERSION) < parse('1.8.0'): raise ImportError( f'The installed `argilla` version is {self.ARGILLA_VERSION} but `ArgillaCallbackHandler` requires at least version 1.8.0. Please upgrade `argilla` with `pip install --upgrade argilla`.' ) if api_url is None and os.getenv('ARGILLA_API_URL') is None: warnings.warn( f'Since `api_url` is None, and the env var `ARGILLA_API_URL` is not set, it will default to `{self.DEFAULT_API_URL}`, which is the default API URL in Argilla Quickstart.' ) api_url = self.DEFAULT_API_URL if api_key is None and os.getenv('ARGILLA_API_KEY') is None: self.DEFAULT_API_KEY = 'admin.apikey' if parse(self.ARGILLA_VERSION ) < parse('1.11.0') else 'owner.apikey' warnings.warn( f'Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not set, it will default to `{self.DEFAULT_API_KEY}`, which is the default API key in Argilla Quickstart.' ) api_url = self.DEFAULT_API_URL try: rg.init(api_key=api_key, api_url=api_url) except Exception as e: raise ConnectionError( f"""Could not connect to Argilla with exception: '{e}'. Please check your `api_key` and `api_url`, and make sure that the Argilla server is up and running. If the problem persists please report it to {self.ISSUES_URL} as an `integration` issue.""" ) from e self.dataset_name = dataset_name self.workspace_name = workspace_name or rg.get_workspace() try: extra_args = {} if parse(self.ARGILLA_VERSION) < parse('1.14.0'): warnings.warn( f'You have Argilla {self.ARGILLA_VERSION}, but Argilla 1.14.0 or higher is recommended.' , UserWarning) extra_args = {'with_records': False} self.dataset = rg.FeedbackDataset.from_argilla(name=self.dataset_name, workspace=self.workspace_name, **extra_args) except Exception as e: raise FileNotFoundError( f"""`FeedbackDataset` retrieval from Argilla failed with exception `{e}`. Please check that the dataset with name={self.dataset_name} in the workspace={self.workspace_name} exists in advance. If you need help on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}. If the problem persists please report it to {self.ISSUES_URL} as an `integration` issue.""" ) from e supported_fields = ['prompt', 'response'] if supported_fields != [field.name for field in self.dataset.fields]: raise ValueError( f'`FeedbackDataset` with name={self.dataset_name} in the workspace={self.workspace_name} had fields that are not supported yet for the`langchain` integration. Supported fields are: {supported_fields}, and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}. For more information on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}.' ) self.prompts: Dict[str, List[str]] = {} warnings.warn( f'The `ArgillaCallbackHandler` is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to {self.ISSUES_URL} as an `integration` issue.' )
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 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_argilla_callback_in_langchain.html. workspace_name: name of the workspace in Argilla where the specified `FeedbackDataset` lives in. Defaults to `None`, which means that the default workspace will be used. api_url: URL of the Argilla Server that we want to use, and where the `FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `ARGILLA_API_KEY` environment variable or the default will be used. Raises: ImportError: if the `argilla` package is not installed. ConnectionError: if the connection to Argilla fails. FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails. """ super().__init__() try: import argilla as rg self.ARGILLA_VERSION = rg.__version__ except ImportError: raise ImportError( 'To use the Argilla callback manager you need to have the `argilla` Python package installed. Please install it with `pip install argilla`' ) if parse(self.ARGILLA_VERSION) < parse('1.8.0'): raise ImportError( f'The installed `argilla` version is {self.ARGILLA_VERSION} but `ArgillaCallbackHandler` requires at least version 1.8.0. Please upgrade `argilla` with `pip install --upgrade argilla`.' ) if api_url is None and os.getenv('ARGILLA_API_URL') is None: warnings.warn( f'Since `api_url` is None, and the env var `ARGILLA_API_URL` is not set, it will default to `{self.DEFAULT_API_URL}`, which is the default API URL in Argilla Quickstart.' ) api_url = self.DEFAULT_API_URL if api_key is None and os.getenv('ARGILLA_API_KEY') is None: self.DEFAULT_API_KEY = 'admin.apikey' if parse(self.ARGILLA_VERSION ) < parse('1.11.0') else 'owner.apikey' warnings.warn( f'Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not set, it will default to `{self.DEFAULT_API_KEY}`, which is the default API key in Argilla Quickstart.' ) api_url = self.DEFAULT_API_URL try: rg.init(api_key=api_key, api_url=api_url) except Exception as e: raise ConnectionError( f"""Could not connect to Argilla with exception: '{e}'. Please check your `api_key` and `api_url`, and make sure that the Argilla server is up and running. If the problem persists please report it to {self.ISSUES_URL} as an `integration` issue.""" ) from e self.dataset_name = dataset_name self.workspace_name = workspace_name or rg.get_workspace() try: extra_args = {} if parse(self.ARGILLA_VERSION) < parse('1.14.0'): warnings.warn( f'You have Argilla {self.ARGILLA_VERSION}, but Argilla 1.14.0 or higher is recommended.' , UserWarning) extra_args = {'with_records': False} self.dataset = rg.FeedbackDataset.from_argilla(name=self. dataset_name, workspace=self.workspace_name, **extra_args) except Exception as e: raise FileNotFoundError( f"""`FeedbackDataset` retrieval from Argilla failed with exception `{e}`. Please check that the dataset with name={self.dataset_name} in the workspace={self.workspace_name} exists in advance. If you need help on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}. If the problem persists please report it to {self.ISSUES_URL} as an `integration` issue.""" ) from e supported_fields = ['prompt', 'response'] if supported_fields != [field.name for field in self.dataset.fields]: raise ValueError( f'`FeedbackDataset` with name={self.dataset_name} in the workspace={self.workspace_name} had fields that are not supported yet for the`langchain` integration. Supported fields are: {supported_fields}, and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}. For more information on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}.' ) self.prompts: Dict[str, List[str]] = {} warnings.warn( f'The `ArgillaCallbackHandler` is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to {self.ISSUES_URL} as an `integration` issue.' )
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_argilla_callback_in_langchain.html. workspace_name: name of the workspace in Argilla where the specified `FeedbackDataset` lives in. Defaults to `None`, which means that the default workspace will be used. api_url: URL of the Argilla Server that we want to use, and where the `FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `ARGILLA_API_KEY` environment variable or the default will be used. Raises: ImportError: if the `argilla` package is not installed. ConnectionError: if the connection to Argilla fails. FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
__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 = boto3.resource('dynamodb', endpoint_url=endpoint_url) else: client = boto3.resource('dynamodb') self.table = client.Table(table_name) self.session_id = session_id self.key: Dict = key or {primary_key_name: session_id} if kms_key_id: try: from dynamodb_encryption_sdk.encrypted.table import EncryptedTable from dynamodb_encryption_sdk.identifiers import CryptoAction from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions except ImportError as e: raise ImportError( 'Unable to import dynamodb_encryption_sdk, please install with `pip install dynamodb-encryption-sdk`.' ) from e actions = AttributeActions(default_action=CryptoAction.DO_NOTHING, attribute_actions={'History': CryptoAction.ENCRYPT_AND_SIGN}) aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=kms_key_id) self.table = EncryptedTable(table=self.table, materials_provider= aws_kms_cmp, attribute_actions=actions, auto_refresh_table_indexes= False)
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', 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 = boto3.resource('dynamodb', endpoint_url=endpoint_url) else: client = boto3.resource('dynamodb') self.table = client.Table(table_name) self.session_id = session_id self.key: Dict = key or {primary_key_name: session_id} if kms_key_id: try: from dynamodb_encryption_sdk.encrypted.table import EncryptedTable from dynamodb_encryption_sdk.identifiers import CryptoAction from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions except ImportError as e: raise ImportError( 'Unable to import dynamodb_encryption_sdk, please install with `pip install dynamodb-encryption-sdk`.' ) from e actions = AttributeActions(default_action=CryptoAction.DO_NOTHING, attribute_actions={'History': CryptoAction.ENCRYPT_AND_SIGN}) aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=kms_key_id) self.table = EncryptedTable(table=self.table, materials_provider= aws_kms_cmp, attribute_actions=actions, auto_refresh_table_indexes=False)
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=embedding, table_name=table_name) vector_db._add_vectors(embeddings, docs, ids) return vector_db
@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 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=embedding, table_name=table_name) vector_db._add_vectors(embeddings, docs, ids) return vector_db
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: Observation1 Thought: Log2 Observation: Observation2 Thought: Log3 Observation: Observation3 Thought: """ assert format_log_to_str(intermediate_steps) == expected_result
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'), 'Observation3')] expected_result = """Log1 Observation: Observation1 Thought: Log2 Observation: Observation2 Thought: Log3 Observation: Observation3 Thought: """ assert format_log_to_str(intermediate_steps) == expected_result
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}:{response.status_code} {response.text}') raise ValueError('Error pushing field') else: uuid = response.json()['uuid'] logger.info(f'Field {id} pushed in queue, uuid: {uuid}') self._results[id] = {'uuid': uuid, 'status': 'pending'} return uuid
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_code != 200: logger.info( f'Error pushing field {id}:{response.status_code} {response.text}') raise ValueError('Error pushing field') else: uuid = response.json()['uuid'] logger.info(f'Field {id} pushed in queue, uuid: {uuid}') self._results[id] = {'uuid': uuid, 'status': 'pending'} return uuid
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 self._return(next_step_output, run_manager=run_manager) self.intermediate_steps.extend(next_step_output) logger.debug('Updated intermediate_steps with step output') if len(next_step_output) == 1: next_step_action = next_step_output[0] tool_return = self.agent_executor._get_tool_return(next_step_action) if tool_return is not None: return self._return(tool_return, run_manager=run_manager) return AddableDict(intermediate_step=next_step_output)
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 output of Agent loop step') if isinstance(next_step_output, AgentFinish): logger.debug( 'Hit AgentFinish: _return -> on_chain_end -> run final output logic' ) return self._return(next_step_output, run_manager=run_manager) self.intermediate_steps.extend(next_step_output) logger.debug('Updated intermediate_steps with step output') if len(next_step_output) == 1: next_step_action = next_step_output[0] tool_return = self.agent_executor._get_tool_return(next_step_action) if tool_return is not None: return self._return(tool_return, run_manager=run_manager) return AddableDict(intermediate_step=next_step_output)
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' + _colored_text if run_manager: run_manager.on_text(_text, end='\n', verbose=self.verbose) if 'stop' in inputs and inputs['stop'] != stop: raise ValueError( 'If `stop` is present in any inputs, should be present in all.') return prompt, stop
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.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), 'green') _text = 'Prompt after formatting:\n' + _colored_text if run_manager: run_manager.on_text(_text, end='\n', verbose=self.verbose) if 'stop' in inputs and inputs['stop'] != stop: raise ValueError( 'If `stop` is present in any inputs, should be present in all.') return prompt, stop
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.outputs or {}).get('llm_output', {}) base_span.results = [self.trace_tree.Result(inputs={'prompt': prompt}, outputs={f'gen_{g_i}': gen['text'] for g_i, gen in enumerate(run. outputs['generations'][ndx])} if run.outputs is not None and len(run. outputs['generations']) > ndx and len(run.outputs['generations'][ndx]) > 0 else None) for ndx, prompt in enumerate(run.inputs['prompts'] or [])] base_span.span_kind = self.trace_tree.SpanKind.LLM return base_span
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: base_span.attributes = {} base_span.attributes['llm_output'] = (run.outputs or {}).get('llm_output', {}) base_span.results = [self.trace_tree.Result(inputs={'prompt': prompt}, outputs={f'gen_{g_i}': gen['text'] for g_i, gen in enumerate(run. outputs['generations'][ndx])} if run.outputs is not None and len( run.outputs['generations']) > ndx and len(run.outputs['generations' ][ndx]) > 0 else None) for ndx, prompt in enumerate(run.inputs[ 'prompts'] or [])] base_span.span_kind = self.trace_tree.SpanKind.LLM return base_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.
_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 in self.metadata_keys}) return create_model('MapRerankOutput', **schema)
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': response} tokens, log_probs = self.response_chain.generate_tokens_and_log_probs( _input, run_manager=_run_manager) low_confidence_spans = _low_confidence_spans(tokens, log_probs, self. min_prob, self.min_token_gap, self.num_pad_tokens) initial_response = response.strip() + ' ' + ''.join(tokens) if not low_confidence_spans: response = initial_response final_response, finished = self.output_parser.parse_folder(response) if finished: return {self.output_keys[0]: final_response} continue marginal, finished = self._do_retrieval(low_confidence_spans, _run_manager, user_input, response, initial_response) response = response.strip() + ' ' + marginal if finished: break return {self.output_keys[0]: response}
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_text(f'Current Response: {response}', color='blue', end='\n') _input = {'user_input': user_input, 'context': '', 'response': response } tokens, log_probs = self.response_chain.generate_tokens_and_log_probs( _input, run_manager=_run_manager) low_confidence_spans = _low_confidence_spans(tokens, log_probs, self.min_prob, self.min_token_gap, self.num_pad_tokens) initial_response = response.strip() + ' ' + ''.join(tokens) if not low_confidence_spans: response = initial_response final_response, finished = self.output_parser.parse_folder(response ) if finished: return {self.output_keys[0]: final_response} continue marginal, finished = self._do_retrieval(low_confidence_spans, _run_manager, user_input, response, initial_response) response = response.strip() + ' ' + marginal if finished: break return {self.output_keys[0]: response}
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) == 2 assert drop(docsearch.index_name)
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_threshold': 0.1}) results = retriever.get_relevant_documents('foo') assert len(results) == 2 assert drop(docsearch.index_name)
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._text_field) score = doc.score docs.append((Document(page_content=text, metadata=metadata), score)) return docs
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 ValueError( f'Fail to query docs by vector, error {self._collection.message}') docs = [] for doc in ret: metadata = doc.fields text = metadata.pop(self._text_field) score = doc.score docs.append((Document(page_content=text, metadata=metadata), score)) return docs
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]], **kwargs: Any) ->Optional[bool]: await self.initialize() return await self.adelete(ids=ids, **kwargs) return asyncio.run(_delete(ids, **kwargs))
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, False otherwise. """ async def _delete(ids: Optional[List[str]], **kwargs: Any) ->Optional[bool ]: await self.initialize() return await self.adelete(ids=ids, **kwargs) return asyncio.run(_delete(ids, **kwargs))
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 None: ids = [str(uuid.uuid1()) for _ in texts] if not metadatas: metadatas = [{} for _ in texts] records = list(zip(ids, metadatas, texts, embeddings)) self.sync_client.upsert(records) return ids
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. embeddings: List of list of embedding vectors. metadatas: List of metadatas associated with the texts. kwargs: vectorstore specific parameters """ if ids is None: ids = [str(uuid.uuid1()) for _ in texts] if not metadatas: metadatas = [{} for _ in texts] records = list(zip(ids, metadatas, texts, embeddings)) self.sync_client.upsert(records) return ids
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 model_name: assert llm.client.model_name == 'models/gemini-pro' else: assert llm.model == 'models/text-bison-001'
@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_tokens=10) output = llm('Say foo:') assert isinstance(output, str) assert llm._llm_type == 'google_palm' if model_name and 'gemini' in model_name: assert llm.client.model_name == 'models/gemini-pro' else: assert llm.model == 'models/text-bison-001'
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. Returns: A prompt template to pass into this agent. """ _prompts = extra_prompt_messages or [] messages: List[Union[BaseMessagePromptTemplate, BaseMessage]] if system_message: messages = [system_message] else: messages = [] messages.extend([*_prompts, HumanMessagePromptTemplate.from_template( '{input}'), MessagesPlaceholder(variable_name='agent_scratchpad')]) return ChatPromptTemplate(messages=messages)
@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: 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. """ _prompts = extra_prompt_messages or [] messages: List[Union[BaseMessagePromptTemplate, BaseMessage]] if system_message: messages = [system_message] else: messages = [] messages.extend([*_prompts, HumanMessagePromptTemplate.from_template( '{input}'), MessagesPlaceholder(variable_name='agent_scratchpad')]) return ChatPromptTemplate(messages=messages)
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.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)
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)): docs.append(doc) return docs
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]: if (doc := self._result_to_document(result)): docs.append(doc) return docs
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 openai. You can install with `pip install "openai>=1.1"`.' ) from e
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 AttributeError( 'Please make sure you are using a v1.1-compatible version of openai. You can install with `pip install "openai>=1.1"`.' ) from e
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. fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 50 lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. kwargs: any other querying variable in VectaraQueryConfig Returns: List of Documents selected by maximal marginal relevance. """ kwargs['mmr_config'] = MMRConfig(is_enabled=True, mmr_k=fetch_k, diversity_bias=1 - lambda_mult) return self.similarity_search(query, **kwargs)
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. 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 to MMR algorithm. Defaults to 50 lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. kwargs: any other querying variable in VectaraQueryConfig Returns: List of Documents selected by maximal marginal relevance. """ kwargs['mmr_config'] = MMRConfig(is_enabled=True, mmr_k=fetch_k, diversity_bias=1 - lambda_mult) return self.similarity_search(query, **kwargs)
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 to MMR algorithm. Defaults to 50 lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. kwargs: any other querying variable in VectaraQueryConfig Returns: List of Documents selected by maximal marginal relevance.
_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['llm'], prompt=PROMPT) return values
@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 in values and values['llm'] is not None: values['llm_chain'] = LLMChain(llm=values['llm'], prompt=PROMPT) return values
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.get('delta', msg.get('message', {'content': ''})) elif 'data' in msg: msg = msg.get('data', [{}])[0] content_holder = msg for k, v in msg.items(): if k in ('content',) and k in content_buffer: content_buffer[k] += v else: content_buffer[k] = v if is_stopped: break content_holder = {**content_holder, **content_buffer} return content_holder, is_stopped
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('choices', [{}])[0] is_stopped = msg.get('finish_reason', '') == 'stop' msg = msg.get('delta', msg.get('message', {'content': ''})) elif 'data' in msg: msg = msg.get('data', [{}])[0] content_holder = msg for k, v in msg.items(): if k in ('content',) and k in content_buffer: content_buffer[k] += v else: content_buffer[k] = v if is_stopped: break content_holder = {**content_holder, **content_buffer} return content_holder, is_stopped
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_parameters = langchain_asset.llm.dict() else: llm_parameters = langchain_asset.dict() except Exception: return {} return llm_parameters
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 = langchain_asset.llm_chain.llm.dict() elif hasattr(langchain_asset, 'llm'): llm_parameters = langchain_asset.llm.dict() else: llm_parameters = langchain_asset.dict() except Exception: return {} return llm_parameters
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(response.content, str)
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]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
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.foundation_models.v1.foundation_models_service_pb2_grpc import TextGenerationServiceStub except ImportError as e: raise ImportError( 'Please install YandexCloud SDK with `pip install yandexcloud`.' ) from e channel_credentials = grpc.ssl_channel_credentials() channel = grpc.secure_channel(self.url, channel_credentials) request = CompletionRequest(model_uri=self.model_uri, completion_options= CompletionOptions(temperature=DoubleValue(value=self.temperature), max_tokens=Int64Value(value=self.max_tokens)), messages=[Message(role= 'user', text=prompt)]) stub = TextGenerationServiceStub(channel) res = stub.Completion(request, metadata=self._grpc_metadata) return list(res)[0].alternatives[0].message.text
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.foundation_models_service_pb2 import CompletionRequest from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import TextGenerationServiceStub except ImportError as e: raise ImportError( 'Please install YandexCloud SDK with `pip install yandexcloud`.' ) from e channel_credentials = grpc.ssl_channel_credentials() channel = grpc.secure_channel(self.url, channel_credentials) request = CompletionRequest(model_uri=self.model_uri, completion_options=CompletionOptions(temperature=DoubleValue(value= self.temperature), max_tokens=Int64Value(value=self.max_tokens)), messages=[Message(role='user', text=prompt)]) stub = TextGenerationServiceStub(channel) res = stub.Completion(request, metadata=self._grpc_metadata) return list(res)[0].alternatives[0].message.text
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_time < time_at_least: raise AssertionError(f'Time sync issue: {update_time} < {time_at_least}') records_to_upsert = [{'key': key, 'namespace': self.namespace, 'updated_at': update_time, 'group_id': group_id} for key, group_id in zip(keys, group_ids)] with self._make_session() as session: if self.dialect == 'sqlite': from sqlalchemy.dialects.sqlite import insert as sqlite_insert insert_stmt = sqlite_insert(UpsertionRecord).values(records_to_upsert) stmt = insert_stmt.on_conflict_do_update([UpsertionRecord.key, UpsertionRecord.namespace], set_=dict(updated_at=insert_stmt. excluded.updated_at, group_id=insert_stmt.excluded.group_id)) elif self.dialect == 'postgresql': from sqlalchemy.dialects.postgresql import insert as pg_insert insert_stmt = pg_insert(UpsertionRecord).values(records_to_upsert) stmt = insert_stmt.on_conflict_do_update('uix_key_namespace', set_= dict(updated_at=insert_stmt.excluded.updated_at, group_id= insert_stmt.excluded.group_id)) else: raise NotImplementedError(f'Unsupported dialect {self.dialect}') session.execute(stmt) session.commit()
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( 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_time < time_at_least: raise AssertionError( f'Time sync issue: {update_time} < {time_at_least}') records_to_upsert = [{'key': key, 'namespace': self.namespace, 'updated_at': update_time, 'group_id': group_id} for key, group_id in zip(keys, group_ids)] with self._make_session() as session: if self.dialect == 'sqlite': from sqlalchemy.dialects.sqlite import insert as sqlite_insert insert_stmt = sqlite_insert(UpsertionRecord).values( records_to_upsert) stmt = insert_stmt.on_conflict_do_update([UpsertionRecord.key, UpsertionRecord.namespace], set_=dict(updated_at= insert_stmt.excluded.updated_at, group_id=insert_stmt. excluded.group_id)) elif self.dialect == 'postgresql': from sqlalchemy.dialects.postgresql import insert as pg_insert insert_stmt = pg_insert(UpsertionRecord).values(records_to_upsert) stmt = insert_stmt.on_conflict_do_update('uix_key_namespace', set_=dict(updated_at=insert_stmt.excluded.updated_at, group_id=insert_stmt.excluded.group_id)) else: raise NotImplementedError(f'Unsupported dialect {self.dialect}') session.execute(stmt) session.commit()
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(client, cache_name) set_llm_cache(llm_cache) yield llm_cache finally: client.delete_cache(cache_name)
@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('MOMENTO_API_KEY'), default_ttl=timedelta (seconds=30)) try: llm_cache = MomentoCache(client, cache_name) set_llm_cache(llm_cache) yield llm_cache finally: client.delete_cache(cache_name)
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, additional_doc_metadata=additional_metadata) else: raise Exception( f'Failed to download {url} (status: {response.status_code})')
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('GET', url, headers={'Authorization': f'Bearer {self.access_token}'}, data={}) if response.ok: return self._parse_dgml(content=response.content, document_name= document_name, additional_doc_metadata=additional_metadata) else: raise Exception( f'Failed to download {url} (status: {response.status_code})')
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 memory2.chat_memory.messages == [] memory2.chat_memory.clear() assert memory1.chat_memory.messages != [] memory1.chat_memory.clear() assert memory1.chat_memory.messages == []
@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 = 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 memory2.chat_memory.messages == [] memory2.chat_memory.clear() assert memory1.chat_memory.messages != [] memory1.chat_memory.clear() assert memory1.chat_memory.messages == []
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: `pip install -U docarray`.' ) except ImportError: raise ImportError( 'Could not import docarray python package. Please install it with `pip install "langchain[docarray]"`.' )
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, received: {docarray.__version__}.To upgrade, please run: `pip install -U docarray`.' ) except ImportError: raise ImportError( 'Could not import docarray python package. Please install it with `pip install "langchain[docarray]"`.' )
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 = remove_exact_and_partial_keys(serialized) return 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. """ serialized = handle_id_and_kwargs(serialized, root=True) serialized = remove_exact_and_partial_keys(serialized) return 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.
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: DatabricksVectorSearch(index, text_column=DEFAULT_TEXT_COLUMN) assert '`embedding` is required for this index.' in str(ex.value)
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'].get('total_tokens', 0) self.completion_tokens = response.llm_output['token_usage'].get( 'completion_tokens', 0) else: self.prompt_tokens = self.total_tokens = self.completion_tokens = 0 for generations in response.generations: for generation in generations: prompt = self.prompt_records[self.step] self.step = self.step + 1 prompt_embedding = pd.Series(self.generator.generate_embeddings( text_col=pd.Series(prompt.replace('\n', ' '))).reset_index(drop =True)) response_text = generation.text.replace('\n', ' ') response_embedding = pd.Series(self.generator.generate_embeddings( text_col=pd.Series(generation.text.replace('\n', ' '))). reset_index(drop=True)) pred_timestamp = datetime.now().timestamp() columns = ['prediction_ts', 'response', 'prompt', 'response_vector', 'prompt_vector', 'prompt_token', 'completion_token', 'total_token'] data = [[pred_timestamp, response_text, prompt, response_embedding[ 0], prompt_embedding[0], self.prompt_tokens, self.total_tokens, self.completion_tokens]] df = pd.DataFrame(data, columns=columns) prompt_columns = EmbeddingColumnNames(vector_column_name= 'prompt_vector', data_column_name='prompt') response_columns = EmbeddingColumnNames(vector_column_name= 'response_vector', data_column_name='response') schema = Schema(timestamp_column_name='prediction_ts', tag_column_names=['prompt_token', 'completion_token', 'total_token'], prompt_column_names=prompt_columns, response_column_names=response_columns) response_from_arize = self.arize_client.log(dataframe=df, schema= schema, model_id=self.model_id, model_version=self. model_version, model_type=ModelTypes.GENERATIVE_LLM, environment=Environments.PRODUCTION) if response_from_arize.status_code == 200: print('✅ Successfully logged data to Arize!') else: print(f'❌ Logging failed "{response_from_arize.text}"')
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( 'prompt_tokens', 0) self.total_tokens = response.llm_output['token_usage'].get( 'total_tokens', 0) self.completion_tokens = response.llm_output['token_usage'].get( 'completion_tokens', 0) else: self.prompt_tokens = self.total_tokens = self.completion_tokens = 0 for generations in response.generations: for generation in generations: prompt = self.prompt_records[self.step] self.step = self.step + 1 prompt_embedding = pd.Series(self.generator.generate_embeddings (text_col=pd.Series(prompt.replace('\n', ' '))).reset_index (drop=True)) response_text = generation.text.replace('\n', ' ') response_embedding = pd.Series(self.generator. generate_embeddings(text_col=pd.Series(generation.text. replace('\n', ' '))).reset_index(drop=True)) pred_timestamp = datetime.now().timestamp() columns = ['prediction_ts', 'response', 'prompt', 'response_vector', 'prompt_vector', 'prompt_token', 'completion_token', 'total_token'] data = [[pred_timestamp, response_text, prompt, response_embedding[0], prompt_embedding[0], self. prompt_tokens, self.total_tokens, self.completion_tokens]] df = pd.DataFrame(data, columns=columns) prompt_columns = EmbeddingColumnNames(vector_column_name= 'prompt_vector', data_column_name='prompt') response_columns = EmbeddingColumnNames(vector_column_name= 'response_vector', data_column_name='response') schema = Schema(timestamp_column_name='prediction_ts', tag_column_names=['prompt_token', 'completion_token', 'total_token'], prompt_column_names=prompt_columns, response_column_names=response_columns) response_from_arize = self.arize_client.log(dataframe=df, schema=schema, model_id=self.model_id, model_version=self. model_version, model_type=ModelTypes.GENERATIVE_LLM, environment=Environments.PRODUCTION) if response_from_arize.status_code == 200: print('✅ Successfully logged data to Arize!') else: print(f'❌ Logging failed "{response_from_arize.text}"')
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, filter=filter) documents = [d[0] for d in docs_and_scores] return documents
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: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(query, k, filter=filter ) documents = [d[0] for d in docs_and_scores] return documents
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 self.sample_size > 0: if self.randomize_sample: randomizer = random.Random(self.sample_seed ) if self.sample_seed else random randomizer.shuffle(items) items = items[:min(len(items), self.sample_size)] pbar = None if self.show_progress: try: from tqdm import tqdm pbar = tqdm(total=len(items)) except ImportError as e: logger.warning( 'To log the progress of DirectoryLoader you need to install tqdm, `pip install tqdm`' ) if self.silent_errors: logger.warning(e) else: raise ImportError( 'To log the progress of DirectoryLoader you need to install tqdm, `pip install tqdm`' ) if self.use_multithreading: with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_concurrency ) as executor: executor.map(lambda i: self.load_file(i, p, docs, pbar), items) else: for i in items: self.load_file(i, p, docs, pbar) if pbar: pbar.close() return docs
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(p.rglob(self.glob) if self.recursive else p.glob(self.glob)) if self.sample_size > 0: if self.randomize_sample: randomizer = random.Random(self.sample_seed ) if self.sample_seed else random randomizer.shuffle(items) items = items[:min(len(items), self.sample_size)] pbar = None if self.show_progress: try: from tqdm import tqdm pbar = tqdm(total=len(items)) except ImportError as e: logger.warning( 'To log the progress of DirectoryLoader you need to install tqdm, `pip install tqdm`' ) if self.silent_errors: logger.warning(e) else: raise ImportError( 'To log the progress of DirectoryLoader you need to install tqdm, `pip install tqdm`' ) if self.use_multithreading: with concurrent.futures.ThreadPoolExecutor(max_workers=self. max_concurrency) as executor: executor.map(lambda i: self.load_file(i, p, docs, pbar), items) else: for i in items: self.load_file(i, p, docs, pbar) if pbar: pbar.close() return docs
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_limit: num_docs -= 1 token_count -= tokens[num_docs] return docs[:num_docs]
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) for doc in docs] token_count = sum(tokens[:num_docs]) while token_count > self.max_tokens_limit: num_docs -= 1 token_count -= tokens[num_docs] return docs[:num_docs]
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 cindy has ten pets, how many pets does jan have? ' ) expected_output = {'chain_answer': None, 'chain_data': NarrativeModel( story_outcome_question='how many pets does jan have? ', story_hypothetical='if cindy has ten pets', story_plot= 'jan has three times the number of pets as marcia. marcia has two more pets than cindy.' ), 'narrative_input': 'jan has three times the number of pets as marcia. marcia has two more pets than cindy.if cindy has ten pets, how many pets does jan have? ' } assert output == expected_output
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 pets as marcia. marcia has two more pets than cindy.if cindy has ten pets, how many pets does jan have? ' ) expected_output = {'chain_answer': None, 'chain_data': NarrativeModel( story_outcome_question='how many pets does jan have? ', story_hypothetical='if cindy has ten pets', story_plot= 'jan has three times the number of pets as marcia. marcia has two more pets than cindy.' ), 'narrative_input': 'jan has three times the number of pets as marcia. marcia has two more pets than cindy.if cindy has ten pets, how many pets does jan have? ' } assert output == expected_output
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 qux']) assert retriever.client.count(retriever.collection_name, exact=True ).count == 6
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=['word', 'antonym'], template= example_template, template_format='jinja2'), examples
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 output for a required action after an initial invocation. file_ids: File ids to include in new run. Used for retrieval. message_metadata: Metadata to associate with new message. thread_metadata: Metadata to associate with new thread. Only relevant when new thread being created. instructions: Additional run instructions. model: Override Assistant model for this run. tools: Override Assistant tools for this run. run_metadata: Metadata to associate with new run. config: Runnable config: Return: If self.as_agent, will return Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise, will return OpenAI types Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]]. """ config = ensure_config(config) callback_manager = CallbackManager.configure(inheritable_callbacks=config. get('callbacks'), inheritable_tags=config.get('tags'), inheritable_metadata=config.get('metadata')) run_manager = callback_manager.on_chain_start(dumpd(self), input, name= config.get('run_name')) try: if self.as_agent and input.get('intermediate_steps'): tool_outputs = self._parse_intermediate_steps(input[ 'intermediate_steps']) run = self.client.beta.threads.runs.submit_tool_outputs(**tool_outputs) elif 'thread_id' not in input: thread = {'messages': [{'role': 'user', 'content': input['content'], 'file_ids': input.get('file_ids', []), 'metadata': input.get( 'message_metadata')}], 'metadata': input.get('thread_metadata')} run = self._create_thread_and_run(input, thread) elif 'run_id' not in input: _ = self.client.beta.threads.messages.create(input['thread_id'], content=input['content'], role='user', file_ids=input.get( 'file_ids', []), metadata=input.get('message_metadata')) run = self._create_run(input) else: run = self.client.beta.threads.runs.submit_tool_outputs(**input) run = self._wait_for_run(run.id, run.thread_id) except BaseException as e: run_manager.on_chain_error(e) raise e try: response = self._get_response(run) except BaseException as e: run_manager.on_chain_error(e, metadata=run.dict()) raise e else: run_manager.on_chain_end(response) return response
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: Existing run to use. Should only be supplied when providing the tool output for a required action after an initial invocation. file_ids: File ids to include in new run. Used for retrieval. message_metadata: Metadata to associate with new message. thread_metadata: Metadata to associate with new thread. Only relevant when new thread being created. instructions: Additional run instructions. model: Override Assistant model for this run. tools: Override Assistant tools for this run. run_metadata: Metadata to associate with new run. config: Runnable config: Return: If self.as_agent, will return Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise, will return OpenAI types Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]]. """ config = ensure_config(config) callback_manager = CallbackManager.configure(inheritable_callbacks= config.get('callbacks'), inheritable_tags=config.get('tags'), inheritable_metadata=config.get('metadata')) run_manager = callback_manager.on_chain_start(dumpd(self), input, name= config.get('run_name')) try: if self.as_agent and input.get('intermediate_steps'): tool_outputs = self._parse_intermediate_steps(input[ 'intermediate_steps']) run = self.client.beta.threads.runs.submit_tool_outputs(** tool_outputs) elif 'thread_id' not in input: thread = {'messages': [{'role': 'user', 'content': input[ 'content'], 'file_ids': input.get('file_ids', []), 'metadata': input.get('message_metadata')}], 'metadata': input.get('thread_metadata')} run = self._create_thread_and_run(input, thread) elif 'run_id' not in input: _ = self.client.beta.threads.messages.create(input['thread_id'], content=input['content'], role='user', file_ids=input.get( 'file_ids', []), metadata=input.get('message_metadata')) run = self._create_run(input) else: run = self.client.beta.threads.runs.submit_tool_outputs(**input) run = self._wait_for_run(run.id, run.thread_id) except BaseException as e: run_manager.on_chain_error(e) raise e try: response = self._get_response(run) except BaseException as e: run_manager.on_chain_error(e, metadata=run.dict()) raise e else: run_manager.on_chain_end(response) return response
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 invocation. file_ids: File ids to include in new run. Used for retrieval. message_metadata: Metadata to associate with new message. thread_metadata: Metadata to associate with new thread. Only relevant when new thread being created. instructions: Additional run instructions. model: Override Assistant model for this run. tools: Override Assistant tools for this run. run_metadata: Metadata to associate with new run. config: Runnable config: Return: If self.as_agent, will return Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise, will return OpenAI types Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].
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 ValueError( f"Expected 'next_inputs' to be {self.next_inputs_type}.") parsed['next_inputs'] = {self.next_inputs_inner_key: parsed['next_inputs']} if parsed['destination'].strip().lower() == self.default_destination.lower( ): parsed['destination'] = None else: parsed['destination'] = parsed['destination'].strip() return parsed except Exception as e: raise OutputParserException( f'Parsing text\n{text}\n raised following error:\n{e}')
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 isinstance(parsed['next_inputs'], self.next_inputs_type): raise ValueError( f"Expected 'next_inputs' to be {self.next_inputs_type}.") parsed['next_inputs'] = {self.next_inputs_inner_key: parsed[ 'next_inputs']} if parsed['destination'].strip().lower( ) == self.default_destination.lower(): parsed['destination'] = None else: parsed['destination'] = parsed['destination'].strip() return parsed except Exception as e: raise OutputParserException( f'Parsing text\n{text}\n raised following error:\n{e}')
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(response.content, str)
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_kwargs, **kwargs} response = completion_with_retry(self, self.use_retry, run_manager= run_manager, stop=stop, **params) return self._create_chat_result(response)
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: RunnableConfig = {'configurable': {'session_id': '2'}} output = with_history.invoke({'messages': [HumanMessage(content='hello')]}, config) assert output == 'you said: hello' output = with_history.invoke({'messages': [HumanMessage(content='good bye') ]}, config) assert output == """you said: hello good bye"""
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, input_messages_key='messages') config: RunnableConfig = {'configurable': {'session_id': '2'}} output = with_history.invoke({'messages': [HumanMessage(content='hello' )]}, config) assert output == 'you said: hello' output = with_history.invoke({'messages': [HumanMessage(content= 'good bye')]}, config) assert output == 'you said: hello\ngood bye'
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 response = chatglm_llm("Who are you?") """ _model_kwargs = self.model_kwargs or {} headers = {'Content-Type': 'application/json'} payload = {'prompt': prompt, 'temperature': self.temperature, 'history': self.history, 'max_length': self.max_token, 'top_p': self.top_p} payload.update(_model_kwargs) payload.update(kwargs) logger.debug(f'ChatGLM payload: {payload}') try: response = requests.post(self.endpoint_url, headers=headers, json=payload) except requests.exceptions.RequestException as e: raise ValueError(f'Error raised by inference endpoint: {e}') logger.debug(f'ChatGLM response: {response}') if response.status_code != 200: raise ValueError(f'Failed with response: {response}') try: parsed_response = response.json() if isinstance(parsed_response, dict): content_keys = 'response' if content_keys in parsed_response: text = parsed_response[content_keys] else: raise ValueError(f'No content in response : {parsed_response}') else: raise ValueError(f'Unexpected response type: {parsed_response}') except requests.exceptions.JSONDecodeError as e: raise ValueError( f"""Error raised during decoding response from inference endpoint: {e}. Response: {response.text}""" ) if stop is not None: text = enforce_stop_tokens(text, stop) if self.with_history: self.history = self.history + [[None, parsed_response['response']]] return text
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 when generating. Returns: The string generated by the model. Example: .. code-block:: python response = chatglm_llm("Who are you?") """ _model_kwargs = self.model_kwargs or {} headers = {'Content-Type': 'application/json'} payload = {'prompt': prompt, 'temperature': self.temperature, 'history': self.history, 'max_length': self.max_token, 'top_p': self.top_p} payload.update(_model_kwargs) payload.update(kwargs) logger.debug(f'ChatGLM payload: {payload}') try: response = requests.post(self.endpoint_url, headers=headers, json= payload) except requests.exceptions.RequestException as e: raise ValueError(f'Error raised by inference endpoint: {e}') logger.debug(f'ChatGLM response: {response}') if response.status_code != 200: raise ValueError(f'Failed with response: {response}') try: parsed_response = response.json() if isinstance(parsed_response, dict): content_keys = 'response' if content_keys in parsed_response: text = parsed_response[content_keys] else: raise ValueError(f'No content in response : {parsed_response}') else: raise ValueError(f'Unexpected response type: {parsed_response}') except requests.exceptions.JSONDecodeError as e: raise ValueError( f"""Error raised during decoding response from inference endpoint: {e}. Response: {response.text}""" ) if stop is not None: text = enforce_stop_tokens(text, stop) if self.with_history: self.history = self.history + [[None, parsed_response['response']]] return text
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.