跳至主要内容

Cloudflare D1 支持的聊天记忆

info

此集成仅在 Cloudflare Workers 中受支持。

为了在聊天会话之间实现更长期的持久性,您可以将支持聊天记忆类的默认内存中 chatHistory(如 BufferMemory)替换为 Cloudflare D1 实例。

设置

您需要安装 LangChain Cloudflare 集成包。对于以下示例,我们也使用 Anthropic,但您可以使用任何您喜欢的模型。

npm install @langchain/cloudflare @langchain/anthropic @langchain/core

按照 官方文档 为您的工作程序设置 D1 实例。您项目的 wrangler.toml 文件应该看起来像这样。

name = "YOUR_PROJECT_NAME"
main = "src/index.ts"
compatibility_date = "2024-01-10"

[vars]
ANTHROPIC_API_KEY = "YOUR_ANTHROPIC_KEY"

[[d1_databases]]
binding = "DB" # available in your Worker as env.DB
database_name = "YOUR_D1_DB_NAME"
database_id = "YOUR_D1_DB_ID"

用法

然后,您可以按如下方式使用 D1 来存储您的历史记录。

import type { D1Database } from "@cloudflare/workers-types";
import { BufferMemory } from "langchain/memory";
import { CloudflareD1MessageHistory } from "@langchain/cloudflare";
import {
ChatPromptTemplate,
MessagesPlaceholder,
} from "@langchain/core/prompts";
import { RunnableSequence } from "@langchain/core/runnables";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { ChatAnthropic } from "@langchain/anthropic";

export interface Env {
DB: D1Database;

ANTHROPIC_API_KEY: string;
}

export default {
async fetch(request: Request, env: Env): Promise<Response> {
try {
const { searchParams } = new URL(request.url);
const input = searchParams.get("input");
if (!input) {
throw new Error(`Missing "input" parameter`);
}
const memory = new BufferMemory({
returnMessages: true,
chatHistory: new CloudflareD1MessageHistory({
tableName: "stored_message",
sessionId: "example",
database: env.DB,
}),
});
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a helpful chatbot"],
new MessagesPlaceholder("history"),
["human", "{input}"],
]);
const model = new ChatAnthropic({
apiKey: env.ANTHROPIC_API_KEY,
});

const chain = RunnableSequence.from([
{
input: (initialInput) => initialInput.input,
memory: () => memory.loadMemoryVariables({}),
},
{
input: (previousOutput) => previousOutput.input,
history: (previousOutput) => previousOutput.memory.history,
},
prompt,
model,
new StringOutputParser(),
]);

const chainInput = { input };

const res = await chain.invoke(chainInput);
await memory.saveContext(chainInput, {
output: res,
});

return new Response(JSON.stringify(res), {
headers: { "content-type": "application/json" },
});
} catch (err: any) {
console.log(err.message);
return new Response(err.message, { status: 500 });
}
},
};

API 参考


此页面对您有帮助吗?


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