ReAct
本教程展示了使用 agent 实现 ReAct 逻辑的示例。
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 = `奥利维亚·怀尔德的男朋友是谁?他目前的年龄乘以0.23次方是多少?`;
const result = await executor.call({ input });
使用聊天模型
您还可以创建使用聊天模型而不是 LLMs 作为 agent 驱动程序的 ReAct agent。
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("加载完成 agent。");
const input = `奥利维亚·怀尔德的男朋友是谁?他目前的年龄乘以0.23次方是多少?`;
console.log(`执行输入 "${input}"...`);
const result = await executor.call({ input });
console.log(`得到输出 ${result.output}`);
console.log(
`得到中间步骤 ${JSON.stringify(
result.intermediateSteps,
null,
2
)}`
);
};