id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
d25444482d96-1
}, ) tsds_client = TensorflowDatasets( dataset_name="mlqa/en", split_name="train", load_max_docs=MAX_DOCS, sample_to_document_function=mlqaen_example_to_document, ) """ dataset_name: str =...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html
d25444482d96-2
for s in self.dataset.take(self.load_max_docs) if self.sample_to_document_function is not None ) [docs] def load(self) -> List[Document]: """Download a selected dataset. Returns: a list of Documents. """ return list(self.lazy_load())
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html
59a8cc85b688-0
Source code for langchain.utilities.graphql import json from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class GraphQLAPIWrapper(BaseModel): """Wrapper around GraphQL API. To use, you should have the ``gql`` python package installed. This wrapper w...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
59a8cc85b688-1
return json.dumps(result, indent=2) def _execute_query(self, query: str) -> Dict[str, Any]: """Execute a GraphQL query and return the results.""" document_node = self.gql_function(query) result = self.gql_client.execute(document_node) return result
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
5150ba5581f8-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https:/...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-1
:class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accepted searx search API <https://docs.searxng.org/dev...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-2
.. code-block:: python # select the github engine and pass the search suffix s = SearchWrapper("langchain library", query_suffix="!gh") s = SearchWrapper("langchain library") # select github the conventional google search syntax s.run("large language models", query_suffix="site:g...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-3
def _get_default_params() -> dict: return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" [docs] def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-4
Example with SSL disabled: .. code-block:: python from langchain.utilities import SearxSearchWrapper # note the unsecure parameter is not needed if you pass the url scheme as # http searx = SearxSearchWrapper(searx_host="http://localhost:8888", ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-5
if categories: values["params"]["categories"] = ",".join(categories) searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") if not searx_host.startswith("http"): print( f"Warning: missing the url scheme on host \ ! assuming secure ht...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-6
) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result else: async with self.aiosession.get( ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-7
searx.run("what is the weather in France ?", engine="qwant") # the same result can be achieved using the `!` syntax of searx # to select the engine using `query_suffix` searx.run("what is the weather in France ?", query_suffix="!qwant") """ _params = { ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) an...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-9
engines: List of engines to use for the query. categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
5150ba5581f8-10
] [docs] async def aresults( self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more i...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
0158369c71a0-0
Source code for langchain.utilities.bibtex """Util that calls bibtexparser.""" import logging from typing import Any, Dict, List, Mapping from pydantic import BaseModel, Extra, root_validator logger = logging.getLogger(__name__) OPTIONAL_FIELDS = [ "annotate", "booktitle", "editor", "howpublished", ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html
0158369c71a0-1
import bibtexparser with open(path) as file: entries = bibtexparser.load(file).entries return entries [docs] def get_metadata( self, entry: Mapping[str, Any], load_extra: bool = False ) -> Dict[str, Any]: """Get metadata for the given entry.""" publication = en...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html
e5d73737ce81-0
Source code for langchain.docstore.arbitrary_fn from typing import Callable, Union from langchain.docstore.base import Docstore from langchain.schema import Document [docs]class DocstoreFn(Docstore): """Langchain Docstore via arbitrary lookup function. This is useful when: * it's expensive to construct an ...
https://api.python.langchain.com/en/latest/_modules/langchain/docstore/arbitrary_fn.html
013ce9284415-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, List, Optional, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simp...
https://api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
013ce9284415-1
""" if search not in self._dict: return f"ID {search} not found." else: return self._dict[search]
https://api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
6e16e2a4f95b-0
Source code for langchain.docstore.base """Interface to access to place that stores documents.""" from abc import ABC, abstractmethod from typing import Dict, List, Union from langchain.docstore.document import Document [docs]class Docstore(ABC): """Interface to access to place that stores documents.""" [docs] @...
https://api.python.langchain.com/en/latest/_modules/langchain/docstore/base.html
4adbd5e7b647-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" [docs] def __init__(self) -> None: "...
https://api.python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
136934ef52e8-0
Source code for langchain.agents.agent_iterator from __future__ import annotations import logging import time from abc import ABC, abstractmethod from asyncio import CancelledError from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, NoReturn, Optional, ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-1
self, agent_executor: AgentExecutor, inputs: Any, callbacks: Callbacks = None, *, tags: Optional[list[str]] = None, include_run_info: bool = False, async_: bool = False, ): """ Initialize the AgentExecutorIterator with the given AgentExecutor, ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-2
return self._tags @tags.setter @rebuild_callback_manager_on_set def tags(self, tags: Optional[List[str]]) -> None: """When tags are changed after __init__, rebuild callback mgr""" self._tags = tags @property def agent_executor(self) -> AgentExecutor: return self._agent_execut...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-3
) [docs] def reset(self) -> None: """ Reset the iterator to its initial state, clearing intermediate steps, iterations, and time elapsed. """ logger.debug("(Re)setting AgentExecutorIterator to fresh state") self.intermediate_steps: list[tuple[AgentAction, str]] = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-4
return self._final_outputs @final_outputs.setter def final_outputs(self, outputs: Optional[Dict[str, Any]]) -> None: # have access to intermediate steps by design in iterator, # so return only outputs may as well always be true. self._final_outputs = None if outputs: ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-5
""" pass async def _on_first_async_step(self) -> None: """ Perform any necessary setup for the first step of the asynchronous iterator. """ # on first step, need to await callback manager and start async timeout ctxmgr if self.iterations == 0: assert isins...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-6
return await self._acall_next() except StopAsyncIteration: raise except (TimeoutError, CancelledError): await self.timeout_manager.__aexit__(None, None, None) self.timeout_manager = None return await self._astop() except (KeyboardInterrupt, Excepti...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-7
run_manager: Optional[CallbackManagerForChainRun], ) -> Dict[str, Union[str, List[Tuple[AgentAction, str]]]]: """ Process the output of the next step, handling AgentFinish and tool return cases. """ logger.debug("Processing output of Agent loop step") if isinstance(ne...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-8
""" Process the output of the next async step, handling AgentFinish and tool return cases. """ logger.debug("Processing output of async Agent loop step") if isinstance(next_step_output, AgentFinish): logger.debug( "Hit AgentFinish: _areturn -> on_chain...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-9
self.intermediate_steps, **self.inputs, ) assert ( isinstance(self.run_manager, CallbackManagerForChainRun) or self.run_manager is None ) returned_output = self.agent_executor._return( output, self.intermediate_steps, run_manager=self.run_m...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
136934ef52e8-10
) next_step_output = self._execute_next_step(self.run_manager) output = self._process_next_step_output(next_step_output, self.run_manager) self.update_iterations() return output async def _acall_next(self) -> dict[str, Any]: """ Perform a single iteration of the async...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html
1ac18c9f5f4d-0
Source code for langchain.agents.agent """Chain that takes in an input and produces an action and action input.""" from __future__ import annotations import asyncio import json import logging import time from abc import abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-1
return None [docs] @abstractmethod def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Ste...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-2
# `force` just returns a constant string return AgentFinish( {"output": "Agent stopped due to iteration limit or time limit."}, "" ) else: raise ValueError( f"Got unsupported early_stopping_method `{early_stopping_method}`" ) [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-3
directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save agent_dict = self.dict() if save_path.suffix == ".json": with open(file_path, "w") as f: json.dump(agent_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(fil...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-4
callbacks: Callbacks = None, **kwargs: Any, ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with the observations. callbacks: Callbacks to run. ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-5
Args: file_path: Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path="path/agent.yaml") """ # Convert file to Path object. if isinstance(file_path, str): sav...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-6
@property def input_keys(self) -> List[str]: """Return the input keys. Returns: List of input keys. """ return list(set(self.llm_chain.input_keys) - {"intermediate_steps"}) [docs] def dict(self, **kwargs: Any) -> Dict: """Return dictionary representation of age...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-7
Returns: Action specifying what tool to use. """ output = await self.llm_chain.arun( intermediate_steps=intermediate_steps, stop=self.stop, callbacks=callbacks, **kwargs, ) return self.output_parser.parse(output) [docs] def t...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-8
f"\n\t{self.observation_prefix.rstrip()}", ] def _construct_scratchpad( self, intermediate_steps: List[Tuple[AgentAction, str]] ) -> Union[str, List[BaseMessage]]: """Construct the scratchpad that lets the agent continue its thought process.""" thoughts = "" for action, o...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-9
**kwargs: User inputs. Returns: Action specifying what tool to use. """ full_inputs = self.get_full_inputs(intermediate_steps, **kwargs) full_output = await self.llm_chain.apredict(callbacks=callbacks, **full_inputs) agent_output = await self.output_parser.aparse(full...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-10
prompt.suffix += "\n{agent_scratchpad}" else: raise ValueError(f"Got unexpected prompt type {type(prompt)}") return values @property @abstractmethod def observation_prefix(self) -> str: """Prefix to append the observation with.""" @property @abstractmethod...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-11
return cls( llm_chain=llm_chain, allowed_tools=tool_names, output_parser=_output_parser, **kwargs, ) [docs] def return_stopped_response( self, early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwarg...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-12
# we just return the full output return AgentFinish({"output": full_output}, full_output) else: raise ValueError( "early_stopping_method should be one of `force` or `generate`, " f"got {early_stopping_method}" ) [docs] def tool_run_loggi...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-13
"""The maximum number of steps to take before ending the execution loop. Setting to 'None' could lead to an infinite loop.""" max_execution_time: Optional[float] = None """The maximum amount of wall clock time to spend in the execution loop. """ early_stopping_method: str = "force" ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-14
tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any, ) -> AgentExecutor: """Create from agent and tools.""" return cls( agent=agent, tools=tools, callback_manager=callback_manager, **kwargs ) @root_validator() d...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-15
"`.save_agent(...)`" ) [docs] def save_agent(self, file_path: Union[Path, str]) -> None: """Save the underlying agent.""" return self.agent.save(file_path) [docs] def iter( self, inputs: Any, callbacks: Callbacks = None, *, include_run_info: bool = F...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-16
return False return True def _return( self, output: AgentFinish, intermediate_steps: list, run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: if run_manager: run_manager.on_agent_finish(output, color="green", verbose=self.ve...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-17
output = self.agent.plan( intermediate_steps, callbacks=run_manager.get_child() if run_manager else None, **inputs, ) except OutputParserException as e: if isinstance(self.handle_parsing_errors, bool): raise_error = not self...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-18
result = [] for agent_action in actions: if run_manager: run_manager.on_agent_action(agent_action, color="green") # Otherwise we lookup the tool if agent_action.tool in name_to_tool_map: tool = name_to_tool_map[agent_action.tool] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-19
"""Take a single step in the thought-action-observation loop. Override this to take control of how the agent makes and acts on choices. """ try: intermediate_steps = self._prepare_intermediate_steps(intermediate_steps) # Call the LLM to see what to do. output ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-20
if isinstance(output, AgentFinish): return output actions: List[AgentAction] if isinstance(output, AgentAction): actions = [output] else: actions = output async def _aperform_agent_action( agent_action: AgentAction, ) -> Tuple[Agent...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-21
result = await asyncio.gather( *[_aperform_agent_action(agent_action) for agent_action in actions] ) return list(result) def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Run text...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-22
if tool_return is not None: return self._return( tool_return, intermediate_steps, run_manager=run_manager ) iterations += 1 time_elapsed = time.time() - start_time output = self.agent.return_stopped_response( sel...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-23
return await self._areturn( next_step_output, intermediate_steps, run_manager=run_manager, ) intermediate_steps.extend(next_step_output) if len(next_step_output) == 1: ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
1ac18c9f5f4d-24
{self.agent.return_values[0]: observation}, "", ) return None def _prepare_intermediate_steps( self, intermediate_steps: List[Tuple[AgentAction, str]] ) -> List[Tuple[AgentAction, str]]: if ( isinstance(self.trim_intermediate_steps, int) ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
203bc18679ac-0
Source code for langchain.agents.load_tools # flake8: noqa """Load tools.""" import warnings from typing import Any, Dict, List, Optional, Callable, Tuple from mypy_extensions import Arg, KwArg from langchain.agents.tools import Tool from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-1
) from langchain.tools.scenexplain.tool import SceneXplainTool from langchain.tools.searx_search.tool import SearxSearchResults, SearxSearchRun from langchain.tools.shell.tool import ShellTool from langchain.tools.sleep.tool import SleepTool from langchain.tools.wikipedia.tool import WikipediaQueryRun from langchain.to...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-2
return PythonREPLTool() def _get_tools_requests_get() -> BaseTool: return RequestsGetTool(requests_wrapper=TextRequestsWrapper()) def _get_tools_requests_post() -> BaseTool: return RequestsPostTool(requests_wrapper=TextRequestsWrapper()) def _get_tools_requests_patch() -> BaseTool: return RequestsPatchTool(...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-3
) def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool: chain = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DOCS) return Tool( name="Open Meteo API", description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-4
) return Tool( name="TMDB API", description="Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.", func=chain.run, ) def _get_podcast_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool: ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-5
def _get_golden_query(**kwargs: Any) -> BaseTool: return GoldenQueryRun(api_wrapper=GoldenQueryAPIWrapper(**kwargs)) def _get_pubmed(**kwargs: Any) -> BaseTool: return PubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs)) def _get_google_serper(**kwargs: Any) -> BaseTool: return GoogleSerperRun(api_wrapper...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-6
func=TwilioAPIWrapper(**kwargs).run, ) def _get_searx_search(**kwargs: Any) -> BaseTool: return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs)) def _get_searx_search_results_json(**kwargs: Any) -> BaseTool: wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"} return SearxSearchR...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-7
def _get_dataforseo_api_search_json(**kwargs: Any) -> BaseTool: return DataForSeoAPISearchResults(api_wrapper=DataForSeoAPIWrapper(**kwargs)) _EXTRA_LLM_TOOLS: Dict[ str, Tuple[Callable[[Arg(BaseLanguageModel, "llm"), KwArg(Any)], BaseTool], List[str]], ] = { "news-api": (_get_news_api, ["news_api_key"]...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-8
"google-serper-results-json": ( _get_google_serper_results_json, ["serper_api_key", "aiosession"], ), "serpapi": (_get_serpapi, ["serpapi_api_key", "aiosession"]), "dalle-image-generator": (_get_dalle_image_generator, ["openai_api_key"]), "twilio": (_get_twilio, ["account_sid", "auth_tok...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-9
_get_dataforseo_api_search_json, ["api_login", "api_password", "aiosession"], ), } def _handle_callbacks( callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks ) -> Callbacks: if callback_manager is not None: warnings.warn( "callback_manager is deprecated. Please ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-10
token=token, remote=remote, **kwargs, ) outputs = hf_tool.outputs if set(outputs) != {"text"}: raise NotImplementedError("Multimodal outputs not supported yet.") inputs = hf_tool.inputs if set(inputs) != {"text"}: raise NotImplementedError("Multimodal inputs not suppo...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-11
tool_names.extend(requests_method_tools) elif name in _BASE_TOOLS: tools.append(_BASE_TOOLS[name]()) elif name in _LLM_TOOLS: if llm is None: raise ValueError(f"Tool {name} requires an LLM to be provided") tool = _LLM_TOOLS[name](llm) tools...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
203bc18679ac-12
return ( list(_BASE_TOOLS) + list(_EXTRA_OPTIONAL_TOOLS) + list(_EXTRA_LLM_TOOLS) + list(_LLM_TOOLS) )
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
4e7c4cc3ea04-0
Source code for langchain.agents.loading """Functionality for loading agents.""" import json import logging from pathlib import Path from typing import Any, List, Optional, Union import yaml from langchain.agents.agent import BaseMultiActionAgent, BaseSingleActionAgent from langchain.agents.tools import Tool from langc...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html
4e7c4cc3ea04-1
tools: List of tools this agent has access to. **kwargs: Additional key word arguments passed to the agent executor. Returns: An agent executor. """ if "_type" not in config: raise ValueError("Must specify an agent Type in config") load_from_tools = config.pop("load_from_llm_and_...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html
4e7c4cc3ea04-2
del config["output_parser"] combined_config = {**config, **kwargs} return agent_cls(**combined_config) # type: ignore [docs]def load_agent( path: Union[str, Path], **kwargs: Any ) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]: """Unified method for loading an agent from LangChainHub or local fs...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html
139bd942b53f-0
Source code for langchain.agents.initialize """Load agent.""" from typing import Any, Optional, Sequence from langchain.agents.agent import AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.loading import AGENT_TO_CLASS, load_agent from langchain.callbacks.base import BaseCallbackMa...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
139bd942b53f-1
agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION if agent is not None and agent_path is not None: raise ValueError( "Both `agent` and `agent_path` are specified, " "but at most only one should be." ) if agent is not None: if agent not in AGENT_TO_CLASS: r...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
052ab803acde-0
Source code for langchain.agents.agent_types from enum import Enum [docs]class AgentType(str, Enum): """Enumerator with the Agent types.""" ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description" REACT_DOCSTORE = "react-docstore" SELF_ASK_WITH_SEARCH = "self-ask-with-search" CONVERSATIONAL_REACT...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html
0c4043ab951b-0
Source code for langchain.agents.tools """Interface for tools.""" from typing import List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool, Tool, tool [docs]class InvalidTool(BaseTool): """Tool that is ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/tools.html
61b29554c313-0
Source code for langchain.agents.utils from typing import Sequence from langchain.tools.base import BaseTool [docs]def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None: """Validate tools for single input.""" for tool in tools: if not tool.is_single_input: raise...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/utils.html
06f177afca8c-0
Source code for langchain.agents.schema from typing import Any, Dict, List, Tuple from langchain.prompts.chat import ChatPromptTemplate from langchain.schema import AgentAction [docs]class AgentScratchPadChatPromptTemplate(ChatPromptTemplate): """Chat prompt template for the agent scratchpad.""" def _construct_...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/schema.html
5e69338ff737-0
Source code for langchain.agents.react.base """Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.""" from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types impo...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
5e69338ff737-1
super()._validate_tools(tools) if len(tools) != 2: raise ValueError(f"Exactly two tools must be specified, but got {tools}") tool_names = {tool.name for tool in tools} if tool_names != {"Lookup", "Search"}: raise ValueError( f"Tool names should be Lookup a...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
5e69338ff737-2
raise ValueError("Cannot lookup without a successful search first") if term.lower() != self.lookup_str: self.lookup_str = term.lower() self.lookup_index = 0 else: self.lookup_index += 1 lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
5e69338ff737-3
if tool_names != {"Play"}: raise ValueError(f"Tool name should be Play, got {tool_names}") [docs]class ReActChain(AgentExecutor): """Chain that implements the ReAct paper. Example: .. code-block:: python from langchain import ReActChain, OpenAI react = ReAct(llm=OpenA...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
96ad1ff4cf8d-0
Source code for langchain.agents.react.output_parser import re from typing import Union from langchain.agents.agent import AgentOutputParser from langchain.schema import AgentAction, AgentFinish, OutputParserException [docs]class ReActOutputParser(AgentOutputParser): """Output parser for the ReAct agent.""" [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/output_parser.html
ca2956768799-0
Source code for langchain.agents.xml.base from typing import Any, List, Tuple, Union from langchain.agents.agent import AgentOutputParser, BaseSingleActionAgent from langchain.agents.xml.prompt import agent_instructions from langchain.callbacks.base import Callbacks from langchain.chains.llm import LLMChain from langch...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/xml/base.html
ca2956768799-1
model = """ tools: List[BaseTool] """List of tools this agent has access to.""" llm_chain: LLMChain """Chain to use to predict action.""" @property def input_keys(self) -> List[str]: return ["input"] [docs] @staticmethod def get_default_prompt() -> ChatPromptTemplate: ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/xml/base.html
ca2956768799-2
callbacks: Callbacks = None, **kwargs: Any, ) -> Union[AgentAction, AgentFinish]: log = "" for action, observation in intermediate_steps: log += ( f"<tool>{action.tool}</tool><tool_input>{action.tool_input}" f"</tool_input><observation>{observation...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/xml/base.html
92c56f7f7aa0-0
Source code for langchain.agents.openai_functions_multi_agent.base """Module implements an agent that uses OpenAI's APIs function enabled API.""" import json from dataclasses import dataclass from json import JSONDecodeError from typing import Any, List, Optional, Sequence, Tuple, Union from pydantic import root_valida...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-1
return [AIMessage(content=agent_action.log)] def _create_function_message( agent_action: AgentAction, observation: str ) -> FunctionMessage: """Convert agent action and observation into a function message. Args: agent_action: the tool invocation request from the agent observation: the result...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-2
except JSONDecodeError: raise OutputParserException( f"Could not parse tool input: {function_call} because " f"the `arguments` is not valid JSON." ) final_tools: List[AgentAction] = [] for tool_schema in tools: _tool_input = tool_schema...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-3
that supports using `functions`. tools: The tools this agent has access to. prompt: The prompt for this agent, should support agent_scratchpad as one of the variables. For an easy way to construct this prompt, use `OpenAIMultiFunctionsAgent.create_prompt(...)` """ llm: Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-4
# to use. "name": "tool_selection", "description": "A list of actions to take.", "parameters": { "title": "tool_selection", "description": "A list of actions to take.", "type": "object", "properties": { ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-5
return [tool_selection] [docs] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-6
selected_inputs = { k: kwargs[k] for k in self.prompt.input_variables if k != "agent_scratchpad" } full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad) prompt = self.prompt.format_prompt(**full_inputs) messages = prompt.to_messages() predicted_mess...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
92c56f7f7aa0-7
cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None, system_message: Optional[SystemMessage] = SystemMessage( content="You are a helpful...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html
ad9b89cb0316-0
Source code for langchain.agents.self_ask_with_search.base """Chain that does self-ask with search.""" from typing import Any, Sequence, Union from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types import AgentType from langchain.agents.se...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
ad9b89cb0316-1
raise ValueError(f"Exactly one tool must be specified, but got {tools}") tool_names = {tool.name for tool in tools} if tool_names != {"Intermediate Answer"}: raise ValueError( f"Tool name should be Intermediate Answer, got {tool_names}" ) @property def obs...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
5e6ecf77ffeb-0
Source code for langchain.agents.self_ask_with_search.output_parser from typing import Sequence, Union from langchain.agents.agent import AgentOutputParser from langchain.schema import AgentAction, AgentFinish, OutputParserException [docs]class SelfAskOutputParser(AgentOutputParser): """Output parser for the self-a...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/output_parser.html
0bc2fb9d19be-0
Source code for langchain.agents.structured_chat.base import re from typing import Any, List, Optional, Sequence, Tuple from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents.structured_chat.output_parser import ( StructuredChatOutputParserWithRetries, ) from la...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html