Skip to main content

Postgres 聊天记忆

如果你需要在聊天会话之间实现更长期的数据持久化,可以将默认的内存型 chatHistory 替换为 Postgres 数据库。

安装配置

首先安装 node-postgres 包:

:::提示 请参阅安装集成包的一般说明部分。 :::

npm install @langchain/openai @langchain/community @langchain/core pg

使用方法

每次聊天历史记录会话都存储在 Postgres 数据库中,并且需要一个会话 ID。

Postgres 的连接是通过连接池(pool)进行管理的。你可以通过 pool 参数传入一个已有的连接池实例,或者通过 poolConfig 参数传入连接池的配置。更多信息请参考 pg-node 的连接池文档。如果同时提供了连接池实例和配置,将以连接池实例为准。

import pg from "pg";

import { PostgresChatMessageHistory } from "@langchain/community/stores/message/postgres";
import { ChatOpenAI } from "@langchain/openai";
import { RunnableWithMessageHistory } from "@langchain/core/runnables";
import {
ChatPromptTemplate,
MessagesPlaceholder,
} from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

const poolConfig = {
host: "127.0.0.1",
port: 5432,
user: "myuser",
password: "ChangeMe",
database: "api",
};

const pool = new pg.Pool(poolConfig);

const model = new ChatOpenAI({
model: "gpt-4o-mini",
});

const prompt = ChatPromptTemplate.fromMessages([
[
"system",
"You are a helpful assistant. Answer all questions to the best of your ability.",
],
new MessagesPlaceholder("chat_history"),
["human", "{input}"],
]);

const chain = prompt.pipe(model).pipe(new StringOutputParser());

const chainWithHistory = new RunnableWithMessageHistory({
runnable: chain,
inputMessagesKey: "input",
historyMessagesKey: "chat_history",
getMessageHistory: async (sessionId) => {
const chatHistory = new PostgresChatMessageHistory({
sessionId,
pool,
// Can also pass `poolConfig` to initialize the pool internally,
// but easier to call `.end()` at the end later.
});
return chatHistory;
},
});

const res1 = await chainWithHistory.invoke(
{
input: "Hi! I'm MJDeligan.",
},
{ configurable: { sessionId: "langchain-test-session" } }
);
console.log(res1);
/*
"Hello MJDeligan! It's nice to meet you. My name is AI. How may I assist you today?"
*/

const res2 = await chainWithHistory.invoke(
{ input: "What did I just say my name was?" },
{ configurable: { sessionId: "langchain-test-session" } }
);
console.log(res2);

/*
"You said your name was MJDeligan."
*/

// If you provided a pool config you should close the created pool when you are done
await pool.end();

API Reference:


Was this page helpful?


You can also leave detailed feedback on GitHub.