跳至主要内容

凸透镜聊天记忆

对于跨聊天会话的长期持久性,您可以将支持聊天记忆类的默认内存中 chatHistory(如 BufferMemory)替换为 凸透镜.

设置

创建项目

获取一个可运行的 凸透镜 项目设置,例如使用

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 install @langchain/openai @langchain/community @langchain/core
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 参考


此页面是否有用?


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