id
stringlengths
14
16
text
stringlengths
45
2.05k
source
stringlengths
53
111
8b7d7ea2619a-2
The most core type of chain is an LLMChain, which consists of a PromptTemplate and an LLM. Extending the previous example, we can construct an LLMChain which takes user input, formats it with a PromptTemplate, and then passes the formatted response to an LLM. from langchain.prompts import PromptTemplate from langchain.llms import OpenAI llm = OpenAI(temperature=0.9) prompt = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) We can now create a very simple chain that will take user input, format the prompt with it, and then send it to the LLM: from langchain.chains import LLMChain chain = LLMChain(llm=llm, prompt=prompt) Now we can run that chain only specifying the product! chain.run("colorful socks") # -> '\n\nSocktastic!' There we go! There’s the first chain - an LLM Chain. This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains. For more details, check out the getting started guide for chains. Agents: Dynamically call chains based on user input So far the chains we’ve looked at run in a predetermined order. Agents no longer do: they use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning to the user. When used correctly agents can be extremely powerful. In this tutorial, we show you how to easily use agents through the simplest, highest level API. In order to load agents, you should understand the following concepts:
https://langchain.readthedocs.io\en\latest\getting_started\getting_started.html
8b7d7ea2619a-3
In order to load agents, you should understand the following concepts: Tool: A function that performs a specific duty. This can be things like: Google Search, Database lookup, Python REPL, other chains. The interface for a tool is currently a function that is expected to have a string as an input, with a string as an output. LLM: The language model powering the agent. Agent: The agent to use. This should be a string that references a support agent class. Because this notebook focuses on the simplest, highest level API, this only covers using the standard supported agents. If you want to implement a custom agent, see the documentation for custom agents (coming soon). Agents: For a list of supported agents and their specifications, see here. Tools: For a list of predefined tools and their specifications, see here. For this example, you will also need to install the SerpAPI Python package. pip install google-search-results And set the appropriate environment variables. import os os.environ["SERPAPI_API_KEY"] = "..." Now we can get started! from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.llms import OpenAI # First, let's load the language model we're going to use to control the agent. llm = OpenAI(temperature=0) # Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in. tools = load_tools(["serpapi", "llm-math"], llm=llm) # Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use. agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) # Now let's test it out!
https://langchain.readthedocs.io\en\latest\getting_started\getting_started.html
8b7d7ea2619a-4
# Now let's test it out! agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?") Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power. Action: Search Action Input: "Olivia Wilde boyfriend" Observation: Jason Sudeikis Thought: I need to find out Jason Sudeikis' age Action: Search Action Input: "Jason Sudeikis age" Observation: 47 years Thought: I need to calculate 47 raised to the 0.23 power Action: Calculator Action Input: 47^0.23 Observation: Answer: 2.4242784855673896 Thought: I now know the final answer Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896. > Finished AgentExecutor chain. "Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896." Memory: Add state to chains and agents
https://langchain.readthedocs.io\en\latest\getting_started\getting_started.html
8b7d7ea2619a-5
Memory: Add state to chains and agents So far, all the chains and agents we’ve gone through have been stateless. But often, you may want a chain or agent to have some concept of “memory” so that it may remember information about its previous interactions. The clearest and simple example of this is when designing a chatbot - you want it to remember previous messages so it can use context from that to have a better conversation. This would be a type of “short-term memory”. On the more complex side, you could imagine a chain/agent remembering key pieces of information over time - this would be a form of “long-term memory”. For more concrete ideas on the latter, see this awesome paper. LangChain provides several specially created chains just for this purpose. This notebook walks through using one of those chains (the ConversationChain) with two different types of memory. By default, the ConversationChain has a simple type of memory that remembers all previous inputs/outputs and adds them to the context that is passed. Let’s take a look at using this chain (setting verbose=True so we can see the prompt). from langchain import OpenAI, ConversationChain llm = OpenAI(temperature=0) conversation = ConversationChain(llm=llm, verbose=True) conversation.predict(input="Hi there!") > Entering new chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Current conversation: Human: Hi there! AI: > Finished chain. ' Hello! How are you today?' conversation.predict(input="I'm doing well! Just having a conversation with an AI.") > Entering new chain... Prompt after formatting:
https://langchain.readthedocs.io\en\latest\getting_started\getting_started.html
8b7d7ea2619a-6
> Entering new chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Current conversation: Human: Hi there! AI: Hello! How are you today? Human: I'm doing well! Just having a conversation with an AI. AI: > Finished chain. " That's great! What would you like to talk about?" previous Welcome to LangChain next Prompt Templates Contents Installation Environment Setup Building a Language Model Application By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\getting_started\getting_started.html
967ffea16479-0
.rst .pdf Agents Agents# Some applications will require not just a predetermined chain of calls to LLMs/other tools, but potentially an unknown chain that depends on the user’s input. In these types of chains, there is a “agent” which has access to a suite of tools. Depending on the user input, the agent can then decide which, if any, of these tools to call. The following sections of documentation are provided: Getting Started: A notebook to help you get started working with agents as quickly as possible. Key Concepts: A conceptual guide going over the various concepts related to agents. How-To Guides: A collection of how-to guides. These highlight how to integrate various types of tools, how to work with different types of agents, and how to customize agents. Reference: API reference documentation for all Agent classes. previous Chains next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents.html
f5996f35305e-0
.rst .pdf Chains Chains# Using an LLM in isolation is fine for some simple applications, but many more complex ones require chaining LLMs - either with each other or with other experts. LangChain provides a standard interface for Chains, as well as some common implementations of chains for ease of use. The following sections of documentation are provided: Getting Started: A getting started guide for chains, to get you up and running quickly. Key Concepts: A conceptual guide going over the various concepts related to chains. How-To Guides: A collection of how-to guides. These highlight how to use various types of chains. Reference: API reference documentation for all Chain classes. previous Vector DB Text Generation next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\chains.html
6b17685869b6-0
.rst .pdf Chat Chat# Chat models are a variation on language models. While chat models use language models under the hood, the interface they expose is a bit different. Rather than expose a “text in, text out” API, they expose an interface where “chat messages” are the inputs and outputs. Chat model APIs are fairly new, so we are still figuring out the correct abstractions. The following sections of documentation are provided: Getting Started: An overview of the basics of chat models. Key Concepts: A conceptual guide going over the various concepts related to chat models. How-To Guides: A collection of how-to guides. These highlight how to accomplish various objectives with our chat model class, as well as how to integrate with various chat model providers. previous Multiple Memory next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\chat.html
28fd137a7d01-0
.rst .pdf Document Loaders Document Loaders# Combining language models with your own text data is a powerful way to differentiate them. The first step in doing this is to load the data into “documents” - a fancy way of say some pieces of text. This module is aimed at making this easy. A primary driver of a lot of this is the Unstructured python package. This package is a great way to transform all types of files - text, powerpoint, images, html, pdf, etc - into text data. For detailed instructions on how to get set up with Unstructured, see installation guidelines here. The following sections of documentation are provided: Key Concepts: A conceptual guide going over the various concepts related to loading documents. How-To Guides: A collection of how-to guides. These highlight different types of loaders. previous LLMs next Key Concepts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\document_loaders.html
d5a4ae619dbf-0
.rst .pdf Indexes Indexes# Indexes refer to ways to structure documents so that LLMs can best interact with them. This module contains utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains. The most common way that indexes are used in chains is in a “retrieval” step. This step refers to taking a user’s query and returning the most relevant documents. We draw this distinction because (1) an index can be used for other things besides retrieval, and (2) retrieval can use other logic besides an index to find relevant documents. We therefor have a concept of a “Retriever” interface - this is the interface that most chains work with. Most of the time when we talk about indexes and retrieval we are talking about indexing and retrieving unstructured data (like text documents). For interacting with structured data (SQL tables, etc) or APIs, please see the corresponding use case sections for links to relevant functionality. The primary index and retrieval types supported by LangChain are currently centered around vector databases, and therefore a lot of the functionality we dive deep on those topics. The following sections of documentation are provided: Getting Started: An overview of the base “Retriever” interface, and then all the functionality LangChain provides for working with indexes. Key Concepts: A conceptual guide going over the various concepts related to indexes and the tools needed to create them. How-To Guides: A collection of how-to guides. These highlight how to use all the relevant tools, the different types of vector databases, different types of retrievers, and how to use retrievers and indexes in chains. previous VectorStores next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\indexes.html
d649260aeaa4-0
.rst .pdf LLMs LLMs# Large Language Models (LLMs) are a core component of LangChain. LangChain is not a provider of LLMs, but rather provides a standard interface through which you can interact with a variety of LLMs. The following sections of documentation are provided: Getting Started: An overview of all the functionality the LangChain LLM class provides. Key Concepts: A conceptual guide going over the various concepts related to LLMs. How-To Guides: A collection of how-to guides. These highlight how to accomplish various objectives with our LLM class, as well as how to integrate with various LLM providers. Reference: API reference documentation for all LLM classes. previous Example Selector next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\llms.html
c3167ac4098a-0
.rst .pdf Memory Memory# By default, Chains and Agents are stateless, meaning that they treat each incoming query independently (as are the underlying LLMs and chat models). In some applications (chatbots being a GREAT example) it is highly important to remember previous interactions, both at a short term but also at a long term level. The concept of “Memory” exists to do exactly that. LangChain provides memory components in two forms. First, LangChain provides helper utilities for managing and manipulating previous chat messages. These are designed to be modular and useful regardless of how they are used. Secondly, LangChain provides easy ways to incorporate these utilities into chains. The following sections of documentation are provided: Getting Started: An overview of how to get started with different types of memory. Key Concepts: A conceptual guide going over the various concepts related to memory. How-To Guides: A collection of how-to guides. These highlight different types of memory, as well as how to use memory in chains. Memory Getting Started Key Concepts How-To Guides previous Agents next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\memory.html
48f937e5b2df-0
.rst .pdf Prompt Templates Prompt Templates# Language models take text as input - that text is commonly referred to as a prompt. Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input. LangChain provides several classes and functions to make constructing and working with prompts easy. The following sections of documentation are provided: Getting Started: An overview of all the functionality LangChain provides for working with and constructing prompts. Key Concepts: A conceptual guide going over the various concepts related to prompts. How-To Guides: A collection of how-to guides. These highlight how to accomplish various objectives with our prompt class. Reference: API reference documentation for all prompt classes. previous Quickstart Guide next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\prompts.html
7f36a57a02d8-0
.rst .pdf Utils Utils# While LLMs are powerful on their own, they are more powerful when connected with other sources of knowledge or computation. This section highlights those sources of knowledge or computation, and goes over how to easily use them from within LangChain. The following sections of documentation are provided: Key Concepts: A conceptual guide going over the various types of utils. How-To Guides: A collection of how-to guides. These highlight how to use various types of utils. Reference: API reference documentation for all Util classes. previous YouTube next Key Concepts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\utils.html
e7b00d88ab10-0
.md .pdf Agents Contents zero-shot-react-description react-docstore self-ask-with-search conversational-react-description Agents# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning a response to the user. For a list of easily loadable tools, see here. Here are the agents available in LangChain. For a tutorial on how to load agents, see here. zero-shot-react-description# This agent uses the ReAct framework to determine which tool to use based solely on the tool’s description. Any number of tools can be provided. This agent requires that a description is provided for each tool. react-docstore# This agent uses the ReAct framework to interact with a docstore. Two tools must be provided: a Search tool and a Lookup tool (they must be named exactly as so). The Search tool should search for a document, while the Lookup tool should lookup a term in the most recently found document. This agent is equivalent to the original ReAct paper, specifically the Wikipedia example. self-ask-with-search# This agent utilizes a single tool that should be named Intermediate Answer. This tool should be able to lookup factual answers to questions. This agent is equivalent to the original self ask with search paper, where a Google search API was provided as the tool. conversational-react-description# This agent is designed to be used in conversational settings. The prompt is designed to make the agent helpful and conversational. It uses the ReAct framework to decide which tool to use, and uses memory to remember the previous conversation interactions. Contents zero-shot-react-description react-docstore self-ask-with-search conversational-react-description By Harrison Chase
https://langchain.readthedocs.io\en\latest\modules\agents\agents.html
e7b00d88ab10-1
self-ask-with-search conversational-react-description By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agents.html
2db39156e89f-0
.ipynb .pdf Getting Started Getting Started# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning to the user. When used correctly agents can be extremely powerful. The purpose of this notebook is to show you how to easily use agents through the simplest, highest level API. In order to load agents, you should understand the following concepts: Tool: A function that performs a specific duty. This can be things like: Google Search, Database lookup, Python REPL, other chains. The interface for a tool is currently a function that is expected to have a string as an input, with a string as an output. LLM: The language model powering the agent. Agent: The agent to use. This should be a string that references a support agent class. Because this notebook focuses on the simplest, highest level API, this only covers using the standard supported agents. If you want to implement a custom agent, see the documentation for custom agents (coming soon). Agents: For a list of supported agents and their specifications, see here. Tools: For a list of predefined tools and their specifications, see here. from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.llms import OpenAI First, let’s load the language model we’re going to use to control the agent. llm = OpenAI(temperature=0) Next, let’s load some tools to use. Note that the llm-math tool uses an LLM, so we need to pass that in. tools = load_tools(["serpapi", "llm-math"], llm=llm) Finally, let’s initialize an agent with the tools, the language model, and the type of agent we want to use.
https://langchain.readthedocs.io\en\latest\modules\agents\getting_started.html
2db39156e89f-1
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) Now let’s test it out! agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I need to find out Camila Morrone's age Action: Search Action Input: "Camila Morrone age" Observation: 25 years Thought: I need to calculate 25 raised to the 0.43 power Action: Calculator Action Input: 25^0.43 Observation: Answer: 3.991298452658078 Thought: I now know the final answer Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078." previous Agents next Key Concepts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\getting_started.html
caf8a7c01e0d-0
.rst .pdf How-To Guides Contents Agent Overview Agent Toolkits Agent Types How-To Guides# There are three types of examples in this section: Agent Overview: how-to-guides for generic agent functionality Agent Toolkits: how-to-guides for specific agent toolkits (agents optimized for interacting with a certain resource) Agent Types: how-to-guides for working with the different agent types Agent Overview# The first category of how-to guides here cover specific parts of working with agents. Load From Hub: This notebook covers how to load agents from LangChainHub. Custom Tools: How to create custom tools that an agent can use. Agents With Vectorstores: How to use vectorstores with agents. Intermediate Steps: How to access and use intermediate steps to get more visibility into the internals of an agent. Custom Agent: How to create a custom agent (specifically, a custom LLM + prompt to drive that agent). Multi Input Tools: How to use a tool that requires multiple inputs with an agent. Search Tools: How to use the different type of search tools that LangChain supports. Max Iterations: How to restrict an agent to a certain number of iterations. Asynchronous: Covering asynchronous functionality. Agent Toolkits# The next set of examples covers agents with toolkits. As opposed to the examples above, these examples are not intended to show off an agent type, but rather to show off an agent applied to particular use case. SQLDatabase Agent: This notebook covers how to interact with an arbitrary SQL database using an agent. JSON Agent: This notebook covers how to interact with a JSON dictionary using an agent. OpenAPI Agent: This notebook covers how to interact with an arbitrary OpenAPI endpoint using an agent. VectorStore Agent: This notebook covers how to interact with VectorStores using an agent.
https://langchain.readthedocs.io\en\latest\modules\agents\how_to_guides.html
caf8a7c01e0d-1
VectorStore Agent: This notebook covers how to interact with VectorStores using an agent. Python Agent: This notebook covers how to produce and execute python code using an agent. Pandas DataFrame Agent: This notebook covers how to do question answering over a pandas dataframe using an agent. Under the hood this calls the Python agent.. CSV Agent: This notebook covers how to do question answering over a csv file. Under the hood this calls the Pandas DataFrame agent. Agent Types# The final set of examples are all end-to-end example of different agent types. In all examples there is an Agent with a particular set of tools. Tools: A tool can be anything that takes in a string and returns a string. This means that you can use both the primitives AND the chains found in this documentation. LangChain also provides a list of easily loadable tools. For detailed information on those, please see this documentation Agents: An agent uses an LLMChain to determine which tools to use. For a list of all available agent types, see here. MRKL Tools used: Search, SQLDatabaseChain, LLMMathChain Agent used: zero-shot-react-description Paper Note: This is the most general purpose example, so if you are looking to use an agent with arbitrary tools, please start here. Example Notebook Self-Ask-With-Search Tools used: Search Agent used: self-ask-with-search Paper Example Notebook ReAct Tools used: Wikipedia Docstore Agent used: react-docstore Paper Example Notebook previous Key Concepts next Agents and Vectorstores Contents Agent Overview Agent Toolkits Agent Types By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\how_to_guides.html
7e269030fa06-0
.md .pdf Key Concepts Contents Agents Tools ToolKits Key Concepts# Agents# Agents use an LLM to determine which actions to take and in what order. For more detailed information on agents, and different types of agents in LangChain, see this documentation. Tools# Tools are functions that agents can use to interact with the world. These tools can be generic utilities (e.g. search), other chains, or even other agents. For more detailed information on tools, and different types of tools in LangChain, see this documentation. ToolKits# Toolkits are groups of tools that are best used together. They allow you to logically group and initialize a set of tools that share a particular resource (such as a database connection or json object). They can be used to construct an agent for a specific use-case. For more detailed information on toolkits and their use cases, see this documentation (the “Agent Toolkits” section). previous Getting Started next How-To Guides Contents Agents Tools ToolKits By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\key_concepts.html
012bd84a34df-0
.md .pdf Tools Contents List of Tools Tools# Tools are functions that agents can use to interact with the world. These tools can be generic utilities (e.g. search), other chains, or even other agents. Currently, tools can be loaded with the following snippet: from langchain.agents import load_tools tool_names = [...] tools = load_tools(tool_names) Some tools (e.g. chains, agents) may require a base LLM to use to initialize them. In that case, you can pass in an LLM as well: from langchain.agents import load_tools tool_names = [...] llm = ... tools = load_tools(tool_names, llm=llm) Below is a list of all supported tools and relevant information: Tool Name: The name the LLM refers to the tool by. Tool Description: The description of the tool that is passed to the LLM. Notes: Notes about the tool that are NOT passed to the LLM. Requires LLM: Whether this tool requires an LLM to be initialized. (Optional) Extra Parameters: What extra parameters are required to initialize this tool. List of Tools# python_repl Tool Name: Python REPL Tool Description: A Python shell. Use this to execute python commands. Input should be a valid python command. If you expect output it should be printed out. Notes: Maintains state. Requires LLM: No serpapi Tool Name: Search Tool Description: A search engine. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Calls the Serp API and then parses results. Requires LLM: No wolfram-alpha Tool Name: Wolfram Alpha
https://langchain.readthedocs.io\en\latest\modules\agents\tools.html
012bd84a34df-1
Requires LLM: No wolfram-alpha Tool Name: Wolfram Alpha Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query. Notes: Calls the Wolfram Alpha API and then parses results. Requires LLM: No Extra Parameters: wolfram_alpha_appid: The Wolfram Alpha app id. requests Tool Name: Requests Tool Description: A portal to the internet. Use this when you need to get specific content from a site. Input should be a specific url, and the output will be all the text on that page. Notes: Uses the Python requests module. Requires LLM: No terminal Tool Name: Terminal Tool Description: Executes commands in a terminal. Input should be valid commands, and the output will be any output from running that command. Notes: Executes commands with subprocess. Requires LLM: No pal-math Tool Name: PAL-MATH Tool Description: A language model that is excellent at solving complex word math problems. Input should be a fully worded hard word math problem. Notes: Based on this paper. Requires LLM: Yes pal-colored-objects Tool Name: PAL-COLOR-OBJ Tool Description: A language model that is wonderful 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. Notes: Based on this paper. Requires LLM: Yes llm-math Tool Name: Calculator Tool Description: Useful for when you need to answer questions about math. Notes: An instance of the LLMMath chain. Requires LLM: Yes open-meteo-api Tool Name: Open Meteo API
https://langchain.readthedocs.io\en\latest\modules\agents\tools.html
012bd84a34df-2
Requires LLM: Yes open-meteo-api Tool Name: Open Meteo API Tool 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. Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), specifically the /v1/forecast endpoint. Requires LLM: Yes news-api Tool Name: News API Tool 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. Notes: A natural language connection to the News API (https://newsapi.org), specifically the /v2/top-headlines endpoint. Requires LLM: Yes Extra Parameters: news_api_key (your API key to access this endpoint) tmdb-api Tool Name: TMDB API Tool 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. Notes: A natural language connection to the TMDB API (https://api.themoviedb.org/3), specifically the /search/movie endpoint. Requires LLM: Yes Extra Parameters: tmdb_bearer_token (your Bearer Token to access this endpoint - note that this is different from the API key) google-search Tool Name: Search Tool Description: A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Uses the Google Custom Search API Requires LLM: No Extra Parameters: google_api_key, google_cse_id For more information on this, see this page searx-search Tool Name: Search
https://langchain.readthedocs.io\en\latest\modules\agents\tools.html
012bd84a34df-3
For more information on this, see this page searx-search Tool Name: Search Tool Description: A wrapper around SearxNG meta search engine. Input should be a search query. Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API. Requires LLM: No Extra Parameters: searx_host google-serper Tool Name: Search Tool Description: A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Calls the serper.dev Google Search API and then parses results. Requires LLM: No Extra Parameters: serper_api_key For more information on this, see this page wikipedia Tool Name: Wikipedia Tool Description: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query. Notes: Uses the wikipedia Python package to call the MediaWiki API and then parses results. Requires LLM: No Extra Parameters: top_k_results podcast-api Tool Name: Podcast API Tool 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. Notes: A natural language connection to the Listen Notes Podcast API (https://www.PodcastAPI.com), specifically the /search/ endpoint. Requires LLM: Yes Extra Parameters: listen_api_key (your api key to access this endpoint) Contents List of Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\tools.html
0f5faa2fc73f-0
.ipynb .pdf CSV Agent CSV Agent# This notebook shows how to use agents to interact with a csv. It is mostly optimized for question answering. NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously. from langchain.agents import create_csv_agent from langchain.llms import OpenAI agent = create_csv_agent(OpenAI(temperature=0), 'titanic.csv', verbose=True) agent.run("how many rows are there?") > Entering new AgentExecutor chain... Thought: I need to count the number of rows Action: python_repl_ast Action Input: len(df) Observation: 891 Thought: I now know the final answer Final Answer: There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.' agent.run("how many people have more than 3 sibligngs") > Entering new AgentExecutor chain... Thought: I need to count the number of people with more than 3 siblings Action: python_repl_ast Action Input: df[df['SibSp'] > 3].shape[0] Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.' agent.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Thought: I need to calculate the average age first Action: python_repl_ast Action Input: df['Age'].mean() Observation: 29.69911764705882
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\csv.html
0f5faa2fc73f-1
Observation: 29.69911764705882 Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: name 'math' is not defined Thought: I need to import the math library Action: python_repl_ast Action Input: import math Observation: None Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: 5.449689683556195 > Finished chain. '5.449689683556195' previous Adding SharedMemory to an Agent and its Tools next JSON Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\csv.html
917dd76aa153-0
.ipynb .pdf JSON Agent Contents Initialization Example: getting the required POST parameters for a request JSON Agent# This notebook showcases an agent designed to interact with large JSON/dict objects. This is useful when you want to answer questions about a JSON blob that’s too large to fit in the context window of an LLM. The agent is able to iteratively explore the blob to find what it needs to answer the user’s question. In the below example, we are using the OpenAPI spec for the OpenAI API, which you can find here. We will use the JSON agent to answer some questions about the API spec. Initialization# import os import yaml from langchain.agents import ( create_json_agent, AgentExecutor ) from langchain.agents.agent_toolkits import JsonToolkit from langchain.chains import LLMChain from langchain.llms.openai import OpenAI from langchain.requests import RequestsWrapper from langchain.tools.json.tool import JsonSpec with open("openai_openapi.yml") as f: data = yaml.load(f, Loader=yaml.FullLoader) json_spec = JsonSpec(dict_=data, max_value_length=4000) json_toolkit = JsonToolkit(spec=json_spec) json_agent_executor = create_json_agent( llm=OpenAI(temperature=0), toolkit=json_toolkit, verbose=True ) Example: getting the required POST parameters for a request# json_agent_executor.run("What are the required parameters in the request body to the /completions endpoint?") > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta']
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\json.html
917dd76aa153-1
Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"] Observation: ['post'] Thought: I should look at the post key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"] Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta'] Thought: I should look at the requestBody key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"] Observation: ['required', 'content'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["required"] Observation: True Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\json.html
917dd76aa153-2
Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"] Observation: ['schema'] Thought: I should look at the schema key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer Final Answer: The required parameters in the request body to the /completions endpoint are 'model'. > Finished chain. "The required parameters in the request body to the /completions endpoint are 'model'." previous CSV Agent next OpenAPI Agent Contents Initialization Example: getting the required POST parameters for a request By Harrison Chase
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\json.html
917dd76aa153-3
Initialization Example: getting the required POST parameters for a request By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\json.html
fba392c3f723-0
.ipynb .pdf OpenAPI Agent Contents Initialization Example: agent capable of analyzing OpenAPI spec and making requests OpenAPI Agent# This notebook showcases an agent designed to interact with an OpenAPI spec and make a correct API request based on the information it has gathered from the spec. In the below example, we are using the OpenAPI spec for the OpenAI API, which you can find here. Initialization# import os import yaml from langchain.agents import create_openapi_agent from langchain.agents.agent_toolkits import OpenAPIToolkit from langchain.llms.openai import OpenAI from langchain.requests import RequestsWrapper from langchain.tools.json.tool import JsonSpec with open("openai_openapi.yml") as f: data = yaml.load(f, Loader=yaml.FullLoader) json_spec=JsonSpec(dict_=data, max_value_length=4000) headers = { "Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}" } requests_wrapper=RequestsWrapper(headers=headers) openapi_toolkit = OpenAPIToolkit.from_llm(OpenAI(temperature=0), json_spec, requests_wrapper, verbose=True) openapi_agent_executor = create_openapi_agent( llm=OpenAI(temperature=0), toolkit=openapi_toolkit, verbose=True ) Example: agent capable of analyzing OpenAPI spec and making requests# openapi_agent_executor.run("Make a post request to openai /completions. The prompt should be 'tell me a joke.'") > Entering new AgentExecutor chain... Action: json_explorer Action Input: What is the base url for the API? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
fba392c3f723-1
> Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the servers key to see what the base url is Action: json_spec_list_keys Action Input: data["servers"][0] Observation: ValueError('Value at path `data["servers"][0]` is not a dict, get the value directly.') Thought: I should get the value of the servers key Action: json_spec_get_value Action Input: data["servers"][0] Observation: {'url': 'https://api.openai.com/v1'} Thought: I now know the base url for the API Final Answer: The base url for the API is https://api.openai.com/v1 > Finished chain. Observation: The base url for the API is https://api.openai.com/v1 Thought: I should find the path for the /completions endpoint. Action: json_explorer Action Input: What is the path for the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"]
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
fba392c3f723-2
Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I now know the path for the /completions endpoint Final Answer: data["paths"][2] > Finished chain. Observation: data["paths"][2] Thought: I should find the required parameters for the POST request. Action: json_explorer Action Input: What are the required parameters for a POST request to the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"]
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
fba392c3f723-3
Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"] Observation: ['post'] Thought: I should look at the post key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"] Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta'] Thought: I should look at the requestBody key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"] Observation: ['required', 'content'] Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
fba392c3f723-4
Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"] Observation: ['schema'] Thought: I should look at the schema key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: ValueError('Value at path `data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]` is not a dict, get the value directly.') Thought: I should look at the $ref key to get the value directly Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'. > Finished chain.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
fba392c3f723-5
> Finished chain. Observation: The required parameters for a POST request to the /completions endpoint are 'model'. Thought: I now know the parameters needed to make the request. Action: requests_post Action Input: { "url": "https://api.openai.com/v1/completions", "data": { "model": "davinci", "prompt": "tell me a joke" } } Observation: {"id":"cmpl-6oeEcNETfq8TOuIUQvAct6NrBXihs","object":"text_completion","created":1677529082,"model":"davinci","choices":[{"text":"\n\n\n\nLove is a battlefield\n\n\n\nIt's me...And some","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} Thought: I now know the final answer. Final Answer: Love is a battlefield. It's me...And some. > Finished chain. "Love is a battlefield. It's me...And some." previous JSON Agent next Pandas Dataframe Agent Contents Initialization Example: agent capable of analyzing OpenAPI spec and making requests By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\openapi.html
a1b6a9df07f4-0
.ipynb .pdf Pandas Dataframe Agent Pandas Dataframe Agent# This notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering. NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously. from langchain.agents import create_pandas_dataframe_agent from langchain.llms import OpenAI import pandas as pd df = pd.read_csv('titanic.csv') agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True) agent.run("how many rows are there?") > Entering new AgentExecutor chain... Thought: I need to count the number of rows Action: python_repl_ast Action Input: len(df) Observation: 891 Thought: I now know the final answer Final Answer: There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.' agent.run("how many people have more than 3 sibligngs") > Entering new AgentExecutor chain... Thought: I need to count the number of people with more than 3 siblings Action: python_repl_ast Action Input: df[df['SibSp'] > 3].shape[0] Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.' agent.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Thought: I need to calculate the average age first Action: python_repl_ast Action Input: df['Age'].mean()
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\pandas.html
a1b6a9df07f4-1
Action: python_repl_ast Action Input: df['Age'].mean() Observation: 29.69911764705882 Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: name 'math' is not defined Thought: I need to import the math library Action: python_repl_ast Action Input: import math Observation: None Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: 5.449689683556195 > Finished chain. '5.449689683556195' previous OpenAPI Agent next Python Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\pandas.html
c9ad078b2e24-0
.ipynb .pdf Python Agent Contents Python Agent Fibonacci Example Training neural net Python Agent# This notebook showcases an agent designed to write and execute python code to answer a question. from langchain.agents.agent_toolkits import create_python_agent from langchain.tools.python.tool import PythonREPLTool from langchain.python import PythonREPL from langchain.llms.openai import OpenAI agent_executor = create_python_agent( llm=OpenAI(temperature=0, max_tokens=1000), tool=PythonREPLTool(), verbose=True ) Fibonacci Example# This example was created by John Wiseman. agent_executor.run("What is the 10th fibonacci number?") > Entering new AgentExecutor chain... I need to calculate the 10th fibonacci number Action: Python REPL Action Input: def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) Observation: Thought: I need to call the function with 10 as the argument Action: Python REPL Action Input: fibonacci(10) Observation: Thought: I now know the final answer Final Answer: 55 > Finished chain. '55' Training neural net# This example was created by Samee Ur Rehman. agent_executor.run("""Understand, write a single neuron neural network in PyTorch. Take synthetic data for y=2x. Train for 1000 epochs and print every 100 epochs. Return prediction for x = 5""") > Entering new AgentExecutor chain... I need to write a neural network in PyTorch and train it on the given data.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\python.html
c9ad078b2e24-1
I need to write a neural network in PyTorch and train it on the given data. Action: Python REPL Action Input: import torch # Define the model model = torch.nn.Sequential( torch.nn.Linear(1, 1) ) # Define the loss loss_fn = torch.nn.MSELoss() # Define the optimizer optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # Define the data x_data = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) y_data = torch.tensor([[2.0], [4.0], [6.0], [8.0]]) # Train the model for epoch in range(1000): # Forward pass y_pred = model(x_data) # Compute and print loss loss = loss_fn(y_pred, y_data) if (epoch+1) % 100 == 0: print(f'Epoch {epoch+1}: loss = {loss.item():.4f}') # Zero the gradients optimizer.zero_grad() # Backward pass loss.backward() # Update the weights optimizer.step() Observation: Epoch 100: loss = 0.0013 Epoch 200: loss = 0.0007 Epoch 300: loss = 0.0004 Epoch 400: loss = 0.0002 Epoch 500: loss = 0.0001 Epoch 600: loss = 0.0001 Epoch 700: loss = 0.0000 Epoch 800: loss = 0.0000 Epoch 900: loss = 0.0000 Epoch 1000: loss = 0.0000 Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\python.html
c9ad078b2e24-2
Thought: I now know the final answer Final Answer: The prediction for x = 5 is 10.0. > Finished chain. 'The prediction for x = 5 is 10.0.' previous Pandas Dataframe Agent next SQL Database Agent Contents Python Agent Fibonacci Example Training neural net By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\python.html
fd79da127dea-0
.ipynb .pdf SQL Database Agent Contents Initialization Example: describing a table Example: describing a table, recovering from an error Example: running queries Recovering from an error SQL Database Agent# This notebook showcases an agent designed to interact with a sql databases. The agent builds off of SQLDatabaseChain and is designed to answer more general questions about a database, as well as recover from errors. Note that, as this agent is in active development, all answers might not be correct. Additionally, it is not guaranteed that the agent won’t perform DML statements on your database given certain questions. Be careful running it on sensitive data! This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. Initialization# from langchain.agents import create_sql_agent from langchain.agents.agent_toolkits import SQLDatabaseToolkit from langchain.sql_database import SQLDatabase from langchain.llms.openai import OpenAI from langchain.agents import AgentExecutor db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db") toolkit = SQLDatabaseToolkit(db=db) agent_executor = create_sql_agent( llm=OpenAI(temperature=0), toolkit=toolkit, verbose=True ) Example: describing a table# agent_executor.run("Describe the playlisttrack table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Artist, Invoice, Playlist, Genre, Album, PlaylistTrack, Track, InvoiceLine, MediaType, Employee, Customer Thought: I should look at the schema of the playlisttrack table Action: schema_sql_db Action Input: "PlaylistTrack" Observation:
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-1
Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table has two columns, PlaylistId and TrackId, and is linked to the Playlist and Track tables. > Finished chain. 'The PlaylistTrack table has two columns, PlaylistId and TrackId, and is linked to the Playlist and Track tables.' Example: describing a table, recovering from an error# In this example, the agent tries to search for a table that doesn’t exist, but finds the next best result agent_executor.run("Describe the playlistsong table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: I should look at the schema of the PlaylistSong table Action: schema_sql_db Action Input: "PlaylistSong" Observation: Error: table_names {'PlaylistSong'} not found in database Thought: I should check the spelling of the table Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: The table is called PlaylistTrack
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-2
Thought: The table is called PlaylistTrack Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables. > Finished chain. 'The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables.' Example: running queries# agent_executor.run("List the total sales per country. Which country's customers spent the most?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the relevant tables to see what columns I can use. Action: schema_sql_db Action Input: "Invoice, Customer" Observation: CREATE TABLE "Customer" ( "CustomerId" INTEGER NOT NULL, "FirstName" NVARCHAR(40) NOT NULL, "LastName" NVARCHAR(20) NOT NULL, "Company" NVARCHAR(80), "Address" NVARCHAR(70),
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-3
"Address" NVARCHAR(70), "City" NVARCHAR(40), "State" NVARCHAR(40), "Country" NVARCHAR(40), "PostalCode" NVARCHAR(10), "Phone" NVARCHAR(24), "Fax" NVARCHAR(24), "Email" NVARCHAR(60) NOT NULL, "SupportRepId" INTEGER, PRIMARY KEY ("CustomerId"), FOREIGN KEY("SupportRepId") REFERENCES "Employee" ("EmployeeId") ) SELECT * FROM 'Customer' LIMIT 3; CustomerId FirstName LastName Company Address City State Country PostalCode Phone Fax Email SupportRepId 1 Luís Gonçalves Embraer - Empresa Brasileira de Aeronáutica S.A. Av. Brigadeiro Faria Lima, 2170 São José dos Campos SP Brazil 12227-000 +55 (12) 3923-5555 +55 (12) 3923-5566 luisg@embraer.com.br 3 2 Leonie Köhler None Theodor-Heuss-Straße 34 Stuttgart None Germany 70174 +49 0711 2842222 None leonekohler@surfeu.de 5 3 François Tremblay None 1498 rue Bélanger Montréal QC Canada H2G 1A7 +1 (514) 721-4711 None ftremblay@gmail.com 3 CREATE TABLE "Invoice" ( "InvoiceId" INTEGER NOT NULL, "CustomerId" INTEGER NOT NULL, "InvoiceDate" DATETIME NOT NULL, "BillingAddress" NVARCHAR(70), "BillingCity" NVARCHAR(40),
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-4
"BillingCity" NVARCHAR(40), "BillingState" NVARCHAR(40), "BillingCountry" NVARCHAR(40), "BillingPostalCode" NVARCHAR(10), "Total" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("InvoiceId"), FOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId") ) SELECT * FROM 'Invoice' LIMIT 3; InvoiceId CustomerId InvoiceDate BillingAddress BillingCity BillingState BillingCountry BillingPostalCode Total 1 2 2009-01-01 00:00:00 Theodor-Heuss-Straße 34 Stuttgart None Germany 70174 1.98 2 4 2009-01-02 00:00:00 Ullevålsveien 14 Oslo None Norway 0171 3.96 3 8 2009-01-03 00:00:00 Grétrystraat 63 Brussels None Belgium 1000 5.94 Thought: I should query the Invoice and Customer tables to get the total sales per country. Action: query_sql_db Action Input: SELECT c.Country, SUM(i.Total) AS TotalSales FROM Invoice i INNER JOIN Customer c ON i.CustomerId = c.CustomerId GROUP BY c.Country ORDER BY TotalSales DESC LIMIT 10
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-5
Observation: [('USA', 523.0600000000003), ('Canada', 303.9599999999999), ('France', 195.09999999999994), ('Brazil', 190.09999999999997), ('Germany', 156.48), ('United Kingdom', 112.85999999999999), ('Czech Republic', 90.24000000000001), ('Portugal', 77.23999999999998), ('India', 75.25999999999999), ('Chile', 46.62)] Thought: I now know the final answer Final Answer: The customers from the USA spent the most, with a total of $523.06. > Finished chain. 'The customers from the USA spent the most, with a total of $523.06.' agent_executor.run("Show the total number of tracks in each playlist. The Playlist name should be included in the result.") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the Playlist and PlaylistTrack tables to see what columns I can use. Action: schema_sql_db Action Input: "Playlist, PlaylistTrack" Observation: CREATE TABLE "Playlist" ( "PlaylistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("PlaylistId") ) SELECT * FROM 'Playlist' LIMIT 3; PlaylistId Name 1 Music 2 Movies 3 TV Shows CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL,
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-6
"TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I can use a SELECT statement to get the total number of tracks in each playlist. Action: query_checker_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Observation: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Thought: The query looks correct, I can now execute it. Action: query_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name LIMIT 10 Observation: [('90’s Music', 1477), ('Brazilian Music', 39), ('Classical', 75), ('Classical 101 - Deep Cuts', 25), ('Classical 101 - Next Steps', 25), ('Classical 101 - The Basics', 25), ('Grunge', 15), ('Heavy Metal Classic', 26), ('Music', 6580), ('Music Videos', 1)] Thought: I now know the final answer.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-7
Thought: I now know the final answer. Final Answer: The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1). > Finished chain. "The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1)." Recovering from an error# In this example, the agent is able to recover from an error after initially trying to access an attribute (Track.ArtistId) which doesn’t exist. agent_executor.run("Who are the top 3 best selling artists?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: MediaType, Track, Invoice, Album, Playlist, Customer, Employee, InvoiceLine, PlaylistTrack, Genre, Artist Thought: I should look at the schema of the Artist, InvoiceLine, and Track tables to see what columns I can use. Action: schema_sql_db Action Input: "Artist, InvoiceLine, Track" Observation: CREATE TABLE "Artist" ( "ArtistId" INTEGER NOT NULL,
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-8
CREATE TABLE "Artist" ( "ArtistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("ArtistId") ) SELECT * FROM 'Artist' LIMIT 3; ArtistId Name 1 AC/DC 2 Accept 3 Aerosmith CREATE TABLE "Track" ( "TrackId" INTEGER NOT NULL, "Name" NVARCHAR(200) NOT NULL, "AlbumId" INTEGER, "MediaTypeId" INTEGER NOT NULL, "GenreId" INTEGER, "Composer" NVARCHAR(220), "Milliseconds" INTEGER NOT NULL, "Bytes" INTEGER, "UnitPrice" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("TrackId"), FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"), FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"), FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId") ) SELECT * FROM 'Track' LIMIT 3; TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99 2 Balls to the Wall 2 2 1 None 342562 5510424 0.99 3 Fast As a Shark 3 2 1 F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman 230619 3990994 0.99 CREATE TABLE "InvoiceLine" ( "InvoiceLineId" INTEGER NOT NULL, "InvoiceId" INTEGER NOT NULL,
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-9
"InvoiceId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, "UnitPrice" NUMERIC(10, 2) NOT NULL, "Quantity" INTEGER NOT NULL, PRIMARY KEY ("InvoiceLineId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("InvoiceId") REFERENCES "Invoice" ("InvoiceId") ) SELECT * FROM 'InvoiceLine' LIMIT 3; InvoiceLineId InvoiceId TrackId UnitPrice Quantity 1 1 2 0.99 1 2 1 4 0.99 1 3 2 6 0.99 1 Thought: I should query the database to get the top 3 best selling artists. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: Error: (sqlite3.OperationalError) no such column: Track.ArtistId [SQL: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3] (Background on this error at: https://sqlalche.me/e/14/e3q8) Thought: I should double check my query before executing it. Action: query_checker_sql_db
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
fd79da127dea-10
Thought: I should double check my query before executing it. Action: query_checker_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3; Thought: I now know the final answer. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId INNER JOIN Track ON Album.AlbumId = Track.AlbumId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: [('Iron Maiden', 140), ('U2', 107), ('Metallica', 91)] Thought: I now know the final answer. Final Answer: The top 3 best selling artists are Iron Maiden, U2, and Metallica. > Finished chain. 'The top 3 best selling artists are Iron Maiden, U2, and Metallica.' previous Python Agent next Vectorstore Agent Contents Initialization Example: describing a table Example: describing a table, recovering from an error Example: running queries Recovering from an error By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\sql_database.html
960160dd0f12-0
.ipynb .pdf Vectorstore Agent Contents Create the Vectorstores Initialize Toolkit and Agent Examples Multiple Vectorstores Examples Vectorstore Agent# This notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources. Create the Vectorstores# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain import OpenAI, VectorDBQA llm = OpenAI(temperature=0) from langchain.document_loaders import TextLoader loader = TextLoader('../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() state_of_union_store = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. from langchain.document_loaders import WebBaseLoader loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/") docs = loader.load() ruff_texts = text_splitter.split_documents(docs) ruff_store = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Initialize Toolkit and Agent# First, we’ll create an agent with a single vectorstore. from langchain.agents.agent_toolkits import ( create_vectorstore_agent, VectorStoreToolkit, VectorStoreInfo, ) vectorstore_info = VectorStoreInfo( name="state_of_union_address",
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
960160dd0f12-1
) vectorstore_info = VectorStoreInfo( name="state_of_union_address", description="the most recent state of the Union adress", vectorstore=state_of_union_store ) toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info) agent_executor = create_vectorstore_agent( llm=llm, toolkit=toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to find the answer in the state of the union address Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address? List the source.") > Entering new AgentExecutor chain... I need to use the state_of_union_address_with_sources tool to answer this question. Action: state_of_union_address_with_sources Action Input: What did biden say about ketanji brown jackson
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
960160dd0f12-2
Action Input: What did biden say about ketanji brown jackson Observation: {"answer": " Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence.\n", "sources": "../../state_of_the_union.txt"} Thought: I now know the final answer Final Answer: Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt > Finished chain. "Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt" Multiple Vectorstores# We can also easily use this initialize an agent with multiple vectorstores and use the agent to route between them. To do this. This agent is optimized for routing, so it is a different toolkit and initializer. from langchain.agents.agent_toolkits import ( create_vectorstore_router_agent, VectorStoreRouterToolkit, VectorStoreInfo, ) ruff_vectorstore_info = VectorStoreInfo( name="ruff", description="Information about the Ruff python linting library", vectorstore=ruff_store ) router_toolkit = VectorStoreRouterToolkit( vectorstores=[vectorstore_info, ruff_vectorstore_info], llm=llm ) agent_executor = create_vectorstore_agent( llm=llm, toolkit=router_toolkit, verbose=True )
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
960160dd0f12-3
toolkit=router_toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to use the state_of_union_address tool to answer this question. Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent_executor.run("What tool does ruff use to run over Jupyter Notebooks?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses to run over Jupyter Notebooks Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
960160dd0f12-4
Thought: I now know the final answer Final Answer: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb > Finished chain. 'Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb' agent_executor.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses and if the president mentioned it in the state of the union. Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I need to find out if the president mentioned nbQA in the state of the union. Action: state_of_union_address Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.' previous SQL Database Agent next
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
960160dd0f12-5
previous SQL Database Agent next MRKL Contents Create the Vectorstores Initialize Toolkit and Agent Examples Multiple Vectorstores Examples By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\agent_toolkits\vectorstore.html
426efe43f175-0
.ipynb .pdf Agents and Vectorstores Contents Create the Vectorstore Create the Agent Use the Agent solely as a router Multi-Hop vectorstore reasoning Agents and Vectorstores# This notebook covers how to combine agents and vectorstores. The use case for this is that you’ve ingested your data into a vectorstore and want to interact with it in an agentic manner. The reccomended method for doing so is to create a VectorDBQAChain and then use that as a tool in the overall agent. Let’s take a look at doing this below. You can do this with multiple different vectordbs, and use the agent as a way to route between them. There are two different ways of doing this - you can either let the agent use the vectorstores as normal tools, or you can set return_direct=True to really just use the agent as a router. Create the Vectorstore# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import RetrievalQA llm = OpenAI(temperature=0) from langchain.document_loaders import TextLoader loader = TextLoader('../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-1
Using DuckDB in-memory for database. Data will be transient. state_of_union = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=docsearch.as_retriever()) from langchain.document_loaders import WebBaseLoader loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/") docs = loader.load() ruff_texts = text_splitter.split_documents(docs) ruff_db = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") ruff = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=ruff_db.as_retriever()) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Create the Agent# # Import things that are needed generically from langchain.agents import initialize_agent, Tool from langchain.tools import BaseTool from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question." ), Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question." ), ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-2
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address. Action: State of Union QA System Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address? Observation: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent.run("Why use ruff over flake8?") > Entering new AgentExecutor chain... I need to find out the advantages of using ruff over flake8 Action: Ruff QA System Action Input: What are the advantages of using ruff over flake8? Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-3
Thought: I now know the final answer Final Answer: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. > Finished chain. 'Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.' Use the Agent solely as a router# You can also set return_direct=True if you intend to use the agent as a router and just want to directly return the result of the RetrievalQAChain. Notice that in the above examples the agent did some extra work after querying the RetrievalQAChain. You can avoid that and just return the result directly. tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.", return_direct=True ), Tool( name = "Ruff QA System", func=ruff.run,
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-4
Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question.", return_direct=True ), ] agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("What did biden say about ketanji brown jackson in the state of the union address?") > Entering new AgentExecutor chain... I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address. Action: State of Union QA System Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address? Observation: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. " Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent.run("Why use ruff over flake8?") > Entering new AgentExecutor chain... I need to find out the advantages of using ruff over flake8 Action: Ruff QA System Action Input: What are the advantages of using ruff over flake8?
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-5
Action Input: What are the advantages of using ruff over flake8? Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. > Finished chain. ' Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.' Multi-Hop vectorstore reasoning# Because vectorstores are easily usable as tools in agents, it is easy to use answer multi-hop questions that depend on vectorstores using the existing agent framework tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question, not referencing any obscure pronouns from the conversation before." ), Tool( name = "Ruff QA System", func=ruff.run,
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-6
Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before." ), ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses to run over Jupyter Notebooks, and if the president mentioned it in the state of the union. Action: Ruff QA System Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I now need to find out if the president mentioned this tool in the state of the union. Action: State of Union QA System Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.' previous How-To Guides next
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
426efe43f175-7
previous How-To Guides next Async API for Agent Contents Create the Vectorstore Create the Agent Use the Agent solely as a router Multi-Hop vectorstore reasoning By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\agent_vectorstore.html
e74e99999b98-0
.ipynb .pdf Async API for Agent Contents Serial vs. Concurrent Execution Using Tracing with Asynchronous Agents Async API for Agent# LangChain provides async support for Agents by leveraging the asyncio library. Async methods are currently supported for the following Tools: SerpAPIWrapper and LLMMathChain. Async support for other agent tools are on the roadmap. For Tools that have a coroutine implemented (the two mentioned above), the AgentExecutor will await them directly. Otherwise, the AgentExecutor will call the Tool’s func via asyncio.get_event_loop().run_in_executor to avoid blocking the main runloop. You can use arun to call an AgentExecutor asynchronously. Serial vs. Concurrent Execution# In this example, we kick off agents to answer some questions serially vs. concurrently. You can see that concurrent execution significantly speeds this up. import asyncio import time from langchain.agents import initialize_agent, load_tools from langchain.llms import OpenAI from langchain.callbacks.stdout import StdOutCallbackHandler from langchain.callbacks.base import CallbackManager from langchain.callbacks.tracers import LangChainTracer from aiohttp import ClientSession questions = [ "Who won the US Open men's final in 2019? What is his age raised to the 0.334 power?", "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?", "Who won the most recent formula 1 grand prix? What is their age raised to the 0.23 power?", "Who won the US Open women's final in 2019? What is her age raised to the 0.34 power?", "Who is Beyonce's husband? What is his age raised to the 0.19 power?" ] def generate_serially(): for q in questions:
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-1
] def generate_serially(): for q in questions: llm = OpenAI(temperature=0) tools = load_tools(["llm-math", "serpapi"], llm=llm) agent = initialize_agent( tools, llm, agent="zero-shot-react-description", verbose=True ) agent.run(q) s = time.perf_counter() generate_serially() elapsed = time.perf_counter() - s print(f"Serial executed in {elapsed:0.2f} seconds.") > Entering new AgentExecutor chain... I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power. Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal Thought: I need to find out Rafael Nadal's age Action: Search Action Input: "Rafael Nadal age" Observation: 36 years Thought: I need to calculate 36 raised to the 0.334 power Action: Calculator Action Input: 36^0.334 Observation: Answer: 3.3098250249682484 Thought: I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. > Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power. Action: Search Action Input: "Olivia Wilde boyfriend" Observation: Jason Sudeikis
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-2
Action Input: "Olivia Wilde boyfriend" Observation: Jason Sudeikis Thought: I need to find out Jason Sudeikis' age Action: Search Action Input: "Jason Sudeikis age" Observation: 47 years Thought: I need to calculate 47 raised to the 0.23 power Action: Calculator Action Input: 47^0.23 Observation: Answer: 2.4242784855673896 Thought: I now know the final answer Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896. > Finished chain. > Entering new AgentExecutor chain... I need to find out who won the grand prix and then calculate their age raised to the 0.23 power. Action: Search Action Input: "Formula 1 Grand Prix Winner" Observation: Max Verstappen Thought: I need to find out Max Verstappen's age Action: Search Action Input: "Max Verstappen Age" Observation: 25 years Thought: I need to calculate 25 raised to the 0.23 power Action: Calculator Action Input: 25^0.23 Observation: Answer: 1.84599359907945 Thought: I now know the final answer Final Answer: Max Verstappen, 25 years old, raised to the 0.23 power is 1.84599359907945. > Finished chain. > Entering new AgentExecutor chain... I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power. Action: Search
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-3
Action: Search Action Input: "US Open women's final 2019 winner" Observation: Bianca Andreescu defeated Serena Williams in the final, 6–3, 7–5 to win the women's singles tennis title at the 2019 US Open. It was her first major title, and she became the first Canadian, as well as the first player born in the 2000s, to win a major singles title. Thought: I need to find out Bianca Andreescu's age. Action: Search Action Input: "Bianca Andreescu age" Observation: 22 years Thought: I now know the age of Bianca Andreescu and can calculate her age raised to the 0.34 power. Action: Calculator Action Input: 22^0.34 Observation: Answer: 2.8603798598506933 Thought: I now know the final answer. Final Answer: Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.8603798598506933. > Finished chain. > Entering new AgentExecutor chain... I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power. Action: Search Action Input: "Who is Beyonce's husband?" Observation: Jay-Z Thought: I need to find out Jay-Z's age Action: Search Action Input: "How old is Jay-Z?" Observation: 53 years Thought: I need to calculate 53 raised to the 0.19 power Action: Calculator Action Input: 53^0.19 Observation: Answer: 2.12624064206896 Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-4
Thought: I now know the final answer Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896. > Finished chain. Serial executed in 65.11 seconds. async def generate_concurrently(): agents = [] # To make async requests in Tools more efficient, you can pass in your own aiohttp.ClientSession, # but you must manually close the client session at the end of your program/event loop aiosession = ClientSession() for _ in questions: manager = CallbackManager([StdOutCallbackHandler()]) llm = OpenAI(temperature=0, callback_manager=manager) async_tools = load_tools(["llm-math", "serpapi"], llm=llm, aiosession=aiosession, callback_manager=manager) agents.append( initialize_agent(async_tools, llm, agent="zero-shot-react-description", verbose=True, callback_manager=manager) ) tasks = [async_agent.arun(q) for async_agent, q in zip(agents, questions)] await asyncio.gather(*tasks) await aiosession.close() s = time.perf_counter() # If running this outside of Jupyter, use asyncio.run(generate_concurrently()) await generate_concurrently() elapsed = time.perf_counter() - s print(f"Concurrent executed in {elapsed:0.2f} seconds.") > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-5
Action: Search Action Input: "Olivia Wilde boyfriend" I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power. Action: Search Action Input: "Who is Beyonce's husband?" Observation: Jay-Z Thought: I need to find out who won the grand prix and then calculate their age raised to the 0.23 power. Action: Search Action Input: "Formula 1 Grand Prix Winner" I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power. Action: Search Action Input: "US Open women's final 2019 winner" Observation: Jason Sudeikis Thought: Observation: Max Verstappen Thought: Observation: Bianca Andreescu defeated Serena Williams in the final, 6–3, 7–5 to win the women's singles tennis title at the 2019 US Open. It was her first major title, and she became the first Canadian, as well as the first player born in the 2000s, to win a major singles title. Thought: I need to find out Jason Sudeikis' age Action: Search Action Input: "Jason Sudeikis age" I need to find out Jay-Z's age Action: Search Action Input: "How old is Jay-Z?" Observation: 53 years Thought: I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power. Action: Search Action Input: "US Open men's final 2019 winner"
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-6
Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Thought: Observation: 47 years Thought: I need to find out Max Verstappen's age Action: Search Action Input: "Max Verstappen Age" Observation: 25 years Thought: I need to find out Bianca Andreescu's age. Action: Search Action Input: "Bianca Andreescu age" Observation: 22 years Thought: I need to calculate 53 raised to the 0.19 power Action: Calculator Action Input: 53^0.19 I need to find out the age of the winner Action: Search Action Input: "Rafael Nadal age" I need to calculate 47 raised to the 0.23 power Action: Calculator Action Input: 47^0.23 Observation: 36 years Thought: I need to calculate 25 raised to the 0.23 power Action: Calculator Action Input: 25^0.23 Observation: Answer: 2.12624064206896 Thought: I now know the age of Bianca Andreescu and can calculate her age raised to the 0.34 power. Action: Calculator Action Input: 22^0.34 Observation: Answer: 1.84599359907945 Thought: Observation: Answer: 2.4242784855673896 Thought: I now need to calculate his age raised to the 0.334 power Action: Calculator
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-7
Action: Calculator Action Input: 36^0.334 Observation: Answer: 2.8603798598506933 Thought: I now know the final answer Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896. > Finished chain. I now know the final answer Final Answer: Max Verstappen, 25 years old, raised to the 0.23 power is 1.84599359907945. > Finished chain. Observation: Answer: 3.3098250249682484 Thought: I now know the final answer Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896. > Finished chain. I now know the final answer. Final Answer: Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.8603798598506933. > Finished chain. I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. Concurrent executed in 12.38 seconds. Using Tracing with Asynchronous Agents# To use tracing with async agents, you must pass in a custom CallbackManager with LangChainTracer to each agent running asynchronously. This way, you avoid collisions while the trace is being collected. # To make async requests in Tools more efficient, you can pass in your own aiohttp.ClientSession,
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-8
# but you must manually close the client session at the end of your program/event loop aiosession = ClientSession() tracer = LangChainTracer() tracer.load_default_session() manager = CallbackManager([StdOutCallbackHandler(), tracer]) # Pass the manager into the llm if you want llm calls traced. llm = OpenAI(temperature=0, callback_manager=manager) async_tools = load_tools(["llm-math", "serpapi"], llm=llm, aiosession=aiosession) async_agent = initialize_agent(async_tools, llm, agent="zero-shot-react-description", verbose=True, callback_manager=manager) await async_agent.arun(questions[0]) await aiosession.close() > Entering new AgentExecutor chain... I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power. Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal Thought: I need to find out Rafael Nadal's age Action: Search Action Input: "Rafael Nadal age" Observation: 36 years Thought: I need to calculate 36 raised to the 0.334 power Action: Calculator Action Input: 36^0.334 Observation: Answer: 3.3098250249682484 Thought: I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. previous Agents and Vectorstores next Conversation Agent (for Chat Models) Contents Serial vs. Concurrent Execution
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
e74e99999b98-9
next Conversation Agent (for Chat Models) Contents Serial vs. Concurrent Execution Using Tracing with Asynchronous Agents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\async_agent.html
825e14613746-0
.ipynb .pdf ChatGPT Plugins ChatGPT Plugins# This example shows how to use ChatGPT Plugins within LangChain abstractions. Note 1: This currently only works for plugins with no auth. Note 2: There are almost certainly other ways to do this, this is just a first pass. If you have better ideas, please open a PR! from langchain.chat_models import ChatOpenAI from langchain.agents import load_tools, initialize_agent from langchain.tools import AIPluginTool tool = AIPluginTool.from_plugin_url("https://www.klarna.com/.well-known/ai-plugin.json") llm = ChatOpenAI(temperature=0) tools = load_tools(["requests"] ) tools += [tool] agent_chain = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent_chain.run("what t shirts are available in klarna?") > Entering new AgentExecutor chain... I need to check the Klarna Shopping API to see if it has information on available t shirts. Action: KlarnaProducts Action Input: None Observation: Usage Guide: Use the Klarna plugin to get relevant product suggestions for any shopping or researching purpose. The query to be sent should not include stopwords like articles, prepositions and determinants. The api works best when searching for words that are related to products, like their name, brand, model or category. Links will always be returned and should be shown to the user.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-1
OpenAPI Spec: {'openapi': '3.0.1', 'info': {'version': 'v0', 'title': 'Open AI Klarna product Api'}, 'servers': [{'url': 'https://www.klarna.com/us/shopping'}], 'tags': [{'name': 'open-ai-product-endpoint', 'description': 'Open AI Product Endpoint. Query for products.'}], 'paths': {'/public/openai/v0/products': {'get': {'tags': ['open-ai-product-endpoint'], 'summary': 'API for fetching Klarna product information', 'operationId': 'productsUsingGET', 'parameters': [{'name': 'q', 'in': 'query', 'description': 'query, must be between 2 and 100 characters', 'required': True, 'schema': {'type': 'string'}}, {'name': 'size', 'in': 'query', 'description': 'number of products returned', 'required': False, 'schema': {'type': 'integer'}}, {'name': 'budget', 'in': 'query', 'description': 'maximum price of the matching product in local currency, filters results', 'required': False, 'schema': {'type': 'integer'}}], 'responses': {'200': {'description': 'Products found', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/ProductResponse'}}}},
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-2
{'schema': {'$ref': '#/components/schemas/ProductResponse'}}}}, '503': {'description': 'one or more services are unavailable'}}, 'deprecated': False}}}, 'components': {'schemas': {'Product': {'type': 'object', 'properties': {'attributes': {'type': 'array', 'items': {'type': 'string'}}, 'name': {'type': 'string'}, 'price': {'type': 'string'}, 'url': {'type': 'string'}}, 'title': 'Product'}, 'ProductResponse': {'type': 'object', 'properties': {'products': {'type': 'array', 'items': {'$ref': '#/components/schemas/Product'}}}, 'title': 'ProductResponse'}}}}
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-3
Thought:I need to use the Klarna Shopping API to search for t shirts. Action: requests_get Action Input: https://www.klarna.com/us/shopping/public/openai/v0/products?q=t%20shirts
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-4
Observation: {"products":[{"name":"Lacoste Men's Pack of Plain T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202043025/Clothing/Lacoste-Men-s-Pack-of-Plain-T-Shirts/?source=openai","price":"$28.99","attributes":["Material:Cotton","Target Group:Man","Color:White,Black"]},{"name":"Hanes Men's Ultimate 6pk. Crewneck T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201808270/Clothing/Hanes-Men-s-Ultimate-6pk.-Crewneck-T-Shirts/?source=openai","price":"$13.40","attributes":["Material:Cotton","Target Group:Man","Color:White"]},{"name":"Nike Boy's Jordan Stretch T-shirts","url":"https://www.klarna.com/us/shopping/pl/cl359/3201863202/Children-s-Clothing/Nike-Boy-s-Jordan-Stretch-T-shirts/?source=openai","price":"$14.99","attributes":["Color:White,Green","Model:Boy","Pattern:Solid Color","Size (Small-Large):S,XL,L,M"]},{"name":"Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203028500/Clothing/Polo-Classic-Fit-Cotton-V-Neck-T-Shirts-3-Pack/?source=openai","price":"$29.95","attributes":["Material:Cotton","Target Group:Man","Color:White,Blue,Black"]},{"name":"adidas Comfort T-shirts Men's
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-5
Comfort T-shirts Men's 3-pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202640533/Clothing/adidas-Comfort-T-shirts-Men-s-3-pack/?source=openai","price":"$14.99","attributes":["Material:Cotton","Target Group:Man","Color:White,Black","Pattern:Solid Color"]}]}
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
825e14613746-6
Thought:The available t shirts on Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack. Final Answer: The available t shirts on Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack. > Finished chain. "The available t shirts on Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack." previous Conversation Agent (for Chat Models) next Custom Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chatgpt_plugins.html
40c26fa8800e-0
.ipynb .pdf Conversation Agent (for Chat Models) Conversation Agent (for Chat Models)# This notebook walks through using an agent optimized for conversation, using ChatModels. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well. This is accomplished with a specific type of agent (chat-conversational-react-description) which expects to be used with a memory component. import os os.environ["LANGCHAIN_HANDLER"] = "langchain" from langchain.agents import Tool from langchain.memory import ConversationBufferMemory from langchain.chat_models import ChatOpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent search = SerpAPIWrapper() tools = [ Tool( name = "Current Search", func=search.run, description="useful for when you need to answer questions about current events or the current state of the world. the input to this should be a single search term." ), ] memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) llm=ChatOpenAI(temperature=0) agent_chain = initialize_agent(tools, llm, agent="chat-conversational-react-description", verbose=True, memory=memory) agent_chain.run(input="hi, i am bob") > Entering new AgentExecutor chain... { "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today?" } > Finished chain. 'Hello Bob! How can I assist you today?' agent_chain.run(input="what's my name?") > Entering new AgentExecutor chain... { "action": "Final Answer",
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chat_conversation_agent.html
40c26fa8800e-1
> Entering new AgentExecutor chain... { "action": "Final Answer", "action_input": "Your name is Bob." } > Finished chain. 'Your name is Bob.' agent_chain.run("what are some good dinners to make this week, if i like thai food?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "Thai food dinner recipes" } Observation: 59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's ... Thought:{ "action": "Final Answer", "action_input": "Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and many more. You can find 59 easy Thai recipes for any night of the week on Marion Grasby's website." } > Finished chain. "Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and many more. You can find 59 easy Thai recipes for any night of the week on Marion Grasby's website." agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?") > Entering new AgentExecutor chain... ```json { "action": "Current Search", "action_input": "who won the world cup in 1978" } ```
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chat_conversation_agent.html
40c26fa8800e-2
"action_input": "who won the world cup in 1978" } ``` Observation: The Argentina national football team represents Argentina in men's international football and is administered by the Argentine Football Association, the governing body for football in Argentina. Nicknamed La Albiceleste, they are the reigning world champions, having won the most recent World Cup in 2022. Thought:```json { "action": "Final Answer", "action_input": "The last letter in your name is 'b'. The Argentina national football team won the World Cup in 1978." } ``` > Finished chain. "The last letter in your name is 'b'. The Argentina national football team won the World Cup in 1978." agent_chain.run(input="whats the weather like in pomfret?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "weather in pomfret" } Observation: Mostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers possible. High near 40F. Winds NNW at 20 to 30 mph. Thought:{ "action": "Final Answer", "action_input": "The weather in Pomfret is mostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers are possible. High near 40F. Winds NNW at 20 to 30 mph." } > Finished chain. 'The weather in Pomfret is mostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers are possible. High near 40F. Winds NNW at 20 to 30 mph.' previous Async API for Agent next ChatGPT Plugins By Harrison Chase
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chat_conversation_agent.html
40c26fa8800e-3
previous Async API for Agent next ChatGPT Plugins By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\chat_conversation_agent.html
2212b8662baa-0
.ipynb .pdf Custom Agent Contents Custom LLMChain Multiple inputs Custom Agent Class Custom Agent# This notebook goes through how to create your own custom agent. An agent consists of three parts: - Tools: The tools the agent has available to use. - LLMChain: The LLMChain that produces the text that is parsed in a certain way to determine which action to take. - The agent class itself: this parses the output of the LLMChain to determin which action to take. In this notebook we walk through two types of custom agents. The first type shows how to create a custom LLMChain, but still use an existing agent class to parse the output. The second shows how to create a custom agent class. Custom LLMChain# The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly reccomended that you work with the ZeroShotAgent, as at the moment that is by far the most generalizable one. Most of the work in creating the custom LLMChain comes down to the prompt. Because we are using an existing agent class to parse the output, it is very important that the prompt say to produce text in that format. Additionally, we currently require an agent_scratchpad input variable to put notes on previous actions and observations. This should almost always be the final part of the prompt. However, besides those instructions, you can customize the prompt as you wish. To ensure that the prompt contains the appropriate instructions, we will utilize a helper method on that class. The helper method for the ZeroShotAgent takes the following arguments: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_agent.html
2212b8662baa-1
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. For this exercise, we will give our agent access to Google Search, and we will customize it in that we will have it answer as a pirate. from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain import OpenAI, SerpAPIWrapper, LLMChain search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] prefix = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:""" suffix = """Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"] ) In case we are curious, we can now take a look at the final prompt template to see what it looks like when its all put together. print(prompt.template) Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: Search: useful for when you need to answer questions about current events Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [Search] Action Input: the input to the action Observation: the result of the action
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_agent.html
2212b8662baa-2
Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad} Note that we are able to feed agents a self-defined prompt template, i.e. not restricted to the prompt generated by the create_prompt function, assuming it meets the agent’s requirements. For example, for ZeroShotAgent, we will need to ensure that it meets the following requirements. There should a string starting with “Action:” and a following string starting with “Action Input:”, and both should be separated by a newline. llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada Action: Search Action Input: Population of Canada 2023 Observation: The current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data. Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_agent.html
2212b8662baa-3
Thought: I now know the final answer Final Answer: Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023! > Finished chain. "Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023!" Multiple inputs# Agents can also work with prompts that require multiple inputs. prefix = """Answer the following questions as best you can. You have access to the following tools:""" suffix = """When answering, you MUST speak in the following language: {language}. Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "language", "agent_scratchpad"] ) llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run(input="How many people live in canada as of 2023?", language="italian") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada in 2023. Action: Search Action Input: Population of Canada in 2023 Observation: The current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data. Thought: I now know the final answer.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_agent.html
2212b8662baa-4
Thought: I now know the final answer. Final Answer: La popolazione del Canada nel 2023 è stimata in 38.610.447 persone. > Finished chain. 'La popolazione del Canada nel 2023 è stimata in 38.610.447 persone.' Custom Agent Class# Coming soon. previous ChatGPT Plugins next Defining Custom Tools Contents Custom LLMChain Multiple inputs Custom Agent Class By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Mar 24, 2023.
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_agent.html
2258cb61a5a5-0
.ipynb .pdf Defining Custom Tools Contents Completely New Tools Tool dataclass Subclassing the BaseTool class Using the tool decorator Modify existing tools Defining the priorities among Tools Using tools to return directly Defining Custom Tools# When constructing your own agent, you will need to provide it with a list of Tools that it can use. Besides the actual function that is called, the Tool consists of several components: name (str), is required description (str), is optional return_direct (bool), defaults to False The function that should be called when the tool is selected should take as input a single string and return a single string. There are two ways to define a tool, we will cover both in the example below. # Import things that are needed generically from langchain.agents import initialize_agent, Tool from langchain.tools import BaseTool from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper Initialize the LLM to use for the agent. llm = OpenAI(temperature=0) Completely New Tools# First, we show how to create completely new tools from scratch. There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class. Tool dataclass# # Load the tool configs that are needed. search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name="Calculator", func=llm_math_chain.run,
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-1
Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ) ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I now need to calculate her age raised to the 0.43 power Action: Calculator Action Input: 22^0.43 > Entering new LLMMathChain chain... 22^0.43 ```python import math print(math.pow(22, 0.43)) ``` Answer: 3.777824273683966 > Finished chain. Observation: Answer: 3.777824273683966 Thought: I now know the final answer Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966. > Finished chain. "Camila Morrone's age raised to the 0.43 power is 3.777824273683966." Subclassing the BaseTool class# class CustomSearchTool(BaseTool): name = "Search" description = "useful for when you need to answer questions about current events" def _run(self, query: str) -> str:
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-2
def _run(self, query: str) -> str: """Use the tool.""" return search.run(query) async def _arun(self, query: str) -> str: """Use the tool asynchronously.""" raise NotImplementedError("BingSearchRun does not support async") class CustomCalculatorTool(BaseTool): name = "Calculator" description = "useful for when you need to answer questions about math" def _run(self, query: str) -> str: """Use the tool.""" return llm_math_chain.run(query) async def _arun(self, query: str) -> str: """Use the tool asynchronously.""" raise NotImplementedError("BingSearchRun does not support async") tools = [CustomSearchTool(), CustomCalculatorTool()] agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I now need to calculate her age raised to the 0.43 power Action: Calculator Action Input: 22^0.43 > Entering new LLMMathChain chain... 22^0.43 ```python import math print(math.pow(22, 0.43)) ``` Answer: 3.777824273683966 > Finished chain. Observation: Answer: 3.777824273683966
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-3
> Finished chain. Observation: Answer: 3.777824273683966 Thought: I now know the final answer Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966. > Finished chain. "Camila Morrone's age raised to the 0.43 power is 3.777824273683966." Using the tool decorator# To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a string as the first argument. Additionally, the decorator will use the function’s docstring as the tool’s description. from langchain.agents import tool @tool def search_api(query: str) -> str: """Searches the API for the query.""" return "Results" search_api Tool(name='search_api', description='search_api(query: str) -> str - Searches the API for the query.', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8700>, coroutine=None) You can also provide arguments like the tool name and whether to return directly. @tool("search", return_direct=True) def search_api(query: str) -> str: """Searches the API for the query.""" return "Results" search_api
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-4
"""Searches the API for the query.""" return "Results" search_api Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8670>, coroutine=None) Modify existing tools# Now, we show how to load existing tools and just modify them. In the example below, we do something really simple and change the Search tool to have the name Google Search. from langchain.agents import load_tools tools = load_tools(["serpapi", "llm-math"], llm=llm) tools[0].name = "Google Search" agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Google Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I need to find out Camila Morrone's age Action: Google Search Action Input: "Camila Morrone age" Observation: 25 years Thought: I need to calculate 25 raised to the 0.43 power Action: Calculator Action Input: 25^0.43 Observation: Answer: 3.991298452658078 Thought: I now know the final answer
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-5
Thought: I now know the final answer Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078." Defining the priorities among Tools# When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools. For example, you made a custom tool, which gets information on music from your database. When a user wants information on songs, You want the Agent to use the custom tool more than the normal Search tool. But the Agent might prioritize a normal Search tool. This can be accomplished by adding a statement such as Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?' to the description. An example is below. # Import things that are needed generically from langchain.agents import initialize_agent, Tool from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name="Music Search", func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function description="A Music search engine. Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'",
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html
2258cb61a5a5-6
) ] agent = initialize_agent(tools, OpenAI(temperature=0), agent="zero-shot-react-description", verbose=True) agent.run("what is the most famous song of christmas") > Entering new AgentExecutor chain... I should use a music search engine to find the answer Action: Music Search Action Input: most famous song of christmas Observation: 'All I Want For Christmas Is You' by Mariah Carey. Thought: I now know the final answer Final Answer: 'All I Want For Christmas Is You' by Mariah Carey. > Finished chain. "'All I Want For Christmas Is You' by Mariah Carey." Using tools to return directly# Often, it can be desirable to have a tool output returned directly to the user, if it’s called. You can do this easily with LangChain by setting the return_direct flag for a tool to be True. llm_math_chain = LLMMathChain(llm=llm) tools = [ Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math", return_direct=True ) ] llm = OpenAI(temperature=0) agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) agent.run("whats 2**.12") > Entering new AgentExecutor chain... I need to calculate this Action: Calculator Action Input: 2**.12 Observation: Answer: 1.2599210498948732 > Finished chain. 'Answer: 1.2599210498948732' previous Custom Agent next Human as a tool Contents Completely New Tools Tool dataclass Subclassing the BaseTool class
https://langchain.readthedocs.io\en\latest\modules\agents\examples\custom_tools.html