method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_chain_type
return 'vector_sql_database_chain'
@property def _chain_type(self) ->str: return 'vector_sql_database_chain'
null
_get_elements
from unstructured.partition.tsv import partition_tsv return partition_tsv(filename=self.file_path, **self.unstructured_kwargs)
def _get_elements(self) ->List: from unstructured.partition.tsv import partition_tsv return partition_tsv(filename=self.file_path, **self.unstructured_kwargs)
null
_Expr
self.fill() self.dispatch(tree.value)
def _Expr(self, tree): self.fill() self.dispatch(tree.value)
null
compress_documents
""" Compress documents using Cohere's rerank API. Args: documents: A sequence of documents to compress. query: The query to use for compressing the documents. callbacks: Callbacks to run during the compression process. Returns: A sequence of comp...
def compress_documents(self, documents: Sequence[Document], query: str, callbacks: Optional[Callbacks]=None) ->Sequence[Document]: """ Compress documents using Cohere's rerank API. Args: documents: A sequence of documents to compress. query: The query to use for compress...
Compress documents using Cohere's rerank API. Args: documents: A sequence of documents to compress. query: The query to use for compressing the documents. callbacks: Callbacks to run during the compression process. Returns: A sequence of compressed documents.
invoke
config = ensure_config(config) return self(input, callbacks=config.get('callbacks'), tags=config.get( 'tags'), metadata=config.get('metadata'), run_name=config.get( 'run_name'), **kwargs)
def invoke(self, input: Dict[str, Any], config: Optional[RunnableConfig]= None, **kwargs: Any) ->Dict[str, Any]: config = ensure_config(config) return self(input, callbacks=config.get('callbacks'), tags=config.get( 'tags'), metadata=config.get('metadata'), run_name=config.get( 'run_name'), *...
null
input_keys
return ['objective']
@property def input_keys(self) ->List[str]: return ['objective']
null
create_spark_sql_agent
"""Construct a Spark SQL agent from an LLM and tools.""" from langchain.agents.agent import AgentExecutor from langchain.agents.mrkl.base import ZeroShotAgent from langchain.chains.llm import LLMChain tools = toolkit.get_tools() prefix = prefix.format(top_k=top_k) prompt_params = {'format_instructions': format_instruct...
def create_spark_sql_agent(llm: BaseLanguageModel, toolkit: SparkSQLToolkit, callback_manager: Optional[BaseCallbackManager]=None, callbacks: Callbacks=None, prefix: str=SQL_PREFIX, suffix: str=SQL_SUFFIX, format_instructions: Optional[str]=None, input_variables: Optional[List [str]]=None, top_k: int=10...
Construct a Spark SQL agent from an LLM and tools.
_format_func
self._validate_func(func) return f'${func.value}'
def _format_func(self, func: Union[Operator, Comparator]) ->str: self._validate_func(func) return f'${func.value}'
null
test_astradb_vectorstore_custom_params
"""Custom batch size and concurrency params.""" emb = SomeEmbeddings(dimension=2) v_store = AstraDB(embedding=emb, collection_name='lc_test_c', token=os. environ['ASTRA_DB_APPLICATION_TOKEN'], api_endpoint=os.environ[ 'ASTRA_DB_API_ENDPOINT'], namespace=os.environ.get('ASTRA_DB_KEYSPACE'), batch_size=17, bu...
def test_astradb_vectorstore_custom_params(self) ->None: """Custom batch size and concurrency params.""" emb = SomeEmbeddings(dimension=2) v_store = AstraDB(embedding=emb, collection_name='lc_test_c', token=os. environ['ASTRA_DB_APPLICATION_TOKEN'], api_endpoint=os.environ[ 'ASTRA_DB_API_END...
Custom batch size and concurrency params.
dispatch
"""Dispatcher function, dispatching tree type T to method _T.""" if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, '_' + tree.__class__.__name__) meth(tree)
def dispatch(self, tree): """Dispatcher function, dispatching tree type T to method _T.""" if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, '_' + tree.__class__.__name__) meth(tree)
Dispatcher function, dispatching tree type T to method _T.
dependable_tiledb_import
"""Import tiledb-vector-search if available, otherwise raise error.""" try: import tiledb as tiledb import tiledb.vector_search as tiledb_vs except ImportError: raise ValueError( 'Could not import tiledb-vector-search python package. Please install it with `conda install -c tiledb tiledb-vector-sear...
def dependable_tiledb_import() ->Any: """Import tiledb-vector-search if available, otherwise raise error.""" try: import tiledb as tiledb import tiledb.vector_search as tiledb_vs except ImportError: raise ValueError( 'Could not import tiledb-vector-search python package. ...
Import tiledb-vector-search if available, otherwise raise error.
test_parse_without_language
llm_output = """I can use the `foo` tool to achieve the goal. Action: ``` { "action": "foo", "action_input": "bar" } ``` """ action, action_input = get_action_and_input(llm_output) assert action == 'foo' assert action_input == 'bar'
def test_parse_without_language() ->None: llm_output = """I can use the `foo` tool to achieve the goal. Action: ``` { "action": "foo", "action_input": "bar" } ``` """ action, action_input = get_action_and_input(llm_output) assert action == 'foo' assert action_input =...
null
model
"""For backwards compatibility.""" return self.llm
@property def model(self) ->BaseChatModel: """For backwards compatibility.""" return self.llm
For backwards compatibility.
build_extra
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get('model_kwargs', {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise V...
@root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) ->Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__. values()} extra = values.get('model_kwargs', {}) for field_name in li...
Build extra kwargs from additional params that were passed in.
on_llm_end
self.saved_things['generation'] = args[0]
def on_llm_end(self, *args: Any, **kwargs: Any) ->Any: self.saved_things['generation'] = args[0]
null
lookup
"""Look up based on prompt and llm_string.""" hit_with_id = self.lookup_with_id(prompt, llm_string) if hit_with_id is not None: return hit_with_id[1] else: return None
def lookup(self, prompt: str, llm_string: str) ->Optional[RETURN_VAL_TYPE]: """Look up based on prompt and llm_string.""" hit_with_id = self.lookup_with_id(prompt, llm_string) if hit_with_id is not None: return hit_with_id[1] else: return None
Look up based on prompt and llm_string.
__add
try: from elasticsearch.helpers import BulkIndexError, bulk except ImportError: raise ImportError( 'Could not import elasticsearch python package. Please install it with `pip install elasticsearch`.' ) bulk_kwargs = bulk_kwargs or {} ids = ids or [str(uuid.uuid4()) for _ in texts] requests = [] ...
def __add(self, texts: Iterable[str], embeddings: Optional[List[List[float] ]], metadatas: Optional[List[Dict[Any, Any]]]=None, ids: Optional[List[ str]]=None, refresh_indices: bool=True, create_index_if_not_exists: bool=True, bulk_kwargs: Optional[Dict]=None, **kwargs: Any) ->List[str]: try: fr...
null
get_output_schema
map_input_schema = self.mapper.get_input_schema(config) map_output_schema = self.mapper.get_output_schema(config) if not map_input_schema.__custom_root_type__ and not map_output_schema.__custom_root_type__: return create_model('RunnableAssignOutput', **{k: (v.type_, v.default) for s in (map_input_schema, ma...
def get_output_schema(self, config: Optional[RunnableConfig]=None) ->Type[ BaseModel]: map_input_schema = self.mapper.get_input_schema(config) map_output_schema = self.mapper.get_output_schema(config) if (not map_input_schema.__custom_root_type__ and not map_output_schema .__custom_root_type__):...
null
test_joplin_loader
loader = JoplinLoader() docs = loader.load() assert isinstance(docs, list) assert isinstance(docs[0].page_content, str) assert isinstance(docs[0].metadata['source'], str) assert isinstance(docs[0].metadata['title'], str)
def test_joplin_loader() ->None: loader = JoplinLoader() docs = loader.load() assert isinstance(docs, list) assert isinstance(docs[0].page_content, str) assert isinstance(docs[0].metadata['source'], str) assert isinstance(docs[0].metadata['title'], str)
null
_import_huggingface_pipeline
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline return HuggingFacePipeline
def _import_huggingface_pipeline() ->Any: from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline return HuggingFacePipeline
null
__init__
"""Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. ...
def __init__(self, session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str='message_store:', ttl: Optional[ timedelta]=None, ensure_cache_exists: bool=True): """Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache cl...
Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. cache_client (CacheClient): The Mo...
test_edenai_call
"""Test simple call to edenai's text moderation endpoint.""" text_moderation = EdenAiTextModerationTool(providers=['openai'], language='en') output = text_moderation('i hate you') assert text_moderation.name == 'edenai_explicit_content_detection_text' assert text_moderation.feature == 'text' assert text_moderation.subf...
def test_edenai_call() ->None: """Test simple call to edenai's text moderation endpoint.""" text_moderation = EdenAiTextModerationTool(providers=['openai'], language='en') output = text_moderation('i hate you') assert text_moderation.name == 'edenai_explicit_content_detection_text' assert te...
Test simple call to edenai's text moderation endpoint.
anonymizer_mapping
"""Return the anonymizer mapping This is just the reverse version of the deanonymizer mapping.""" return {key: {v: k for k, v in inner_dict.items()} for key, inner_dict in self.deanonymizer_mapping.items()}
@property def anonymizer_mapping(self) ->MappingDataType: """Return the anonymizer mapping This is just the reverse version of the deanonymizer mapping.""" return {key: {v: k for k, v in inner_dict.items()} for key, inner_dict in self.deanonymizer_mapping.items()}
Return the anonymizer mapping This is just the reverse version of the deanonymizer mapping.
test_react_chain_bad_action
"""Test react chain when bad action given.""" bad_action_name = 'BadAction' responses = [f"""I'm turning evil Action: {bad_action_name}[langchain]""", """Oh well Action: Finish[curses foiled again]"""] fake_llm = FakeListLLM(responses=responses) react_chain = ReActChain(llm=fake_llm, docstore=FakeDocstore()) output...
def test_react_chain_bad_action() ->None: """Test react chain when bad action given.""" bad_action_name = 'BadAction' responses = [f"I'm turning evil\nAction: {bad_action_name}[langchain]", """Oh well Action: Finish[curses foiled again]"""] fake_llm = FakeListLLM(responses=responses) react_c...
Test react chain when bad action given.
get_model_details
"""Get more meta-details about a model retrieved by a given name""" if model is None: model = self.model model_key = self.client._get_invoke_url(model).split('/')[-1] known_fns = self.client.available_functions fn_spec = [f for f in known_fns if f.get('id') == model_key][0] return fn_spec
def get_model_details(self, model: Optional[str]=None) ->dict: """Get more meta-details about a model retrieved by a given name""" if model is None: model = self.model model_key = self.client._get_invoke_url(model).split('/')[-1] known_fns = self.client.available_functions fn_spec = [f for f...
Get more meta-details about a model retrieved by a given name
load
"""Load and return documents from the JSON file.""" docs: List[Document] = [] if self._json_lines: with self.file_path.open(encoding='utf-8') as f: for line in f: line = line.strip() if line: self._parse(line, docs) else: self._parse(self.file_path.read_text(encod...
def load(self) ->List[Document]: """Load and return documents from the JSON file.""" docs: List[Document] = [] if self._json_lines: with self.file_path.open(encoding='utf-8') as f: for line in f: line = line.strip() if line: self._parse...
Load and return documents from the JSON file.
_import_bing_search_tool_BingSearchRun
from langchain_community.tools.bing_search.tool import BingSearchRun return BingSearchRun
def _import_bing_search_tool_BingSearchRun() ->Any: from langchain_community.tools.bing_search.tool import BingSearchRun return BingSearchRun
null
config_specs
return super().config_specs + [ConfigurableFieldSpec(id=id_, annotation= Callable[[], Any]) for id_ in self.ids]
@property def config_specs(self) ->List[ConfigurableFieldSpec]: return super().config_specs + [ConfigurableFieldSpec(id=id_, annotation =Callable[[], Any]) for id_ in self.ids]
null
inference_fn
"""Inference function for testing.""" return pipeline(prompt)[0]['generated_text']
def inference_fn(pipeline: Any, prompt: str, stop: Optional[List[str]]=None ) ->str: """Inference function for testing.""" return pipeline(prompt)[0]['generated_text']
Inference function for testing.
save
output = {'output': input_output.pop('output')} memory.save_context(input_output, output) return output['output']
def save(input_output): output = {'output': input_output.pop('output')} memory.save_context(input_output, output) return output['output']
null
test_concurrent_language_loader_for_python
"""Test Python ConcurrentLoader with parser enabled.""" file_path = Path(__file__).parent.parent.parent / 'examples' loader = ConcurrentLoader.from_filesystem(file_path, glob='hello_world.py', parser=LanguageParser(parser_threshold=5)) docs = loader.load() assert len(docs) == 2
def test_concurrent_language_loader_for_python() ->None: """Test Python ConcurrentLoader with parser enabled.""" file_path = Path(__file__).parent.parent.parent / 'examples' loader = ConcurrentLoader.from_filesystem(file_path, glob= 'hello_world.py', parser=LanguageParser(parser_threshold=5)) do...
Test Python ConcurrentLoader with parser enabled.
_import_searchapi_tool_SearchAPIRun
from langchain_community.tools.searchapi.tool import SearchAPIRun return SearchAPIRun
def _import_searchapi_tool_SearchAPIRun() ->Any: from langchain_community.tools.searchapi.tool import SearchAPIRun return SearchAPIRun
null
create_openai_functions_agent
"""Create an agent that uses OpenAI function calling. Examples: Creating an agent with no memory .. code-block:: python from langchain_community.chat_models import ChatOpenAI from langchain.agents import AgentExecutor, create_openai_functions_agent from langch...
def create_openai_functions_agent(llm: BaseLanguageModel, tools: Sequence[ BaseTool], prompt: ChatPromptTemplate) ->Runnable: """Create an agent that uses OpenAI function calling. Examples: Creating an agent with no memory .. code-block:: python from langchain_community.chat_...
Create an agent that uses OpenAI function calling. Examples: Creating an agent with no memory .. code-block:: python from langchain_community.chat_models import ChatOpenAI from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain import hub pro...
_astream
raise NotImplementedError()
def _astream(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[AsyncCallbackManagerForLLMRun]=None, **kwargs: Any ) ->AsyncIterator[GenerationChunk]: raise NotImplementedError()
null
_load_documents_from_paths
"""Load documents from a list of Dropbox file paths.""" if not self.dropbox_file_paths: raise ValueError('file_paths must be set') return [doc for doc in (self._load_file_from_path(file_path) for file_path in self.dropbox_file_paths) if doc is not None]
def _load_documents_from_paths(self) ->List[Document]: """Load documents from a list of Dropbox file paths.""" if not self.dropbox_file_paths: raise ValueError('file_paths must be set') return [doc for doc in (self._load_file_from_path(file_path) for file_path in self.dropbox_file_paths) if ...
Load documents from a list of Dropbox file paths.
validate_imports_and_browser_provided
"""Check that the arguments are valid.""" lazy_import_playwright_browsers() if values.get('async_browser') is None and values.get('sync_browser') is None: raise ValueError('Either async_browser or sync_browser must be specified.') return values
@root_validator def validate_imports_and_browser_provided(cls, values: dict) ->dict: """Check that the arguments are valid.""" lazy_import_playwright_browsers() if values.get('async_browser') is None and values.get('sync_browser' ) is None: raise ValueError( 'Either async_browser...
Check that the arguments are valid.
_import_bearly_tool
from langchain_community.tools.bearly.tool import BearlyInterpreterTool return BearlyInterpreterTool
def _import_bearly_tool() ->Any: from langchain_community.tools.bearly.tool import BearlyInterpreterTool return BearlyInterpreterTool
null
_import_baseten
from langchain_community.llms.baseten import Baseten return Baseten
def _import_baseten() ->Any: from langchain_community.llms.baseten import Baseten return Baseten
null
validate_params
"""Validate that custom searx params are merged with default ones.""" user_params = values['params'] default = _get_default_params() values['params'] = {**default, **user_params} engines = values.get('engines') if engines: values['params']['engines'] = ','.join(engines) categories = values.get('categories') if cate...
@root_validator() def validate_params(cls, values: Dict) ->Dict: """Validate that custom searx params are merged with default ones.""" user_params = values['params'] default = _get_default_params() values['params'] = {**default, **user_params} engines = values.get('engines') if engines: ...
Validate that custom searx params are merged with default ones.
test_embedding_documents_1
documents = ['foo bar'] embedding = ErnieEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 1 assert len(output[0]) == 384
def test_embedding_documents_1() ->None: documents = ['foo bar'] embedding = ErnieEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 1 assert len(output[0]) == 384
null
test_nested_list_features_throws
with pytest.raises(ValueError): base.embed({'test_namespace': [[1, 2], [3, 4]]}, MockEncoder())
@pytest.mark.requires('vowpal_wabbit_next') def test_nested_list_features_throws() ->None: with pytest.raises(ValueError): base.embed({'test_namespace': [[1, 2], [3, 4]]}, MockEncoder())
null
InputType
return cast(Type[Input], self.custom_input_type ) if self.custom_input_type is not None else self.bound.InputType
@property def InputType(self) ->Type[Input]: return cast(Type[Input], self.custom_input_type ) if self.custom_input_type is not None else self.bound.InputType
null
validate_environment
"""Validate that awadb library is installed.""" try: from awadb import AwaEmbedding except ImportError as exc: raise ImportError( 'Could not import awadb library. Please install it with `pip install awadb`' ) from exc values['client'] = AwaEmbedding() return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that awadb library is installed.""" try: from awadb import AwaEmbedding except ImportError as exc: raise ImportError( 'Could not import awadb library. Please install it with `pip install awadb`' ...
Validate that awadb library is installed.
MilvusRetreiver
"""Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: MilvusRetriever """ warnings.warn( "MilvusRetreiver will be deprecated in the future. Please use MilvusRetriever ('i' before 'e') instead." , DeprecationWarni...
def MilvusRetreiver(*args: Any, **kwargs: Any) ->MilvusRetriever: """Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: MilvusRetriever """ warnings.warn( "MilvusRetreiver will be deprecated in the future...
Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: MilvusRetriever
test_chroma_with_persistence
"""Test end to end construction and search, with persistence.""" chroma_persist_dir = './tests/persist_dir' collection_name = 'test_collection' texts = ['foo', 'bar', 'baz'] docsearch = Chroma.from_texts(collection_name=collection_name, texts=texts, embedding=FakeEmbeddings(), persist_directory=chroma_persist_dir) ...
def test_chroma_with_persistence() ->None: """Test end to end construction and search, with persistence.""" chroma_persist_dir = './tests/persist_dir' collection_name = 'test_collection' texts = ['foo', 'bar', 'baz'] docsearch = Chroma.from_texts(collection_name=collection_name, texts= texts...
Test end to end construction and search, with persistence.
create_prompt
"""Create a prompt for this class."""
@classmethod @abstractmethod def create_prompt(cls, tools: Sequence[BaseTool]) ->BasePromptTemplate: """Create a prompt for this class."""
Create a prompt for this class.
__eq__
"""Check for LLMResult equality by ignoring any metadata related to runs.""" if not isinstance(other, LLMResult): return NotImplemented return self.generations == other.generations and self.llm_output == other.llm_output
def __eq__(self, other: object) ->bool: """Check for LLMResult equality by ignoring any metadata related to runs.""" if not isinstance(other, LLMResult): return NotImplemented return (self.generations == other.generations and self.llm_output == other.llm_output)
Check for LLMResult equality by ignoring any metadata related to runs.
on_chain_error
"""Run when chain errors."""
def on_chain_error(self, error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: """Run when chain errors."""
Run when chain errors.
query
"""Query FalkorDB database.""" try: data = self._graph.query(query, params) return data.result_set except Exception as e: raise ValueError(f'Generated Cypher Statement is not valid\n{e}')
def query(self, query: str, params: dict={}) ->List[Dict[str, Any]]: """Query FalkorDB database.""" try: data = self._graph.query(query, params) return data.result_set except Exception as e: raise ValueError(f'Generated Cypher Statement is not valid\n{e}')
Query FalkorDB database.
authenticate
"""Authenticate using the Amadeus API""" try: from amadeus import Client except ImportError as e: raise ImportError( 'Cannot import amadeus. Please install the package with `pip install amadeus`.' ) from e if 'AMADEUS_CLIENT_ID' in os.environ and 'AMADEUS_CLIENT_SECRET' in os.environ: client...
def authenticate() ->Client: """Authenticate using the Amadeus API""" try: from amadeus import Client except ImportError as e: raise ImportError( 'Cannot import amadeus. Please install the package with `pip install amadeus`.' ) from e if ('AMADEUS_CLIENT_ID' in os...
Authenticate using the Amadeus API
_List
self.write('[') interleave(lambda : self.write(', '), self.dispatch, t.elts) self.write(']')
def _List(self, t): self.write('[') interleave(lambda : self.write(', '), self.dispatch, t.elts) self.write(']')
null
test_format_headers_access_token
"""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_oauth_access_token='test')) headers = tool.api_wrapper._format_headers() assert headers['Content-Type'] =...
def test_format_headers_access_token() ->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_oauth_access_token='test')) headers = ...
Test that the action headers is being created correctly.
_create_retry_decorator
from gpt_router import exceptions errors = [exceptions.GPTRouterApiTimeoutError, exceptions. GPTRouterInternalServerError, exceptions.GPTRouterNotAvailableError, exceptions.GPTRouterTooManyRequestsError] return create_base_retry_decorator(error_types=errors, max_retries=llm. max_retries, run_manager=run_man...
def _create_retry_decorator(llm: GPTRouter, run_manager: Optional[Union[ AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]]=None) ->Callable[ [Any], Any]: from gpt_router import exceptions errors = [exceptions.GPTRouterApiTimeoutError, exceptions. GPTRouterInternalServerError, exceptions....
null
add_files
""" Vectara provides a way to add documents directly via our API where pre-processing and chunking occurs internally in an optimal way This method provides a way to use that API in LangChain Args: files_list: Iterable of strings, each representing a local file path. ...
def add_files(self, files_list: Iterable[str], metadatas: Optional[List[ dict]]=None, **kwargs: Any) ->List[str]: """ Vectara provides a way to add documents directly via our API where pre-processing and chunking occurs internally in an optimal way This method provides a way to use that ...
Vectara provides a way to add documents directly via our API where pre-processing and chunking occurs internally in an optimal way This method provides a way to use that API in LangChain Args: files_list: Iterable of strings, each representing a local file path. Files could be text, HTML, PDF, markdown...
format_prompt
"""Create Chat Messages.""" return StringPromptValue(text=self.format(**kwargs))
def format_prompt(self, **kwargs: Any) ->PromptValue: """Create Chat Messages.""" return StringPromptValue(text=self.format(**kwargs))
Create Chat Messages.
_sort_entities
sorted_nodes = self._networkx_wrapper.get_topological_sort() self.causal_operations.entities.sort(key=lambda x: sorted_nodes.index(x.name))
def _sort_entities(self) ->None: sorted_nodes = self._networkx_wrapper.get_topological_sort() self.causal_operations.entities.sort(key=lambda x: sorted_nodes.index(x .name))
null
stream
yield from self.bound.stream(input, self._merge_configs(config), **{**self. kwargs, **kwargs})
def stream(self, input: Input, config: Optional[RunnableConfig]=None, ** kwargs: Optional[Any]) ->Iterator[Output]: yield from self.bound.stream(input, self._merge_configs(config), **{** self.kwargs, **kwargs})
null
test_agent_tool_return_direct
"""Test agent using tools that return directly.""" tool = 'Search' responses = [f"""FooBarBaz Action: {tool} Action Input: misalignment""", """Oh well Final Answer: curses foiled again"""] fake_llm = FakeListLLM(responses=responses) tools = [Tool(name='Search', func=lambda x: x, description= 'Useful for searchi...
def test_agent_tool_return_direct() ->None: """Test agent using tools that return directly.""" tool = 'Search' responses = [f'FooBarBaz\nAction: {tool}\nAction Input: misalignment', """Oh well Final Answer: curses foiled again"""] fake_llm = FakeListLLM(responses=responses) tools = [Tool(nam...
Test agent using tools that return directly.
_import_office365_messages_search
from langchain_community.tools.office365.messages_search import O365SearchEmails return O365SearchEmails
def _import_office365_messages_search() ->Any: from langchain_community.tools.office365.messages_search import O365SearchEmails return O365SearchEmails
null
test_sync_async_equivalent
url = 'https://docs.python.org/3.9/' loader = RecursiveUrlLoader(url, use_async=False, max_depth=2) async_loader = RecursiveUrlLoader(url, use_async=False, max_depth=2) docs = sorted(loader.load(), key=lambda d: d.metadata['source']) async_docs = sorted(async_loader.load(), key=lambda d: d.metadata['source']) assert do...
def test_sync_async_equivalent() ->None: url = 'https://docs.python.org/3.9/' loader = RecursiveUrlLoader(url, use_async=False, max_depth=2) async_loader = RecursiveUrlLoader(url, use_async=False, max_depth=2) docs = sorted(loader.load(), key=lambda d: d.metadata['source']) async_docs = sorted(async...
null
test_create_action_payload
"""Test that the action payload is being created correctly.""" tool = ZapierNLARunAction(action_id='test', zapier_description='test', params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper( zapier_nla_api_key='test')) payload = tool.api_wrapper._create_action_payload('some instructions') assert payload['i...
def test_create_action_payload() ->None: """Test that the action payload is being created correctly.""" tool = ZapierNLARunAction(action_id='test', zapier_description='test', params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper( zapier_nla_api_key='test')) payload = tool.api_wrapper....
Test that the action payload is being created correctly.
_import_promptlayer
from langchain_community.llms.promptlayer_openai import PromptLayerOpenAI return PromptLayerOpenAI
def _import_promptlayer() ->Any: from langchain_community.llms.promptlayer_openai import PromptLayerOpenAI return PromptLayerOpenAI
null
_call
"""Generate Cypher statement, use it to look up in db and answer question.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() question = inputs[self.input_key] intermediate_steps: List = [] generated_cypher = self.cypher_generation_chain.run({'question': ...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: """Generate Cypher statement, use it to look up in db and answer question.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child(...
Generate Cypher statement, use it to look up in db and answer question.
test_opensearch_with_custom_field_name_appx_true
"""Test Approximate Search with custom field name appx true.""" text_input = ['add', 'test', 'text', 'method'] docsearch = OpenSearchVectorSearch.from_texts(text_input, FakeEmbeddings(), opensearch_url=DEFAULT_OPENSEARCH_URL, is_appx_search=True) output = docsearch.similarity_search('add', k=1) assert output == [Do...
def test_opensearch_with_custom_field_name_appx_true() ->None: """Test Approximate Search with custom field name appx true.""" text_input = ['add', 'test', 'text', 'method'] docsearch = OpenSearchVectorSearch.from_texts(text_input, FakeEmbeddings(), opensearch_url=DEFAULT_OPENSEARCH_URL, is_...
Test Approximate Search with custom field name appx true.
foo
"""Docstring Args: bar: int baz: str """ assert callbacks is not None return str(bar) + baz
def foo(bar: int, baz: str, callbacks: Optional[CallbackManagerForToolRun]=None ) ->str: """Docstring Args: bar: int baz: str """ assert callbacks is not None return str(bar) + baz
Docstring Args: bar: int baz: str
get_lc_namespace
"""Get the namespace of the langchain object.""" return ['langchain', 'llms', 'openai']
@classmethod def get_lc_namespace(cls) ->List[str]: """Get the namespace of the langchain object.""" return ['langchain', 'llms', 'openai']
Get the namespace of the langchain object.
observation_prefix
"""Prefix to append the observation with.""" return 'Observation: '
@property def observation_prefix(self) ->str: """Prefix to append the observation with.""" return 'Observation: '
Prefix to append the observation with.
_type
return 'vector_sql_retrieve_all_parser'
@property def _type(self) ->str: return 'vector_sql_retrieve_all_parser'
null
test_sequential_missing_inputs
"""Test error is raised when input variables are missing.""" chain_1 = FakeChain(input_variables=['foo'], output_variables=['bar']) chain_2 = FakeChain(input_variables=['bar', 'test'], output_variables=['baz']) with pytest.raises(ValueError): SequentialChain(chains=[chain_1, chain_2], input_variables=['foo'])
def test_sequential_missing_inputs() ->None: """Test error is raised when input variables are missing.""" chain_1 = FakeChain(input_variables=['foo'], output_variables=['bar']) chain_2 = FakeChain(input_variables=['bar', 'test'], output_variables=[ 'baz']) with pytest.raises(ValueError): ...
Test error is raised when input variables are missing.
test_whatsapp_chat_loader
"""Test WhatsAppChatLoader.""" file_path = Path(__file__).parent.parent / 'examples' / 'whatsapp_chat.txt' loader = WhatsAppChatLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 assert docs[0].metadata['source'] == str(file_path) assert docs[0].page_content == """James on 05.05.23, 15:48:11: Hi here Us...
def test_whatsapp_chat_loader() ->None: """Test WhatsAppChatLoader.""" file_path = Path(__file__).parent.parent / 'examples' / 'whatsapp_chat.txt' loader = WhatsAppChatLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 assert docs[0].metadata['source'] == str(file_path) assert...
Test WhatsAppChatLoader.
body_params
if self.request_body is None: return [] return [prop.name for prop in self.request_body.properties]
@property def body_params(self) ->List[str]: if self.request_body is None: return [] return [prop.name for prop in self.request_body.properties]
null
test_runnable_lambda_stream
"""Test that stream works for both normal functions & those returning Runnable.""" output: List[Any] = [chunk for chunk in RunnableLambda(range).stream(5)] assert output == [range(5)] llm_res = "i'm a textbot" llm = FakeStreamingListLLM(responses=[llm_res], sleep=0.01) output = list(RunnableLambda(lambda x: llm).stream...
def test_runnable_lambda_stream() ->None: """Test that stream works for both normal functions & those returning Runnable.""" output: List[Any] = [chunk for chunk in RunnableLambda(range).stream(5)] assert output == [range(5)] llm_res = "i'm a textbot" llm = FakeStreamingListLLM(responses=[llm_res], ...
Test that stream works for both normal functions & those returning Runnable.
test_self_hosted_huggingface_pipeline_text_generation
"""Test valid call to self-hosted HuggingFace text generation model.""" gpu = get_remote_instance() llm = SelfHostedHuggingFaceLLM(model_id='gpt2', task='text-generation', model_kwargs={'n_positions': 1024}, hardware=gpu, model_reqs=model_reqs) output = llm('Say foo:') assert isinstance(output, str)
def test_self_hosted_huggingface_pipeline_text_generation() ->None: """Test valid call to self-hosted HuggingFace text generation model.""" gpu = get_remote_instance() llm = SelfHostedHuggingFaceLLM(model_id='gpt2', task='text-generation', model_kwargs={'n_positions': 1024}, hardware=gpu, model_reqs...
Test valid call to self-hosted HuggingFace text generation model.
_hash_string_to_uuid
"""Hash a string and returns the corresponding UUID.""" hash_value = hashlib.sha1(input_string.encode('utf-8')).hexdigest() return uuid.uuid5(NAMESPACE_UUID, hash_value)
def _hash_string_to_uuid(input_string: str) ->uuid.UUID: """Hash a string and returns the corresponding UUID.""" hash_value = hashlib.sha1(input_string.encode('utf-8')).hexdigest() return uuid.uuid5(NAMESPACE_UUID, hash_value)
Hash a string and returns the corresponding UUID.
load
"""Load data into Document objects. Attention: This implementation starts an asyncio event loop which will only work if running in a sync env. In an async env, it should fail since there is already an event loop running. This code should be updated to kick off the event loop f...
def load(self) ->List[Document]: """Load data into Document objects. Attention: This implementation starts an asyncio event loop which will only work if running in a sync env. In an async env, it should fail since there is already an event loop running. This code should be...
Load data into Document objects. Attention: This implementation starts an asyncio event loop which will only work if running in a sync env. In an async env, it should fail since there is already an event loop running. This code should be updated to kick off the event loop from a separate thread if running within an ...
__getattr__
"""Get attr name.""" if name == 'create_xorbits_agent': HERE = Path(__file__).parents[3] here = as_import_path(Path(__file__).parent, relative_to=HERE) old_path = 'langchain.' + here + '.' + name new_path = 'langchain_experimental.' + here + '.' + name raise ImportError( f"""This agent has b...
def __getattr__(name: str) ->Any: """Get attr name.""" if name == 'create_xorbits_agent': HERE = Path(__file__).parents[3] here = as_import_path(Path(__file__).parent, relative_to=HERE) old_path = 'langchain.' + here + '.' + name new_path = 'langchain_experimental.' + here + '.' ...
Get attr name.
load
try: from git import Blob, Repo except ImportError as ex: raise ImportError( 'Could not import git python package. Please install it with `pip install GitPython`.' ) from ex if not os.path.exists(self.repo_path) and self.clone_url is None: raise ValueError(f'Path {self.repo_path} does not ex...
def load(self) ->List[Document]: try: from git import Blob, Repo except ImportError as ex: raise ImportError( 'Could not import git python package. Please install it with `pip install GitPython`.' ) from ex if not os.path.exists(self.repo_path) and self.clone_url is N...
null
__init__
try: from cassio.vector import VectorTable except (ImportError, ModuleNotFoundError): raise ImportError( 'Could not import cassio python package. Please install it with `pip install cassio`.' ) """Create a vector table.""" self.embedding = embedding self.session = session self.keyspace = keyspac...
def __init__(self, embedding: Embeddings, session: Session, keyspace: str, table_name: str, ttl_seconds: Optional[int]=None) ->None: try: from cassio.vector import VectorTable except (ImportError, ModuleNotFoundError): raise ImportError( 'Could not import cassio python package. P...
null
structured_tool
"""Return the arguments directly.""" return {'some_enum': some_enum, 'some_base_model': some_base_model}
@tool def structured_tool(some_enum: SomeEnum, some_base_model: SomeBaseModel ) ->dict: """Return the arguments directly.""" return {'some_enum': some_enum, 'some_base_model': some_base_model}
Return the arguments directly.
_get_connection
try: import singlestoredb as s2 except ImportError: raise ImportError( 'Could not import singlestoredb python package. Please install it with `pip install singlestoredb`.' ) return s2.connect(**self.connection_kwargs)
def _get_connection(self: SingleStoreDB) ->Any: try: import singlestoredb as s2 except ImportError: raise ImportError( 'Could not import singlestoredb python package. Please install it with `pip install singlestoredb`.' ) return s2.connect(**self.connection_kwargs)
null
_call
""" Wrapper around the bittensor top miner models. Its built by Neural Internet. Call the Neural Internet's BTVEP Server and return the output. Parameters (optional): system_prompt(str): A system prompt defining how your model should respond. top_responses(int): Total t...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """ Wrapper around the bittensor top miner models. Its built by Neural Internet. Call the Neural Internet's BTVEP Server and return the output. Param...
Wrapper around the bittensor top miner models. Its built by Neural Internet. Call the Neural Internet's BTVEP Server and return the output. Parameters (optional): system_prompt(str): A system prompt defining how your model should respond. top_responses(int): Total top miner responses to retrieve from Bittenso...
test_selector_threshold_zero
"""Tests NGramOverlapExampleSelector threshold set to 0.0.""" selector.threshold = 0.0 sentence = 'Spot can run.' output = selector.select_examples({'input': sentence}) assert output == [EXAMPLES[2], EXAMPLES[0]]
def test_selector_threshold_zero(selector: NGramOverlapExampleSelector) ->None: """Tests NGramOverlapExampleSelector threshold set to 0.0.""" selector.threshold = 0.0 sentence = 'Spot can run.' output = selector.select_examples({'input': sentence}) assert output == [EXAMPLES[2], EXAMPLES[0]]
Tests NGramOverlapExampleSelector threshold set to 0.0.
_import_huggingface_endpoint
from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint return HuggingFaceEndpoint
def _import_huggingface_endpoint() ->Any: from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint return HuggingFaceEndpoint
null
load
"""Load documents.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load documents.""" return list(self.lazy_load())
Load documents.
similarity_search_by_vector
"""Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query vector. """ raise NotImplementedError
def similarity_search_by_vector(self, embedding: List[float], k: int=4, ** kwargs: Any) ->List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. Return...
Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query vector.
_convert_message_to_dict
message_dict: Dict[str, Any] if isinstance(message, ChatMessage): message_dict = {'role': message.role, 'content': message.content} elif isinstance(message, HumanMessage): message_dict = {'role': 'user', 'content': message.content} elif isinstance(message, AIMessage): message_dict = {'role': 'assistant', 'c...
def _convert_message_to_dict(message: BaseMessage) ->dict: message_dict: Dict[str, Any] if isinstance(message, ChatMessage): message_dict = {'role': message.role, 'content': message.content} elif isinstance(message, HumanMessage): message_dict = {'role': 'user', 'content': message.content} ...
null
__init__
"""Initialize with a file path. Args: file_path: The path to the file to load. """ with open(file_path, 'rb') as f: encoding, _ = tokenize.detect_encoding(f.readline) super().__init__(file_path=file_path, encoding=encoding)
def __init__(self, file_path: str): """Initialize with a file path. Args: file_path: The path to the file to load. """ with open(file_path, 'rb') as f: encoding, _ = tokenize.detect_encoding(f.readline) super().__init__(file_path=file_path, encoding=encoding)
Initialize with a file path. Args: file_path: The path to the file to load.
get_format_instructions
return FORMAT_INSTRUCTIONS
def get_format_instructions(self) ->str: return FORMAT_INSTRUCTIONS
null
test_default_embeddings_mixed_w_explicit_user_embeddings
llm, PROMPT = setup() feature_embedder = pick_best_chain.PickBestFeatureEmbedder(auto_embed=True, model=MockEncoderReturnsList()) chain = pick_best_chain.PickBest.from_llm(llm=llm, prompt=PROMPT, feature_embedder=feature_embedder, auto_embed=True) str1 = '0' str2 = '1' encoded_str2 = rl_chain.stringify_embeddin...
@pytest.mark.requires('vowpal_wabbit_next', 'sentence_transformers') def test_default_embeddings_mixed_w_explicit_user_embeddings() ->None: llm, PROMPT = setup() feature_embedder = pick_best_chain.PickBestFeatureEmbedder(auto_embed= True, model=MockEncoderReturnsList()) chain = pick_best_chain.PickB...
null
test_from_texts_not_supported
with pytest.raises(NotImplementedError) as ex: DatabricksVectorSearch.from_texts(fake_texts, FakeEmbeddings()) assert '`from_texts` is not supported. Use `add_texts` to add to existing direct-access index.' in str( ex.value)
@pytest.mark.requires('databricks', 'databricks.vector_search') def test_from_texts_not_supported() ->None: with pytest.raises(NotImplementedError) as ex: DatabricksVectorSearch.from_texts(fake_texts, FakeEmbeddings()) assert '`from_texts` is not supported. Use `add_texts` to add to existing direct-acce...
null
_create_index_by_id
"""Creates a MatchingEngineIndex object by id. Args: index_id: The created index id. project_id: The project to retrieve index from. region: Location to retrieve index from. credentials: GCS credentials. Returns: A configured MatchingEngineIn...
@classmethod def _create_index_by_id(cls, index_id: str, project_id: str, region: str, credentials: 'Credentials') ->MatchingEngineIndex: """Creates a MatchingEngineIndex object by id. Args: index_id: The created index id. project_id: The project to retrieve index from. ...
Creates a MatchingEngineIndex object by id. Args: index_id: The created index id. project_id: The project to retrieve index from. region: Location to retrieve index from. credentials: GCS credentials. Returns: A configured MatchingEngineIndex.
_import_reddit_search_RedditSearchRun
from langchain_community.tools.reddit_search.tool import RedditSearchRun return RedditSearchRun
def _import_reddit_search_RedditSearchRun() ->Any: from langchain_community.tools.reddit_search.tool import RedditSearchRun return RedditSearchRun
null
similarity_search_with_score_by_vector
""" Performs a search on the query string and returns results with scores. Args: embedding (List[float]): The embedding vector being searched. k (int, optional): The number of results to return. Default is 4. param (dict): Specifies the search parameters ...
def similarity_search_with_score_by_vector(self, embedding: List[float], k: int=4, param: Optional[dict]=None, expr: Optional[str]=None, timeout: Optional[int]=None, **kwargs: Any) ->List[Tuple[Document, float]]: """ Performs a search on the query string and returns results with scores. Arg...
Performs a search on the query string and returns results with scores. Args: embedding (List[float]): The embedding vector being searched. k (int, optional): The number of results to return. Default is 4. param (dict): Specifies the search parameters for the index. Default is None. expr (str, o...
on_llm_new_token
self.on_llm_new_token_common()
def on_llm_new_token(self, *args: Any, **kwargs: Any) ->Any: self.on_llm_new_token_common()
null
__init__
"""Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function. """ load_fn_kwargs = {'model_id': kwargs.get('model_...
def __init__(self, **kwargs: Any): """Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function. """ load_...
Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference function.
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. fetch_k: Num...
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, filter: Optional[Dict[str, str]]=None, ** kwargs: Any) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query ...
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. fetch_k: Number of Documents to fetch to pass to MMR algorithm....
test_cypher_return_correct_schema
"""Test that chain returns direct results.""" 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.q...
def test_cypher_return_correct_schema() ->None: """Test that chain returns direct results.""" 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 No...
Test that chain returns direct results.
test_llamacpp_incorrect_field
with pytest.warns(match='not default parameter'): llm = LlamaCpp(model_path=get_model(), n_gqa=None) llm.model_kwargs == {'n_gqa': None}
def test_llamacpp_incorrect_field() ->None: with pytest.warns(match='not default parameter'): llm = LlamaCpp(model_path=get_model(), n_gqa=None) llm.model_kwargs == {'n_gqa': None}
null
test_truncate_word
assert truncate_word('Hello World', length=5) == 'He...' assert truncate_word('Hello World', length=0) == 'Hello World' assert truncate_word('Hello World', length=-10) == 'Hello World' assert truncate_word('Hello World', length=5, suffix='!!!') == 'He!!!' assert truncate_word('Hello World', length=12, suffix='!!!') == ...
def test_truncate_word() ->None: assert truncate_word('Hello World', length=5) == 'He...' assert truncate_word('Hello World', length=0) == 'Hello World' assert truncate_word('Hello World', length=-10) == 'Hello World' assert truncate_word('Hello World', length=5, suffix='!!!') == 'He!!!' assert trun...
null
_identifying_params
"""Get the identifying parameters.""" return {'model': self.model, 'model_config': self.model_config, 'generation_config': self.generation_config, 'streaming': self.streaming}
@property def _identifying_params(self) ->Dict[str, Any]: """Get the identifying parameters.""" return {'model': self.model, 'model_config': self.model_config, 'generation_config': self.generation_config, 'streaming': self. streaming}
Get the identifying parameters.