DynamoDB 支持的聊天内存
¥DynamoDB-Backed Chat Memory
为了在聊天会话中实现更长期的持久化,你可以将支持聊天内存类(如 BufferMemory)的默认内存 chatHistory 替换为 DynamoDB 实例。
¥For longer-term persistence across chat sessions, you can swap out the default in-memory chatHistory that backs chat memory classes like BufferMemory for a DynamoDB instance.
设置
¥Setup
首先,在你的项目中安装 AWS DynamoDB 客户端:
¥First, install the AWS DynamoDB client in your project:
- 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。确保你的分区键是字符串。你可以保留排序键和其他设置。
¥Next, sign into your AWS account and create a DynamoDB table. Name the table langchain, and name your partition key id. Make sure your partition key is a string. You can leave sort key and the other settings alone.
你还需要检索有权访问该表的角色或用户的 AWS 访问密钥和密钥,并将其添加到你的环境变量中。
¥You'll also need to retrieve an AWS access key and secret key for a role or user that has access to the table and add them to your environment variables.
用法
¥Usage
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 Reference:
- BufferMemory from
langchain/memory - DynamoDBChatMessageHistory from
@langchain/community/stores/message/dynamodb - ChatOpenAI from
@langchain/openai - ConversationChain from
langchain/chains