Enhance Postgres connection string handling in ChatService to prioritize LANGGRAPH_PG_URL, derive from DATABASE_URL if available, and fallback to localhost configuration.

This commit is contained in:
eason 2026-03-03 13:41:29 +08:00
parent bb58eebe50
commit 6bc6327647
1 changed files with 16 additions and 7 deletions

View File

@ -201,13 +201,22 @@ class ChatService:
if not ChatService._checkpointer_initialized:
from langgraph.checkpoint.postgres import PostgresSaver
import psycopg2
# LangGraph 使用的 Postgres 连接串,优先从环境变量读取,便于在 Docker / 本地区分配置
# - Docker 内建议LANGGRAPH_PG_URL=postgresql://drgraph:yingping@db:5432/th_agenter
# - 本地开发可用: LANGGRAPH_PG_URL=postgresql://drgraph:yingping@localhost:5433/th_agenter
conn_string = os.getenv(
"LANGGRAPH_PG_URL",
"postgresql://drgraph:yingping@localhost:5433/th_agenter",
import re
# LangGraph 使用的 Postgres 连接串psycopg 格式postgresql://
# 优先级LANGGRAPH_PG_URL > 从 DATABASE_URL 派生 > 默认 localhost
conn_string = os.getenv("LANGGRAPH_PG_URL")
if not conn_string:
db_url = os.getenv("DATABASE_URL", "")
if db_url and "postgresql" in db_url.split("://")[0].lower():
# 将 postgresql+asyncpg:// 转为 postgresql://,供 LangGraph/psycopg 使用
conn_string = re.sub(
r"^postgresql\+[a-zA-Z0-9]+://",
"postgresql://",
db_url,
count=1,
)
else:
conn_string = "postgresql://drgraph:yingping@localhost:5433/th_agenter"
ChatService._conn_string = conn_string
# 检查必要的表是否已存在