Cassandra 聊天记忆
为了在聊天会话之间实现更持久的持久性,您可以将支持聊天记忆类(例如 BufferMemory
)的默认内存中 chatHistory
替换为 Cassandra 集群。
设置
首先,安装 Cassandra Node.js 驱动程序
提示
- npm
- Yarn
- pnpm
npm install cassandra-driver @langchain/openai @langchain/community
yarn add cassandra-driver @langchain/openai @langchain/community
pnpm add cassandra-driver @langchain/openai @langchain/community
具体连接数据库的方式会因您的数据库提供商而异。我们将创建一个名为 configConnection
的文档,用作向量存储配置的一部分。
Apache Cassandra®
const configConnection = {
contactPoints: ['h1', 'h2'],
localDataCenter: 'datacenter1',
credentials: {
username: <...> as string,
password: <...> as string,
},
};
Astra DB
Astra DB 是一个云原生 Cassandra 即服务平台。
- 创建一个 Astra DB 帐户。
- 创建一个 支持向量的数据库。
- 为您的数据库创建一个 令牌。
const configConnection = {
serviceProviderArgs: {
astra: {
token: <...> as string,
endpoint: <...> as string,
},
},
};
您可以提供属性 datacenterID:
,并可选地提供 regionName:
,而不是 endpoint:
。
使用
import { BufferMemory } from "langchain/memory";
import { CassandraChatMessageHistory } from "@langchain/community/stores/message/cassandra";
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";
// The example below uses Astra DB, but you can use any Cassandra connection
const configConnection = {
serviceProviderArgs: {
astra: {
token: "<your Astra Token>" as string,
endpoint: "<your Astra Endpoint>" as string,
},
},
};
const memory = new BufferMemory({
chatHistory: new CassandraChatMessageHistory({
...configConnection,
keyspace: "langchain",
table: "message_history",
sessionId: "<some unique session identifier>",
}),
});
const model = new ChatOpenAI();
const chain = new ConversationChain({ llm: model, memory });
const res1 = await chain.invoke({ input: "Hi! I'm Jonathan." });
console.log({ res1 });
/*
{
res1: {
text: "Hello Jonathan! How can 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 Jonathan."
}
}
*/
API 参考
- BufferMemory 来自
langchain/memory
- CassandraChatMessageHistory 来自
@langchain/community/stores/message/cassandra
- ChatOpenAI 来自
@langchain/openai
- ConversationChain 来自
langchain/chains