由 Momento 支持的聊天记忆
对于跨聊天会话的分布式无服务器持久化,您可以使用由 Momento 支持的聊天消息历史记录。 由于 Momento 缓存可立即使用且不需要任何基础设施维护,因此无论是在本地开发还是在生产环境中,它都是开始使用聊天历史记录的绝佳方式。
安装配置
您需要在项目中安装 Momento 客户端库。鉴于 Momento 兼容 Node.js、浏览器和边缘环境,请确保安装相应的包。
在 Node.js 环境中安装:
- npm
- Yarn
- pnpm
npm install @gomomento/sdk
yarn add @gomomento/sdk
pnpm add @gomomento/sdk
在 浏览器/边缘工作线程 环境中安装:
- npm
- Yarn
- pnpm
npm install @gomomento/sdk-web
yarn add @gomomento/sdk-web
pnpm add @gomomento/sdk-web
:::提示 请参阅安装集成包的一般说明部分。 :::
- 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
您还需要从 Momento 获取一个 API 密钥。您可以 在此处 注册一个免费账户。
使用方法
为了区分不同的聊天历史会话,我们需要一个唯一的 sessionId。您还可以提供一个可选的 sessionTtl,以使会话在指定的秒数后过期。
import {
CacheClient,
Configurations,
CredentialProvider,
} from "@gomomento/sdk"; // `from "gomomento/sdk-web";` for browser/edge
import { BufferMemory } from "langchain/memory";
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";
import { MomentoChatMessageHistory } from "@langchain/community/stores/message/momento";
// See https://github.com/momentohq/client-sdk-javascript for connection options
const client = new CacheClient({
configuration: Configurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: "MOMENTO_API_KEY",
}),
defaultTtlSeconds: 60 * 60 * 24,
});
// Create a unique session ID
const sessionId = new Date().toISOString();
const cacheName = "langchain";
const memory = new BufferMemory({
chatHistory: await MomentoChatMessageHistory.fromProps({
client,
cacheName,
sessionId,
sessionTtl: 300,
}),
});
console.log(
`cacheName=${cacheName} and sessionId=${sessionId} . This will be used to store the chat history. You can inspect the values at your Momento console at https://console.gomomento.com.`
);
const model = new ChatOpenAI({
model: "gpt-3.5-turbo",
temperature: 0,
});
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."
}
}
*/
// See the chat history in the Momento
console.log(await memory.chatHistory.getMessages());
API Reference:
- BufferMemory from
langchain/memory - ChatOpenAI from
@langchain/openai - ConversationChain from
langchain/chains - MomentoChatMessageHistory from
@langchain/community/stores/message/momento