You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

LangChain整合Google Gemini模型时Agent多轮对话上下文记忆失效问题求助

LangChain整合Google Gemini模型时Agent多轮对话上下文记忆失效问题求助

我仔细看了你的代码和遇到的问题——用LangGraph整合Google Gemini做Agent时,多轮对话的上下文记忆没生效,明明传了thread_id但Agent记不住之前说过的话对吧?我帮你分析下问题,再给你改好的代码方案:

问题根源分析

你已经用了MemorySaver作为checkpointer,也在调用时传了thread_id,逻辑方向是对的,但可能卡在这几个细节上:

  1. 消息格式的隐性要求:LangGraph的预构建React Agent对输入消息的类型有要求,直接传普通对象可能不如用LangChain封装的消息类型(比如HumanMessage)兼容性好
  2. 系统提示的缺失:没有给Agent明确的系统提示强化记忆逻辑,Gemini可能没意识到需要关联对话历史
  3. 版本兼容性:旧版LangChain的createReactAgent对checkpointer的支持存在小bug,可能导致历史没被正确读写

修正后的代码方案

我调整了你的代码,针对性解决了上面的问题,确保对话记忆能正常生效:

import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { MemorySaver } from "@langchain/langgraph";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import type { Tool } from "langchain/tools";
import { HumanMessage } from "@langchain/core/messages";

interface AgentInfo{
  id: string,
  name: string,
  job: string,
  sex: 'male' | 'female',
}

class Agent {
  private model: BaseChatModel;
  private tools: Tool[];
  private agent: any;
  private checkpointer: MemorySaver;
  public info: AgentInfo;

  constructor(model: BaseChatModel, tools: Tool[], info: AgentInfo) {
    const checkpointer = new MemorySaver();
    this.model = model;
    this.tools = tools;
    this.checkpointer = checkpointer 
    this.info = info;

    // 增加系统提示强化记忆逻辑,同时确保checkpointer参数正确传递
    const agent = createReactAgent({
      llm: model,
      tools: tools,
      checkpointSaver: this.checkpointer,
      systemPrompt: `你是${info.name},一名${info.job},请严格根据对话历史上下文回答用户问题。`,
    });

    this.agent = agent;
  }

  public getId(){
    return this.info.id
  }

  public async invoke(prompt: string, thread_id?: string) {
    // 给thread_id设置默认值,避免undefined导致记忆混乱
    const targetThreadId = thread_id || `default-thread-${this.info.id}`;

    // 使用LangChain封装的HumanMessage类型,确保消息格式符合Agent要求
    const result = await this.agent.invoke(
      {
        messages: [new HumanMessage(prompt)],
      },
      {
        configurable: {
          thread_id: targetThreadId,
        },
      }
    );

    // (可选调试用)打印完整对话历史,确认记忆是否被正确保存
    console.log(`[线程${targetThreadId}] 完整对话历史:`, result.messages);

    // 返回最后一条助手回复的内容
    return result.messages.at(-1)?.content || "暂无回复";
  }
}

// 初始化Gemini模型,记得替换成你的Google API Key
const geminiModel = new ChatGoogleGenerativeAI({
  model: "gemini-1.5-flash-8b",
  apiKey: process.env.GOOGLE_API_KEY, // 可以从环境变量读取,避免硬编码
});

const agent = new Agent(geminiModel, [], {id: '1', name:'josh', job: 'developer', sex: 'male'});

// 测试多轮对话
(async () => {
  console.log(await agent.invoke('My name is test', 'test-thread'));
  console.log(await agent.invoke('What is my name', 'test-thread'));
})();

额外排查建议

  1. 更新LangChain依赖:运行npm update @langchain/core @langchain/google-genai @langchain/langgraph到最新版本,旧版本的checkpointer确实存在一些记忆读写的小bug
  2. 验证API权限:确保你的Google API Key有Gemini模型的调用权限,且没有触发配额限制
  3. 调试checkpointer内容:可以在invoke方法里加这段代码,确认历史是否被正确保存:
// 调试用:列出指定线程的所有历史 checkpoint
const checkpoints = await this.checkpointer.listCheckpoints({
  threadId: targetThreadId,
});
console.log(`[线程${targetThreadId}] 已保存的checkpoint:`, checkpoints);

备注:内容来源于stack exchange,提问作者Matteturtle09

火山引擎 最新活动