DynamoDB 支持的聊天记忆
为了在聊天会话之间实现更长期的持久性,您可以将支持聊天记忆类的默认内存中 chatHistory
(例如 BufferMemory
)替换为 DynamoDB 实例。
设置
首先,在您的项目中安装 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 @langchain/core
yarn add @langchain/openai @langchain/community @langchain/core
pnpm add @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();
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