id
stringlengths
14
16
text
stringlengths
29
2.31k
source
stringlengths
57
122
ac14f79d9545-0
Source code for langchain.agents.tools """Interface for tools.""" from inspect import signature from typing import Any, Awaitable, Callable, Optional, Union from langchain.tools.base import BaseTool [docs]class Tool(BaseTool): """Tool that takes in function or coroutine directly.""" description: str = "" func: Callable[[str], str] coroutine: Optional[Callable[[str], Awaitable[str]]] = None def _run(self, tool_input: str) -> str: """Use the tool.""" return self.func(tool_input) async def _arun(self, tool_input: str) -> str: """Use the tool asynchronously.""" if self.coroutine: return await self.coroutine(tool_input) raise NotImplementedError("Tool does not support async") # TODO: this is for backwards compatibility, remove in future def __init__( self, name: str, func: Callable[[str], str], description: str, **kwargs: Any ) -> None: """Initialize tool.""" super(Tool, self).__init__( name=name, func=func, description=description, **kwargs ) class InvalidTool(BaseTool): """Tool that is run when invalid tool name is encountered by agent.""" name = "invalid_tool" description = "Called when tool name is invalid." def _run(self, tool_name: str) -> str:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/tools.html
ac14f79d9545-1
name is invalid." def _run(self, tool_name: str) -> str: """Use the tool.""" return f"{tool_name} is not a valid tool, try another one." async def _arun(self, tool_name: str) -> str: """Use the tool asynchronously.""" return f"{tool_name} is not a valid tool, try another one." [docs]def tool(*args: Union[str, Callable], return_direct: bool = False) -> Callable: """Make tools out of functions, can be used with or without arguments. Requires: - Function must be of type (str) -> str - Function must have a docstring Examples: .. code-block:: python @tool def search_api(query: str) -> str: # Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return """ def _make_with_name(tool_name: str) -> Callable: def _make_tool(func: Callable[[str],
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/tools.html
ac14f79d9545-2
-> Callable: def _make_tool(func: Callable[[str], str]) -> Tool: assert func.__doc__, "Function must have a docstring" # Description example: # search_api(query: str) - Searches the API for the query. description = f"{tool_name}{signature(func)} - {func.__doc__.strip()}" tool_ = Tool( name=tool_name, func=func, description=description, return_direct=return_direct, ) return tool_ return _make_tool if len(args) == 1 and isinstance(args[0], str): # if the argument is a string, then we use the string as the tool name # Example usage: @tool("search", return_direct=True) return _make_with_name(args[0]) elif len(args) == 1 and callable(args[0]): # if the argument is a function, then we use the function name as the tool name # Example usage: @tool return
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/tools.html
ac14f79d9545-3
# Example usage: @tool return _make_with_name(args[0].__name__)(args[0]) elif len(args) == 0: # if there are no arguments, then we use the function name as the tool name # Example usage: @tool(return_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: raise ValueError("Too many arguments for tool decorator") By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/tools.html
33e5cdcc62a3-0
Source code for langchain.agents.loading """Functionality for loading agents.""" import json from pathlib import Path from typing import Any, List, Optional, Union import yaml from langchain.agents.agent import BaseSingleActionAgent from langchain.agents.agent_types import AgentType from langchain.agents.chat.base import ChatAgent from langchain.agents.chat_v2.base import ChatAgentV2 from langchain.agents.conversational.base import ConversationalAgent from langchain.agents.conversational_chat.base import ConversationalChatAgent from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.react.base import ReActDocstoreAgent from langchain.agents.self_ask_with_search.base import SelfAskWithSearchAgent from langchain.agents.tools import Tool from langchain.chains.loading import load_chain, load_chain_from_config from langchain.llms.base import BaseLLM from langchain.utilities.loading import try_load_from_hub AGENT_TO_CLASS = { AgentType.ZERO_SHOT_REACT_DESCRIPTION: ZeroShotAgent, AgentType.REACT_DOCSTORE: ReActDocstoreAgent, AgentType.SELF_ASK_WITH_SEARCH: SelfAskWithSearchAgent, AgentType.CONVERSATIONAL_REACT_DESCRIPTION: ConversationalAgent, AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION: ChatAgent, AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent, AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION_V2: ChatAgentV2, } URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/" def _load_agent_from_tools( config: dict, llm: BaseLLM, tools: List[Tool], **kwargs: Any ) -> BaseSingleActionAgent:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/loading.html
33e5cdcc62a3-1
tools: List[Tool], **kwargs: Any ) -> BaseSingleActionAgent: config_type = config.pop("_type") if config_type not in AGENT_TO_CLASS: raise ValueError(f"Loading {config_type} agent not supported") if config_type not in AGENT_TO_CLASS: raise ValueError(f"Loading {config_type} agent not supported") agent_cls = AGENT_TO_CLASS[config_type] combined_config = {**config, **kwargs} return agent_cls.from_llm_and_tools(llm, tools, **combined_config) def load_agent_from_config( config: dict, llm: Optional[BaseLLM] = None, tools: Optional[List[Tool]] = None, **kwargs: Any, ) -> BaseSingleActionAgent: """Load agent from Config Dict.""" if "_type" not in config: raise ValueError("Must specify an agent Type in config") load_from_tools = config.pop("load_from_llm_and_tools", False) if load_from_tools: if llm is None: raise ValueError( "If `load_from_llm_and_tools` is set to True, " "then LLM must be provided" ) if tools is None: raise ValueError( "If
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/loading.html
33e5cdcc62a3-2
raise ValueError( "If `load_from_llm_and_tools` is set to True, " "then tools must be provided" ) return _load_agent_from_tools(config, llm, tools, **kwargs) config_type = config.pop("_type") if config_type not in AGENT_TO_CLASS: raise ValueError(f"Loading {config_type} agent not supported") agent_cls = AGENT_TO_CLASS[config_type] if "llm_chain" in config: config["llm_chain"] = load_chain_from_config(config.pop("llm_chain")) elif "llm_chain_path" in config: config["llm_chain"] = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` and `llm_chain_path` should be specified.") combined_config = {**config, **kwargs} return agent_cls(**combined_config) # type: ignore [docs]def load_agent(path: Union[str, Path], **kwargs: Any) -> BaseSingleActionAgent: """Unified method for loading a agent from LangChainHub or local fs.""" if hub_result := try_load_from_hub( path, _load_agent_from_file, "agents", {"json", "yaml"} ): return hub_result else: return _load_agent_from_file(path,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/loading.html
33e5cdcc62a3-3
else: return _load_agent_from_file(path, **kwargs) def _load_agent_from_file( file: Union[str, Path], **kwargs: Any ) -> BaseSingleActionAgent: """Load agent from file.""" # Convert file to Path object. if isinstance(file, str): file_path = Path(file) else: file_path = file # Load from either json or yaml. 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("File type must be json or yaml") # Load the agent from the config now. return load_agent_from_config(config, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/loading.html
5a8f5fd4dbc9-0
Source code for langchain.agents.load_tools # flake8: noqa """Load tools.""" import warnings from typing import Any, List, Optional from langchain.agents.tools import Tool from langchain.callbacks.base import BaseCallbackManager from langchain.chains.api import news_docs, open_meteo_docs, podcast_docs, tmdb_docs from langchain.chains.api.base import APIChain from langchain.chains.llm_math.base import LLMMathChain from langchain.chains.pal.base import PALChain from langchain.llms.base import BaseLLM from langchain.requests import TextRequestsWrapper from langchain.tools.base import BaseTool from langchain.tools.bing_search.tool import BingSearchRun from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun from langchain.tools.human.tool import HumanInputRun from langchain.tools.python.tool import PythonREPLTool from langchain.tools.requests.tool import ( RequestsDeleteTool, RequestsGetTool, RequestsPatchTool, RequestsPostTool, RequestsPutTool, ) from langchain.tools.searx_search.tool import SearxSearchResults, SearxSearchRun from langchain.tools.wikipedia.tool import WikipediaQueryRun from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun from langchain.utilities.apify import ApifyWrapper from langchain.utilities.bash import BashProcess from langchain.utilities.bing_search import BingSearchAPIWrapper from langchain.utilities.google_search import GoogleSearchAPIWrapper from langchain.utilities.google_serper import GoogleSerperAPIWrapper from langchain.utilities.searx_search import SearxSearchWrapper from langchain.utilities.serpapi import SerpAPIWrapper from langchain.utilities.wikipedia import WikipediaAPIWrapper from langchain.utilities.wolfram_alpha import
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-1
langchain.utilities.wikipedia import WikipediaAPIWrapper from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper def _get_python_repl() -> BaseTool: 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(requests_wrapper=TextRequestsWrapper()) def _get_tools_requests_put() -> BaseTool: return RequestsPutTool(requests_wrapper=TextRequestsWrapper()) def _get_tools_requests_delete() -> BaseTool: return RequestsDeleteTool(requests_wrapper=TextRequestsWrapper()) def _get_terminal() -> BaseTool: return Tool( name="Terminal", description="Executes commands in a terminal. Input should be valid commands, and the output will be any output from running that command.", func=BashProcess().run, ) _BASE_TOOLS = { "python_repl": _get_python_repl, "requests": _get_tools_requests_get, # preserved for backwards compatability "requests_get": _get_tools_requests_get, "requests_post": _get_tools_requests_post, "requests_patch": _get_tools_requests_patch, "requests_put": _get_tools_requests_put, "requests_delete": _get_tools_requests_delete, "terminal": _get_terminal, } def _get_pal_math(llm: BaseLLM) -> BaseTool: return Tool(
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-2
-> BaseTool: return Tool( name="PAL-MATH", description="A language model that is really good at solving complex word math problems. Input should be a fully worded hard word math problem.", func=PALChain.from_math_prompt(llm).run, ) def _get_pal_colored_objects(llm: BaseLLM) -> BaseTool: return Tool( name="PAL-COLOR-OBJ", description="A language model that is really good at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning problem. Make sure to include all information about the objects AND the final question you want to answer.", func=PALChain.from_colored_object_prompt(llm).run, ) def _get_llm_math(llm: BaseLLM) -> BaseTool: return Tool( name="Calculator", description="Useful for when you need to answer questions about math.", func=LLMMathChain(llm=llm, callback_manager=llm.callback_manager).run, coroutine=LLMMathChain(llm=llm, callback_manager=llm.callback_manager).arun, ) def _get_open_meteo_api(llm: BaseLLM) -> 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
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-3
Meteo API", description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.", func=chain.run, ) _LLM_TOOLS = { "pal-math": _get_pal_math, "pal-colored-objects": _get_pal_colored_objects, "llm-math": _get_llm_math, "open-meteo-api": _get_open_meteo_api, } def _get_news_api(llm: BaseLLM, **kwargs: Any) -> BaseTool: news_api_key = kwargs["news_api_key"] chain = APIChain.from_llm_and_api_docs( llm, news_docs.NEWS_DOCS, headers={"X-Api-Key": news_api_key} ) return Tool( name="News API", description="Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.", func=chain.run, ) def _get_tmdb_api(llm: BaseLLM, **kwargs: Any) -> BaseTool: tmdb_bearer_token = kwargs["tmdb_bearer_token"] chain = APIChain.from_llm_and_api_docs( llm, tmdb_docs.TMDB_DOCS, headers={"Authorization": f"Bearer {tmdb_bearer_token}"}, ) return Tool(
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-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: BaseLLM, **kwargs: Any) -> BaseTool: listen_api_key = kwargs["listen_api_key"] chain = APIChain.from_llm_and_api_docs( llm, podcast_docs.PODCAST_DOCS, headers={"X-ListenAPI-Key": listen_api_key}, ) return Tool( name="Podcast API", description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.", func=chain.run, ) def _get_wolfram_alpha(**kwargs: Any) -> BaseTool: return WolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs)) def _get_google_search(**kwargs: Any) -> BaseTool: return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs)) def _get_wikipedia(**kwargs: Any) -> BaseTool: return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs)) def _get_google_serper(**kwargs: Any) -> BaseTool: return Tool( name="Serper Search", func=GoogleSerperAPIWrapper(**kwargs).run,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-5
func=GoogleSerperAPIWrapper(**kwargs).run, description="A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query.", ) def _get_google_search_results_json(**kwargs: Any) -> BaseTool: return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs)) def _get_serpapi(**kwargs: Any) -> BaseTool: return Tool( name="Search", description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.", func=SerpAPIWrapper(**kwargs).run, coroutine=SerpAPIWrapper(**kwargs).arun, ) 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 SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs) def _get_bing_search(**kwargs: Any) -> BaseTool: return BingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs)) def _get_human_tool(**kwargs: Any) -> BaseTool: return HumanInputRun(**kwargs) _EXTRA_LLM_TOOLS = { "news-api": (_get_news_api, ["news_api_key"]), "tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]), "podcast-api":
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-6
["tmdb_bearer_token"]), "podcast-api": (_get_podcast_api, ["listen_api_key"]), } _EXTRA_OPTIONAL_TOOLS = { "wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha_appid"]), "google-search": (_get_google_search, ["google_api_key", "google_cse_id"]), "google-search-results-json": ( _get_google_search_results_json, ["google_api_key", "google_cse_id", "num_results"], ), "searx-search-results-json": ( _get_searx_search_results_json, ["searx_host", "engines", "num_results", "aiosession"], ), "bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]), "google-serper": (_get_google_serper, ["serper_api_key"]), "serpapi": (_get_serpapi, ["serpapi_api_key", "aiosession"]), "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]), "wikipedia": (_get_wikipedia, ["top_k_results"]), "human": (_get_human_tool, ["prompt_func", "input_func"]), } [docs]def load_tools( tool_names: List[str], llm: Optional[BaseLLM] = None, callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any, ) -> List[BaseTool]: """Load tools based on their name.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-7
-> List[BaseTool]: """Load tools based on their name. Args: tool_names: name of tools to load. llm: Optional language model, may be needed to initialize certain tools. callback_manager: Optional callback manager. If not provided, default global callback manager will be used. Returns: List of tools. """ tools = [] for name in tool_names: if name == "requests": warnings.warn( "tool name `requests` is deprecated - " "please use `requests_all` or specify the requests method" ) if name == "requests_all": # expand requests into various methods requests_method_tools = [ _tool for _tool in _BASE_TOOLS if _tool.startswith("requests_") ] 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:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-8
if llm is None: raise ValueError(f"Tool {name} requires an LLM to be provided") tool = _LLM_TOOLS[name](llm) if callback_manager is not None: tool.callback_manager = callback_manager tools.append(tool) elif name in _EXTRA_LLM_TOOLS: if llm is None: raise ValueError(f"Tool {name} requires an LLM to be provided") _get_llm_tool_func, extra_keys = _EXTRA_LLM_TOOLS[name] missing_keys = set(extra_keys).difference(kwargs) if missing_keys: raise ValueError( f"Tool {name} requires some parameters that were not " f"provided: {missing_keys}" ) sub_kwargs = {k: kwargs[k] for k in extra_keys} tool = _get_llm_tool_func(llm=llm,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-9
tool = _get_llm_tool_func(llm=llm, **sub_kwargs) if callback_manager is not None: tool.callback_manager = callback_manager tools.append(tool) elif name in _EXTRA_OPTIONAL_TOOLS: _get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name] sub_kwargs = {k: kwargs[k] for k in extra_keys if k in kwargs} tool = _get_tool_func(**sub_kwargs) if callback_manager is not None: tool.callback_manager = callback_manager tools.append(tool) else: raise ValueError(f"Got unknown tool {name}") return tools [docs]def get_all_tool_names() -> List[str]: """Get a list of all possible tool names.""" return ( list(_BASE_TOOLS) + list(_EXTRA_OPTIONAL_TOOLS) + list(_EXTRA_LLM_TOOLS) + list(_LLM_TOOLS) ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
5a8f5fd4dbc9-10
Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html
d7ac3f50b4d4-0
Source code for langchain.agents.agent_types from enum import Enum [docs]class AgentType(str, Enum): ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description" REACT_DOCSTORE = "react-docstore" SELF_ASK_WITH_SEARCH = "self-ask-with-search" CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-description" CHAT_ZERO_SHOT_REACT_DESCRIPTION = "chat-zero-shot-react-description" CHAT_CONVERSATIONAL_REACT_DESCRIPTION = "chat-conversational-react-description" CHAT_ZERO_SHOT_REACT_DESCRIPTION_V2 = "chat-zero-shot-react-description-002" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_types.html
545a96376be2-0
Source code for langchain.agents.self_ask_with_search.base """Chain that does self ask with search.""" from typing import Any, Optional, Sequence, Tuple, Union from langchain.agents.agent import Agent, AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.self_ask_with_search.prompt import PROMPT from langchain.agents.tools import Tool from langchain.llms.base import BaseLLM from langchain.prompts.base import BasePromptTemplate from langchain.tools.base import BaseTool from langchain.utilities.google_serper import GoogleSerperAPIWrapper from langchain.utilities.serpapi import SerpAPIWrapper class SelfAskWithSearchAgent(Agent): """Agent for the self-ask-with-search paper.""" @property def _agent_type(self) -> str: """Return Identifier of agent type.""" return AgentType.SELF_ASK_WITH_SEARCH @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Prompt does not depend on tools.""" return PROMPT @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: if len(tools) != 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
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
545a96376be2-1
f"Tool name should be Intermediate Answer, got {tool_names}" ) def _extract_tool_and_input(self, text: str) -> Optional[Tuple[str, str]]: followup = "Follow up:" last_line = text.split("\n")[-1] if followup not in last_line: finish_string = "So the final answer is: " if finish_string not in last_line: return None return "Final Answer", last_line[len(finish_string) :] after_colon = text.split(":")[-1] if " " == after_colon[0]: after_colon = after_colon[1:] return "Intermediate Answer", after_colon def _fix_text(self, text: str) -> str: return f"{text}\nSo the final answer is:" @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Intermediate answer: " @property def llm_prefix(self) -> str: """Prefix to append the LLM call with.""" return "" @property def
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
545a96376be2-2
return "" @property def starter_string(self) -> str: """Put this string after user input but before first LLM call.""" return "Are follow up questions needed here:" [docs]class SelfAskWithSearchChain(AgentExecutor): """Chain that does self ask with search. Example: .. code-block:: python from langchain import SelfAskWithSearchChain, OpenAI, GoogleSerperAPIWrapper search_chain = GoogleSerperAPIWrapper() self_ask = SelfAskWithSearchChain(llm=OpenAI(), search_chain=search_chain) """ def __init__( self, llm: BaseLLM, search_chain: Union[GoogleSerperAPIWrapper, SerpAPIWrapper], **kwargs: Any, ): """Initialize with just an LLM and a search chain.""" search_tool = Tool( name="Intermediate Answer", func=search_chain.run, description="Search" ) agent = SelfAskWithSearchAgent.from_llm_and_tools(llm, [search_tool]) super().__init__(agent=agent, tools=[search_tool], **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
545a96376be2-3
© Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
1ebc458cdeec-0
Source code for langchain.agents.mrkl.base """Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.""" from __future__ import annotations import re from typing import Any, Callable, List, NamedTuple, Optional, Sequence, Tuple from langchain.agents.agent import Agent, AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS, PREFIX, SUFFIX from langchain.agents.tools import Tool from langchain.callbacks.base import BaseCallbackManager from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.schema import BaseLanguageModel from langchain.tools.base import BaseTool FINAL_ANSWER_ACTION = "Final Answer:" class ChainConfig(NamedTuple): """Configuration for chain to use in MRKL system. Args: action_name: Name of the action. action: Action function to call. action_description: Description of the action. """ action_name: str action: Callable action_description: str def get_action_and_input(llm_output: str) -> Tuple[str, str]: """Parse out the action and input from the LLM output. Note: if you're specifying a custom prompt for the ZeroShotAgent, you will need to ensure that it meets the following Regex requirements. The string starting with "Action:" and the following string starting with "Action Input:" should be separated by a newline. """ if FINAL_ANSWER_ACTION in llm_output: return "Final Answer",
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-1
in llm_output: return "Final Answer", llm_output.split(FINAL_ANSWER_ACTION)[-1].strip() # \s matches against tab/newline/whitespace regex = r"Action: (.*?)[\n]*Action Input:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) return action, action_input.strip(" ").strip('"') [docs]class ZeroShotAgent(Agent): """Agent for the MRKL chain.""" @property def _agent_type(self) -> str: """Return Identifier of agent type.""" return AgentType.ZERO_SHOT_REACT_DESCRIPTION @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-2
SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, ) -> PromptTemplate: """Create prompt in the style of the zero shot agent. Args: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools. suffix: String to put after the list of tools. input_variables: List of input variables the final prompt will expect. Returns: A PromptTemplate with the template assembled from the pieces here. """ tool_strings = "\n".join([f"{tool.name}: {tool.description}" for tool in tools]) tool_names = ", ".join([tool.name for tool in tools]) format_instructions = format_instructions.format(tool_names=tool_names) template = "\n\n".join([prefix, tool_strings, format_instructions, suffix]) if input_variables is None: input_variables = ["input", "agent_scratchpad"] return PromptTemplate(template=template, input_variables=input_variables) [docs] @classmethod def from_llm_and_tools(
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-3
@classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, **kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) prompt = cls.create_prompt( tools, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] return cls(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) @classmethod
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-4
allowed_tools=tool_names, **kwargs) @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: for tool in tools: if tool.description is None: raise ValueError( f"Got a tool {tool.name} without a description. For this agent, " f"a description must always be provided." ) def _extract_tool_and_input(self, text: str) -> Optional[Tuple[str, str]]: return get_action_and_input(text) [docs]class MRKLChain(AgentExecutor): """Chain that implements the MRKL system. Example: .. code-block:: python from langchain import OpenAI, MRKLChain from langchain.chains.mrkl.base import ChainConfig llm = OpenAI(temperature=0) prompt = PromptTemplate(...) chains = [...] mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt) """ [docs] @classmethod def from_chains( cls, llm:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-5
def from_chains( cls, llm: BaseLanguageModel, chains: List[ChainConfig], **kwargs: Any ) -> AgentExecutor: """User friendly way to initialize the MRKL chain. This is intended to be an easy way to get up and running with the MRKL chain. Args: llm: The LLM to use as the agent LLM. chains: The chains the MRKL system has access to. **kwargs: parameters to be passed to initialization. Returns: An initialized MRKL chain. Example: .. code-block:: python from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, MRKLChain from langchain.chains.mrkl.base import ChainConfig llm = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm) chains = [
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-6
chains = [ ChainConfig( action_name = "Search", action=search.search, action_description="useful for searching" ), ChainConfig( action_name="Calculator", action=llm_math_chain.run, action_description="useful for doing math" ) ] mrkl = MRKLChain.from_chains(llm, chains) """ tools = [ Tool( name=c.action_name, func=c.action,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
1ebc458cdeec-7
func=c.action, description=c.action_description, ) for c in chains ] agent = ZeroShotAgent.from_llm_and_tools(llm, tools) return cls(agent=agent, tools=tools, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/mrkl/base.html
5647c4b7fe00-0
Source code for langchain.agents.conversational_chat.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations import json from typing import Any, List, Optional, Sequence, Tuple from langchain.agents.agent import Agent from langchain.agents.conversational_chat.prompt import ( FORMAT_INSTRUCTIONS, PREFIX, SUFFIX, TEMPLATE_TOOL_RESPONSE, ) from langchain.callbacks.base import BaseCallbackManager from langchain.chains import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.chat import ( ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, ) from langchain.schema import ( AgentAction, AIMessage, BaseLanguageModel, BaseMessage, BaseOutputParser, HumanMessage, ) from langchain.tools.base import BaseTool class AgentOutputParser(BaseOutputParser): def get_format_instructions(self) -> str: return FORMAT_INSTRUCTIONS def parse(self, text: str) -> Any: cleaned_output = text.strip() if "```json" in cleaned_output: _, cleaned_output = cleaned_output.split("```json") if "```" in cleaned_output: cleaned_output, _ = cleaned_output.split("```") if cleaned_output.startswith("```json"): cleaned_output = cleaned_output[len("```json") :] if
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
5647c4b7fe00-1
cleaned_output = cleaned_output[len("```json") :] if cleaned_output.startswith("```"): cleaned_output = cleaned_output[len("```") :] if cleaned_output.endswith("```"): cleaned_output = cleaned_output[: -len("```")] cleaned_output = cleaned_output.strip() response = json.loads(cleaned_output) return {"action": response["action"], "action_input": response["action_input"]} [docs]class ConversationalChatAgent(Agent): """An agent designed to hold a conversation in addition to using tools.""" output_parser: BaseOutputParser @property def _agent_type(self) -> str: raise NotImplementedError @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], system_message: str = PREFIX, human_message: str = SUFFIX, input_variables: Optional[List[str]] = None, output_parser: Optional[BaseOutputParser] = None,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
5647c4b7fe00-2
output_parser: Optional[BaseOutputParser] = None, ) -> BasePromptTemplate: tool_strings = "\n".join( [f"> {tool.name}: {tool.description}" for tool in tools] ) tool_names = ", ".join([tool.name for tool in tools]) _output_parser = output_parser or AgentOutputParser() format_instructions = human_message.format( format_instructions=_output_parser.get_format_instructions() ) final_prompt = format_instructions.format( tool_names=tool_names, tools=tool_strings ) if input_variables is None: input_variables = ["input", "chat_history", "agent_scratchpad"] messages = [ SystemMessagePromptTemplate.from_template(system_message), MessagesPlaceholder(variable_name="chat_history"), HumanMessagePromptTemplate.from_template(final_prompt), MessagesPlaceholder(variable_name="agent_scratchpad"), ] return ChatPromptTemplate(input_variables=input_variables, messages=messages) def _extract_tool_and_input(self, llm_output: str) -> Optional[Tuple[str, str]]: try:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
5647c4b7fe00-3
str]]: try: response = self.output_parser.parse(llm_output) return response["action"], response["action_input"] except Exception: raise ValueError(f"Could not parse LLM output: {llm_output}") def _construct_scratchpad( self, intermediate_steps: List[Tuple[AgentAction, str]] ) -> List[BaseMessage]: """Construct the scratchpad that lets the agent continue its thought process.""" thoughts: List[BaseMessage] = [] for action, observation in intermediate_steps: thoughts.append(AIMessage(content=action.log)) human_message = HumanMessage( content=TEMPLATE_TOOL_RESPONSE.format(observation=observation) ) thoughts.append(human_message) return thoughts [docs] @classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, system_message: str = PREFIX, human_message: str = SUFFIX, input_variables:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
5647c4b7fe00-4
human_message: str = SUFFIX, input_variables: Optional[List[str]] = None, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) _output_parser = output_parser or AgentOutputParser() prompt = cls.create_prompt( tools, system_message=system_message, human_message=human_message, input_variables=input_variables, output_parser=_output_parser, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] return cls( llm_chain=llm_chain, allowed_tools=tool_names, output_parser=_output_parser, **kwargs, ) By Harrison Chase
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
5647c4b7fe00-5
**kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational_chat/base.html
00633ee8f4b0-0
Source code for langchain.agents.agent_toolkits.openapi.base """OpenAPI spec agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.openapi.prompt import ( OPENAPI_PREFIX, OPENAPI_SUFFIX, ) from langchain.agents.agent_toolkits.openapi.toolkit import OpenAPIToolkit from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM [docs]def create_openapi_agent( llm: BaseLLM, toolkit: OpenAPIToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = OPENAPI_PREFIX, suffix: str = OPENAPI_SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = "force", verbose: bool = False, return_intermediate_steps: bool = False, **kwargs: Any, ) -> AgentExecutor: """Construct a json agent from an LLM and tools.""" tools = toolkit.get_tools() prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html
00633ee8f4b0-1
format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools=toolkit.get_tools(), verbose=verbose, return_intermediate_steps=return_intermediate_steps, max_iterations=max_iterations, max_execution_time=max_execution_time, early_stopping_method=early_stopping_method, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html
b8aefa129f48-0
Source code for langchain.agents.agent_toolkits.json.base """Json agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.json.prompt import JSON_PREFIX, JSON_SUFFIX from langchain.agents.agent_toolkits.json.toolkit import JsonToolkit from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM [docs]def create_json_agent( llm: BaseLLM, toolkit: JsonToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = JSON_PREFIX, suffix: str = JSON_SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, verbose: bool = False, **kwargs: Any, ) -> AgentExecutor: """Construct a json agent from an LLM and tools.""" tools = toolkit.get_tools() prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools]
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html
b8aefa129f48-1
) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools=toolkit.get_tools(), verbose=verbose ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html
8770b1a9d785-0
Source code for langchain.agents.agent_toolkits.csv.base """Agent for working with csvs.""" from typing import Any, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agent from langchain.llms.base import BaseLLM [docs]def create_csv_agent( llm: BaseLLM, path: str, pandas_kwargs: Optional[dict] = None, **kwargs: Any ) -> AgentExecutor: """Create csv agent by loading to a dataframe and using pandas agent.""" import pandas as pd _kwargs = pandas_kwargs or {} df = pd.read_csv(path, **_kwargs) return create_pandas_dataframe_agent(llm, df, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/csv/base.html
dd989f20d3f8-0
Source code for langchain.agents.agent_toolkits.pandas.base """Agent for working with pandas objects.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.pandas.prompt import PREFIX, SUFFIX from langchain.agents.mrkl.base import ZeroShotAgent from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM from langchain.tools.python.tool import PythonAstREPLTool [docs]def create_pandas_dataframe_agent( llm: BaseLLM, df: Any, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = PREFIX, suffix: str = SUFFIX, input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = "force", **kwargs: Any, ) -> AgentExecutor: """Construct a pandas agent from an LLM and dataframe.""" import pandas as pd if not isinstance(df, pd.DataFrame): raise ValueError(f"Expected pandas object, got {type(df)}") if input_variables is None: input_variables = ["df", "input", "agent_scratchpad"] tools = [PythonAstREPLTool(locals={"df": df})] prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/pandas/base.html
dd989f20d3f8-1
tools, prefix=prefix, suffix=suffix, input_variables=input_variables ) partial_prompt = prompt.partial(df=str(df.head())) llm_chain = LLMChain( llm=llm, prompt=partial_prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=verbose, return_intermediate_steps=return_intermediate_steps, max_iterations=max_iterations, max_execution_time=max_execution_time, early_stopping_method=early_stopping_method, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/pandas/base.html
02d323c12090-0
Source code for langchain.agents.agent_toolkits.vectorstore.base """VectorStore agent.""" from typing import Any, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.vectorstore.prompt import PREFIX, ROUTER_PREFIX from langchain.agents.agent_toolkits.vectorstore.toolkit import ( VectorStoreRouterToolkit, VectorStoreToolkit, ) from langchain.agents.mrkl.base import ZeroShotAgent from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM [docs]def create_vectorstore_agent( llm: BaseLLM, toolkit: VectorStoreToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = PREFIX, verbose: bool = False, **kwargs: Any, ) -> AgentExecutor: """Construct a vectorstore agent from an LLM and tools.""" tools = toolkit.get_tools() prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=verbose) [docs]def create_vectorstore_router_agent( llm: BaseLLM, toolkit: VectorStoreRouterToolkit, callback_manager:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html
02d323c12090-1
BaseLLM, toolkit: VectorStoreRouterToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = ROUTER_PREFIX, verbose: bool = False, **kwargs: Any, ) -> AgentExecutor: """Construct a vectorstore router agent from an LLM and tools.""" tools = toolkit.get_tools() prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=verbose) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html
9d2d26382aa8-0
Source code for langchain.agents.agent_toolkits.sql.base """SQL agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.sql.prompt import SQL_PREFIX, SQL_SUFFIX from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM [docs]def create_sql_agent( llm: BaseLLM, toolkit: SQLDatabaseToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = SQL_PREFIX, suffix: str = SQL_SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, top_k: int = 10, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = "force", verbose: bool = False, **kwargs: Any, ) -> AgentExecutor: """Construct a sql agent from an LLM and tools.""" tools = toolkit.get_tools() prefix = prefix.format(dialect=toolkit.dialect, top_k=top_k) prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
9d2d26382aa8-1
format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=verbose, max_iterations=max_iterations, max_execution_time=max_execution_time, early_stopping_method=early_stopping_method, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
d76dc02d8efb-0
Source code for langchain.agents.conversational.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations import re from typing import Any, List, Optional, Sequence, Tuple from langchain.agents.agent import Agent from langchain.agents.agent_types import AgentType from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS, PREFIX, SUFFIX from langchain.callbacks.base import BaseCallbackManager from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.schema import BaseLanguageModel from langchain.tools.base import BaseTool [docs]class ConversationalAgent(Agent): """An agent designed to hold a conversation in addition to using tools.""" ai_prefix: str = "AI" @property def _agent_type(self) -> str: """Return Identifier of agent type.""" return AgentType.CONVERSATIONAL_REACT_DESCRIPTION @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational/base.html
d76dc02d8efb-1
format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variables: Optional[List[str]] = None, ) -> PromptTemplate: """Create prompt in the style of the zero shot agent. Args: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools. suffix: String to put after the list of tools. ai_prefix: String to use before AI output. human_prefix: String to use before human output. input_variables: List of input variables the final prompt will expect. Returns: A PromptTemplate with the template assembled from the pieces here. """ tool_strings = "\n".join( [f"> {tool.name}: {tool.description}" for tool in tools] ) tool_names = ", ".join([tool.name for tool in tools]) format_instructions = format_instructions.format( tool_names=tool_names,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational/base.html
d76dc02d8efb-2
tool_names=tool_names, ai_prefix=ai_prefix, human_prefix=human_prefix ) template = "\n\n".join([prefix, tool_strings, format_instructions, suffix]) if input_variables is None: input_variables = ["input", "chat_history", "agent_scratchpad"] return PromptTemplate(template=template, input_variables=input_variables) @property def finish_tool_name(self) -> str: """Name of the tool to use to finish the chain.""" return self.ai_prefix def _extract_tool_and_input(self, llm_output: str) -> Optional[Tuple[str, str]]: if f"{self.ai_prefix}:" in llm_output: return self.ai_prefix, llm_output.split(f"{self.ai_prefix}:")[-1].strip() regex = r"Action: (.*?)[\n]*Action Input: (.*)" match = re.search(regex, llm_output) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1) action_input = match.group(2) return action.strip(), action_input.strip(" ").strip('"') [docs] @classmethod def from_llm_and_tools(
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational/base.html
d76dc02d8efb-3
@classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variables: Optional[List[str]] = None, **kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) prompt = cls.create_prompt( tools, ai_prefix=ai_prefix, human_prefix=human_prefix, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational/base.html
d76dc02d8efb-4
prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] return cls( llm_chain=llm_chain, allowed_tools=tool_names, ai_prefix=ai_prefix, **kwargs ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/conversational/base.html
be2d2f9483fe-0
Source code for langchain.agents.react.base """Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.""" import re from typing import Any, List, Optional, Sequence, Tuple from langchain.agents.agent import Agent, AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.react.textworld_prompt import TEXTWORLD_PROMPT from langchain.agents.react.wiki_prompt import WIKI_PROMPT from langchain.agents.tools import Tool from langchain.docstore.base import Docstore from langchain.docstore.document import Document from langchain.llms.base import BaseLLM from langchain.prompts.base import BasePromptTemplate from langchain.tools.base import BaseTool class ReActDocstoreAgent(Agent): """Agent for the ReAct chain.""" @property def _agent_type(self) -> str: """Return Identifier of agent type.""" return AgentType.REACT_DOCSTORE @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Return default prompt.""" return WIKI_PROMPT @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: 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(
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
be2d2f9483fe-1
"Search"}: raise ValueError( f"Tool names should be Lookup and Search, got {tool_names}" ) def _fix_text(self, text: str) -> str: return text + "\nAction:" def _extract_tool_and_input(self, text: str) -> Optional[Tuple[str, str]]: action_prefix = "Action: " if not text.strip().split("\n")[-1].startswith(action_prefix): return None action_block = text.strip().split("\n")[-1] action_str = action_block[len(action_prefix) :] # Parse out the action and the directive. re_matches = re.search(r"(.*?)\[(.*?)\]", action_str) if re_matches is None: raise ValueError(f"Could not parse action directive: {action_str}") return re_matches.group(1), re_matches.group(2) @property def finish_tool_name(self) -> str: """Name of the tool of when to finish the chain.""" return "Finish" @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
be2d2f9483fe-2
return "Observation: " @property def _stop(self) -> List[str]: return ["\nObservation:"] @property def llm_prefix(self) -> str: """Prefix to append the LLM call with.""" return "Thought:" class DocstoreExplorer: """Class to assist with exploration of a document store.""" def __init__(self, docstore: Docstore): """Initialize with a docstore, and set initial document to None.""" self.docstore = docstore self.document: Optional[Document] = None self.lookup_str = "" self.lookup_index = 0 def search(self, term: str) -> str: """Search for a term in the docstore, and if found save.""" result = self.docstore.search(term) if isinstance(result, Document): self.document = result return self._summary else: self.document = None return result def lookup(self, term: str) -> str: """Lookup a term in document (if saved).""" if self.document is None: raise ValueError("Cannot lookup without a
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
be2d2f9483fe-3
None: 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()] if len(lookups) == 0: return "No Results" elif self.lookup_index >= len(lookups): return "No More Results" else: result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})" return f"{result_prefix} {lookups[self.lookup_index]}" @property def _summary(self) -> str: return self._paragraphs[0] @property def _paragraphs(self) -> List[str]: if self.document is None: raise ValueError("Cannot get paragraphs without a document") return self.document.page_content.split("\n\n") [docs]class ReActTextWorldAgent(ReActDocstoreAgent): """Agent for the ReAct TextWorld chain.""" [docs]
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
be2d2f9483fe-4
"""Agent for the ReAct TextWorld chain.""" [docs] @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Return default prompt.""" return TEXTWORLD_PROMPT @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: if len(tools) != 1: raise ValueError(f"Exactly one tool must be specified, but got {tools}") tool_names = {tool.name for tool in tools} 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=OpenAI()) """ def __init__(self, llm: BaseLLM, docstore: Docstore, **kwargs: Any): """Initialize with the LLM and a docstore.""" docstore_explorer = DocstoreExplorer(docstore) tools = [ Tool( name="Search",
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
be2d2f9483fe-5
name="Search", func=docstore_explorer.search, description="Search for a term in the docstore.", ), Tool( name="Lookup", func=docstore_explorer.lookup, description="Lookup a term in the docstore.", ), ] agent = ReActDocstoreAgent.from_llm_and_tools(llm, tools) super().__init__(agent=agent, tools=tools, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/react/base.html
0591b95e1073-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://github.com/dewitt/opensearch/blob/master/opensearch-1-1-draft-6.md>`_ specification. More detailes on the installtion instructions `here. <../../ecosystem/searx.html>`_ For the search API refer to https://docs.searxng.org/dev/search_api.html Quick Start ----------- In order to use this utility you need to provide the searx host. This can be done by passing the named parameter :attr:`searx_host <SearxSearchWrapper.searx_host>` or exporting the environment variable SEARX_HOST. Note: this is the only required parameter. Then create a searx search instance like this: .. code-block:: python from langchain.utilities import SearxSearchWrapper # when the host starts with `http` SSL is disabled and the connection # is assumed to be on a private network searx_host='http://self.hosted' search = SearxSearchWrapper(searx_host=searx_host) You can now use the ``search`` instance to query the searx API. Searching --------- Use the :meth:`run() <SearxSearchWrapper.run>` and :meth:`results() <SearxSearchWrapper.results>` methods to query the searx API. Other methods are are available for
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-1
methods to query the searx API. Other methods are are available for convenience. :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/search_api.html>`_ parameters to the :py:class:`SearxSearchWrapper` instance. In the following example we are using the :attr:`engines <SearxSearchWrapper.engines>` and the ``language`` parameters: .. code-block:: python # assuming the searx host is set as above or exported as an env variable s = SearxSearchWrapper(engines=['google', 'bing'], language='es') Search Tips ----------- Searx offers a special `search syntax <https://docs.searxng.org/user/index.html#search-syntax>`_ that can also be used instead of passing engine parameters. For example the following query: .. code-block:: python s = SearxSearchWrapper("langchain library", engines=['github']) # can also be written as: s = SearxSearchWrapper("langchain library !github") # or even: s = SearxSearchWrapper("langchain library !gh") In some situations you might want to pass an extra string to the
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-2
library !gh") In some situations you might want to pass an extra string to the search query. For example when the `run()` method is called by an agent. The search suffix can also be used as a way to pass extra parameters to searx or the underlying search engines. .. 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:github.com") *NOTE*: A search suffix can be defined on both the instance and the method level. The resulting query will be the concatenation of the two with the former taking precedence. See `SearxNG Configured Engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and `SearxNG Search Syntax <https://docs.searxng.org/user/index.html#id1>`_ for more details. Notes ----- This wrapper is based on the SearxNG fork https://github.com/searxng/searxng which is better maintained than the original Searx project and offers more features. Public searxNG instances often use a rate limiter for API usage, so you might want to use a self hosted instance and disable the rate limiter. If you are self-hosting an instance you can customize the rate limiter for your own network as described `here <https://github.com/searxng/searxng/pull/2129>`_. For a list of public SearxNG instances see
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-3
a list of public SearxNG instances see https://searx.space/ """ import json from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator from langchain.utils import get_from_dict_or_env def _get_default_params() -> dict: return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.loads(data) super().__init__(json_data) self.__dict__ = self def __str__(self) -> str: """Text representation of searx result.""" return self._data @property def results(self) -> Any: """Silence mypy for accessing this field. :meta private: """ return self.get("results") @property def answers(self) -> Any: """Helper accessor on the json result.""" return self.get("answers") [docs]class SearxSearchWrapper(BaseModel): """Wrapper for Searx API. To use you need to provide the searx host by passing the named parameter
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-4
To use you need to provide the searx host by passing the named parameter ``searx_host`` or exporting the environment variable ``SEARX_HOST``. In some situations you might want to disable SSL verification, for example if you are running searx locally. You can do this by passing the named parameter ``unsecure``. You can also pass the host url scheme as ``http`` to disable SSL. Example: .. code-block:: python from langchain.utilities import SearxSearchWrapper searx = SearxSearchWrapper(searx_host="http://localhost:8888") 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", unsecure=True) """ _result: SearxResults = PrivateAttr() searx_host: str = "" unsecure: bool = False params: dict = Field(default_factory=_get_default_params)
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-5
bool = False params: dict = Field(default_factory=_get_default_params) headers: Optional[dict] = None engines: Optional[List[str]] = [] categories: Optional[List[str]] = [] query_suffix: Optional[str] = "" k: int = 10 aiosession: Optional[Any] = None @validator("unsecure") def disable_ssl_warnings(cls, v: bool) -> bool: """Disable SSL warnings.""" if v: # requests.urllib3.disable_warnings() try: import urllib3 urllib3.disable_warnings() except ImportError as e: print(e) return v @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: values["params"]["engines"] = ",".join(engines) categories =
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-6
= ",".join(engines) categories = values.get("categories") 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 https://{searx_host} " ) searx_host = "https://" + searx_host elif searx_host.startswith("http://"): values["unsecure"] = True cls.disable_ssl_warnings(True) values["searx_host"] = searx_host return values class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _searx_api_query(self, params: dict) -> SearxResults: """Actual request to searx API.""" raw_result = requests.get( self.searx_host,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-7
self.searx_host, headers=self.headers, params=params, verify=not self.unsecure, ) # test if http result is ok if not raw_result.ok: raise ValueError("Searx API returned an error: ", raw_result.text) res = SearxResults(raw_result.text) self._result = res return res async def _asearx_api_query(self, params: dict) -> SearxResults: if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.get( self.searx_host, headers=self.headers, params=params, ssl=(lambda: False if self.unsecure else None)(), ) as response: if not response.ok:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-8
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( self.searx_host, headers=self.headers, params=params, verify=not self.unsecure, ) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result return result [docs] def run( self, query: str, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-9
categories: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> str: """Run query through Searx API and parse results. You can pass any other params to the searx query API. Args: query: The query to search for. query_suffix: Extra suffix appended to the query. 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: str: The result of the query. Raises: ValueError: If an error occured with the query. Example: This will make a query to the qwant engine: .. code-block:: python from langchain.utilities import SearxSearchWrapper searx = SearxSearchWrapper(searx_host="http://my.searx.host") searx.run("what is the weather in France ?",
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-10
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 = { "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) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) if isinstance(categories, list) and len(categories) > 0: params["categories"] = ",".join(categories) res = self._searx_api_query(params) if len(res.answers) > 0:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-11
if len(res.answers) > 0: toret = res.answers[0] # only return the content of the results list elif len(res.results) > 0: toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) else: toret = "No good search result found" return toret [docs] async def arun( self, query: str, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> 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) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list)
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-12
" + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) res = await self._asearx_api_query(params) if len(res.answers) > 0: toret = res.answers[0] # only return the content of the results list elif len(res.results) > 0: toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) else: toret = "No good search result found" return toret [docs] def results( self, query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Run query through Searx API and returns the results with metadata. Args: query: The query to search for. query_suffix: Extra suffix appended to the query.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-13
query_suffix: Extra suffix appended to the query. num_results: Limit the number of results to return. 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. title: The title of the result. link: The link to the result. engines: The engines used for the result. category: Searx category of the result. } """ _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)
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-14
" + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) if isinstance(categories, list) and len(categories) > 0: params["categories"] = ",".join(categories) results = self._searx_api_query(params).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ] [docs] async def aresults( self,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-15
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 info. """ _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) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) results = (await self._asearx_api_query(params)).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0591b95e1073-16
"No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html
0fe667826214-0
Source code for langchain.utilities.serpapi """Chain that calls SerpAPI. Heavily borrowed from https://github.com/ofirpress/self-ask """ import os import sys from typing import Any, Dict, Optional, Tuple import aiohttp from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dict_or_env class HiddenPrints: """Context manager to hide prints.""" def __enter__(self) -> None: """Open file to pipe stdout to.""" self._original_stdout = sys.stdout sys.stdout = open(os.devnull, "w") def __exit__(self, *_: Any) -> None: """Close file that stdout was piped to.""" sys.stdout.close() sys.stdout = self._original_stdout [docs]class SerpAPIWrapper(BaseModel): """Wrapper around SerpAPI. To use, you should have the ``google-search-results`` python package installed, and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass `serpapi_api_key` as a named parameter to the constructor. Example: .. code-block:: python from langchain import SerpAPIWrapper serpapi = SerpAPIWrapper() """ search_engine: Any #: :meta private: params: dict = Field( default={
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
0fe667826214-1
default={ "engine": "google", "google_domain": "google.com", "gl": "us", "hl": "en", } ) serpapi_api_key: Optional[str] = None aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" serpapi_api_key = get_from_dict_or_env( values, "serpapi_api_key", "SERPAPI_API_KEY" ) values["serpapi_api_key"] = serpapi_api_key try: from serpapi import GoogleSearch values["search_engine"] = GoogleSearch except ImportError: raise ValueError( "Could not import serpapi python package. "
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
0fe667826214-2
python package. " "Please install it with `pip install google-search-results`." ) return values [docs] async def arun(self, query: str) -> str: """Use aiohttp to run query through SerpAPI and parse result.""" def construct_url_and_params() -> Tuple[str, Dict[str, str]]: params = self.get_params(query) params["source"] = "python" if self.serpapi_api_key: params["serp_api_key"] = self.serpapi_api_key params["output"] = "json" url = "https://serpapi.com/search" return url, params url, params = construct_url_and_params() if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as response: res = await response.json() else: async with self.aiosession.get(url, params=params) as response:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
0fe667826214-3
async with self.aiosession.get(url, params=params) as response: res = await response.json() return self._process_response(res) [docs] def run(self, query: str) -> str: """Run query through SerpAPI and parse result.""" return self._process_response(self.results(query)) [docs] def results(self, query: str) -> dict: """Run query through SerpAPI and return the raw result.""" params = self.get_params(query) with HiddenPrints(): search = self.search_engine(params) res = search.get_dict() return res [docs] def get_params(self, query: str) -> Dict[str, str]: """Get parameters for SerpAPI.""" _params = { "api_key": self.serpapi_api_key, "q": query, } params = {**self.params, **_params} return params @staticmethod def _process_response(res: dict) -> str: """Process response from SerpAPI.""" if "error" in res.keys(): raise ValueError(f"Got error
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
0fe667826214-4
res.keys(): raise ValueError(f"Got error from SerpAPI: {res['error']}") if "answer_box" in res.keys() and "answer" in res["answer_box"].keys(): toret = res["answer_box"]["answer"] elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys(): toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0] elif ( "sports_results" in res.keys() and "game_spotlight" in res["sports_results"].keys() ): toret = res["sports_results"]["game_spotlight"] elif ( "knowledge_graph" in res.keys() and "description" in res["knowledge_graph"].keys() ): toret = res["knowledge_graph"]["description"] elif "snippet" in
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
0fe667826214-5
= res["knowledge_graph"]["description"] elif "snippet" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["snippet"] else: toret = "No good search result found" return toret By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html
478ff309f542-0
Source code for langchain.vectorstores.opensearch_vector_search """Wrapper around OpenSearch vector database.""" from __future__ import annotations import uuid from typing import Any, Dict, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env from langchain.vectorstores.base import VectorStore IMPORT_OPENSEARCH_PY_ERROR = ( "Could not import OpenSearch. Please install it with `pip install opensearch-py`." ) SCRIPT_SCORING_SEARCH = "script_scoring" PAINLESS_SCRIPTING_SEARCH = "painless_scripting" MATCH_ALL_QUERY = {"match_all": {}} # type: Dict def _import_opensearch() -> Any: """Import OpenSearch if available, otherwise raise error.""" try: from opensearchpy import OpenSearch except ImportError: raise ValueError(IMPORT_OPENSEARCH_PY_ERROR) return OpenSearch def _import_bulk() -> Any: """Import bulk if available, otherwise raise error.""" try: from opensearchpy.helpers import bulk except ImportError: raise ValueError(IMPORT_OPENSEARCH_PY_ERROR) return bulk def _get_opensearch_client(opensearch_url: str, **kwargs: Any) -> Any: """Get OpenSearch client from the opensearch_url, otherwise raise error.""" try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-1
**kwargs) except ValueError as e: raise ValueError( f"OpenSearch client string provided is not in proper format. " f"Got error: {e} " ) return client def _validate_embeddings_and_bulk_size(embeddings_length: int, bulk_size: int) -> None: """Validate Embeddings Length and Bulk Size.""" if embeddings_length == 0: raise RuntimeError("Embeddings size is zero") if bulk_size < embeddings_length: raise RuntimeError( f"The embeddings count, {embeddings_length} is more than the " f"[bulk_size], {bulk_size}. Increase the value of [bulk_size]." ) def _bulk_ingest_embeddings( client: Any, index_name: str, embeddings: List[List[float]], texts: Iterable[str], metadatas: Optional[List[dict]] = None, vector_field: str = "vector_field", text_field: str = "text", ) -> List[str]: """Bulk Ingest Embeddings into given index.""" bulk = _import_bulk() requests = [] ids = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} _id = str(uuid.uuid4()) request = {
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-2
str(uuid.uuid4()) request = { "_op_type": "index", "_index": index_name, vector_field: embeddings[i], text_field: text, "metadata": metadata, "_id": _id, } requests.append(request) ids.append(_id) bulk(client, requests) client.indices.refresh(index=index_name) return ids def _default_scripting_text_mapping( dim: int, vector_field: str = "vector_field", ) -> Dict: """For Painless Scripting or Script Scoring,the default mapping to create index.""" return { "mappings": { "properties": { vector_field: {"type": "knn_vector", "dimension": dim}, } } } def _default_text_mapping( dim: int, engine: str = "nmslib", space_type: str = "l2", ef_search: int = 512, ef_construction: int = 512, m: int = 16, vector_field: str = "vector_field", ) -> Dict: """For
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-3
vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Search, this is the default mapping to create index.""" return { "settings": {"index": {"knn": True, "knn.algo_param.ef_search": ef_search}}, "mappings": { "properties": { vector_field: { "type": "knn_vector", "dimension": dim, "method": { "name": "hnsw", "space_type": space_type, "engine": engine, "parameters": {"ef_construction": ef_construction, "m": m}, }, } } }, } def _default_approximate_search_query( query_vector: List[float],
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-4
_default_approximate_search_query( query_vector: List[float], size: int = 4, k: int = 4, vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Search, this is the default query.""" return { "size": size, "query": {"knn": {vector_field: {"vector": query_vector, "k": k}}}, } def _default_script_query( query_vector: List[float], space_type: str = "l2", pre_filter: Dict = MATCH_ALL_QUERY, vector_field: str = "vector_field", ) -> Dict: """For Script Scoring Search, this is the default query.""" return { "query": { "script_score": { "query": pre_filter, "script": { "source": "knn_score", "lang": "knn", "params": { "field": vector_field, "query_value": query_vector,
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-5
"query_value": query_vector, "space_type": space_type, }, }, } } } def __get_painless_scripting_source( space_type: str, query_vector: List[float], vector_field: str = "vector_field" ) -> str: """For Painless Scripting, it returns the script source based on space type.""" source_value = ( "(1.0 + " + space_type + "(" + str(query_vector) + ", doc['" + vector_field + "']))" ) if space_type == "cosineSimilarity": return source_value else: return "1/" + source_value def _default_painless_scripting_query( query_vector: List[float], space_type: str = "l2Squared", pre_filter: Dict = MATCH_ALL_QUERY, vector_field: str = "vector_field", ) -> Dict: """For Painless Scripting Search, this is the default query.""" source = __get_painless_scripting_source(space_type, query_vector) return {
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-6
__get_painless_scripting_source(space_type, query_vector) return { "query": { "script_score": { "query": pre_filter, "script": { "source": source, "params": { "field": vector_field, "query_value": query_vector, }, }, } } } def _get_kwargs_value(kwargs: Any, key: str, default_value: Any) -> Any: """Get the value of the key if present. Else get the default_value.""" if key in kwargs: return kwargs.get(key) return default_value [docs]class OpenSearchVectorSearch(VectorStore): """Wrapper around OpenSearch as a vector database. Example: .. code-block:: python from langchain import OpenSearchVectorSearch opensearch_vector_search =
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-7
opensearch_vector_search = OpenSearchVectorSearch( "http://localhost:9200", "embeddings", embedding_function ) """ def __init__( self, opensearch_url: str, index_name: str, embedding_function: Embeddings, **kwargs: Any, ): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index_name = index_name self.client = _get_opensearch_client(opensearch_url, **kwargs) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, bulk_size: int = 500, **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.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-8
metadatas: Optional list of metadatas associated with the texts. bulk_size: Bulk API request count; Default: 500 Returns: List of ids from adding the texts into the vectorstore. Optional Args: vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of the document is stored in. Defaults to "text". """ embeddings = self.embedding_function.embed_documents(list(texts)) _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field") text_field = _get_kwargs_value(kwargs, "text_field", "text") return _bulk_ingest_embeddings( self.client, self.index_name, embeddings, texts, metadatas, vector_field, text_field, ) [docs] def similarity_search( self, query:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-9
def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. By default supports Approximate Search. Also supports Script Scoring and Painless Scripting. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. Optional Args: vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of the document is stored in. Defaults to "text". metadata_field: Document field that metadata is stored in. Defaults to "metadata". Can be set to a special value "*" to include the entire document. Optional Args for Approximate Search: search_type: "approximate_search"; default: "approximate_search" size: number of results the query actually returns; default: 4 Optional
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-10
of results the query actually returns; default: 4 Optional Args for Script Scoring Search: search_type: "script_scoring"; default: "approximate_search" space_type: "l2", "l1", "linf", "cosinesimil", "innerproduct", "hammingbit"; default: "l2" pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} Optional Args for Painless Scripting Search: search_type: "painless_scripting"; default: "approximate_search" space_type: "l2Squared", "l1Norm", "cosineSimilarity"; default: "l2Squared" pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} """ embedding = self.embedding_function.embed_query(query) search_type = _get_kwargs_value(kwargs, "search_type", "approximate_search") text_field = _get_kwargs_value(kwargs, "text_field", "text") metadata_field = _get_kwargs_value(kwargs, "metadata_field", "metadata") vector_field = _get_kwargs_value(kwargs, "vector_field",
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-11
vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field") if search_type == "approximate_search": size = _get_kwargs_value(kwargs, "size", 4) search_query = _default_approximate_search_query( embedding, size, k, vector_field ) elif search_type == SCRIPT_SCORING_SEARCH: space_type = _get_kwargs_value(kwargs, "space_type", "l2") pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY) search_query = _default_script_query( embedding, space_type, pre_filter, vector_field ) elif search_type == PAINLESS_SCRIPTING_SEARCH: space_type = _get_kwargs_value(kwargs, "space_type", "l2Squared") pre_filter = _get_kwargs_value(kwargs, "pre_filter", MATCH_ALL_QUERY) search_query = _default_painless_scripting_query( embedding, space_type, pre_filter, vector_field ) else:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-12
) else: raise ValueError("Invalid `search_type` provided as an argument") response = self.client.search(index=self.index_name, body=search_query) hits = [hit["_source"] for hit in response["hits"]["hits"][:k]] documents = [ Document( page_content=hit[text_field], metadata=hit if metadata_field == "*" or metadata_field not in hit else hit[metadata_field], ) for hit in hits ] return documents [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, **kwargs: Any, ) -> OpenSearchVectorSearch: """Construct OpenSearchVectorSearch wrapper from raw documents. Example: .. code-block:: python
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-13
.. code-block:: python from langchain import OpenSearchVectorSearch from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() opensearch_vector_search = OpenSearchVectorSearch.from_texts( texts, embeddings, opensearch_url="http://localhost:9200" ) OpenSearch by default supports Approximate Search powered by nmslib, faiss and lucene engines recommended for large datasets. Also supports brute force search through Script Scoring and Painless Scripting. Optional Args: vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of the document is stored in. Defaults to "text". Optional Keyword Args for Approximate Search: engine: "nmslib", "faiss", "hnsw"; default:
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-14
engine: "nmslib", "faiss", "hnsw"; default: "nmslib" space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2" ef_search: Size of the dynamic list used during k-NN searches. Higher values lead to more accurate but slower searches; default: 512 ef_construction: Size of the dynamic list used during k-NN graph creation. Higher values lead to more accurate graph but slower indexing speed; default: 512 m: Number of bidirectional links created for each new element. Large impact on memory consumption. Between 2 and 100; default: 16 Keyword Args for Script Scoring or Painless Scripting: is_appx_search: False """ opensearch_url = get_from_dict_or_env( kwargs, "opensearch_url", "OPENSEARCH_URL" ) client = _get_opensearch_client(opensearch_url) embeddings = embedding.embed_documents(texts) _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) dim
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-15
bulk_size) dim = len(embeddings[0]) # Get the index name from either from kwargs or ENV Variable # before falling back to random generation index_name = get_from_dict_or_env( kwargs, "index_name", "OPENSEARCH_INDEX_NAME", default=uuid.uuid4().hex ) is_appx_search = _get_kwargs_value(kwargs, "is_appx_search", True) vector_field = _get_kwargs_value(kwargs, "vector_field", "vector_field") text_field = _get_kwargs_value(kwargs, "text_field", "text") if is_appx_search: engine = _get_kwargs_value(kwargs, "engine", "nmslib") space_type = _get_kwargs_value(kwargs, "space_type", "l2") ef_search = _get_kwargs_value(kwargs, "ef_search", 512) ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512) m = _get_kwargs_value(kwargs, "m", 16) mapping = _default_text_mapping( dim, engine, space_type, ef_search, ef_construction, m, vector_field )
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
478ff309f542-16
vector_field ) else: mapping = _default_scripting_text_mapping(dim) client.indices.create(index=index_name, body=mapping) _bulk_ingest_embeddings( client, index_name, embeddings, texts, metadatas, vector_field, text_field ) return cls(opensearch_url, index_name, embedding) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html