Skip to main content

基于 DynamoDB 的聊天记忆

为了在聊天会话间实现更长期的持久化存储,您可以将支持 BufferMemory 等聊天记忆类的默认内存中 chatHistory 替换为 DynamoDB 实例。

安装配置

首先,在您的项目中安装 AWS DynamoDB 客户端:

npm install @aws-sdk/client-dynamodb

:::提示 请参阅安装集成包的一般说明部分。 :::

npm install @langchain/openai @langchain/community @langchain/core

接下来,登录您的 AWS 账户并创建一个 DynamoDB 表。将表命名为 langchain,分区键命名为 id。请确保您的分区键是字符串类型。排序键和其他设置可以保持默认。

您还需要获取具有访问该表权限的角色或用户的 AWS 访问密钥和密钥,并将它们添加到您的环境变量中。

使用方法

import { BufferMemory } from "langchain/memory";
import { DynamoDBChatMessageHistory } from "@langchain/community/stores/message/dynamodb";
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";

const memory = new BufferMemory({
chatHistory: new DynamoDBChatMessageHistory({
tableName: "langchain",
partitionKey: "id",
sessionId: new Date().toISOString(), // Or some other unique identifier for the conversation
config: {
region: "us-east-2",
credentials: {
accessKeyId: "<your AWS access key id>",
secretAccessKey: "<your AWS secret access key>",
},
},
}),
});

const model = new ChatOpenAI({
model: "gpt-4o-mini",
});
const chain = new ConversationChain({ llm: model, memory });

const res1 = await chain.invoke({ input: "Hi! I'm Jim." });
console.log({ res1 });
/*
{
res1: {
text: "Hello Jim! It's nice to meet you. My name is AI. How may I assist you today?"
}
}
*/

const res2 = await chain.invoke({ input: "What did I just say my name was?" });
console.log({ res2 });

/*
{
res1: {
text: "You said your name was Jim."
}
}
*/

API Reference:


Was this page helpful?


You can also leave detailed feedback on GitHub.