id
stringlengths
14
17
text
stringlengths
42
2.11k
4e9727215e95-3000
}}[agent/action] [1:chain:AgentExecutor] Agent selected action: { "tool": "search", "toolInput": { "input": "current weather in New York" }, "log": ""}[tool/start] [1:chain:AgentExecutor > 3:tool:SerpAPI] Entering Tool run with input: "current weather in New York"[tool/end] [1:chain:AgentExecutor > 3:tool:SerpAPI] [1.90s] Exiting Tool run with output: "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ..."[llm/start] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3001
", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\"input\":\"current weather in New York\"}" } } } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "FunctionMessage" ], "kwargs": { "content": "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ...", "name": "search", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] [3.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW.
4e9727215e95-3002
The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "additional_kwargs": {} } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 58, "promptTokens": 180, "totalTokens": 238 } }}[chain/end] [1:chain:AgentExecutor] [7.73s] Exiting Chain run with output: { "output": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. "}PreviousZep MemoryNextAgent typesAction agentsPlan-and-execute agentsGet started Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI reference Agent types Tools Toolkits
4e9727215e95-3003
Agent types Tools Toolkits ModulesAgentsOn this pageAgentsSome applications require a flexible chain of calls to LLMs and other tools based on user input. The Agent interface provides the flexibility for such applications. An agent has access to a suite of tools, and determines which ones to use depending on the user input. Agents can use multiple tools, and use the output of one tool as the input to the next.There are two main types of agents:Action agents: at each timestep, decide on the next action using the outputs of all previous actionsPlan-and-execute agents: decide on the full sequence of actions up front, then execute them all without updating the planAction agents are suitable for small tasks, while plan-and-execute agents are better for complex or long-running tasks that require maintaining long-term objectives and focus. Often the best approach is to combine the dynamism of an action agent with the planning abilities of a plan-and-execute agent by letting the plan-and-execute agent use action agents to execute plans.For a full list of agent types see agent types. Additional abstractions involved in agents are:Tools: the actions an agent can take. What tools you give an agent highly depend on what you want the agent to doToolkits: wrappers around collections of tools that can be used together a specific use case. For example, in order for an agent to
4e9727215e95-3004
interact with a SQL database it will likely need one tool to execute queries and another to inspect tablesAction agents​At a high-level an action agent:Receives user inputDecides which tool, if any, to use and the tool inputCalls the tool and records the output (also known as an "observation")Decides the next step using the history of tools, tool inputs, and observationsRepeats 3-4 until it determines it can respond directly to the userAction agents are wrapped in agent executors, chains which are responsible for calling the agent, getting back an action and action input, calling the tool that the action references with the generated input, getting the output of the tool, and then passing all that information back into the agent to get the next action it should take.Although an agent can be constructed in many ways, it typically involves these components:Prompt template: Responsible for taking the user input and previous steps and constructing a prompt
4e9727215e95-3005
to send to the language modelLanguage model: Takes the prompt with use input and action history and decides what to do nextOutput parser: Takes the output of the language model and parses it into the next action or a final answerPlan-and-execute agents​At a high-level a plan-and-execute agent:Receives user inputPlans the full sequence of steps to takeExecutes the steps in order, passing the outputs of past steps as inputs to future stepsThe most typical implementation is to have the planner be a language model, and the executor be an action agent. Read more here.Get started​LangChain offers several types of agents. Here's an example using one powered by OpenAI functions:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3006
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorAnd here is the logged verbose output:[chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "What is the weather in New York? ", "chat_history": []}[llm/start] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3007
", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] [1.97s] Exiting LLM run with output: { "generations": [ [ { "text": "", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\n \"input\": \"current weather in New York\"\n}" } } } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 18, "promptTokens": 121, "totalTokens": 139 }
4e9727215e95-3008
}}[agent/action] [1:chain:AgentExecutor] Agent selected action: { "tool": "search", "toolInput": { "input": "current weather in New York" }, "log": ""}[tool/start] [1:chain:AgentExecutor > 3:tool:SerpAPI] Entering Tool run with input: "current weather in New York"[tool/end] [1:chain:AgentExecutor > 3:tool:SerpAPI] [1.90s] Exiting Tool run with output: "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ..."[llm/start] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3009
", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\"input\":\"current weather in New York\"}" } } } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "FunctionMessage" ], "kwargs": { "content": "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ...", "name": "search", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] [3.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW.
4e9727215e95-3010
The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "additional_kwargs": {} } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 58, "promptTokens": 180, "totalTokens": 238 } }}[chain/end] [1:chain:AgentExecutor] [7.73s] Exiting Chain run with output: { "output": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. "}PreviousZep MemoryNextAgent typesAction agentsPlan-and-execute agentsGet started
4e9727215e95-3011
ModulesAgentsOn this pageAgentsSome applications require a flexible chain of calls to LLMs and other tools based on user input. The Agent interface provides the flexibility for such applications. An agent has access to a suite of tools, and determines which ones to use depending on the user input. Agents can use multiple tools, and use the output of one tool as the input to the next.There are two main types of agents:Action agents: at each timestep, decide on the next action using the outputs of all previous actionsPlan-and-execute agents: decide on the full sequence of actions up front, then execute them all without updating the planAction agents are suitable for small tasks, while plan-and-execute agents are better for complex or long-running tasks that require maintaining long-term objectives and focus. Often the best approach is to combine the dynamism of an action agent with the planning abilities of a plan-and-execute agent by letting the plan-and-execute agent use action agents to execute plans.For a full list of agent types see agent types. Additional abstractions involved in agents are:Tools: the actions an agent can take. What tools you give an agent highly depend on what you want the agent to doToolkits: wrappers around collections of tools that can be used together a specific use case. For example, in order for an agent to
4e9727215e95-3012
interact with a SQL database it will likely need one tool to execute queries and another to inspect tablesAction agents​At a high-level an action agent:Receives user inputDecides which tool, if any, to use and the tool inputCalls the tool and records the output (also known as an "observation")Decides the next step using the history of tools, tool inputs, and observationsRepeats 3-4 until it determines it can respond directly to the userAction agents are wrapped in agent executors, chains which are responsible for calling the agent, getting back an action and action input, calling the tool that the action references with the generated input, getting the output of the tool, and then passing all that information back into the agent to get the next action it should take.Although an agent can be constructed in many ways, it typically involves these components:Prompt template: Responsible for taking the user input and previous steps and constructing a prompt
4e9727215e95-3013
to send to the language modelLanguage model: Takes the prompt with use input and action history and decides what to do nextOutput parser: Takes the output of the language model and parses it into the next action or a final answerPlan-and-execute agents​At a high-level a plan-and-execute agent:Receives user inputPlans the full sequence of steps to takeExecutes the steps in order, passing the outputs of past steps as inputs to future stepsThe most typical implementation is to have the planner be a language model, and the executor be an action agent. Read more here.Get started​LangChain offers several types of agents. Here's an example using one powered by OpenAI functions:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3014
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorAnd here is the logged verbose output:[chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "What is the weather in New York? ", "chat_history": []}[llm/start] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3015
", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] [1.97s] Exiting LLM run with output: { "generations": [ [ { "text": "", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\n \"input\": \"current weather in New York\"\n}" } } } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 18, "promptTokens": 121, "totalTokens": 139 }
4e9727215e95-3016
}}[agent/action] [1:chain:AgentExecutor] Agent selected action: { "tool": "search", "toolInput": { "input": "current weather in New York" }, "log": ""}[tool/start] [1:chain:AgentExecutor > 3:tool:SerpAPI] Entering Tool run with input: "current weather in New York"[tool/end] [1:chain:AgentExecutor > 3:tool:SerpAPI] [1.90s] Exiting Tool run with output: "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ..."[llm/start] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3017
", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\"input\":\"current weather in New York\"}" } } } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "FunctionMessage" ], "kwargs": { "content": "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ...", "name": "search", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] [3.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW.
4e9727215e95-3018
The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "additional_kwargs": {} } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 58, "promptTokens": 180, "totalTokens": 238 } }}[chain/end] [1:chain:AgentExecutor] [7.73s] Exiting Chain run with output: { "output": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. "}PreviousZep MemoryNextAgent types
4e9727215e95-3019
AgentsSome applications require a flexible chain of calls to LLMs and other tools based on user input. The Agent interface provides the flexibility for such applications. An agent has access to a suite of tools, and determines which ones to use depending on the user input. Agents can use multiple tools, and use the output of one tool as the input to the next.There are two main types of agents:Action agents: at each timestep, decide on the next action using the outputs of all previous actionsPlan-and-execute agents: decide on the full sequence of actions up front, then execute them all without updating the planAction agents are suitable for small tasks, while plan-and-execute agents are better for complex or long-running tasks that require maintaining long-term objectives and focus. Often the best approach is to combine the dynamism of an action agent with the planning abilities of a plan-and-execute agent by letting the plan-and-execute agent use action agents to execute plans.For a full list of agent types see agent types. Additional abstractions involved in agents are:Tools: the actions an agent can take. What tools you give an agent highly depend on what you want the agent to doToolkits: wrappers around collections of tools that can be used together a specific use case. For example, in order for an agent to
4e9727215e95-3020
interact with a SQL database it will likely need one tool to execute queries and another to inspect tablesAction agents​At a high-level an action agent:Receives user inputDecides which tool, if any, to use and the tool inputCalls the tool and records the output (also known as an "observation")Decides the next step using the history of tools, tool inputs, and observationsRepeats 3-4 until it determines it can respond directly to the userAction agents are wrapped in agent executors, chains which are responsible for calling the agent, getting back an action and action input, calling the tool that the action references with the generated input, getting the output of the tool, and then passing all that information back into the agent to get the next action it should take.Although an agent can be constructed in many ways, it typically involves these components:Prompt template: Responsible for taking the user input and previous steps and constructing a prompt
4e9727215e95-3021
to send to the language modelLanguage model: Takes the prompt with use input and action history and decides what to do nextOutput parser: Takes the output of the language model and parses it into the next action or a final answerPlan-and-execute agents​At a high-level a plan-and-execute agent:Receives user inputPlans the full sequence of steps to takeExecutes the steps in order, passing the outputs of past steps as inputs to future stepsThe most typical implementation is to have the planner be a language model, and the executor be an action agent. Read more here.Get started​LangChain offers several types of agents. Here's an example using one powered by OpenAI functions:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3022
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorAnd here is the logged verbose output:[chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "What is the weather in New York? ", "chat_history": []}[llm/start] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3023
", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] [1.97s] Exiting LLM run with output: { "generations": [ [ { "text": "", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\n \"input\": \"current weather in New York\"\n}" } } } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 18, "promptTokens": 121, "totalTokens": 139 }
4e9727215e95-3024
}}[agent/action] [1:chain:AgentExecutor] Agent selected action: { "tool": "search", "toolInput": { "input": "current weather in New York" }, "log": ""}[tool/start] [1:chain:AgentExecutor > 3:tool:SerpAPI] Entering Tool run with input: "current weather in New York"[tool/end] [1:chain:AgentExecutor > 3:tool:SerpAPI] [1.90s] Exiting Tool run with output: "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ..."[llm/start] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3025
", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\"input\":\"current weather in New York\"}" } } } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "FunctionMessage" ], "kwargs": { "content": "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ...", "name": "search", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] [3.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW.
4e9727215e95-3026
The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "additional_kwargs": {} } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 58, "promptTokens": 180, "totalTokens": 238 } }}[chain/end] [1:chain:AgentExecutor] [7.73s] Exiting Chain run with output: { "output": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain."} Some applications require a flexible chain of calls to LLMs and other tools based on user input. The Agent interface provides the flexibility for such applications. An agent has access to a suite of tools, and determines which ones to use depending on the user input. Agents can use multiple tools, and use the output of one tool as the input to the next. There are two main types of agents: Action agents are suitable for small tasks, while plan-and-execute agents are better for complex or long-running tasks that require maintaining long-term objectives and focus. Often the best approach is to combine the dynamism of an action agent with the planning abilities of a plan-and-execute agent by letting the plan-and-execute agent use action agents to execute plans. For a full list of agent types see agent types. Additional abstractions involved in agents are: At a high-level an action agent:
4e9727215e95-3027
At a high-level an action agent: Action agents are wrapped in agent executors, chains which are responsible for calling the agent, getting back an action and action input, calling the tool that the action references with the generated input, getting the output of the tool, and then passing all that information back into the agent to get the next action it should take. Although an agent can be constructed in many ways, it typically involves these components: At a high-level a plan-and-execute agent: The most typical implementation is to have the planner be a language model, and the executor be an action agent. Read more here. LangChain offers several types of agents. Here's an example using one powered by OpenAI functions: import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. */ API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculator And here is the logged verbose output:
4e9727215e95-3028
And here is the logged verbose output: [chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "What is the weather in New York? ", "chat_history": []}[llm/start] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3029
", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] [1.97s] Exiting LLM run with output: { "generations": [ [ { "text": "", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\n \"input\": \"current weather in New York\"\n}" } } } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 18, "promptTokens": 121, "totalTokens": 139 }
4e9727215e95-3030
}}[agent/action] [1:chain:AgentExecutor] Agent selected action: { "tool": "search", "toolInput": { "input": "current weather in New York" }, "log": ""}[tool/start] [1:chain:AgentExecutor > 3:tool:SerpAPI] Entering Tool run with input: "current weather in New York"[tool/end] [1:chain:AgentExecutor > 3:tool:SerpAPI] [1.90s] Exiting Tool run with output: "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ..."[llm/start] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] Entering LLM run with input: { "messages": [ [ { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "SystemMessage" ], "kwargs": { "content": "You are a helpful AI assistant. ", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "HumanMessage" ], "kwargs": { "content": "What is the weather in New York?
4e9727215e95-3031
", "additional_kwargs": {} } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "", "additional_kwargs": { "function_call": { "name": "search", "arguments": "{\"input\":\"current weather in New York\"}" } } } }, { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "FunctionMessage" ], "kwargs": { "content": "1 am · Feels Like72° · WindSSW 1 mph · Humidity89% · UV Index0 of 11 · Cloud Cover79% · Rain Amount0 in ...", "name": "search", "additional_kwargs": {} } } ] ]}[llm/end] [1:chain:AgentExecutor > 4:llm:ChatOpenAI] [3.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "message": { "lc": 1, "type": "constructor", "id": [ "langchain", "schema", "AIMessage" ], "kwargs": { "content": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW.
4e9727215e95-3032
The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain. ", "additional_kwargs": {} } } } ] ], "llmOutput": { "tokenUsage": { "completionTokens": 58, "promptTokens": 180, "totalTokens": 238 } }}[chain/end] [1:chain:AgentExecutor] [7.73s] Exiting Chain run with output: { "output": "The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain."} Action agentsPlan-and-execute agentsGet started Page Title: Agent types | 🦜️🔗 Langchain Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesOn this pageAgent typesAction 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. Here are the agents available in LangChain.Zero-shot ReAct​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.
4e9727215e95-3033
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.Note: This is the most general purpose action agent.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​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.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.PreviousAgentsNextConversationalAction agentsZero-shot ReActOpenAI FunctionsConversationalPlan-and-execute agentsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesOn this pageAgent typesAction 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. Here are the agents available in LangChain.Zero-shot ReAct​This agent uses the ReAct framework to determine which tool to use
4e9727215e95-3034
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.Note: This is the most general purpose action agent.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​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.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.PreviousAgentsNextConversationalAction agentsZero-shot ReActOpenAI FunctionsConversationalPlan-and-execute agents Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI reference ModulesAgentsAgent typesOn this pageAgent typesAction 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. Here are the agents available in LangChain.Zero-shot ReAct​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.
4e9727215e95-3035
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.Note: This is the most general purpose action agent.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​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.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.PreviousAgentsNextConversationalAction agentsZero-shot ReActOpenAI FunctionsConversationalPlan-and-execute agents ModulesAgentsAgent typesOn this pageAgent typesAction 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. Here are the agents available in LangChain.Zero-shot ReAct​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.Note: This is the most general purpose action agent.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a
4e9727215e95-3036
function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​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.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.PreviousAgentsNextConversational Agent typesAction 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. Here are the agents available in LangChain.Zero-shot ReAct​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.Note: This is the most general purpose action agent.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​This agent is designed to be used in conversational settings. The prompt is designed to make the agent helpful and conversational.
4e9727215e95-3037
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.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper. 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. Here are the agents available in LangChain. 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. Note: This is the most general purpose action agent. Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models. 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. Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper. Conversational Action agentsZero-shot ReActOpenAI FunctionsConversationalPlan-and-execute agents Page Title: Conversational | 🦜️🔗 Langchain Paragraphs:
4e9727215e95-3038
Page Title: Conversational | 🦜️🔗 Langchain Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesConversationalConversationalThis walkthrough demonstrates how to use an agent optimized for conversation. 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 example covers how to create a conversational agent for a chat model. It will utilize chat specific prompts.import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { process.env.LANGCHAIN_HANDLER = "langchain"; const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; // Passing "chat-conversational-react-description" as the agent type // automatically creates and uses BufferMemory with the executor.
4e9727215e95-3039
// If you would like to override this, you can pass in a custom // memory option, but the memoryKey set on it must be "chat_history". const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-conversational-react-description", verbose: true, }); console.log("Loaded agent. "); const input0 = "hi, i am bob"; const result0 = await executor.call({ input: input0 }); console.log(`Got output ${result0.output}`); const input1 = "whats my name? "; const result1 = await executor.call({ input: input1 }); console.log(`Got output ${result1.output}`); const input2 = "whats the weather in pomfret? "; const result2 = await executor.call({ input: input2 }); console.log(`Got output ${result2.output}`);};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorLoaded agent.Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today? "}Finished chain.Got output Hello Bob! How can I assist you today?Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Your name is Bob. "}Finished chain.Got output Your name is Bob.Entering new agent_executor chain...```json{ "action": "search", "action_input": "weather in pomfret"}```A steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph.
4e9727215e95-3040
Chance of rain 80%.```json{ "action": "Final Answer", "action_input": "The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%. "}```Finished chain.Got output The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.PreviousAgent typesNextOpenAI functionsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
4e9727215e95-3041
Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesConversationalConversationalThis walkthrough demonstrates how to use an agent optimized for conversation. 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 example covers how to create a conversational agent for a chat model. It will utilize chat specific prompts.import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { process.env.LANGCHAIN_HANDLER = "langchain"; const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; // Passing "chat-conversational-react-description" as the agent type // automatically creates and uses BufferMemory with the executor.
4e9727215e95-3042
// If you would like to override this, you can pass in a custom // memory option, but the memoryKey set on it must be "chat_history". const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-conversational-react-description", verbose: true, }); console.log("Loaded agent. "); const input0 = "hi, i am bob"; const result0 = await executor.call({ input: input0 }); console.log(`Got output ${result0.output}`); const input1 = "whats my name? "; const result1 = await executor.call({ input: input1 }); console.log(`Got output ${result1.output}`); const input2 = "whats the weather in pomfret? "; const result2 = await executor.call({ input: input2 }); console.log(`Got output ${result2.output}`);};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorLoaded agent.Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today? "}Finished chain.Got output Hello Bob! How can I assist you today?Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Your name is Bob. "}Finished chain.Got output Your name is Bob.Entering new agent_executor chain...```json{ "action": "search", "action_input": "weather in pomfret"}```A steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph.
4e9727215e95-3043
Chance of rain 80%.```json{ "action": "Final Answer", "action_input": "The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%. "}```Finished chain.Got output The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.PreviousAgent typesNextOpenAI functions
4e9727215e95-3044
ModulesAgentsAgent typesConversationalConversationalThis walkthrough demonstrates how to use an agent optimized for conversation. 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 example covers how to create a conversational agent for a chat model. It will utilize chat specific prompts.import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { process.env.LANGCHAIN_HANDLER = "langchain"; const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; // Passing "chat-conversational-react-description" as the agent type // automatically creates and uses BufferMemory with the executor. // If you would like to override this, you can pass in a custom // memory option, but the memoryKey set on it must be "chat_history". const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-conversational-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3045
"); const input0 = "hi, i am bob"; const result0 = await executor.call({ input: input0 }); console.log(`Got output ${result0.output}`); const input1 = "whats my name? "; const result1 = await executor.call({ input: input1 }); console.log(`Got output ${result1.output}`); const input2 = "whats the weather in pomfret? "; const result2 = await executor.call({ input: input2 }); console.log(`Got output ${result2.output}`);};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorLoaded agent.Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today? "}Finished chain.Got output Hello Bob! How can I assist you today?Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Your name is Bob. "}Finished chain.Got output Your name is Bob.Entering new agent_executor chain...```json{ "action": "search", "action_input": "weather in pomfret"}```A steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.```json{ "action": "Final Answer", "action_input": "The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.
4e9727215e95-3046
"}```Finished chain.Got output The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.PreviousAgent typesNextOpenAI functions ConversationalThis walkthrough demonstrates how to use an agent optimized for conversation. 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 example covers how to create a conversational agent for a chat model. It will utilize chat specific prompts.import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { process.env.LANGCHAIN_HANDLER = "langchain"; const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; // Passing "chat-conversational-react-description" as the agent type // automatically creates and uses BufferMemory with the executor. // If you would like to override this, you can pass in a custom // memory option, but the memoryKey set on it must be "chat_history". const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-conversational-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3047
"); const input0 = "hi, i am bob"; const result0 = await executor.call({ input: input0 }); console.log(`Got output ${result0.output}`); const input1 = "whats my name? "; const result1 = await executor.call({ input: input1 }); console.log(`Got output ${result1.output}`); const input2 = "whats the weather in pomfret? "; const result2 = await executor.call({ input: input2 }); console.log(`Got output ${result2.output}`);};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorLoaded agent.Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today? "}Finished chain.Got output Hello Bob! How can I assist you today?Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Your name is Bob. "}Finished chain.Got output Your name is Bob.Entering new agent_executor chain...```json{ "action": "search", "action_input": "weather in pomfret"}```A steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.```json{ "action": "Final Answer", "action_input": "The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.
4e9727215e95-3048
"}```Finished chain.Got output The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%. This walkthrough demonstrates how to use an agent optimized for conversation. 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 example covers how to create a conversational agent for a chat model. It will utilize chat specific prompts.
4e9727215e95-3049
import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { process.env.LANGCHAIN_HANDLER = "langchain"; const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; // Passing "chat-conversational-react-description" as the agent type // automatically creates and uses BufferMemory with the executor. // If you would like to override this, you can pass in a custom // memory option, but the memoryKey set on it must be "chat_history". const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-conversational-react-description", verbose: true, }); console.log("Loaded agent. "); const input0 = "hi, i am bob"; const result0 = await executor.call({ input: input0 }); console.log(`Got output ${result0.output}`); const input1 = "whats my name? "; const result1 = await executor.call({ input: input1 }); console.log(`Got output ${result1.output}`); const input2 = "whats the weather in pomfret? "; const result2 = await executor.call({ input: input2 }); console.log(`Got output ${result2.output}`);}; API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsSerpAPI from langchain/toolsCalculator from langchain/tools/calculator
4e9727215e95-3050
Loaded agent.Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today? "}Finished chain.Got output Hello Bob! How can I assist you today?Entering new agent_executor chain...{ "action": "Final Answer", "action_input": "Your name is Bob. "}Finished chain.Got output Your name is Bob.Entering new agent_executor chain...```json{ "action": "search", "action_input": "weather in pomfret"}```A steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%.```json{ "action": "Final Answer", "action_input": "The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%. "}```Finished chain.Got output The weather in Pomfret is a steady rain early...then remaining cloudy with a few showers. High 48F. Winds WNW at 10 to 15 mph. Chance of rain 80%. OpenAI functions Page Title: OpenAI functions | 🦜️🔗 Langchain Paragraphs:
4e9727215e95-3051
Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesOpenAI functionsOpenAI functionsCertain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions.
4e9727215e95-3052
The goal of the OpenAI Function APIs is to more reliably return valid and useful function calls than a generic text completion or chat API.The OpenAI Functions Agent is designed to work with these models.CompatibilityMust be used with an OpenAI Functions model.This agent also supports StructuredTools with more complex input schemas.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3053
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPrompt customization​You can pass in a custom string to be used as the system message of the prompt as follows:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const prefix = "You are a helpful AI assistant. However, all final response to the user must be in pirate dialect. ";const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true, agentArgs: { prefix, },});const result = await executor.run("What is the weather in New York? ");console.log(result);// Arr matey, in New York, it be feelin' like 75 degrees, with a gentle breeze blowin' from the northwest at 3 knots. The air be 77% full o' water, and the clouds be coverin' 35% of the sky. There be no rain in sight, yarr!API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousConversationalNextPlan and executeCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
4e9727215e95-3054
Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesOpenAI functionsOpenAI functionsCertain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions.
4e9727215e95-3055
The goal of the OpenAI Function APIs is to more reliably return valid and useful function calls than a generic text completion or chat API.The OpenAI Functions Agent is designed to work with these models.CompatibilityMust be used with an OpenAI Functions model.This agent also supports StructuredTools with more complex input schemas.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3056
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPrompt customization​You can pass in a custom string to be used as the system message of the prompt as follows:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const prefix = "You are a helpful AI assistant. However, all final response to the user must be in pirate dialect. ";const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true, agentArgs: { prefix, },});const result = await executor.run("What is the weather in New York? ");console.log(result);// Arr matey, in New York, it be feelin' like 75 degrees, with a gentle breeze blowin' from the northwest at 3 knots. The air be 77% full o' water, and the clouds be coverin' 35% of the sky. There be no rain in sight, yarr!API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousConversationalNextPlan and execute
4e9727215e95-3057
ModulesAgentsAgent typesOpenAI functionsOpenAI functionsCertain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions. The goal of the OpenAI Function APIs is to more reliably return valid and useful function calls than a generic text completion or chat API.The OpenAI Functions Agent is designed to work with these models.CompatibilityMust be used with an OpenAI Functions model.This agent also supports StructuredTools with more complex input schemas.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3058
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPrompt customization​You can pass in a custom string to be used as the system message of the prompt as follows:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const prefix = "You are a helpful AI assistant. However, all final response to the user must be in pirate dialect. ";const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true, agentArgs: { prefix, },});const result = await executor.run("What is the weather in New York? ");console.log(result);// Arr matey, in New York, it be feelin' like 75 degrees, with a gentle breeze blowin' from the northwest at 3 knots. The air be 77% full o' water, and the clouds be coverin' 35% of the sky. There be no rain in sight, yarr!API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousConversationalNextPlan and execute
4e9727215e95-3059
OpenAI functionsCertain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions. The goal of the OpenAI Function APIs is to more reliably return valid and useful function calls than a generic text completion or chat API.The OpenAI Functions Agent is designed to work with these models.CompatibilityMust be used with an OpenAI Functions model.This agent also supports StructuredTools with more complex input schemas.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true,});const result = await executor.run("What is the weather in New York? ");console.log(result);/* The current weather in New York is 72°F with a wind speed of 1 mph coming from the SSW. The humidity is at 89% and the UV index is 0 out of 11. The cloud cover is 79% and there has been no rain.
4e9727215e95-3060
/API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPrompt customization​You can pass in a custom string to be used as the system message of the prompt as follows:import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const prefix = "You are a helpful AI assistant. However, all final response to the user must be in pirate dialect. ";const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true, agentArgs: { prefix, },});const result = await executor.run("What is the weather in New York? ");console.log(result);// Arr matey, in New York, it be feelin' like 75 degrees, with a gentle breeze blowin' from the northwest at 3 knots. The air be 77% full o' water, and the clouds be coverin' 35% of the sky. There be no rain in sight, yarr!API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculator Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function.
4e9727215e95-3061
In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions. The goal of the OpenAI Function APIs is to more reliably return valid and useful function calls than a generic text completion or chat API. The OpenAI Functions Agent is designed to work with these models. This agent also supports StructuredTools with more complex input schemas. You can pass in a custom string to be used as the system message of the prompt as follows: import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const tools = [new Calculator(), new SerpAPI()];const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });const prefix = "You are a helpful AI assistant. However, all final response to the user must be in pirate dialect. ";const executor = await initializeAgentExecutorWithOptions(tools, chat, { agentType: "openai-functions", verbose: true, agentArgs: { prefix, },});const result = await executor.run("What is the weather in New York? ");console.log(result);// Arr matey, in New York, it be feelin' like 75 degrees, with a gentle breeze blowin' from the northwest at 3 knots. The air be 77% full o' water, and the clouds be coverin' 35% of the sky. There be no rain in sight, yarr! Plan and execute Page Title: Plan and execute | 🦜️🔗 Langchain Paragraphs:
4e9727215e95-3062
Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesPlan and executePlan and executePlan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.The planning is almost always done by an LLM.The execution is usually done by a separate agent (equipped with tools).This agent uses a two step process:First, the agent uses an LLM to create a plan to answer the query with clear steps.Once it has a plan, it uses an embedded traditional Action Agent to solve each step.The idea is that the planning step keeps the LLM more "on track" by breaking up a larger task into simpler subtasks.
4e9727215e95-3063
However, this method requires more individual LLM queries and has higher latency compared to Action Agents.Note: This agent currently only supports Chat Models.import { Calculator } from "langchain/tools/calculator";import { SerpAPI } from "langchain/tools";import { ChatOpenAI } from "langchain/chat_models/openai";import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";const tools = [new Calculator(), new SerpAPI()];const model = new ChatOpenAI({ temperature: 0, modelName: "gpt-3.5-turbo", verbose: true,});const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({ llm: model, tools,});const result = await executor.call({ input: `Who is the current president of the United States? What is their current age raised to the second power?`,});console.log({ result });API Reference:Calculator from langchain/tools/calculatorSerpAPI from langchain/toolsChatOpenAI from langchain/chat_models/openaiPlanAndExecuteAgentExecutor from langchain/experimental/plan_and_executePreviousOpenAI functionsNextReActCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
4e9727215e95-3064
Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesPlan and executePlan and executePlan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.The planning is almost always done by an LLM.The execution is usually done by a separate agent (equipped with tools).This agent uses a two step process:First, the agent uses an LLM to create a plan to answer the query with clear steps.Once it has a plan, it uses an embedded traditional Action Agent to solve each step.The idea is that the planning step keeps the LLM more "on track" by breaking up a larger task into simpler subtasks.
4e9727215e95-3065
However, this method requires more individual LLM queries and has higher latency compared to Action Agents.Note: This agent currently only supports Chat Models.import { Calculator } from "langchain/tools/calculator";import { SerpAPI } from "langchain/tools";import { ChatOpenAI } from "langchain/chat_models/openai";import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";const tools = [new Calculator(), new SerpAPI()];const model = new ChatOpenAI({ temperature: 0, modelName: "gpt-3.5-turbo", verbose: true,});const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({ llm: model, tools,});const result = await executor.call({ input: `Who is the current president of the United States? What is their current age raised to the second power?`,});console.log({ result });API Reference:Calculator from langchain/tools/calculatorSerpAPI from langchain/toolsChatOpenAI from langchain/chat_models/openaiPlanAndExecuteAgentExecutor from langchain/experimental/plan_and_executePreviousOpenAI functionsNextReAct ModulesAgentsAgent typesPlan and executePlan and executePlan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.The planning is almost always done by an LLM.The execution is usually done by a separate agent (equipped with tools).This agent uses a two step process:First, the agent uses an LLM to create a plan to answer the query with clear steps.Once it has a plan, it uses an embedded traditional Action Agent to solve each step.The idea is that the planning step keeps the LLM more "on track" by breaking up a larger task into simpler subtasks.
4e9727215e95-3066
However, this method requires more individual LLM queries and has higher latency compared to Action Agents.Note: This agent currently only supports Chat Models.import { Calculator } from "langchain/tools/calculator";import { SerpAPI } from "langchain/tools";import { ChatOpenAI } from "langchain/chat_models/openai";import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";const tools = [new Calculator(), new SerpAPI()];const model = new ChatOpenAI({ temperature: 0, modelName: "gpt-3.5-turbo", verbose: true,});const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({ llm: model, tools,});const result = await executor.call({ input: `Who is the current president of the United States? What is their current age raised to the second power?`,});console.log({ result });API Reference:Calculator from langchain/tools/calculatorSerpAPI from langchain/toolsChatOpenAI from langchain/chat_models/openaiPlanAndExecuteAgentExecutor from langchain/experimental/plan_and_executePreviousOpenAI functionsNextReAct Plan and executePlan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.The planning is almost always done by an LLM.The execution is usually done by a separate agent (equipped with tools).This agent uses a two step process:First, the agent uses an LLM to create a plan to answer the query with clear steps.Once it has a plan, it uses an embedded traditional Action Agent to solve each step.The idea is that the planning step keeps the LLM more "on track" by breaking up a larger task into simpler subtasks.
4e9727215e95-3067
However, this method requires more individual LLM queries and has higher latency compared to Action Agents.Note: This agent currently only supports Chat Models.import { Calculator } from "langchain/tools/calculator";import { SerpAPI } from "langchain/tools";import { ChatOpenAI } from "langchain/chat_models/openai";import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";const tools = [new Calculator(), new SerpAPI()];const model = new ChatOpenAI({ temperature: 0, modelName: "gpt-3.5-turbo", verbose: true,});const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({ llm: model, tools,});const result = await executor.call({ input: `Who is the current president of the United States? What is their current age raised to the second power?`,});console.log({ result });API Reference:Calculator from langchain/tools/calculatorSerpAPI from langchain/toolsChatOpenAI from langchain/chat_models/openaiPlanAndExecuteAgentExecutor from langchain/experimental/plan_and_execute The planning is almost always done by an LLM. The execution is usually done by a separate agent (equipped with tools). This agent uses a two step process: The idea is that the planning step keeps the LLM more "on track" by breaking up a larger task into simpler subtasks. However, this method requires more individual LLM queries and has higher latency compared to Action Agents. Note: This agent currently only supports Chat Models.
4e9727215e95-3068
Note: This agent currently only supports Chat Models. import { Calculator } from "langchain/tools/calculator";import { SerpAPI } from "langchain/tools";import { ChatOpenAI } from "langchain/chat_models/openai";import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";const tools = [new Calculator(), new SerpAPI()];const model = new ChatOpenAI({ temperature: 0, modelName: "gpt-3.5-turbo", verbose: true,});const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({ llm: model, tools,});const result = await executor.call({ input: `Who is the current president of the United States? What is their current age raised to the second power?`,});console.log({ result }); API Reference:Calculator from langchain/tools/calculatorSerpAPI from langchain/toolsChatOpenAI from langchain/chat_models/openaiPlanAndExecuteAgentExecutor from langchain/experimental/plan_and_execute ReAct Page Title: ReAct | 🦜️🔗 Langchain Paragraphs:
4e9727215e95-3069
Page Title: ReAct | 🦜️🔗 Langchain Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesReActOn this pageReActThis walkthrough showcases using an agent to implement the ReAct logic.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3070
What is his current age raised to the 0.23 power?`;const result = await executor.call({ input });API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorUsing chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3071
What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );};API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousPlan and executeNextStructured tool chatUsing chat modelsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesReActOn this pageReActThis walkthrough showcases using an agent to implement the ReAct logic.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3072
What is his current age raised to the 0.23 power?`;const result = await executor.call({ input });API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorUsing chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );};API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousPlan and executeNextStructured tool chatUsing chat models
4e9727215e95-3073
ModulesAgentsAgent typesReActOn this pageReActThis walkthrough showcases using an agent to implement the ReAct logic.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3074
What is his current age raised to the 0.23 power?`;const result = await executor.call({ input });API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorUsing chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );};API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousPlan and executeNextStructured tool chatUsing chat models
4e9727215e95-3075
ModulesAgentsAgent typesReActOn this pageReActThis walkthrough showcases using an agent to implement the ReAct logic.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3076
What is his current age raised to the 0.23 power?`;const result = await executor.call({ input });API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorUsing chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );};API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousPlan and executeNextStructured tool chat
4e9727215e95-3077
ReActThis walkthrough showcases using an agent to implement the ReAct logic.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3078
What is his current age raised to the 0.23 power?`;const result = await executor.call({ input });API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorUsing chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );};API Reference:initializeAgentExecutorWithOptions from langchain/agentsChatOpenAI from langchain/chat_models/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculator This walkthrough showcases using an agent to implement the ReAct logic.
4e9727215e95-3079
This walkthrough showcases using an agent to implement the ReAct logic. import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description", verbose: true,});const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`;const result = await executor.call({ input }); API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculator You can also create ReAct agents that use chat models instead of LLMs as the agent driver.
4e9727215e95-3080
import { initializeAgentExecutorWithOptions } from "langchain/agents";import { ChatOpenAI } from "langchain/chat_models/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "chat-zero-shot-react-description", returnIntermediateSteps: true, }); console.log("Loaded agent. "); const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log(`Got output ${result.output}`); console.log( `Got intermediate steps ${JSON.stringify( result.intermediateSteps, null, 2 )}` );}; Structured tool chat Using chat models Page Title: Structured tool chat | 🦜️🔗 Langchain Paragraphs:
4e9727215e95-3081
Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesStructured tool chatStructured tool chatThe structured tool chat agent is capable of using multi-input tools.Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input.This makes it easier to create and use tools that require multiple input values - rather than prompting for a stringified object or comma separated list, you can specify an object with multiple keys.
4e9727215e95-3082
Here's an example with a DynamicStructuredTool:import { z } from "zod";import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { DynamicStructuredTool } from "langchain/tools";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new Calculator(), // Older existing single input tools will still work new DynamicStructuredTool({ name: "random-number-generator", description: "generates a random number between two input numbers", schema: z.object({ low: z.number().describe("The lower bound of the generated number"), high: z.number().describe("The upper bound of the generated number"), }), func: async ({ low, high }) => (Math.random() * (high - low) + low).toString(), // Outputs still must be strings returnDirect: false, // This is an option that allows the tool to return the output directly }), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3083
"); const input = `What is a random number between 5 and 10 raised to the second power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log({ result }); /* { "output": "67.95299776074" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorDynamicStructuredTool from langchain/toolsAdding Memory​You can add memory to this agent like this:import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { MessagesPlaceholder } from "langchain/prompts";import { BufferMemory } from "langchain/memory";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [new Calculator()]; const executor = await initializeAgentExecutorWithOptions(tools,
4e9727215e95-3084
model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, memory: new BufferMemory({ memoryKey: "chat_history", returnMessages: true, }), agentArgs: { inputVariables: ["input", "agent_scratchpad", "chat_history"], memoryPrompts: [new MessagesPlaceholder("chat_history")], }, }); const result = await executor.call({ input: `what is 9 to the 2nd power?` }); console.log(result); /* { "output": "81" } */ const result2 = await executor.call({ input: `what is that number squared?`, }); console.log(result2); /* { "output": "6561" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorMessagesPlaceholder from langchain/promptsBufferMemory from langchain/memoryPreviousReActNextSubscribing to eventsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. Get startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsPlan and executeReActStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsAgent typesStructured tool chatStructured tool chatThe structured tool chat agent is capable of using multi-input tools.Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input.This makes it easier to create and use tools that require multiple input values - rather than prompting for a stringified object or comma separated list, you can specify an object with multiple keys.
4e9727215e95-3085
Here's an example with a DynamicStructuredTool:import { z } from "zod";import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { DynamicStructuredTool } from "langchain/tools";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new Calculator(), // Older existing single input tools will still work new DynamicStructuredTool({ name: "random-number-generator", description: "generates a random number between two input numbers", schema: z.object({ low: z.number().describe("The lower bound of the generated number"), high: z.number().describe("The upper bound of the generated number"), }), func: async ({ low, high }) => (Math.random() * (high - low) + low).toString(), // Outputs still must be strings returnDirect: false, // This is an option that allows the tool to return the output directly }), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3086
"); const input = `What is a random number between 5 and 10 raised to the second power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log({ result }); /* { "output": "67.95299776074" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorDynamicStructuredTool from langchain/toolsAdding Memory​You can add memory to this agent like this:import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { MessagesPlaceholder } from "langchain/prompts";import { BufferMemory } from "langchain/memory";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [new Calculator()]; const executor =
4e9727215e95-3087
await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, memory: new BufferMemory({ memoryKey: "chat_history", returnMessages: true, }), agentArgs: { inputVariables: ["input", "agent_scratchpad", "chat_history"], memoryPrompts: [new MessagesPlaceholder("chat_history")], }, }); const result = await executor.call({ input: `what is 9 to the 2nd power?` }); console.log(result); /* { "output": "81" } */ const result2 = await executor.call({ input: `what is that number squared?`, }); console.log(result2); /* { "output": "6561" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorMessagesPlaceholder from langchain/promptsBufferMemory from langchain/memoryPreviousReActNextSubscribing to events ModulesAgentsAgent typesStructured tool chatStructured tool chatThe structured tool chat agent is capable of using multi-input tools.Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input.This makes it easier to create and use tools that require multiple input values - rather than prompting for a stringified object or comma separated list, you can specify an object with multiple keys.
4e9727215e95-3088
Here's an example with a DynamicStructuredTool:import { z } from "zod";import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { DynamicStructuredTool } from "langchain/tools";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new Calculator(), // Older existing single input tools will still work new DynamicStructuredTool({ name: "random-number-generator", description: "generates a random number between two input numbers", schema: z.object({ low: z.number().describe("The lower bound of the generated number"), high: z.number().describe("The upper bound of the generated number"), }), func: async ({ low, high }) => (Math.random() * (high - low) + low).toString(), // Outputs still must be strings returnDirect: false, // This is an option that allows the tool to return the output directly }), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3089
"); const input = `What is a random number between 5 and 10 raised to the second power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log({ result }); /* { "output": "67.95299776074" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorDynamicStructuredTool from langchain/toolsAdding Memory​You can add memory to this agent like this:import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { MessagesPlaceholder } from "langchain/prompts";import { BufferMemory } from "langchain/memory";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [new Calculator()]; const executor =
4e9727215e95-3090
await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, memory: new BufferMemory({ memoryKey: "chat_history", returnMessages: true, }), agentArgs: { inputVariables: ["input", "agent_scratchpad", "chat_history"], memoryPrompts: [new MessagesPlaceholder("chat_history")], }, }); const result = await executor.call({ input: `what is 9 to the 2nd power?` }); console.log(result); /* { "output": "81" } */ const result2 = await executor.call({ input: `what is that number squared?`, }); console.log(result2); /* { "output": "6561" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorMessagesPlaceholder from langchain/promptsBufferMemory from langchain/memoryPreviousReActNextSubscribing to events Structured tool chatThe structured tool chat agent is capable of using multi-input tools.Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input.This makes it easier to create and use tools that require multiple input values - rather than prompting for a stringified object or comma separated list, you can specify an object with multiple keys.
4e9727215e95-3091
Here's an example with a DynamicStructuredTool:import { z } from "zod";import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { DynamicStructuredTool } from "langchain/tools";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new Calculator(), // Older existing single input tools will still work new DynamicStructuredTool({ name: "random-number-generator", description: "generates a random number between two input numbers", schema: z.object({ low: z.number().describe("The lower bound of the generated number"), high: z.number().describe("The upper bound of the generated number"), }), func: async ({ low, high }) => (Math.random() * (high - low) + low).toString(), // Outputs still must be strings returnDirect: false, // This is an option that allows the tool to return the output directly }), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, }); console.log("Loaded agent.
4e9727215e95-3092
"); const input = `What is a random number between 5 and 10 raised to the second power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log({ result }); /* { "output": "67.95299776074" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorDynamicStructuredTool from langchain/toolsAdding Memory​You can add memory to this agent like this:import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { MessagesPlaceholder } from "langchain/prompts";import { BufferMemory } from "langchain/memory";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [new Calculator()];
4e9727215e95-3093
const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, memory: new BufferMemory({ memoryKey: "chat_history", returnMessages: true, }), agentArgs: { inputVariables: ["input", "agent_scratchpad", "chat_history"], memoryPrompts: [new MessagesPlaceholder("chat_history")], }, }); const result = await executor.call({ input: `what is 9 to the 2nd power?` }); console.log(result); /* { "output": "81" } */ const result2 = await executor.call({ input: `what is that number squared?`, }); console.log(result2); /* { "output": "6561" } */};API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorMessagesPlaceholder from langchain/promptsBufferMemory from langchain/memory The structured tool chat agent is capable of using multi-input tools. Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input. This makes it easier to create and use tools that require multiple input values - rather than prompting for a stringified object or comma separated list, you can specify an object with multiple keys. Here's an example with a DynamicStructuredTool:
4e9727215e95-3094
Here's an example with a DynamicStructuredTool: import { z } from "zod";import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { DynamicStructuredTool } from "langchain/tools";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [ new Calculator(), // Older existing single input tools will still work new DynamicStructuredTool({ name: "random-number-generator", description: "generates a random number between two input numbers", schema: z.object({ low: z.number().describe("The lower bound of the generated number"), high: z.number().describe("The upper bound of the generated number"), }), func: async ({ low, high }) => (Math.random() * (high - low) + low).toString(), // Outputs still must be strings returnDirect: false, // This is an option that allows the tool to return the output directly }), ]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, }); console.log("Loaded agent. "); const input = `What is a random number between 5 and 10 raised to the second power?`; console.log(`Executing with input "${input}"...`); const result = await executor.call({ input }); console.log({ result }); /* { "output": "67.95299776074" } */}; API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorDynamicStructuredTool from langchain/tools
4e9727215e95-3095
You can add memory to this agent like this: import { ChatOpenAI } from "langchain/chat_models/openai";import { initializeAgentExecutorWithOptions } from "langchain/agents";import { Calculator } from "langchain/tools/calculator";import { MessagesPlaceholder } from "langchain/prompts";import { BufferMemory } from "langchain/memory";export const run = async () => { const model = new ChatOpenAI({ temperature: 0 }); const tools = [new Calculator()]; const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "structured-chat-zero-shot-react-description", verbose: true, memory: new BufferMemory({ memoryKey: "chat_history", returnMessages: true, }), agentArgs: { inputVariables: ["input", "agent_scratchpad", "chat_history"], memoryPrompts: [new MessagesPlaceholder("chat_history")], }, }); const result = await executor.call({ input: `what is 9 to the 2nd power?` }); console.log(result); /* { "output": "81" } */ const result2 = await executor.call({ input: `what is that number squared?`, }); console.log(result2); /* { "output": "6561" } */}; API Reference:ChatOpenAI from langchain/chat_models/openaiinitializeAgentExecutorWithOptions from langchain/agentsCalculator from langchain/tools/calculatorMessagesPlaceholder from langchain/promptsBufferMemory from langchain/memory Paragraphs:
4e9727215e95-3096
Paragraphs: Skip to main content🦜️🔗 LangChainDocsUse casesAPILangSmithPython DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesHow-toSubscribing to eventsCancelling requestsCustom LLM AgentCustom LLM Agent (with a ChatModel)Logging and tracingAdding a timeoutToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesCommunity navigatorAPI referenceModulesAgentsHow-toSubscribing to eventsSubscribing to eventsYou can subscribe to a number of events that are emitted by the Agent and the underlying tools, chains and models via callbacks.For more info on the events available see the Callbacks section of the docs.import { initializeAgentExecutorWithOptions } from "langchain/agents";import { OpenAI } from "langchain/llms/openai";import { SerpAPI } from "langchain/tools";import { Calculator } from "langchain/tools/calculator";const model = new OpenAI({ temperature: 0 });const tools = [ new SerpAPI(process.env.SERPAPI_API_KEY, { location: "Austin,Texas,United States", hl: "en", gl: "us", }), new Calculator(),];const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "zero-shot-react-description",});const input = `Who is Olivia Wilde's boyfriend?
4e9727215e95-3097
What is his current age raised to the 0.23 power?`;const result = await executor.run(input, [ { handleAgentAction(action, runId) { console.log("\nhandleAgentAction", action, runId); }, handleAgentEnd(action, runId) { console.log("\nhandleAgentEnd", action, runId); }, handleToolEnd(output, runId) { console.log("\nhandleToolEnd", output, runId); }, },]);/*handleAgentAction { tool: 'search', toolInput: 'Olivia Wilde boyfriend', log: " I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n" + 'Action: search\n' + 'Action Input: "Olivia Wilde boyfriend"'} 9b978461-1f6f-4d5f-80cf-5b229ce181b6handleToolEnd In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling. Their relationship ended in November 2022.
4e9727215e95-3098
062fef47-8ad1-4729-9949-a57be252e002handleAgentAction { tool: 'search', toolInput: 'Harry Styles age', log: " I need to find out Harry Styles' age.\n" + 'Action: search\n' + 'Action Input: "Harry Styles age"'} 9b978461-1f6f-4d5f-80cf-5b229ce181b6handleToolEnd 29 years 9ec91e41-2fbf-4de0-85b6-12b3e6b3784e 61d77e10-c119-435d-a985-1f9d45f0ef08handleAgentAction { tool: 'calculator', toolInput: '29^0.23', log: ' I need to calculate 29 raised to the 0.23 power.\n' + 'Action: calculator\n' + 'Action Input: 29^0.23'} 9b978461-1f6f-4d5f-80cf-5b229ce181b6handleToolEnd 2.169459462491557 07aec96a-ce19-4425-b863-2eae39db8199handleAgentEnd { returnValues: { output: "Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557." }, log: ' I now know the final answer.\n' + "Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557."}
4e9727215e95-3099
age raised to the 0.23 power is 2.169459462491557."} 9b978461-1f6f-4d5f-80cf-5b229ce181b6*/console.log({ result });// { result: "Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557." }API Reference:initializeAgentExecutorWithOptions from langchain/agentsOpenAI from langchain/llms/openaiSerpAPI from langchain/toolsCalculator from langchain/tools/calculatorPreviousStructured tool chatNextCancelling requestsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.