method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
test_one_namespace_w_list_of_features_no_emb
str1 = 'test1' str2 = 'test2' expected = [{'test_namespace': [str1, str2]}] assert base.embed({'test_namespace': [str1, str2]}, MockEncoder()) == expected
@pytest.mark.requires('vowpal_wabbit_next') def test_one_namespace_w_list_of_features_no_emb() ->None: str1 = 'test1' str2 = 'test2' expected = [{'test_namespace': [str1, str2]}] assert base.embed({'test_namespace': [str1, str2]}, MockEncoder() ) == expected
null
__init__
super().__init__() self._lock = threading.Lock()
def __init__(self) ->None: super().__init__() self._lock = threading.Lock()
null
test_myscale
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] config = MyScaleSettings() config.table = 'test_myscale' docsearch = MyScale.from_texts(texts, FakeEmbeddings(), config=config) output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo', metadata={'_dummy': 0})] docsearch.drop()
def test_myscale() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] config = MyScaleSettings() config.table = 'test_myscale' docsearch = MyScale.from_texts(texts, FakeEmbeddings(), config=config) output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo', metadata={'_dummy': 0})] docsearch.drop()
Test end to end construction and search.
_import_spark_sql
from langchain_community.utilities.spark_sql import SparkSQL return SparkSQL
def _import_spark_sql() ->Any: from langchain_community.utilities.spark_sql import SparkSQL return SparkSQL
null
_run
"""Use the tool.""" return self.api_wrapper.run(query)
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] =None) ->str: """Use the tool.""" return self.api_wrapper.run(query)
Use the tool.
_format_chat_history
buffer = [] for human, ai in chat_history: buffer.append(HumanMessage(content=human)) buffer.append(AIMessage(content=ai)) return buffer
def _format_chat_history(chat_history: List[Tuple[str, str]]): buffer = [] for human, ai in chat_history: buffer.append(HumanMessage(content=human)) buffer.append(AIMessage(content=ai)) return buffer
null
random_string
return str(uuid.uuid4())
def random_string() ->str: return str(uuid.uuid4())
null
visit_Name
if isinstance(node.ctx, ast.Load): self.loads.add(node.id) elif isinstance(node.ctx, ast.Store): self.stores.add(node.id)
def visit_Name(self, node: ast.Name) ->Any: if isinstance(node.ctx, ast.Load): self.loads.add(node.id) elif isinstance(node.ctx, ast.Store): self.stores.add(node.id)
null
test_openai_modelname_to_contextsize_valid
"""Test model name to context size on a valid model.""" assert OpenAI().modelname_to_contextsize('davinci') == 2049
def test_openai_modelname_to_contextsize_valid() ->None: """Test model name to context size on a valid model.""" assert OpenAI().modelname_to_contextsize('davinci') == 2049
Test model name to context size on a valid model.
deanonymize
"""Deanonymize text""" return self._deanonymize(text_to_deanonymize, deanonymizer_matching_strategy)
def deanonymize(self, text_to_deanonymize: str, deanonymizer_matching_strategy: Callable[[str, MappingDataType], str]= DEFAULT_DEANONYMIZER_MATCHING_STRATEGY) ->str: """Deanonymize text""" return self._deanonymize(text_to_deanonymize, deanonymizer_matching_strategy)
Deanonymize text
test_ip
"""Test inner product distance.""" texts = ['foo', 'bar', 'baz'] docsearch = USearch.from_texts(texts, FakeEmbeddings(), metric='ip') output = docsearch.similarity_search_with_score('far', k=2) _, score = output[1] assert score == -8.0
def test_ip() ->None: """Test inner product distance.""" texts = ['foo', 'bar', 'baz'] docsearch = USearch.from_texts(texts, FakeEmbeddings(), metric='ip') output = docsearch.similarity_search_with_score('far', k=2) _, score = output[1] assert score == -8.0
Test inner product distance.
_llm_params
params: Dict[str, Any] = {'temperature': self.temperature, 'n': self.n} if self.stop: params['stop'] = self.stop if self.max_tokens is not None: params['max_tokens'] = self.max_tokens return params
@property def _llm_params(self) ->Dict[str, Any]: params: Dict[str, Any] = {'temperature': self.temperature, 'n': self.n} if self.stop: params['stop'] = self.stop if self.max_tokens is not None: params['max_tokens'] = self.max_tokens return params
null
output_keys
"""Return the output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys
@property def output_keys(self) ->List[str]: """Return the output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys
Return the output keys. :meta private:
_identifying_params
"""Get the identifying parameters.""" return {**{'model': self.model}, **self._default_params}
@property def _identifying_params(self) ->Dict[str, Any]: """Get the identifying parameters.""" return {**{'model': self.model}, **self._default_params}
Get the identifying parameters.
test_qdrant_similarity_search_filters
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i, 'metadata': {'page': i + 1, 'pages': [i + 2, -1]}} for i in range(len(texts))] docsearch = Qdrant.from_texts(texts, ConsistentFakeEmbeddings(), metadatas= metadatas, location=':memory:', batch_size=batch_size, vector_name= vector_name) output = docsearch.similarity_search('foo', k=1, filter={'page': 1, 'metadata': {'page': 2, 'pages': [3]}}) assert output == [Document(page_content='bar', metadata={'page': 1, 'metadata': {'page': 2, 'pages': [3, -1]}})]
@pytest.mark.parametrize('batch_size', [1, 64]) @pytest.mark.parametrize('vector_name', [None, 'my-vector']) def test_qdrant_similarity_search_filters(batch_size: int, vector_name: Optional[str]) ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i, 'metadata': {'page': i + 1, 'pages': [i + 2, - 1]}} for i in range(len(texts))] docsearch = Qdrant.from_texts(texts, ConsistentFakeEmbeddings(), metadatas=metadatas, location=':memory:', batch_size=batch_size, vector_name=vector_name) output = docsearch.similarity_search('foo', k=1, filter={'page': 1, 'metadata': {'page': 2, 'pages': [3]}}) assert output == [Document(page_content='bar', metadata={'page': 1, 'metadata': {'page': 2, 'pages': [3, -1]}})]
Test end to end construction and search.
get_tag
return datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
def get_tag(self) ->str: return datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
null
_import_titan_takeoff
from langchain_community.llms.titan_takeoff import TitanTakeoff return TitanTakeoff
def _import_titan_takeoff() ->Any: from langchain_community.llms.titan_takeoff import TitanTakeoff return TitanTakeoff
null
test_openllm_llm_local
llm = OpenLLM(model_name='flan-t5', model_id='google/flan-t5-small') output = llm('Say foo:') assert isinstance(output, str)
def test_openllm_llm_local() ->None: llm = OpenLLM(model_name='flan-t5', model_id='google/flan-t5-small') output = llm('Say foo:') assert isinstance(output, str)
null
test_python_repl
"""Test functionality when globals/locals are not provided.""" repl = PythonREPL() repl.run('foo = 1') assert repl.locals is not None assert repl.locals['foo'] == 1 repl.run('bar = foo * 2') assert repl.locals is not None assert repl.locals['bar'] == 2
def test_python_repl() ->None: """Test functionality when globals/locals are not provided.""" repl = PythonREPL() repl.run('foo = 1') assert repl.locals is not None assert repl.locals['foo'] == 1 repl.run('bar = foo * 2') assert repl.locals is not None assert repl.locals['bar'] == 2
Test functionality when globals/locals are not provided.
_get_mock_document
return {'uri': f'{uri}', 'title': f'Title {uri}', 'content': f'Content {uri}'}
def _get_mock_document(self, uri: str) ->Dict: return {'uri': f'{uri}', 'title': f'Title {uri}', 'content': f'Content {uri}'}
null
test_add_documents
documents = [Document(page_content='test_add_documents document')] added_documents = time_weighted_retriever.add_documents(documents) assert isinstance(added_documents, list) assert len(added_documents) == 1 assert time_weighted_retriever.memory_stream[-1].page_content == documents[0 ].page_content
def test_add_documents(time_weighted_retriever: TimeWeightedVectorStoreRetriever) ->None: documents = [Document(page_content='test_add_documents document')] added_documents = time_weighted_retriever.add_documents(documents) assert isinstance(added_documents, list) assert len(added_documents) == 1 assert time_weighted_retriever.memory_stream[-1].page_content == documents[ 0].page_content
null
validate_inputs
"""Ensure we have an LLM for each step.""" llm = values.get('llm') ideation_llm = values.get('ideation_llm') critique_llm = values.get('critique_llm') resolver_llm = values.get('resolver_llm') if not llm and not ideation_llm: raise ValueError( 'Either ideation_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if not llm and not critique_llm: raise ValueError( 'Either critique_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if not llm and not resolver_llm: raise ValueError( 'Either resolve_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if llm and ideation_llm and critique_llm and resolver_llm: raise ValueError( 'LLMs are given for each step (ideation_llm, critique_llm, resolver_llm), but backup LLM (llm) is also given, which would not be used.' ) return values
@root_validator @classmethod def validate_inputs(cls, values: Dict[str, Any]) ->Dict[str, Any]: """Ensure we have an LLM for each step.""" llm = values.get('llm') ideation_llm = values.get('ideation_llm') critique_llm = values.get('critique_llm') resolver_llm = values.get('resolver_llm') if not llm and not ideation_llm: raise ValueError( 'Either ideation_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if not llm and not critique_llm: raise ValueError( 'Either critique_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if not llm and not resolver_llm: raise ValueError( 'Either resolve_llm or llm needs to be given. Pass llm, if you want to use the same llm for all steps, or pass ideation_llm, critique_llm and resolver_llm if you want to use different llms for each step.' ) if llm and ideation_llm and critique_llm and resolver_llm: raise ValueError( 'LLMs are given for each step (ideation_llm, critique_llm, resolver_llm), but backup LLM (llm) is also given, which would not be used.' ) return values
Ensure we have an LLM for each step.
test_load
loader = GoogleSpeechToTextLoader(project_id='test_project_id', file_path= './testfile.mp3') docs = loader.load() assert len(docs) == 1 assert docs[0].page_content == 'Test transcription text' assert docs[0].metadata['language_code'] == 'en-US'
@pytest.mark.requires('google.api_core') def test_load() ->None: loader = GoogleSpeechToTextLoader(project_id='test_project_id', file_path='./testfile.mp3') docs = loader.load() assert len(docs) == 1 assert docs[0].page_content == 'Test transcription text' assert docs[0].metadata['language_code'] == 'en-US'
null
_get_complexity_metrics
"""Compute text complexity metrics using textstat. Parameters: text (str): The text to analyze. Returns: (dict): A dictionary containing the complexity metrics. """ resp = {} if self.complexity_metrics: text_complexity_metrics = _fetch_text_complexity_metrics(text) resp.update(text_complexity_metrics) return resp
def _get_complexity_metrics(self, text: str) ->dict: """Compute text complexity metrics using textstat. Parameters: text (str): The text to analyze. Returns: (dict): A dictionary containing the complexity metrics. """ resp = {} if self.complexity_metrics: text_complexity_metrics = _fetch_text_complexity_metrics(text) resp.update(text_complexity_metrics) return resp
Compute text complexity metrics using textstat. Parameters: text (str): The text to analyze. Returns: (dict): A dictionary containing the complexity metrics.
test_model_no_session_id_field_error
class Base(DeclarativeBase): pass class Model(Base): __tablename__ = 'test_table' id = Column(Integer, primary_key=True) test_field = Column(Text) class CustomMessageConverter(DefaultMessageConverter): def get_sql_model_class(self) ->Any: return Model with pytest.raises(ValueError): SQLChatMessageHistory('test', con_str, custom_message_converter= CustomMessageConverter('test_table'))
def test_model_no_session_id_field_error(con_str: str) ->None: class Base(DeclarativeBase): pass class Model(Base): __tablename__ = 'test_table' id = Column(Integer, primary_key=True) test_field = Column(Text) class CustomMessageConverter(DefaultMessageConverter): def get_sql_model_class(self) ->Any: return Model with pytest.raises(ValueError): SQLChatMessageHistory('test', con_str, custom_message_converter= CustomMessageConverter('test_table'))
null
raw_results
params = {'api_key': self.tavily_api_key, 'query': query, 'max_results': max_results, 'search_depth': search_depth, 'include_domains': include_domains, 'exclude_domains': exclude_domains, 'include_answer': include_answer, 'include_raw_content': include_raw_content, 'include_images': include_images} response = requests.post(f'{TAVILY_API_URL}/search', json=params) response.raise_for_status() return response.json()
def raw_results(self, query: str, max_results: Optional[int]=5, search_depth: Optional[str]='advanced', include_domains: Optional[List[ str]]=[], exclude_domains: Optional[List[str]]=[], include_answer: Optional[bool]=False, include_raw_content: Optional[bool]=False, include_images: Optional[bool]=False) ->Dict: params = {'api_key': self.tavily_api_key, 'query': query, 'max_results': max_results, 'search_depth': search_depth, 'include_domains': include_domains, 'exclude_domains': exclude_domains, 'include_answer': include_answer, 'include_raw_content': include_raw_content, 'include_images': include_images} response = requests.post(f'{TAVILY_API_URL}/search', json=params) response.raise_for_status() return response.json()
null
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
format_memories_simple
return '; '.join([f'{mem.page_content}' for mem in relevant_memories])
def format_memories_simple(self, relevant_memories: List[Document]) ->str: return '; '.join([f'{mem.page_content}' for mem in relevant_memories])
null
test_litellm_call
"""Test valid call to litellm.""" chat = ChatLiteLLM(model='test') message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
def test_litellm_call() ->None: """Test valid call to litellm.""" chat = ChatLiteLLM(model='test') message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
Test valid call to litellm.
output_keys
"""Expect output key. :meta private: """ return [self.output_key]
@property def output_keys(self) ->List[str]: """Expect output key. :meta private: """ return [self.output_key]
Expect output key. :meta private:
_get_default_parser
"""Get default mime-type based parser.""" return MimeTypeBasedParser(handlers={'application/pdf': PyMuPDFParser(), 'text/plain': TextParser(), 'application/msword': MsWordParser(), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': MsWordParser()}, fallback_parser=None)
def _get_default_parser() ->BaseBlobParser: """Get default mime-type based parser.""" return MimeTypeBasedParser(handlers={'application/pdf': PyMuPDFParser(), 'text/plain': TextParser(), 'application/msword': MsWordParser(), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : MsWordParser()}, fallback_parser=None)
Get default mime-type based parser.
iter
"""Enables iteration over steps taken to reach final output.""" return AgentExecutorIterator(self, inputs, callbacks, tags=self.tags, include_run_info=include_run_info)
def iter(self, inputs: Any, callbacks: Callbacks=None, *, include_run_info: bool=False, async_: bool=False) ->AgentExecutorIterator: """Enables iteration over steps taken to reach final output.""" return AgentExecutorIterator(self, inputs, callbacks, tags=self.tags, include_run_info=include_run_info)
Enables iteration over steps taken to reach final output.
memory_variables
"""The list of keys emitted from the load_memory_variables method.""" return [self.memory_key]
@property def memory_variables(self) ->List[str]: """The list of keys emitted from the load_memory_variables method.""" return [self.memory_key]
The list of keys emitted from the load_memory_variables method.
get_input_variables
"""Get input variables.""" created_variables = set() all_variables = set() for k, prompt in values['pipeline_prompts']: created_variables.add(k) all_variables.update(prompt.input_variables) values['input_variables'] = list(all_variables.difference(created_variables)) return values
@root_validator(pre=True) def get_input_variables(cls, values: Dict) ->Dict: """Get input variables.""" created_variables = set() all_variables = set() for k, prompt in values['pipeline_prompts']: created_variables.add(k) all_variables.update(prompt.input_variables) values['input_variables'] = list(all_variables.difference( created_variables)) return values
Get input variables.
get_openai_output_parser
"""Get the appropriate function output parser given the user functions. Args: functions: Sequence where element is a dictionary, a pydantic.BaseModel class, or a Python function. If a dictionary is passed in, it is assumed to already be a valid OpenAI function. Returns: A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise a JsonOutputFunctionsParser. If there's only one function and it is not a Pydantic class, then the output parser will automatically extract only the function arguments and not the function name. """ function_names = [convert_to_openai_function(f)['name'] for f in functions] if isinstance(functions[0], type) and issubclass(functions[0], BaseModel): if len(functions) > 1: pydantic_schema: Union[Dict, Type[BaseModel]] = {name: fn for name, fn in zip(function_names, functions)} else: pydantic_schema = functions[0] output_parser: Union[BaseOutputParser, BaseGenerationOutputParser ] = PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema) else: output_parser = JsonOutputFunctionsParser(args_only=len(functions) <= 1) return output_parser
def get_openai_output_parser(functions: Sequence[Union[Dict[str, Any], Type [BaseModel], Callable]]) ->Union[BaseOutputParser, BaseGenerationOutputParser]: """Get the appropriate function output parser given the user functions. Args: functions: Sequence where element is a dictionary, a pydantic.BaseModel class, or a Python function. If a dictionary is passed in, it is assumed to already be a valid OpenAI function. Returns: A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise a JsonOutputFunctionsParser. If there's only one function and it is not a Pydantic class, then the output parser will automatically extract only the function arguments and not the function name. """ function_names = [convert_to_openai_function(f)['name'] for f in functions] if isinstance(functions[0], type) and issubclass(functions[0], BaseModel): if len(functions) > 1: pydantic_schema: Union[Dict, Type[BaseModel]] = {name: fn for name, fn in zip(function_names, functions)} else: pydantic_schema = functions[0] output_parser: Union[BaseOutputParser, BaseGenerationOutputParser ] = PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema) else: output_parser = JsonOutputFunctionsParser(args_only=len(functions) <= 1 ) return output_parser
Get the appropriate function output parser given the user functions. Args: functions: Sequence where element is a dictionary, a pydantic.BaseModel class, or a Python function. If a dictionary is passed in, it is assumed to already be a valid OpenAI function. Returns: A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise a JsonOutputFunctionsParser. If there's only one function and it is not a Pydantic class, then the output parser will automatically extract only the function arguments and not the function name.
load
"""Load data into Document objects."""
@abstractmethod def load(self) ->List[Document]: """Load data into Document objects."""
Load data into Document objects.
_chain_type
return 'llm_requests_chain'
@property def _chain_type(self) ->str: return 'llm_requests_chain'
null
test_format_headers_api_key
"""Test that the action headers is being created correctly.""" tool = ZapierNLARunAction(action_id='test', zapier_description='test', params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper( zapier_nla_api_key='test')) headers = tool.api_wrapper._format_headers() assert headers['Content-Type'] == 'application/json' assert headers['Accept'] == 'application/json' assert headers['X-API-Key'] == 'test'
def test_format_headers_api_key() ->None: """Test that the action headers is being created correctly.""" tool = ZapierNLARunAction(action_id='test', zapier_description='test', params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper( zapier_nla_api_key='test')) headers = tool.api_wrapper._format_headers() assert headers['Content-Type'] == 'application/json' assert headers['Accept'] == 'application/json' assert headers['X-API-Key'] == 'test'
Test that the action headers is being created correctly.
load
"""Load documents.""" try: from azure.storage.blob import BlobClient except ImportError as exc: raise ImportError( 'Could not import azure storage blob python package. Please install it with `pip install azure-storage-blob`.' ) from exc client = BlobClient.from_connection_string(conn_str=self.conn_str, container_name=self.container, blob_name=self.blob) with tempfile.TemporaryDirectory() as temp_dir: file_path = f'{temp_dir}/{self.container}/{self.blob}' os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(f'{file_path}', 'wb') as file: blob_data = client.download_blob() blob_data.readinto(file) loader = UnstructuredFileLoader(file_path) return loader.load()
def load(self) ->List[Document]: """Load documents.""" try: from azure.storage.blob import BlobClient except ImportError as exc: raise ImportError( 'Could not import azure storage blob python package. Please install it with `pip install azure-storage-blob`.' ) from exc client = BlobClient.from_connection_string(conn_str=self.conn_str, container_name=self.container, blob_name=self.blob) with tempfile.TemporaryDirectory() as temp_dir: file_path = f'{temp_dir}/{self.container}/{self.blob}' os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(f'{file_path}', 'wb') as file: blob_data = client.download_blob() blob_data.readinto(file) loader = UnstructuredFileLoader(file_path) return loader.load()
Load documents.
update
"""Change the expander's label and expanded state""" if new_label is None: new_label = self._label if new_expanded is None: new_expanded = self._expanded if self._label == new_label and self._expanded == new_expanded: return self._label = new_label self._expanded = new_expanded self._container = self._parent_cursor.expander(new_label, new_expanded) prev_records = self._child_records self._child_records = [] for record in prev_records: self._create_child(record.type, record.kwargs)
def update(self, *, new_label: Optional[str]=None, new_expanded: Optional[ bool]=None) ->None: """Change the expander's label and expanded state""" if new_label is None: new_label = self._label if new_expanded is None: new_expanded = self._expanded if self._label == new_label and self._expanded == new_expanded: return self._label = new_label self._expanded = new_expanded self._container = self._parent_cursor.expander(new_label, new_expanded) prev_records = self._child_records self._child_records = [] for record in prev_records: self._create_child(record.type, record.kwargs)
Change the expander's label and expanded state
_default_params
"""Get the default parameters for calling Baichuan API.""" normal_params = {'model': self.model, 'temperature': self.temperature, 'top_p': self.top_p, 'top_k': self.top_k, 'with_search_enhance': self. with_search_enhance} return {**normal_params, **self.model_kwargs}
@property def _default_params(self) ->Dict[str, Any]: """Get the default parameters for calling Baichuan API.""" normal_params = {'model': self.model, 'temperature': self.temperature, 'top_p': self.top_p, 'top_k': self.top_k, 'with_search_enhance': self.with_search_enhance} return {**normal_params, **self.model_kwargs}
Get the default parameters for calling Baichuan API.
validate_environment
"""Validate that api key and python package exists in environment.""" if values['n'] < 1: raise ValueError('n must be at least 1.') if values['streaming'] and values['n'] > 1: raise ValueError('Cannot stream results when n > 1.') if values['streaming'] and values['best_of'] > 1: raise ValueError('Cannot stream results when best_of > 1.') values['openai_api_key'] = values['openai_api_key'] or os.getenv( 'AZURE_OPENAI_API_KEY') or os.getenv('OPENAI_API_KEY') values['azure_endpoint'] = values['azure_endpoint'] or os.getenv( 'AZURE_OPENAI_ENDPOINT') values['azure_ad_token'] = values['azure_ad_token'] or os.getenv( 'AZURE_OPENAI_AD_TOKEN') values['openai_api_base'] = values['openai_api_base'] or os.getenv( 'OPENAI_API_BASE') values['openai_proxy'] = get_from_dict_or_env(values, 'openai_proxy', 'OPENAI_PROXY', default='') values['openai_organization'] = values['openai_organization'] or os.getenv( 'OPENAI_ORG_ID') or os.getenv('OPENAI_ORGANIZATION') values['openai_api_version'] = values['openai_api_version'] or os.getenv( 'OPENAI_API_VERSION') values['openai_api_type'] = get_from_dict_or_env(values, 'openai_api_type', 'OPENAI_API_TYPE', default='azure') try: import openai except ImportError: raise ImportError( 'Could not import openai python package. Please install it with `pip install openai`.' ) if is_openai_v1(): openai_api_base = values['openai_api_base'] if openai_api_base and values['validate_base_url']: if '/openai' not in openai_api_base: values['openai_api_base'] = values['openai_api_base'].rstrip('/' ) + '/openai' warnings.warn( f"As of openai>=1.0.0, Azure endpoints should be specified via the `azure_endpoint` param not `openai_api_base` (or alias `base_url`). Updating `openai_api_base` from {openai_api_base} to {values['openai_api_base']}." ) if values['deployment_name']: warnings.warn( 'As of openai>=1.0.0, if `deployment_name` (or alias `azure_deployment`) is specified then `openai_api_base` (or alias `base_url`) should not be. Instead use `deployment_name` (or alias `azure_deployment`) and `azure_endpoint`.' ) if values['deployment_name'] not in values['openai_api_base']: warnings.warn( f"As of openai>=1.0.0, if `openai_api_base` (or alias `base_url`) is specified it is expected to be of the form https://example-resource.azure.openai.com/openai/deployments/example-deployment. Updating {openai_api_base} to {values['openai_api_base']}." ) values['openai_api_base'] += '/deployments/' + values[ 'deployment_name'] values['deployment_name'] = None client_params = {'api_version': values['openai_api_version'], 'azure_endpoint': values['azure_endpoint'], 'azure_deployment': values['deployment_name'], 'api_key': values['openai_api_key'], 'azure_ad_token': values['azure_ad_token'], 'azure_ad_token_provider': values['azure_ad_token_provider'], 'organization': values['openai_organization'], 'base_url': values[ 'openai_api_base'], 'timeout': values['request_timeout'], 'max_retries': values['max_retries'], 'default_headers': values[ 'default_headers'], 'default_query': values['default_query'], 'http_client': values['http_client']} values['client'] = openai.AzureOpenAI(**client_params).completions values['async_client'] = openai.AsyncAzureOpenAI(**client_params ).completions else: values['client'] = openai.Completion return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" if values['n'] < 1: raise ValueError('n must be at least 1.') if values['streaming'] and values['n'] > 1: raise ValueError('Cannot stream results when n > 1.') if values['streaming'] and values['best_of'] > 1: raise ValueError('Cannot stream results when best_of > 1.') values['openai_api_key'] = values['openai_api_key'] or os.getenv( 'AZURE_OPENAI_API_KEY') or os.getenv('OPENAI_API_KEY') values['azure_endpoint'] = values['azure_endpoint'] or os.getenv( 'AZURE_OPENAI_ENDPOINT') values['azure_ad_token'] = values['azure_ad_token'] or os.getenv( 'AZURE_OPENAI_AD_TOKEN') values['openai_api_base'] = values['openai_api_base'] or os.getenv( 'OPENAI_API_BASE') values['openai_proxy'] = get_from_dict_or_env(values, 'openai_proxy', 'OPENAI_PROXY', default='') values['openai_organization'] = values['openai_organization'] or os.getenv( 'OPENAI_ORG_ID') or os.getenv('OPENAI_ORGANIZATION') values['openai_api_version'] = values['openai_api_version'] or os.getenv( 'OPENAI_API_VERSION') values['openai_api_type'] = get_from_dict_or_env(values, 'openai_api_type', 'OPENAI_API_TYPE', default='azure') try: import openai except ImportError: raise ImportError( 'Could not import openai python package. Please install it with `pip install openai`.' ) if is_openai_v1(): openai_api_base = values['openai_api_base'] if openai_api_base and values['validate_base_url']: if '/openai' not in openai_api_base: values['openai_api_base'] = values['openai_api_base'].rstrip( '/') + '/openai' warnings.warn( f"As of openai>=1.0.0, Azure endpoints should be specified via the `azure_endpoint` param not `openai_api_base` (or alias `base_url`). Updating `openai_api_base` from {openai_api_base} to {values['openai_api_base']}." ) if values['deployment_name']: warnings.warn( 'As of openai>=1.0.0, if `deployment_name` (or alias `azure_deployment`) is specified then `openai_api_base` (or alias `base_url`) should not be. Instead use `deployment_name` (or alias `azure_deployment`) and `azure_endpoint`.' ) if values['deployment_name'] not in values['openai_api_base']: warnings.warn( f"As of openai>=1.0.0, if `openai_api_base` (or alias `base_url`) is specified it is expected to be of the form https://example-resource.azure.openai.com/openai/deployments/example-deployment. Updating {openai_api_base} to {values['openai_api_base']}." ) values['openai_api_base'] += '/deployments/' + values[ 'deployment_name'] values['deployment_name'] = None client_params = {'api_version': values['openai_api_version'], 'azure_endpoint': values['azure_endpoint'], 'azure_deployment': values['deployment_name'], 'api_key': values['openai_api_key'], 'azure_ad_token': values['azure_ad_token'], 'azure_ad_token_provider': values['azure_ad_token_provider'], 'organization': values['openai_organization'], 'base_url': values['openai_api_base'], 'timeout': values['request_timeout'], 'max_retries': values['max_retries'], 'default_headers': values ['default_headers'], 'default_query': values['default_query'], 'http_client': values['http_client']} values['client'] = openai.AzureOpenAI(**client_params).completions values['async_client'] = openai.AsyncAzureOpenAI(**client_params ).completions else: values['client'] = openai.Completion return values
Validate that api key and python package exists in environment.
clear
"""Clear session memory from Zep. Note that Zep is long-term storage for memory and this is not advised unless you have specific data retention requirements. """ try: self.zep_client.memory.delete_memory(self.session_id) except NotFoundError: logger.warning( f'Session {self.session_id} not found in Zep. Skipping delete.')
def clear(self) ->None: """Clear session memory from Zep. Note that Zep is long-term storage for memory and this is not advised unless you have specific data retention requirements. """ try: self.zep_client.memory.delete_memory(self.session_id) except NotFoundError: logger.warning( f'Session {self.session_id} not found in Zep. Skipping delete.')
Clear session memory from Zep. Note that Zep is long-term storage for memory and this is not advised unless you have specific data retention requirements.
on_text
"""Do nothing""" pass
def on_text(self, text: str, **kwargs: Any) ->None: """Do nothing""" pass
Do nothing
transform_documents
"""Transform a list of documents. Args: documents: A sequence of Documents to be transformed. Returns: A list of transformed Documents. """
@abstractmethod def transform_documents(self, documents: Sequence[Document], **kwargs: Any ) ->Sequence[Document]: """Transform a list of documents. Args: documents: A sequence of Documents to be transformed. Returns: A list of transformed Documents. """
Transform a list of documents. Args: documents: A sequence of Documents to be transformed. Returns: A list of transformed Documents.
mock_requests_wrapper
return _MockTextRequestsWrapper()
@pytest.fixture def mock_requests_wrapper() ->TextRequestsWrapper: return _MockTextRequestsWrapper()
null
add_texts
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. Returns: List of ids from adding the texts into the vectorstore. """ names: List[str] = [] for text in texts: doc_name = str(uuid.uuid4()) response = self._session.post( f'{self.base_url}/datastores/{self._datastore_id}/text', json={ 'name': doc_name, 'text': text}, verify=True, headers=self. _get_post_headers()) if response.status_code != 200: logging.error( f'Create request failed for doc_name = {doc_name} with status code {response.status_code}, reason {response.reason}, text {response.text}' ) return names names.append(doc_name) return names
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, **kwargs: Any) ->List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. Returns: List of ids from adding the texts into the vectorstore. """ names: List[str] = [] for text in texts: doc_name = str(uuid.uuid4()) response = self._session.post( f'{self.base_url}/datastores/{self._datastore_id}/text', json={ 'name': doc_name, 'text': text}, verify=True, headers=self. _get_post_headers()) if response.status_code != 200: logging.error( f'Create request failed for doc_name = {doc_name} with status code {response.status_code}, reason {response.reason}, text {response.text}' ) return names names.append(doc_name) return names
Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. Returns: List of ids from adding the texts into the vectorstore.
test_fireworks_streaming_stop_words
"""Test stream completion with stop words.""" generator = llm.stream("Who's the best quarterback in the NFL?", stop=[',']) assert isinstance(generator, Generator) last_token = '' for token in generator: last_token = token assert isinstance(token, str) assert last_token[-1] == ','
@pytest.mark.scheduled def test_fireworks_streaming_stop_words(llm: Fireworks) ->None: """Test stream completion with stop words.""" generator = llm.stream("Who's the best quarterback in the NFL?", stop=[','] ) assert isinstance(generator, Generator) last_token = '' for token in generator: last_token = token assert isinstance(token, str) assert last_token[-1] == ','
Test stream completion with stop words.
_convert_dict_to_message
role = _dict['role'] content = _dict['content'] if role == 'user': return HumanMessage(content=content) elif role == 'assistant': return AIMessage(content=content) elif role == 'system': return SystemMessage(content=content) else: return ChatMessage(content=content, role=role)
@staticmethod def _convert_dict_to_message(_dict: Mapping[str, Any]) ->BaseMessage: role = _dict['role'] content = _dict['content'] if role == 'user': return HumanMessage(content=content) elif role == 'assistant': return AIMessage(content=content) elif role == 'system': return SystemMessage(content=content) else: return ChatMessage(content=content, role=role)
null
create_llm_result
"""Create the LLMResult from the choices and prompts.""" generations = [] for i, _ in enumerate(prompts): sub_choices = choices[i:i + 1] generations.append([Generation(text=choice.__dict__['choices'][0].text) for choice in sub_choices]) llm_output = {'model': self.model} return LLMResult(generations=generations, llm_output=llm_output)
def create_llm_result(self, choices: Any, prompts: List[str]) ->LLMResult: """Create the LLMResult from the choices and prompts.""" generations = [] for i, _ in enumerate(prompts): sub_choices = choices[i:i + 1] generations.append([Generation(text=choice.__dict__['choices'][0]. text) for choice in sub_choices]) llm_output = {'model': self.model} return LLMResult(generations=generations, llm_output=llm_output)
Create the LLMResult from the choices and prompts.
__init__
"""Initializes private fields.""" texttospeech = _import_google_cloud_texttospeech() super().__init__(**kwargs) self._client = texttospeech.TextToSpeechClient(client_info=get_client_info( module='text-to-speech'))
def __init__(self, **kwargs: Any) ->None: """Initializes private fields.""" texttospeech = _import_google_cloud_texttospeech() super().__init__(**kwargs) self._client = texttospeech.TextToSpeechClient(client_info= get_client_info(module='text-to-speech'))
Initializes private fields.
test_copy_file_errs_outside_root_dir
"""Test the FileCopy tool when a root dir is specified.""" with TemporaryDirectory() as temp_dir: tool = CopyFileTool(root_dir=temp_dir) result = tool.run({'source_path': '../source.txt', 'destination_path': '../destination.txt'}) assert result == INVALID_PATH_TEMPLATE.format(arg_name='source_path', value='../source.txt')
def test_copy_file_errs_outside_root_dir() ->None: """Test the FileCopy tool when a root dir is specified.""" with TemporaryDirectory() as temp_dir: tool = CopyFileTool(root_dir=temp_dir) result = tool.run({'source_path': '../source.txt', 'destination_path': '../destination.txt'}) assert result == INVALID_PATH_TEMPLATE.format(arg_name= 'source_path', value='../source.txt')
Test the FileCopy tool when a root dir is specified.
pull
""" Pulls an object from the hub and returns it as a LangChain object. :param owner_repo_commit: The full name of the repo to pull from in the format of `owner/repo:commit_hash`. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. """ client = _get_client(api_url=api_url, api_key=api_key) resp: str = client.pull(owner_repo_commit) return loads(resp)
def pull(owner_repo_commit: str, *, api_url: Optional[str]=None, api_key: Optional[str]=None) ->Any: """ Pulls an object from the hub and returns it as a LangChain object. :param owner_repo_commit: The full name of the repo to pull from in the format of `owner/repo:commit_hash`. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. """ client = _get_client(api_url=api_url, api_key=api_key) resp: str = client.pull(owner_repo_commit) return loads(resp)
Pulls an object from the hub and returns it as a LangChain object. :param owner_repo_commit: The full name of the repo to pull from in the format of `owner/repo:commit_hash`. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API.
next_thought
""" Generate the next thought given the problem description and the thoughts generated so far. """
@abstractmethod def next_thought(self, problem_description: str, thoughts_path: Tuple[str, ...]=(), **kwargs: Any) ->str: """ Generate the next thought given the problem description and the thoughts generated so far. """
Generate the next thought given the problem description and the thoughts generated so far.
validate_url_scheme
"""Check that the URL scheme is valid.""" parsed_url = urlparse(url) if parsed_url.scheme not in ('http', 'https'): raise ValueError("URL scheme must be 'http' or 'https'") return url
@validator('url') def validate_url_scheme(cls, url: str) ->str: """Check that the URL scheme is valid.""" parsed_url = urlparse(url) if parsed_url.scheme not in ('http', 'https'): raise ValueError("URL scheme must be 'http' or 'https'") return url
Check that the URL scheme is valid.
fetch_results
self.fetch_page_result(queue) while self.find_options.get('pageState'): self.fetch_page_result(queue) queue.put(None)
def fetch_results(self, queue: Queue): self.fetch_page_result(queue) while self.find_options.get('pageState'): self.fetch_page_result(queue) queue.put(None)
null
_get_elements
from unstructured.partition.auto import partition return partition(file=self.file, **self.unstructured_kwargs)
def _get_elements(self) ->List: from unstructured.partition.auto import partition return partition(file=self.file, **self.unstructured_kwargs)
null
zep_chat
mock_zep_client: ZepClient = mocker.patch('zep_python.ZepClient', autospec=True ) mock_zep_client.memory = mocker.patch('zep_python.memory.client.MemoryClient', autospec=True) zep_chat: ZepChatMessageHistory = ZepChatMessageHistory('test_session', 'http://localhost:8000') zep_chat.zep_client = mock_zep_client return zep_chat
@pytest.fixture @pytest.mark.requires('zep_python') def zep_chat(mocker: MockerFixture) ->ZepChatMessageHistory: mock_zep_client: ZepClient = mocker.patch('zep_python.ZepClient', autospec=True) mock_zep_client.memory = mocker.patch( 'zep_python.memory.client.MemoryClient', autospec=True) zep_chat: ZepChatMessageHistory = ZepChatMessageHistory('test_session', 'http://localhost:8000') zep_chat.zep_client = mock_zep_client return zep_chat
null
test_search
zep_chat.search('test query') zep_chat.zep_client.memory.search_memory.assert_called_once_with('test_session' , mocker.ANY, limit=None)
@pytest.mark.requires('zep_python') def test_search(mocker: MockerFixture, zep_chat: ZepChatMessageHistory) ->None: zep_chat.search('test query') zep_chat.zep_client.memory.search_memory.assert_called_once_with( 'test_session', mocker.ANY, limit=None)
null
__init__
self.host = host self.aiosession = aiosession if self.host is None or len(self.host) < 3: raise ValueError(' param `host` must be set to a valid url') self._batch_size = 128
def __init__(self, host: str='http://localhost:7797/v1', aiosession: Optional[aiohttp.ClientSession]=None) ->None: self.host = host self.aiosession = aiosession if self.host is None or len(self.host) < 3: raise ValueError(' param `host` must be set to a valid url') self._batch_size = 128
null
_value_serializer
"""Serialize a value.""" return json.dumps(value).encode()
def _value_serializer(value: Sequence[float]) ->bytes: """Serialize a value.""" return json.dumps(value).encode()
Serialize a value.
_get_elements
"""Get elements.""" from unstructured.partition.auto import partition try: import boto3 except ImportError: raise ImportError( 'Could not import `boto3` python package. Please install it with `pip install boto3`.' ) s3 = boto3.client('s3', region_name=self.region_name, api_version=self. api_version, use_ssl=self.use_ssl, verify=self.verify, endpoint_url= self.endpoint_url, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, aws_session_token= self.aws_session_token, config=self.boto_config) with tempfile.TemporaryDirectory() as temp_dir: file_path = f'{temp_dir}/{self.key}' os.makedirs(os.path.dirname(file_path), exist_ok=True) s3.download_file(self.bucket, self.key, file_path) return partition(filename=file_path)
def _get_elements(self) ->List: """Get elements.""" from unstructured.partition.auto import partition try: import boto3 except ImportError: raise ImportError( 'Could not import `boto3` python package. Please install it with `pip install boto3`.' ) s3 = boto3.client('s3', region_name=self.region_name, api_version=self. api_version, use_ssl=self.use_ssl, verify=self.verify, endpoint_url =self.endpoint_url, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, aws_session_token =self.aws_session_token, config=self.boto_config) with tempfile.TemporaryDirectory() as temp_dir: file_path = f'{temp_dir}/{self.key}' os.makedirs(os.path.dirname(file_path), exist_ok=True) s3.download_file(self.bucket, self.key, file_path) return partition(filename=file_path)
Get elements.
_import_typesense
from langchain_community.vectorstores.typesense import Typesense return Typesense
def _import_typesense() ->Any: from langchain_community.vectorstores.typesense import Typesense return Typesense
null
_openai_v1_installed
try: return is_openai_v1() except Exception as _: return False
def _openai_v1_installed() ->bool: try: return is_openai_v1() except Exception as _: return False
null
__init__
self.fail_starts_with = fail_starts_with
def __init__(self, fail_starts_with: str) ->None: self.fail_starts_with = fail_starts_with
null
test_include_types
"""Test include types from schema.""" url = os.environ.get('NEO4J_URI') username = os.environ.get('NEO4J_USERNAME') password = os.environ.get('NEO4J_PASSWORD') assert url is not None assert username is not None assert password is not None graph = Neo4jGraph(url=url, username=username, password=password) graph.query('MATCH (n) DETACH DELETE n') graph.query( "CREATE (a:Actor {name:'Bruce Willis'})-[:ACTED_IN]->(:Movie {title: 'Pulp Fiction'})<-[:DIRECTED]-(p:Person {name:'John'})" ) graph.refresh_schema() chain = GraphCypherQAChain.from_llm(OpenAI(temperature=0), graph=graph, include_types=['Movie', 'Actor', 'ACTED_IN']) expected_schema = """Node properties are the following: Movie {title: STRING},Actor {name: STRING} Relationship properties are the following: The relationships are the following: (:Actor)-[:ACTED_IN]->(:Movie)""" assert chain.graph_schema == expected_schema
def test_include_types() ->None: """Test include types from schema.""" url = os.environ.get('NEO4J_URI') username = os.environ.get('NEO4J_USERNAME') password = os.environ.get('NEO4J_PASSWORD') assert url is not None assert username is not None assert password is not None graph = Neo4jGraph(url=url, username=username, password=password) graph.query('MATCH (n) DETACH DELETE n') graph.query( "CREATE (a:Actor {name:'Bruce Willis'})-[:ACTED_IN]->(:Movie {title: 'Pulp Fiction'})<-[:DIRECTED]-(p:Person {name:'John'})" ) graph.refresh_schema() chain = GraphCypherQAChain.from_llm(OpenAI(temperature=0), graph=graph, include_types=['Movie', 'Actor', 'ACTED_IN']) expected_schema = """Node properties are the following: Movie {title: STRING},Actor {name: STRING} Relationship properties are the following: The relationships are the following: (:Actor)-[:ACTED_IN]->(:Movie)""" assert chain.graph_schema == expected_schema
Test include types from schema.
_get_default_output_parser
return ReActOutputParser()
@classmethod def _get_default_output_parser(cls, **kwargs: Any) ->AgentOutputParser: return ReActOutputParser()
null
embed_documents
"""Compute document embeddings using an OctoAI instruct model.""" texts = list(map(lambda x: x.replace('\n', ' '), texts)) return self._compute_embeddings(texts, self.embed_instruction)
def embed_documents(self, texts: List[str]) ->List[List[float]]: """Compute document embeddings using an OctoAI instruct model.""" texts = list(map(lambda x: x.replace('\n', ' '), texts)) return self._compute_embeddings(texts, self.embed_instruction)
Compute document embeddings using an OctoAI instruct model.
_import_vectara
from langchain_community.vectorstores.vectara import Vectara return Vectara
def _import_vectara() ->Any: from langchain_community.vectorstores.vectara import Vectara return Vectara
null
parser
"""Parse LLM output into a pydantic object.""" if cls.pydantic_model is None: raise NotImplementedError( f'pydantic_model not implemented for {cls.__name__}') return PydanticOutputParser(pydantic_object=cls.pydantic_model)
@classmethod def parser(cls) ->PydanticOutputParser: """Parse LLM output into a pydantic object.""" if cls.pydantic_model is None: raise NotImplementedError( f'pydantic_model not implemented for {cls.__name__}') return PydanticOutputParser(pydantic_object=cls.pydantic_model)
Parse LLM output into a pydantic object.
convert_python_function_to_ernie_function
"""Convert a Python function to an Ernie function-calling API compatible dict. Assumes the Python function has type hints and a docstring with a description. If the docstring has Google Python style argument descriptions, these will be included as well. """ description, arg_descriptions = _parse_python_function_docstring(function) return {'name': _get_python_function_name(function), 'description': description, 'parameters': {'type': 'object', 'properties': _get_python_function_arguments(function, arg_descriptions), 'required': _get_python_function_required_args(function)}}
def convert_python_function_to_ernie_function(function: Callable) ->Dict[ str, Any]: """Convert a Python function to an Ernie function-calling API compatible dict. Assumes the Python function has type hints and a docstring with a description. If the docstring has Google Python style argument descriptions, these will be included as well. """ description, arg_descriptions = _parse_python_function_docstring(function) return {'name': _get_python_function_name(function), 'description': description, 'parameters': {'type': 'object', 'properties': _get_python_function_arguments(function, arg_descriptions), 'required': _get_python_function_required_args(function)}}
Convert a Python function to an Ernie function-calling API compatible dict. Assumes the Python function has type hints and a docstring with a description. If the docstring has Google Python style argument descriptions, these will be included as well.
visit_structured_query
if structured_query.filter is None: kwargs = {} else: kwargs = {'filter': structured_query.filter.accept(self)} return structured_query.query, kwargs
def visit_structured_query(self, structured_query: StructuredQuery) ->Tuple[ str, dict]: if structured_query.filter is None: kwargs = {} else: kwargs = {'filter': structured_query.filter.accept(self)} return structured_query.query, kwargs
null
_get_default_document_prompt
return PromptTemplate(input_variables=['page_content'], template= '{page_content}')
def _get_default_document_prompt() ->PromptTemplate: return PromptTemplate(input_variables=['page_content'], template= '{page_content}')
null
int
return int(item)
def int(self, item: Any) ->int: return int(item)
null
add_texts
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. batch_size: How many vectors upload per-request. Default: 64 Returns: List of ids from adding the texts into the vectorstore. """ added_ids = [] for batch_ids, points in self._generate_rest_batches(texts, metadatas, ids, batch_size): self.client.upsert(collection_name=self.collection_name, points=points, **kwargs) added_ids.extend(batch_ids) return added_ids
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, ids: Optional[Sequence[str]]=None, batch_size: int=64, **kwargs: Any ) ->List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. batch_size: How many vectors upload per-request. Default: 64 Returns: List of ids from adding the texts into the vectorstore. """ added_ids = [] for batch_ids, points in self._generate_rest_batches(texts, metadatas, ids, batch_size): self.client.upsert(collection_name=self.collection_name, points= points, **kwargs) added_ids.extend(batch_ids) return added_ids
Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. Ids have to be uuid-like strings. batch_size: How many vectors upload per-request. Default: 64 Returns: List of ids from adding the texts into the vectorstore.
_generate_reaction
"""React to a given observation or dialogue act.""" prompt = PromptTemplate.from_template('{agent_summary_description}' + """ It is {current_time}.""" + """ {agent_name}'s status: {agent_status}""" + """ Summary of relevant context from {agent_name}'s memory:""" + """ {relevant_memories}""" + """ Most recent observations: {most_recent_memories}""" + """ Observation: {observation}""" + '\n\n' + suffix) agent_summary_description = self.get_summary(now=now) relevant_memories_str = self.summarize_related_memories(observation) current_time_str = datetime.now().strftime('%B %d, %Y, %I:%M %p' ) if now is None else now.strftime('%B %d, %Y, %I:%M %p') kwargs: Dict[str, Any] = dict(agent_summary_description= agent_summary_description, current_time=current_time_str, relevant_memories=relevant_memories_str, agent_name=self.name, observation=observation, agent_status=self.status) consumed_tokens = self.llm.get_num_tokens(prompt.format( most_recent_memories='', **kwargs)) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip()
def _generate_reaction(self, observation: str, suffix: str, now: Optional[ datetime]=None) ->str: """React to a given observation or dialogue act.""" prompt = PromptTemplate.from_template('{agent_summary_description}' + """ It is {current_time}.""" + """ {agent_name}'s status: {agent_status}""" + """ Summary of relevant context from {agent_name}'s memory:""" + """ {relevant_memories}""" + """ Most recent observations: {most_recent_memories}""" + """ Observation: {observation}""" + '\n\n' + suffix) agent_summary_description = self.get_summary(now=now) relevant_memories_str = self.summarize_related_memories(observation) current_time_str = datetime.now().strftime('%B %d, %Y, %I:%M %p' ) if now is None else now.strftime('%B %d, %Y, %I:%M %p') kwargs: Dict[str, Any] = dict(agent_summary_description= agent_summary_description, current_time=current_time_str, relevant_memories=relevant_memories_str, agent_name=self.name, observation=observation, agent_status=self.status) consumed_tokens = self.llm.get_num_tokens(prompt.format( most_recent_memories='', **kwargs)) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip()
React to a given observation or dialogue act.
_identifying_params
"""Get the identifying parameters.""" return {'model_name': self.model, 'aviary_url': self.aviary_url}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {'model_name': self.model, 'aviary_url': self.aviary_url}
Get the identifying parameters.
_get_doc_cls
"""Get docarray Document class describing the schema of DocIndex.""" from docarray import BaseDoc from docarray.typing import NdArray class DocArrayDoc(BaseDoc): text: Optional[str] embedding: Optional[NdArray] = Field(**embeddings_params) metadata: Optional[dict] return DocArrayDoc
@staticmethod def _get_doc_cls(**embeddings_params: Any) ->Type['BaseDoc']: """Get docarray Document class describing the schema of DocIndex.""" from docarray import BaseDoc from docarray.typing import NdArray class DocArrayDoc(BaseDoc): text: Optional[str] embedding: Optional[NdArray] = Field(**embeddings_params) metadata: Optional[dict] return DocArrayDoc
Get docarray Document class describing the schema of DocIndex.
on_llm_new_token
"""Do nothing when a new token is generated.""" pass
def on_llm_new_token(self, token: str, **kwargs: Any) ->None: """Do nothing when a new token is generated.""" pass
Do nothing when a new token is generated.
test_visit_comparison_in
comp = Comparison(comparator=Comparator.IN, attribute='name', value='foo') expected = {'name': {'$in': ['foo']}} actual = DEFAULT_TRANSLATOR.visit_comparison(comp) assert expected == actual
def test_visit_comparison_in() ->None: comp = Comparison(comparator=Comparator.IN, attribute='name', value='foo') expected = {'name': {'$in': ['foo']}} actual = DEFAULT_TRANSLATOR.visit_comparison(comp) assert expected == actual
null
foo
"""Docstring Args: bar: int baz: str """ raise NotImplementedError()
def foo(bar: int, baz: str) ->str: """Docstring Args: bar: int baz: str """ raise NotImplementedError()
Docstring Args: bar: int baz: str
_generate
raise NotImplementedError
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->ChatResult: raise NotImplementedError
null
_parse_filename_from_url
"""Parse the filename from an url. Args: url: Url to parse the filename from. Returns: The filename. Raises: ValueError: If the filename could not be parsed. """ filename_matches = re.search('filename%2A%3DUTF-8%27%27(.+)', url) if filename_matches: filename = filename_matches.group(1) else: raise ValueError(f'Could not parse filename from {url}') if '.pdf' not in filename: raise ValueError(f'Incorrect file type: {filename}') filename = filename.split('.pdf')[0] + '.pdf' filename = unquote(filename) filename = filename.replace('%20', ' ') return filename
def _parse_filename_from_url(self, url: str) ->str: """Parse the filename from an url. Args: url: Url to parse the filename from. Returns: The filename. Raises: ValueError: If the filename could not be parsed. """ filename_matches = re.search('filename%2A%3DUTF-8%27%27(.+)', url) if filename_matches: filename = filename_matches.group(1) else: raise ValueError(f'Could not parse filename from {url}') if '.pdf' not in filename: raise ValueError(f'Incorrect file type: {filename}') filename = filename.split('.pdf')[0] + '.pdf' filename = unquote(filename) filename = filename.replace('%20', ' ') return filename
Parse the filename from an url. Args: url: Url to parse the filename from. Returns: The filename. Raises: ValueError: If the filename could not be parsed.
__init__
self.connection_string = connection_string self.engine = create_engine(connection_string, echo=False) self.session_id_field_name = session_id_field_name self.converter = custom_message_converter or DefaultMessageConverter(table_name ) self.sql_model_class = self.converter.get_sql_model_class() if not hasattr(self.sql_model_class, session_id_field_name): raise ValueError('SQL model class must have session_id column') self._create_table_if_not_exists() self.session_id = session_id self.Session = sessionmaker(self.engine)
def __init__(self, session_id: str, connection_string: str, table_name: str ='message_store', session_id_field_name: str='session_id', custom_message_converter: Optional[BaseMessageConverter]=None): self.connection_string = connection_string self.engine = create_engine(connection_string, echo=False) self.session_id_field_name = session_id_field_name self.converter = custom_message_converter or DefaultMessageConverter( table_name) self.sql_model_class = self.converter.get_sql_model_class() if not hasattr(self.sql_model_class, session_id_field_name): raise ValueError('SQL model class must have session_id column') self._create_table_if_not_exists() self.session_id = session_id self.Session = sessionmaker(self.engine)
null
get_noop_manager
"""Return a manager that doesn't perform any operations. Returns: BaseRunManager: The noop manager. """ return cls(run_id=uuid.uuid4(), handlers=[], inheritable_handlers=[], tags= [], inheritable_tags=[], metadata={}, inheritable_metadata={})
@classmethod def get_noop_manager(cls: Type[BRM]) ->BRM: """Return a manager that doesn't perform any operations. Returns: BaseRunManager: The noop manager. """ return cls(run_id=uuid.uuid4(), handlers=[], inheritable_handlers=[], tags=[], inheritable_tags=[], metadata={}, inheritable_metadata={})
Return a manager that doesn't perform any operations. Returns: BaseRunManager: The noop manager.
test_batch_size
llm = FakeListLLM(responses=['foo'] * 3) with collect_runs() as cb: llm.batch(['foo', 'bar', 'foo'], {'callbacks': [cb]}) assert all([((r.extra or {}).get('batch_size') == 3) for r in cb. traced_runs]) assert len(cb.traced_runs) == 3 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: llm.batch(['foo'], {'callbacks': [cb]}) assert all([((r.extra or {}).get('batch_size') == 1) for r in cb. traced_runs]) assert len(cb.traced_runs) == 1 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: llm.invoke('foo') assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: list(llm.stream('foo')) assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1 llm = FakeListLLM(responses=['foo'] * 1) with collect_runs() as cb: llm.predict('foo') assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1
def test_batch_size() ->None: llm = FakeListLLM(responses=['foo'] * 3) with collect_runs() as cb: llm.batch(['foo', 'bar', 'foo'], {'callbacks': [cb]}) assert all([((r.extra or {}).get('batch_size') == 3) for r in cb. traced_runs]) assert len(cb.traced_runs) == 3 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: llm.batch(['foo'], {'callbacks': [cb]}) assert all([((r.extra or {}).get('batch_size') == 1) for r in cb. traced_runs]) assert len(cb.traced_runs) == 1 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: llm.invoke('foo') assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1 llm = FakeListLLM(responses=['foo']) with collect_runs() as cb: list(llm.stream('foo')) assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1 llm = FakeListLLM(responses=['foo'] * 1) with collect_runs() as cb: llm.predict('foo') assert len(cb.traced_runs) == 1 assert (cb.traced_runs[0].extra or {}).get('batch_size') == 1
null
validate_environment
"""Validate that api key and python package exists in environment.""" values['openai_api_key'] = get_from_dict_or_env(values, 'openai_api_key', 'OPENAI_API_KEY') values['openai_api_base'] = get_from_dict_or_env(values, 'openai_api_base', 'OPENAI_API_BASE', default='') values['openai_proxy'] = get_from_dict_or_env(values, 'openai_proxy', 'OPENAI_PROXY', default='') default_api_version = '' values['openai_api_version'] = get_from_dict_or_env(values, 'openai_api_version', 'OPENAI_API_VERSION', default=default_api_version) values['openai_organization'] = get_from_dict_or_env(values, 'openai_organization', 'OPENAI_ORGANIZATION', default='') try: import openai values['client'] = openai.Embedding except ImportError: raise ImportError( 'Could not import openai python package. Please install it with `pip install openai`.' ) return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and python package exists in environment.""" values['openai_api_key'] = get_from_dict_or_env(values, 'openai_api_key', 'OPENAI_API_KEY') values['openai_api_base'] = get_from_dict_or_env(values, 'openai_api_base', 'OPENAI_API_BASE', default='') values['openai_proxy'] = get_from_dict_or_env(values, 'openai_proxy', 'OPENAI_PROXY', default='') default_api_version = '' values['openai_api_version'] = get_from_dict_or_env(values, 'openai_api_version', 'OPENAI_API_VERSION', default=default_api_version ) values['openai_organization'] = get_from_dict_or_env(values, 'openai_organization', 'OPENAI_ORGANIZATION', default='') try: import openai values['client'] = openai.Embedding except ImportError: raise ImportError( 'Could not import openai python package. Please install it with `pip install openai`.' ) return values
Validate that api key and python package exists in environment.
_generate_inputs
"""Create the input for the triton inference server.""" query = np.array(prompt).astype(object) request_output_len = np.array([tokens]).astype(np.uint32).reshape((1, -1)) runtime_top_k = np.array([top_k]).astype(np.uint32).reshape((1, -1)) runtime_top_p = np.array([top_p]).astype(np.float32).reshape((1, -1)) temperature_array = np.array([temperature]).astype(np.float32).reshape((1, -1)) len_penalty = np.array([length_penalty]).astype(np.float32).reshape((1, -1)) repetition_penalty_array = np.array([repetition_penalty]).astype(np.float32 ).reshape((1, -1)) random_seed = np.array([self.seed]).astype(np.uint64).reshape((1, -1)) beam_width_array = np.array([beam_width]).astype(np.uint32).reshape((1, -1)) streaming_data = np.array([[stream]], dtype=bool) inputs = [self._prepare_tensor('text_input', query), self._prepare_tensor( 'max_tokens', request_output_len), self._prepare_tensor('top_k', runtime_top_k), self._prepare_tensor('top_p', runtime_top_p), self. _prepare_tensor('temperature', temperature_array), self._prepare_tensor ('length_penalty', len_penalty), self._prepare_tensor( 'repetition_penalty', repetition_penalty_array), self._prepare_tensor( 'random_seed', random_seed), self._prepare_tensor('beam_width', beam_width_array), self._prepare_tensor('stream', streaming_data)] return inputs
def _generate_inputs(self, prompt: Sequence[Sequence[str]], tokens: int=300, temperature: float=1.0, top_k: float=1, top_p: float=0, beam_width: int =1, repetition_penalty: float=1, length_penalty: float=1.0, stream: bool=True) ->List[grpcclient.InferRequestedOutput]: """Create the input for the triton inference server.""" query = np.array(prompt).astype(object) request_output_len = np.array([tokens]).astype(np.uint32).reshape((1, -1)) runtime_top_k = np.array([top_k]).astype(np.uint32).reshape((1, -1)) runtime_top_p = np.array([top_p]).astype(np.float32).reshape((1, -1)) temperature_array = np.array([temperature]).astype(np.float32).reshape(( 1, -1)) len_penalty = np.array([length_penalty]).astype(np.float32).reshape((1, -1) ) repetition_penalty_array = np.array([repetition_penalty]).astype(np.float32 ).reshape((1, -1)) random_seed = np.array([self.seed]).astype(np.uint64).reshape((1, -1)) beam_width_array = np.array([beam_width]).astype(np.uint32).reshape((1, -1) ) streaming_data = np.array([[stream]], dtype=bool) inputs = [self._prepare_tensor('text_input', query), self. _prepare_tensor('max_tokens', request_output_len), self. _prepare_tensor('top_k', runtime_top_k), self._prepare_tensor( 'top_p', runtime_top_p), self._prepare_tensor('temperature', temperature_array), self._prepare_tensor('length_penalty', len_penalty), self._prepare_tensor('repetition_penalty', repetition_penalty_array), self._prepare_tensor('random_seed', random_seed), self._prepare_tensor('beam_width', beam_width_array), self._prepare_tensor('stream', streaming_data)] return inputs
Create the input for the triton inference server.
__iter__
yield from self._children
def __iter__(self) ->Iterator[AsyncIterator[T]]: yield from self._children
null
update
"""Update cache based on prompt and llm_string.""" for gen in return_val: if not isinstance(gen, Generation): raise ValueError( f'UpstashRedisCache supports caching of normal LLM generations, got {type(gen)}' ) if isinstance(gen, ChatGeneration): warnings.warn( 'NOTE: Generation has not been cached. UpstashRedisCache does not support caching ChatModel outputs.' ) return key = self._key(prompt, llm_string) mapping = {str(idx): generation.text for idx, generation in enumerate( return_val)} self.redis.hset(key=key, values=mapping) if self.ttl is not None: self.redis.expire(key, self.ttl)
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE ) ->None: """Update cache based on prompt and llm_string.""" for gen in return_val: if not isinstance(gen, Generation): raise ValueError( f'UpstashRedisCache supports caching of normal LLM generations, got {type(gen)}' ) if isinstance(gen, ChatGeneration): warnings.warn( 'NOTE: Generation has not been cached. UpstashRedisCache does not support caching ChatModel outputs.' ) return key = self._key(prompt, llm_string) mapping = {str(idx): generation.text for idx, generation in enumerate( return_val)} self.redis.hset(key=key, values=mapping) if self.ttl is not None: self.redis.expire(key, self.ttl)
Update cache based on prompt and llm_string.
__call__
results: List[Dict[str, Any]] = [] for fields in fields_collection: results.append(self.generator({'fields': fields, 'preferences': self. sentence_preferences})) return results
def __call__(self, fields_collection: List[List[Any]]) ->List[Dict[str, Any]]: results: List[Dict[str, Any]] = [] for fields in fields_collection: results.append(self.generator({'fields': fields, 'preferences': self.sentence_preferences})) return results
null
transform_output
"""Transforms the output from the model to string that the LLM class expects. """
@abstractmethod def transform_output(self, output: bytes) ->OUTPUT_TYPE: """Transforms the output from the model to string that the LLM class expects. """
Transforms the output from the model to string that the LLM class expects.
_import_databricks_chat
from langchain_community.chat_models.databricks import ChatDatabricks return ChatDatabricks
def _import_databricks_chat() ->Any: from langchain_community.chat_models.databricks import ChatDatabricks return ChatDatabricks
null
validate_environment
"""Validate that api key and endpoint exists in environment.""" azure_cogs_key = get_from_dict_or_env(values, 'azure_cogs_key', 'AZURE_COGS_KEY') azure_cogs_endpoint = get_from_dict_or_env(values, 'azure_cogs_endpoint', 'AZURE_COGS_ENDPOINT') try: import azure.ai.textanalytics as sdk from azure.core.credentials import AzureKeyCredential values['text_analytics_client'] = sdk.TextAnalyticsClient(endpoint= azure_cogs_endpoint, credential=AzureKeyCredential(azure_cogs_key)) except ImportError: raise ImportError( 'azure-ai-textanalytics is not installed. Run `pip install azure-ai-textanalytics` to install.' ) return values
@root_validator(pre=True) def validate_environment(cls, values: Dict) ->Dict: """Validate that api key and endpoint exists in environment.""" azure_cogs_key = get_from_dict_or_env(values, 'azure_cogs_key', 'AZURE_COGS_KEY') azure_cogs_endpoint = get_from_dict_or_env(values, 'azure_cogs_endpoint', 'AZURE_COGS_ENDPOINT') try: import azure.ai.textanalytics as sdk from azure.core.credentials import AzureKeyCredential values['text_analytics_client'] = sdk.TextAnalyticsClient(endpoint= azure_cogs_endpoint, credential=AzureKeyCredential(azure_cogs_key)) except ImportError: raise ImportError( 'azure-ai-textanalytics is not installed. Run `pip install azure-ai-textanalytics` to install.' ) return values
Validate that api key and endpoint exists in environment.
get_relative_path
"""Get the path of the file as a relative path to the package directory.""" if isinstance(file, str): file = Path(file) return str(file.relative_to(relative_to))
def get_relative_path(file: Union[Path, str], *, relative_to: Path=PACKAGE_DIR ) ->str: """Get the path of the file as a relative path to the package directory.""" if isinstance(file, str): file = Path(file) return str(file.relative_to(relative_to))
Get the path of the file as a relative path to the package directory.
from_text
"""Create graph index from text.""" if self.llm is None: raise ValueError('llm should not be None') graph = self.graph_type() chain = LLMChain(llm=self.llm, prompt=prompt) output = chain.predict(text=text) knowledge = parse_triples(output) for triple in knowledge: graph.add_triple(triple) return graph
def from_text(self, text: str, prompt: BasePromptTemplate= KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT) ->NetworkxEntityGraph: """Create graph index from text.""" if self.llm is None: raise ValueError('llm should not be None') graph = self.graph_type() chain = LLMChain(llm=self.llm, prompt=prompt) output = chain.predict(text=text) knowledge = parse_triples(output) for triple in knowledge: graph.add_triple(triple) return graph
Create graph index from text.
test_sentence_transformer_db_query
"""Test sentence_transformer similarity search.""" embedding = SentenceTransformerEmbeddings() texts = ["we will foo your bar until you can't foo any more", 'the quick brown fox jumped over the lazy dog'] query = 'what the foo is a bar?' query_vector = embedding.embed_query(query) assert len(query_vector) == 384 db = Chroma(embedding_function=embedding) db.add_texts(texts) docs = db.similarity_search_by_vector(query_vector, k=2) assert docs[0 ].page_content == "we will foo your bar until you can't foo any more"
def test_sentence_transformer_db_query() ->None: """Test sentence_transformer similarity search.""" embedding = SentenceTransformerEmbeddings() texts = ["we will foo your bar until you can't foo any more", 'the quick brown fox jumped over the lazy dog'] query = 'what the foo is a bar?' query_vector = embedding.embed_query(query) assert len(query_vector) == 384 db = Chroma(embedding_function=embedding) db.add_texts(texts) docs = db.similarity_search_by_vector(query_vector, k=2) assert docs[0 ].page_content == "we will foo your bar until you can't foo any more"
Test sentence_transformer similarity search.
_load_prompt_from_file
"""Load prompt from file.""" if isinstance(file, str): file_path = Path(file) else: file_path = file if file_path.suffix == '.json': with open(file_path) as f: config = json.load(f) elif file_path.suffix == '.yaml': with open(file_path, 'r') as f: config = yaml.safe_load(f) else: raise ValueError(f'Got unsupported file type {file_path.suffix}') return load_prompt_from_config(config)
def _load_prompt_from_file(file: Union[str, Path]) ->BasePromptTemplate: """Load prompt from file.""" if isinstance(file, str): file_path = Path(file) else: file_path = file if file_path.suffix == '.json': with open(file_path) as f: config = json.load(f) elif file_path.suffix == '.yaml': with open(file_path, 'r') as f: config = yaml.safe_load(f) else: raise ValueError(f'Got unsupported file type {file_path.suffix}') return load_prompt_from_config(config)
Load prompt from file.
_run
return f'{arg1} {arg2} {arg3}'
def _run(self, arg1: int, arg2: bool, arg3: Optional[dict]=None) ->str: return f'{arg1} {arg2} {arg3}'
null
librarian_rag
return get_docs_message(x['message'])
def librarian_rag(x): return get_docs_message(x['message'])
null