凸聊天记忆
为了实现跨聊天会话的长期持久性,您可以将支持聊天记忆类(如 BufferMemory
)的默认内存中 chatHistory
替换为 Convex。
设置
创建项目
获取一个可以工作的 Convex 项目设置,例如,使用
npm create convex@latest
添加数据库访问器
将查询和变异帮助程序添加到 convex/langchain/db.ts
convex/langchain/db.ts
export * from "@langchain/community/utils/convex";
配置您的模式
设置您的模式(用于索引)
convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
messages: defineTable({
sessionId: v.string(),
message: v.object({
type: v.string(),
data: v.object({
content: v.string(),
role: v.optional(v.string()),
name: v.optional(v.string()),
additional_kwargs: v.optional(v.any()),
}),
}),
}).index("bySessionId", ["sessionId"]),
});
用法
存储在 Convex 中的每个聊天历史会话都必须具有唯一的会话 ID。
提示
- npm
- Yarn
- pnpm
npm install @langchain/openai @langchain/community
yarn add @langchain/openai @langchain/community
pnpm add @langchain/openai @langchain/community
convex/myActions.ts
"use node";
import { v } from "convex/values";
import { BufferMemory } from "langchain/memory";
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";
import { ConvexChatMessageHistory } from "@langchain/community/stores/message/convex";
import { action } from "./_generated/server.js";
export const ask = action({
args: { sessionId: v.string() },
handler: async (ctx, args) => {
// pass in a sessionId string
const { sessionId } = args;
const memory = new BufferMemory({
chatHistory: new ConvexChatMessageHistory({ sessionId, ctx }),
});
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 });
/*
{
res2: {
text: "You said your name was Jim."
}
}
*/
// See the chat history in the Convex database
console.log(await memory.chatHistory.getMessages());
// clear chat history
await memory.chatHistory.clear();
},
});
API 参考
- BufferMemory 来自
langchain/memory
- ChatOpenAI 来自
@langchain/openai
- ConversationChain 来自
langchain/chains
- ConvexChatMessageHistory 来自
@langchain/community/stores/message/convex