ReAct
This walkthrough showcases using an agent to implement the ReAct logic.
Setup
Install the OpenAI integration package, retrieve your key, and store it as an environment variable named OPENAI_API_KEY
:
- npm
- Yarn
- pnpm
npm install @langchain/openai
yarn add @langchain/openai
pnpm add @langchain/openai
This demo also uses Tavily, but you can also swap in another built in tool.
You'll need to sign up for an API key and set it as TAVILY_API_KEY
.
Initialize Tools
We will first create a tool:
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
// Define the tools the agent will have access to.
const tools = [new TavilySearchResults({ maxResults: 1 })];
Create Agent
import { AgentExecutor, createReactAgent } from "langchain/agents";
import { pull } from "langchain/hub";
import { OpenAI } from "@langchain/openai";
import type { PromptTemplate } from "@langchain/core/prompts";
// Get the prompt to use - you can modify this!
// If you want to see the prompt in full, you can at:
// https://smith.langchain.com/hub/hwchase17/react
const prompt = await pull<PromptTemplate>("hwchase17/react");
const llm = new OpenAI({
model: "gpt-3.5-turbo-instruct",
temperature: 0,
});
const agent = await createReactAgent({
llm,
tools,
prompt,
});
Run Agent
Now, let's run our agent!
const agentExecutor = new AgentExecutor({
agent,
tools,
});
const result = await agentExecutor.invoke({
input: "what is LangChain?",
});
console.log(result);
/*
{
input: 'what is LangChain?',
output: 'LangChain is a platform for building applications using LLMs (Language Model Microservices) through composability. It can be used for tasks such as retrieval augmented generation, analyzing structured data, and creating chatbots.'
}
*/
Using with chat history
For more details, see this section of the agent quickstart.
// Get the prompt to use - you can modify this!
// If you want to see the prompt in full, you can at:
// https://smith.langchain.com/hub/hwchase17/react-chat
const promptWithChat = await pull<PromptTemplate>("hwchase17/react-chat");
const agentWithChat = await createReactAgent({
llm,
tools,
prompt: promptWithChat,
});
const agentExecutorWithChat = new AgentExecutor({
agent: agentWithChat,
tools,
});
const result2 = await agentExecutorWithChat.invoke({
input: "what's my name?",
// Notice that chat_history is a string, since this prompt is aimed at LLMs, not chat models
chat_history: "Human: Hi! My name is Cob\nAI: Hello Cob! Nice to meet you",
});
console.log(result2);
/*
{
input: "what's my name?",
chat_history: 'Human: Hi! My name is Cob\nAI: Hello Cob! Nice to meet you',
output: 'Your name is Cob.'
}
*/