DynamoDB 支持的聊天记忆
为了实现跨聊天会话的更长期持久性,您可以用 DynamoDB 实例替换支持聊天记忆类(如 BufferMemory
)的默认内存中 chatHistory
。
设置
首先,在您的项目中安装 AWS DynamoDB 客户端
- npm
- Yarn
- pnpm
npm install @aws-sdk/client-dynamodb
yarn add @aws-sdk/client-dynamodb
pnpm add @aws-sdk/client-dynamodb
提示
- npm
- Yarn
- pnpm
npm install @langchain/openai @langchain/community
yarn add @langchain/openai @langchain/community
pnpm add @langchain/openai @langchain/community
接下来,登录您的 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();
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 参考
- BufferMemory 来自
langchain/memory
- DynamoDBChatMessageHistory 来自
@langchain/community/stores/message/dynamodb
- ChatOpenAI 来自
@langchain/openai
- ConversationChain 来自
langchain/chains