History Postgres¶
简介¶
by-framework-history-postgres 库提供了基于 PostgreSQL 的会话历史存储实现,适合大规模生产环境。
安装¶
核心组件¶
PostgresHistoryStore¶
from by_framework_history_postgres import PostgresHistoryStore
store = PostgresHistoryStore(
dsn="postgresql://user:pass@localhost/dbname",
)
使用示例¶
from by_framework_history_postgres import PostgresHistoryStore
# 初始化
store = PostgresHistoryStore(
dsn="postgresql://user:pass@localhost/dbname",
)
# 保存消息
await store.save_message(
session_id="sess_123",
message_id="msg_456",
role="user",
content="Hello!",
)
# 获取历史
messages = await store.get_history(
session_id="sess_123",
limit=50,
)
# 搜索历史
results = await store.search_messages(
query="hello",
session_id="sess_123",
)
# 清空历史
await store.clear_history(session_id="sess_123")
配置选项¶
| 参数 | 类型 | 描述 | 默认值 |
|---|---|---|---|
dsn |
str |
PostgreSQL 连接字符串 | 必填 |
pool_size |
int |
连接池大小 | 10 |
max_overflow |
int |
最大溢出连接 | 20 |
pool_timeout |
int |
池超时(秒) | 30 |
pool_recycle |
int |
连接回收时间(秒) | 3600 |
数据库表结构¶
CREATE TABLE IF NOT EXISTS message_history (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL,
message_id VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
metadata JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
);
CREATE INDEX idx_session_id ON message_history(session_id);
CREATE INDEX idx_created_at ON message_history(created_at);