跳至主要内容

Cassandra 聊天记忆

为了在聊天会话之间进行更长期的持久性,您可以将支持聊天记忆类的默认内存中 chatHistory(例如 BufferMemory)换成 Cassandra 集群。

设置

首先,安装 Cassandra Node.js 驱动程序

npm install cassandra-driver @langchain/openai @langchain/community @langchain/core

根据您的数据库提供商,连接到数据库的具体方法会有所不同。我们将创建一个文档 configConnection,它将用作向量存储配置的一部分。

Apache Cassandra®

const configConnection = {
contactPoints: ['h1', 'h2'],
localDataCenter: 'datacenter1',
credentials: {
username: <...> as string,
password: <...> as string,
},
};

Astra DB

Astra DB 是一个云原生 Cassandra 即服务平台。

  1. 创建一个Astra DB 帐户
  2. 创建一个启用向量的数据库
  3. 为您的数据库创建一个令牌
const configConnection = {
serviceProviderArgs: {
astra: {
token: <...> as string,
endpoint: <...> as string,
},
},
};

您可以提供属性 datacenterID: 而不是 endpoint:,并且可以选择提供 regionName:

用法

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 参考


此页面是否有帮助?


您也可以在 GitHub 上留下详细的反馈 GitHub.