跳到内容

如何使用预构建的 ReAct 代理

在本操作指南中,我们将创建一个简单的 ReAct 代理应用,它可以检查天气。该应用由代理(LLM)和工具组成。当我们与应用交互时,我们将首先调用代理(LLM)来决定我们是否应该使用工具。然后我们将运行一个循环

  1. 如果代理表示要执行操作(即调用工具),我们将运行工具并将结果传递回代理
  2. 如果代理未要求运行工具,我们将完成操作(响应用户)

预构建代理

请注意,这里我们将使用预构建的代理。LangGraph 的一大优势在于您可以轻松创建自己的代理架构。因此,虽然从这里开始快速构建代理是可行的,但我们强烈建议学习如何构建自己的代理,以便您可以充分利用 LangGraph。阅读本指南,了解如何从头开始创建自己的 ReAct 代理。

设置

首先,我们需要安装所需的软件包。

yarn add @langchain/langgraph @langchain/openai @langchain/core

本指南将使用 OpenAI 的 GPT-4o 模型。我们将选择性地为 LangSmith 追踪设置我们的 API 密钥,这将为我们提供一流的可观察性。

// process.env.OPENAI_API_KEY = "sk_...";

// Optional, add tracing in LangSmith
// process.env.LANGCHAIN_API_KEY = "ls__..."
// process.env.LANGCHAIN_CALLBACKS_BACKGROUND = "true";
process.env.LANGCHAIN_CALLBACKS_BACKGROUND = "true";
process.env.LANGCHAIN_TRACING_V2 = "true";
process.env.LANGCHAIN_PROJECT = "ReAct Agent: LangGraphJS";
ReAct Agent: LangGraphJS

代码

现在我们可以使用预构建的 createReactAgent 函数来设置我们的代理

import { ChatOpenAI } from "@langchain/openai";
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const model = new ChatOpenAI({
  model: "gpt-4o",
});

const getWeather = tool((input) => {
  if (['sf', 'san francisco', 'san francisco, ca'].includes(input.location.toLowerCase())) {
    return 'It\'s 60 degrees and foggy.';
  } else {
    return 'It\'s 90 degrees and sunny.';
  }
}, {
  name: 'get_weather',
  description: 'Call to get the current weather.',
  schema: z.object({
    location: z.string().describe("Location to get the weather for."),
  })
})

const agent = createReactAgent({ llm: model, tools: [getWeather] });

用法

首先,让我们可视化我们刚刚创建的图

import * as tslab from "tslab";

const graph = agent.getGraph();
const image = await graph.drawMermaidPng();
const arrayBuffer = await image.arrayBuffer();

await tslab.display.png(new Uint8Array(arrayBuffer));

让我们使用需要工具调用的输入来运行该应用

let inputs = { messages: [{ role: "user", content: "what is the weather in SF?" }] };

let stream = await agent.stream(inputs, {
  streamMode: "values",
});

for await (const { messages } of stream) {
  let msg = messages[messages?.length - 1];
  if (msg?.content) {
    console.log(msg.content);
  } else if (msg?.tool_calls?.length > 0) {
    console.log(msg.tool_calls);
  } else {
    console.log(msg);
  }
  console.log("-----\n");
}
what is the weather in sf?
-----

[
  {
    name: 'get_weather',
    args: { location: 'San Francisco, CA' },
    type: 'tool_call',
    id: 'call_wfXCh5IhSp1C0Db3gaJWDbRP'
  }
]
-----

It's 60 degrees and foggy.
-----

The weather in San Francisco is currently 60 degrees and foggy.
-----
现在让我们尝试一个不需要工具的问题

inputs = { messages: [{ role: "user", content: "who built you?" }] };

stream = await agent.stream(inputs, {
  streamMode: "values",
});

for await (
  const { messages } of stream
) {
  let msg = messages[messages?.length - 1];
  if (msg?.content) {
    console.log(msg.content);
  } else if (msg?.tool_calls?.length > 0) {
    console.log(msg.tool_calls);
  } else {
    console.log(msg);
  }
  console.log("-----\n");
}
who built you?
-----

I was developed by OpenAI, an AI research and deployment company.
-----
完美!该代理正确地没有调用任何工具,而是直接响应了用户。

此页是否对您有帮助?