Skip to main content

DynamoDB支持的聊天记录

如果需要在聊天进程之间进行更长期的持久化,您可以将默认的内存chatHistory替换为DynamoDB实例,作为支持BufferMemory等聊天记录类的后端。,注意:chatHistory指聊天记录类,BufferMemory指缓存存储器类。

设置

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

npm install @aws-sdk/client-dynamodb

接下来,登录您的AWS帐户并创建一个DynamoDB表格。将表格命名为langchain,指定您的分区键为id,分区键必须是字符串类型,其他设置保持默认即可。

您还需要检索一个AWS访问密钥和密钥,以便拥有访问该表格的角色或用户,并将它们添加到环境变量中。

使用方法

import { BufferMemory } from "langchain/memory";
import { DynamoDBChatMessageHistory } from "langchain/stores/message/dynamodb";
import { ChatOpenAI } from "langchain/chat_models/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();
const chain = new ConversationChain({ llm: model, memory });

const res1 = await chain.call({ 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.call({ input: "What did I just say my name was?" });
console.log({ res2 });

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