跳到内容

如何为预构建的 ReAct 代理添加记忆

本教程将展示如何为预构建的 ReAct 代理添加记忆。请参阅此教程,了解如何开始使用预构建的 ReAct 代理

我们启用记忆所需做的就是将一个检查点传递给 createReactAgent

设置

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

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 with memory: LangGraphJS";
ReAct Agent with memory: LangGraphJS

代码

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

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

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

const getWeather = tool((input) => {
    if (input.location === 'sf') {
        return 'It\'s always sunny in sf';
    } else {
        return 'It might be cloudy in nyc';
    }
}, {
    name: 'get_weather',
    description: 'Call to get the current weather.',
    schema: z.object({
        location: z.enum(['sf','nyc']).describe("Location to get the weather for."),
    })
})

// Here we only save in-memory
const memory = new MemorySaver();

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

用法

让我们多次与其交互,以展示它可以记住先前的信息

let inputs = { messages: [{ role: "user", content: "what is the weather in NYC?" }] };
let config = { configurable: { thread_id: "1" } };
let stream = await agent.stream(inputs, {
  ...config,
  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 NYC?
-----

[
  {
    name: 'get_weather',
    args: { location: 'nyc' },
    type: 'tool_call',
    id: 'call_m0zEI6sidPPH81G6ygMsKYs1'
  }
]
-----

It might be cloudy in nyc
-----

The weather in NYC appears to be cloudy.
-----
请注意,当我们传递相同的线程 ID 时,聊天记录会被保留

inputs = { messages: [{ role: "user", content: "What's it known for?" }] };
stream = await agent.stream(inputs, {
  ...config,
  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's it known for?
-----

New York City (NYC) is known for many things, including:

1. **Landmarks and Attractions:**
   - **Statue of Liberty**: An iconic symbol of freedom.
   - **Empire State Building**: A famous skyscraper offering panoramic views.
   - **Times Square**: Known for its neon lights and bustling atmosphere.
   - **Central Park**: A large, urban park offering a natural oasis.

2. **Cultural Institutions:**
   - **Broadway**: Famous for its theatre productions.
   - **Metropolitan Museum of Art (The Met)**: One of the largest and most prestigious art museums.
   - **Museum of Modern Art (MoMA) and American Museum of Natural History**: Other significant museums.

3. **Economy and Business:**
   - **Wall Street**: The financial hub of the world, home to the New York Stock Exchange.
   - **Headquarters of major corporations**: NYC hosts the headquarters of many large multinational companies.

4. **Diversity and Neighborhoods:**
   - **Cultural Melting Pot**: NYC is known for its diverse population with a wide range of ethnicities and cultures.
   - **Distinct Neighborhoods**: Each borough and neighborhood (like Brooklyn, The Bronx, Queens, Staten Island, and Manhattan) has its unique character.

5. **Food and Cuisine:**
   - **Culinary Capital**: Known for diverse food options from street food like hot dogs and pretzels to high-end dining.
   - **Cultural Cuisine**: Offers a variety of world cuisines due to its diverse population.

6. **Media and Entertainment:**
   - **Media Headquarters**: Home to major media companies and news networks.
   - **Film and Television**: A popular setting and production location for films and TV shows.

7. **Events and Festivities:**
   - **Macy's Thanksgiving Day Parade**: A famous annual parade.
   - **New Year's Eve in Times Square**: Known for the ball drop and celebrations.

NYC is a dynamic and vibrant city with a rich history and an influence that extends globally in various sectors.
-----
当我们传递新的线程 ID 时,所有历史记录都会丢失,并且没有任何记忆

inputs = { messages: [{ role: "user", content: "how close is it to boston?" }] };
config = { configurable: { thread_id: "2" } };
stream = await agent.stream(inputs, {
  ...config,
  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");
  }
how close is it to boston?
-----

[
  {
    name: 'get_weather',
    args: { location: 'nyc' },
    type: 'tool_call',
    id: 'call_CKgDJqHiadzNLGhB8T8pHQWM'
  }
]
-----

It might be cloudy in nyc
-----

To determine how close "it" is to Boston, could you please specify which location you're referring to? For instance, are you asking about the distance from New York City, San Francisco, or another location? This detail will help me provide an accurate answer.
-----