tianyajum commited on
Commit
ba98117
·
1 Parent(s): 9ca76dd

【xxx】重构整改,新增action

Browse files
.agent/rules/ai-code-ws.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ trigger: always_on
3
+ ---
4
+
5
+ # Role (角色)
6
+ 你是一位精通 FastAPI、LangGraph 和异步编程的 Python AI 工程师。
7
+
8
+ # Tech Stack (技术栈)
9
+ - Python 3.10+
10
+ - FastAPI (Web Server)
11
+ - LangGraph & LangChain (Agent 编排)
12
+ - Pydantic (数据验证)
13
+ - mcp[sse] (官方 MCP SDK)
14
+ - nacos-sdk-python (服务发现)
15
+ - PostgreSQL (Asyncpg) 或 MongoDB (Motor)
16
+
17
+ # Coding Standards (编码规范)
18
+ 1. **异步优先 (Async First)**:
19
+ - **始终**使用 `async def` 和 `await`。
20
+ - 网络请求必须使用 `httpx`,禁止使用 `requests`。
21
+ - 数据库操作必须使用 `asyncpg` 或其他异步驱动。
22
+
23
+ 2. **LangGraph 实现**:
24
+ - 使用 `TypedDict` 或 Pydantic 模型清晰定义 `State` (状态)。
25
+ - 显式定义节点 (Nodes:思考、工具调用、生成) 和 边 (Edges)。
26
+ - 使用 `AsyncPostgresSaver` 对 Agent 状态进行持久化 (Checkpointing)。
27
+
28
+ 3. **MCP Client 集成**:
29
+ - **禁止**硬编码 localhost。必须使用 `nacos-sdk-python` 动态获取 Java 服务的 IP 和端口。
30
+ - 实现完整的 MCP Client 生命周期:连接 -> 初始化 (Initialize) -> 获取工具列表 (List Tools) -> 调用工具 (Call Tool)。
31
+ - 必须优雅地处理 SSE 断线重连逻辑。
32
+
33
+ 4. **API 设计**:
34
+ - 通过 FastAPI 暴露接口。
35
+ - 聊天接口必须使用 `StreamingResponse`,将 LLM/LangGraph 生成的 Token 实时流式转发给网关。
36
+
37
+ # Key Context (关键背景)
38
+ 本服务是系统的“大脑” (Brain)。它接收来自网关的用户提问,在数据库中维护对话上下文 (Memory),并在需要执行业务操作时,通过 MCP 协议调用 Java 后端。
.env.example CHANGED
@@ -14,3 +14,10 @@ NACOS_GATEWAY_SERVICE_NAME=gateway
14
 
15
  # MCP Config
16
  # MCP_BRAVE_PATH=C:\Program Files\nodejs\npx.cmd
 
 
 
 
 
 
 
 
14
 
15
  # MCP Config
16
  # MCP_BRAVE_PATH=C:\Program Files\nodejs\npx.cmd
17
+
18
+ # postgreSQL
19
+ PG_HOST=127.0.0.1
20
+ PG_PORT=5432
21
+ PG_USER=postgres
22
+ PG_PASSWORD=
23
+ PG_DB=postgres
.github/workflows/docker-build.yml ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Python Agent DockerImage
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master # 主分支提交时触发
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ contents: read
13
+ packages: write
14
+
15
+ steps:
16
+ - name: Checkout code
17
+ uses: actions/checkout@v4
18
+
19
+ - name: Set up Docker Buildx
20
+ uses: docker/setup-buildx-action@v3
21
+
22
+ - name: Login to Docker Hub
23
+ uses: docker/login-action@v3
24
+ with:
25
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
26
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
27
+
28
+ - name: Extract metadata (tags, labels) for Docker
29
+ id: meta
30
+ uses: docker/metadata-action@v5
31
+ with:
32
+ images: |
33
+ tianyaqpzm/python-agent
34
+ tags: |
35
+ type=ref,event=branch
36
+ type=ref,event=pr
37
+ type=sha,format=short
38
+
39
+ - name: Build and push Docker image
40
+ id: docker_build
41
+ uses: docker/build-push-action@v5
42
+ with:
43
+ context: .
44
+ file: ./Dockerfile
45
+ platforms: linux/amd64,linux/arm64
46
+ push: ${{ github.event_name != 'pull_request' }}
47
+ tags: ${{ steps.meta.outputs.tags }}
48
+ labels: ${{ steps.meta.outputs.labels }}
49
+
50
+ - name: Image digest
51
+ run: echo ${{ steps.docker_build.outputs.digest }}
52
+
53
+ deploy:
54
+ needs: build
55
+ runs-on: ubuntu-latest
56
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
57
+ steps:
58
+ - name: Deploy to VPS
59
+ uses: appleboy/ssh-action@v1.0.3
60
+ with:
61
+ host: ${{ secrets.HOST }}
62
+ username: ${{ secrets.VPS_USERNAME }}
63
+ password: ${{ secrets.VPS_PASSWORD }}
64
+ port: ${{ secrets.PORT || 22 }}
65
+ script: |
66
+ # 停止并删除旧容器
67
+ docker stop python-agent || true
68
+ docker rm python-agent || true
69
+
70
+ # 拉取最新镜像
71
+ docker pull tianyaqpzm/python-agent:master
72
+
73
+ # 启动新容器
74
+ docker run -d \
75
+ --name python-agent \
76
+ --restart unless-stopped \
77
+ -p 8181:8181 \
78
+ -e TZ=Asia/Shanghai \
79
+ -e APP_ENV=production \
80
+ -e NACOS_SERVER_ADDR=${{ secrets.NACOS_SERVER_ADDR }} \
81
+ -e NACOS_USERNAME=${{ secrets.NACOS_USERNAME }} \
82
+ -e NACOS_PASSWORD=${{ secrets.NACOS_PASSWORD }} \
83
+ -e PG_HOST=${{ secrets.PG_HOST }} \
84
+ -e PG_PORT=${{ secrets.PG_PORT }} \
85
+ -e PG_USER=${{ secrets.PG_USER }} \
86
+ -e PG_PASSWORD=${{ secrets.PG_PASSWORD }} \
87
+ -e PG_DB=${{ secrets.PG_DB }} \
88
+ tianyaqpzm/python-agent:master
89
+
90
+ # 清理无用镜像
91
+ docker image prune -f
Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 使用官方 Python 基础镜像
2
+ FROM python:3.11-slim
3
+
4
+ # 设置工作目录
5
+ WORKDIR /app
6
+
7
+ # 设置环境变量
8
+ # 防止 Python 生成pyc文件
9
+ ENV PYTHONDONTWRITEBYTECODE=1
10
+ # 防止 Python 缓冲 stdout 和 stderr
11
+ ENV PYTHONUNBUFFERED=1
12
+ ENV APP_PORT=8181
13
+
14
+ # 安装系统依赖 (如果需要 pg_config 等,可能需要 install libpq-dev gcc)
15
+ # psycopg[binary] 通常包含二进制,slim 镜像一般能直接用,如果报错再加
16
+ RUN apt-get update && apt-get install -y --no-install-recommends \
17
+ curl \
18
+ && rm -rf /var/lib/apt/lists/*
19
+
20
+ # 复制依赖文件
21
+ COPY requirements.txt .
22
+
23
+ # 安装 Python 依赖
24
+ RUN pip install --no-cache-dir -r requirements.txt
25
+
26
+ # 复制应用代码
27
+ COPY . .
28
+
29
+ # 暴露端口
30
+ EXPOSE $APP_PORT
31
+
32
+ # 创建非 root 用户运行
33
+ RUN useradd -m myuser
34
+ USER myuser
35
+
36
+ # 启动命令
37
+ # 使用 uvicorn 直接启动,生产环境不需要 --reload
38
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8181"]
app/agent/factory.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
2
+ from app.services.chat_graph import workflow
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+
8
+ async def get_graph_runnable(conn):
9
+ """
10
+ 业务逻辑 -> 用 asyncpg (SQLAlchemy) -> 高性能。
11
+ LangGraph -> 用 psycopg (官方 Saver) -> 高可靠、零维护。
12
+ Get the compiled graph runnable with checkpointer.
13
+ """
14
+ # Initialize checkpointer with the connection pool
15
+ checkpointer = AsyncPostgresSaver(conn)
16
+ return workflow.compile(checkpointer=checkpointer)
app/api/routers/chat.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Request
2
+ from pydantic import BaseModel
3
+ from fastapi.responses import StreamingResponse
4
+ from app.agent.factory import get_graph_runnable
5
+ from app.services.chat_graph import save_chat_history
6
+ from app.core.database import AsyncSessionLocal # 🔥 从 database.py 导入 Session 工厂
7
+ from langchain_core.messages import HumanMessage
8
+ import json
9
+ import logging
10
+
11
+ router = APIRouter()
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ChatRequest(BaseModel):
16
+ session_id: str
17
+ message: str
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+ router = APIRouter()
22
+
23
+
24
+ @router.post("/rest/dark/v1/agent/chat")
25
+ async def chat_endpoint(request: Request, body: ChatRequest):
26
+ # 1. 拿到连接池
27
+ lg_pool = request.app.state.lg_pool
28
+
29
+ async def event_generator():
30
+ # 🔥 2. 手动申请连接 (Context Manager)
31
+ # 这样连接的生命周期就完全覆盖了整个流式响应过程 (Start -> End)
32
+ async with lg_pool.connection() as conn:
33
+ try:
34
+ # 🔥🔥 3. 核弹级修复:再次强制禁用 Prepared Statements
35
+ # 虽然 main.py 配了,但为了 100% 确保这个会话不报错,这里再设一次
36
+ conn.prepare_threshold = None
37
+
38
+ # 4. 把这个“干净”的连接传给 Graph
39
+ graph = await get_graph_runnable(conn)
40
+
41
+ input_message = HumanMessage(content=body.message)
42
+ config = {"configurable": {"thread_id": body.session_id}}
43
+ final_response = ""
44
+
45
+ # 5. 运行 Graph (使用当前的 conn)
46
+ async for event in graph.astream_events(
47
+ {"messages": [input_message]}, config, version="v1"
48
+ ):
49
+ kind = event["event"]
50
+ # ... 处理流逻辑 ...
51
+ if kind == "on_chain_end" and event["name"] == "agent":
52
+ output = event["data"]["output"]
53
+ # 兼容性处理,防止 output 为 None
54
+ if output and "messages" in output and output["messages"]:
55
+ final_response = output["messages"][-1].content
56
+ yield f"data: {json.dumps({'content': final_response})}\n\n"
57
+
58
+ # 还可以加个心跳,防止中间静默太久被防火墙切断
59
+ # yield ": keep-alive\n\n"
60
+
61
+ yield "data: [DONE]\n\n"
62
+
63
+ except Exception as e:
64
+ logger.error(f"Stream error: {e}", exc_info=True)
65
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
66
+
67
+ # 离开 async with 时,连接会自动 rollback (如果出错) 并归还给 pool
68
+
69
+ # --- 6. 历史记录保存 (连接归还后单独进行) ---
70
+ # 此时 conn 已经还回去了,我们用 SQLAlchemy 的新连接存历史
71
+ if final_response:
72
+ async with AsyncSessionLocal() as session:
73
+ try:
74
+ await save_chat_history(
75
+ session, body.session_id, body.message, final_response
76
+ )
77
+ except Exception as e:
78
+ logger.error(f"History save failed: {e}")
79
+
80
+ return StreamingResponse(event_generator(), media_type="text/event-stream")
app/core/config.py CHANGED
@@ -1,39 +1,57 @@
1
  import os
2
- import logging
3
  from functools import lru_cache
4
 
 
5
  class Config:
6
  """Base configuration."""
 
7
  APP_ENV = os.getenv("APP_ENV", "development")
8
-
9
  # Server
10
  HOST = os.getenv("HOST", "127.0.0.1")
11
  PORT = int(os.getenv("PORT", 8181))
12
-
13
  # Nacos
14
- NACOS_SERVER_ADDR = os.getenv("NACOS_SERVER_ADDR", "pei.12277.xyz:18848")
15
  NACOS_NAMESPACE = os.getenv("NACOS_NAMESPACE", "public")
16
- NACOS_USERNAME = os.getenv("NACOS_USERNAME", "nacos")
17
- NACOS_PASSWORD = os.getenv("NACOS_PASSWORD", "nacos")
18
  SERVICE_NAME = os.getenv("SERVICE_NAME", "python-agent")
19
-
20
  # MCP Clients
21
- MCP_BRAVE_PATH = os.getenv("MCP_BRAVE_PATH") # Optional override
22
  NACOS_GATEWAY_SERVICE_NAME = os.getenv("NACOS_GATEWAY_SERVICE_NAME", "gateway")
23
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  class DevelopmentConfig(Config):
25
  """Development configuration."""
 
26
  DEBUG = True
27
- # In Dev, we might want to default to localhost if not specified,
28
  # but the user's current valid config points to an external Nacos.
29
  # We'll keep the external Nacos as default for now based on current working code.
30
  pass
31
 
 
32
  class ProductionConfig(Config):
33
  """Production configuration."""
 
34
  DEBUG = False
35
  # Enforce stricter defaults or require env vars here if needed
36
 
 
37
  @lru_cache()
38
  def get_settings():
39
  env = os.getenv("APP_ENV", "development")
@@ -41,4 +59,5 @@ def get_settings():
41
  return ProductionConfig()
42
  return DevelopmentConfig()
43
 
 
44
  settings = get_settings()
 
1
  import os
2
+
3
  from functools import lru_cache
4
 
5
+
6
  class Config:
7
  """Base configuration."""
8
+
9
  APP_ENV = os.getenv("APP_ENV", "development")
10
+
11
  # Server
12
  HOST = os.getenv("HOST", "127.0.0.1")
13
  PORT = int(os.getenv("PORT", 8181))
14
+
15
  # Nacos
16
+ NACOS_SERVER_ADDR = os.getenv("NACOS_SERVER_ADDR", "127.0.0.1:8848")
17
  NACOS_NAMESPACE = os.getenv("NACOS_NAMESPACE", "public")
18
+ NACOS_USERNAME = os.getenv("NACOS_USERNAME", "")
19
+ NACOS_PASSWORD = os.getenv("NACOS_PASSWORD", "")
20
  SERVICE_NAME = os.getenv("SERVICE_NAME", "python-agent")
21
+
22
  # MCP Clients
23
+ MCP_BRAVE_PATH = os.getenv("MCP_BRAVE_PATH") # Optional override
24
  NACOS_GATEWAY_SERVICE_NAME = os.getenv("NACOS_GATEWAY_SERVICE_NAME", "gateway")
25
 
26
+ # Database
27
+ PG_HOST = os.getenv("PG_HOST", "localhost")
28
+ PG_PORT = int(os.getenv("PG_PORT", 5432))
29
+ PG_USER = os.getenv("PG_USER", "postgres")
30
+ PG_PASSWORD = os.getenv("PG_PASSWORD", "postgres")
31
+ PG_DB = os.getenv("PG_DB", "postgres")
32
+ DB_URI = f"postgresql://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{PG_DB}"
33
+ DB_ASYNC_URI = (
34
+ f"postgresql+psycopg://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{PG_DB}"
35
+ )
36
+
37
+
38
  class DevelopmentConfig(Config):
39
  """Development configuration."""
40
+
41
  DEBUG = True
42
+ # In Dev, we might want to default to localhost if not specified,
43
  # but the user's current valid config points to an external Nacos.
44
  # We'll keep the external Nacos as default for now based on current working code.
45
  pass
46
 
47
+
48
  class ProductionConfig(Config):
49
  """Production configuration."""
50
+
51
  DEBUG = False
52
  # Enforce stricter defaults or require env vars here if needed
53
 
54
+
55
  @lru_cache()
56
  def get_settings():
57
  env = os.getenv("APP_ENV", "development")
 
59
  return ProductionConfig()
60
  return DevelopmentConfig()
61
 
62
+
63
  settings = get_settings()
app/core/database.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
2
+ from sqlalchemy.orm import sessionmaker, declarative_base
3
+ from sqlalchemy import Column, String, Text, DateTime, BigInteger, func
4
+ from app.core.config import settings
5
+
6
+
7
+ engine = create_async_engine(
8
+ settings.DB_ASYNC_URI,
9
+ echo=False,
10
+ max_overflow=10,
11
+ # 🔥 关键配置:开启预检查,彻底解决 server closed connection 报错
12
+ pool_pre_ping=True,
13
+ # 以此配置,SQLAlchemy 会自动处理断开的连接
14
+ pool_size=20,
15
+ pool_recycle=3600,
16
+ )
17
+ AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
18
+ Base = declarative_base()
19
+
20
+
21
+ class ChatMessageModel(Base):
22
+ __tablename__ = "chat_messages"
23
+
24
+ id = Column(BigInteger, primary_key=True, autoincrement=True)
25
+ session_id = Column(String(255), nullable=False, index=True)
26
+ role = Column(String(50), nullable=False) # 'user' or 'ai'
27
+ content = Column(Text, nullable=False)
28
+ created_at = Column(DateTime(timezone=True), server_default=func.now())
29
+
30
+
31
+ async def get_db():
32
+ async with AsyncSessionLocal() as session:
33
+ yield session
34
+
35
+
36
+ async def init_db():
37
+ async with engine.begin() as conn:
38
+ await conn.run_sync(Base.metadata.create_all)
app/core/lifecycle.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from contextlib import asynccontextmanager
4
+ from fastapi import FastAPI
5
+ from psycopg_pool import AsyncConnectionPool
6
+ from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
7
+
8
+ from app.core.config import settings
9
+ from app.core.nacos import nacos_manager
10
+ from app.core.database import engine, init_db
11
+ from app.core.mcp_initialization import setup_mcp_clients, connect_clients
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # 定义一个全局集合,用来存放后台任务的引用,防止被 GC
16
+ background_tasks = set()
17
+
18
+
19
+ # 🔥 配置函数:禁用 Prepared Statements (解决 consuming input failed)
20
+ async def configure_conn(conn):
21
+ conn.prepare_threshold = None
22
+
23
+
24
+ @asynccontextmanager
25
+ async def lifespan(app: FastAPI):
26
+ # --- Startup Logic ---
27
+ logger.info("Agent starting up...")
28
+
29
+ # 1. 初始化业务数据库 (SQLAlchemy)
30
+ try:
31
+ logger.info("⚡ Initializing database tables...")
32
+ await init_db()
33
+ logger.info("✅ Database initialized successfully.")
34
+ except Exception as e:
35
+ logger.error(f"❌ Database initialization failed: {e}")
36
+ # 建议抛出异常,数据库连不上服务启动也没意义
37
+ raise e
38
+
39
+ # 2. 🔥 初始化 LangGraph 专用连接池 (Psycopg)
40
+ # 清洗 URI,确保它是标准的 postgresql:// 格式
41
+ pg_uri = str(settings.DB_URI).replace("+asyncpg", "").replace("+psycopg", "")
42
+
43
+ app.state.lg_pool = AsyncConnectionPool(
44
+ conninfo=pg_uri,
45
+ max_size=20,
46
+ min_size=1, # 保持最小连接数
47
+ # ✅ 关键配置 A: 借出时检查连接健康度
48
+ check=AsyncConnectionPool.check_connection,
49
+ # ✅ 关键配置 B: 禁用预编译语句
50
+ configure=configure_conn,
51
+ # ✅ 关键配置 C: 强制连接 10分钟轮转
52
+ max_lifetime=600,
53
+ kwargs={
54
+ "autocommit": True,
55
+ "keepalives": 1,
56
+ "keepalives_idle": 30,
57
+ "keepalives_interval": 10,
58
+ "keepalives_count": 5,
59
+ },
60
+ )
61
+ await app.state.lg_pool.open()
62
+ logger.info("✅ LangGraph Checkpoint Pool created.")
63
+
64
+ # 3. 运行 Setup (确保表结构存在)
65
+ try:
66
+ async with app.state.lg_pool.connection() as conn:
67
+ # 显式开启 autocommit (虽然 pool 已经设了,但保险起见)
68
+ await conn.set_autocommit(True)
69
+ logger.info("⚙️ Running LangGraph table setup...")
70
+ checkpointer = AsyncPostgresSaver(conn)
71
+ await checkpointer.setup()
72
+ logger.info("✅ LangGraph tables setup complete.")
73
+ except Exception as e:
74
+ logger.warning(f"⚠️ LangGraph setup warning: {e}")
75
+
76
+ # 4. 🔥 Nacos 连接与注册 (异步非阻塞重试)
77
+ max_retries = 3
78
+ for i in range(max_retries):
79
+ try:
80
+ # 注意:如果 nacos_manager.connect 是同步阻塞的,
81
+ # 在高并发下建议放到 run_in_executor,但在启动阶段勉强可以接受
82
+ nacos_manager.connect()
83
+ nacos_manager.register_service()
84
+ logger.info("✅ Nacos connected and service registered.")
85
+ break
86
+ except Exception as e:
87
+ if i < max_retries - 1:
88
+ logger.warning(
89
+ f"⚠️ Nacos connection failed, retrying in 2s ({i + 1}/{max_retries})..."
90
+ )
91
+ # ✅✅✅ 必须使用 await asyncio.sleep,不能用 time.sleep
92
+ await asyncio.sleep(2)
93
+ else:
94
+ logger.error("❌ Nacos connection failed after retries.")
95
+ # raise e # 根据需要决定是否终止启动
96
+
97
+ # 5. Setup MCP Clients
98
+ try:
99
+ await setup_mcp_clients()
100
+ except Exception as e:
101
+ logger.error(f"❌ MCP Setup failed: {e}")
102
+
103
+ # 6. 启动后台任务
104
+ task = asyncio.create_task(connect_clients())
105
+ background_tasks.add(task)
106
+ task.add_done_callback(background_tasks.discard)
107
+
108
+ yield
109
+
110
+ # --- Shutdown Logic ---
111
+ logger.info("Agent shutting down...")
112
+
113
+ # 7. 资源清理
114
+ try:
115
+ nacos_manager.deregister_service()
116
+ except Exception:
117
+ pass
118
+
119
+ # 关闭数据库
120
+ await engine.dispose() # 关闭 SQLAlchemy
121
+ await app.state.lg_pool.close() # 关闭 LangGraph Pool
122
+ logger.info("✅ Database resources released.")
app/{setup.py → core/mcp_initialization.py} RENAMED
@@ -9,29 +9,32 @@ from app.core.config import settings
9
 
10
  logger = logging.getLogger(__name__)
11
 
 
12
  async def setup_mcp_clients():
13
  # 1. Stdio Client (e.g., Brave Search)
14
  # We'll use a placeholder command or the one requested if we can find it.
15
  # The user mentioned "Node.js MCP Server (如 Brave Search)".
16
  # Let's assume the user has npx and the package.
17
-
18
  # Check config first, then fall back to auto-discovery
19
  npx_path = settings.MCP_BRAVE_PATH or shutil.which("npx")
20
 
21
  # 2. 安全检查:如果没有安装 Node.js/npx,提前报错
22
  if not npx_path:
23
- raise FileNotFoundError("未找到 npx 命令,请确保已安装 Node.js 并添加到环境变量中,或在配置中指定路径。")
 
 
24
 
25
  # 3. 初始化客户端
26
  brave_client = StdioMCPClient(
27
  name="brave-search",
28
  command=npx_path, # 传入绝对路径,如 "C:\...\npx.cmd"
29
- args=["-y", "@modelcontextprotocol/server-brave-search"]
30
  )
31
  # We register it but connection happens async
32
  # await brave_client.connect() # Connect in background
33
  register_mcp_client(brave_client)
34
-
35
  # 2. SSE Client (Java Service)
36
  # Discover via Nacos
37
  # In a real app we might poll or wait for service to be available.
@@ -39,11 +42,13 @@ async def setup_mcp_clients():
39
  # Wait, the java service is running? User said "run time query".
40
  pass
41
 
 
42
  async def connect_clients():
43
  # Connect Stdio
44
  try:
45
  # We need to find the client from registry
46
  from app.services.mcp_client import mcp_clients
 
47
  if "brave-search" in mcp_clients:
48
  await mcp_clients["brave-search"].connect()
49
  except Exception as e:
@@ -56,14 +61,16 @@ async def connect_clients():
56
  if instances:
57
  # Pick one
58
  target = instances[0]
59
- ip = target['ip']
60
- port = target['port']
61
  url = f"http://{ip}:{port}"
62
  sse_client = SSEMCPClient(name="java-service", base_url=url)
63
  # await sse_client.connect()
64
  register_mcp_client(sse_client)
65
  logger.info(f"Registered SSE client for Java service at {url}")
66
  else:
67
- logger.warning(f"No {settings.NACOS_GATEWAY_SERVICE_NAME} service found in Nacos")
 
 
68
  except Exception as e:
69
  logger.error(f"Failed to setup SSE client: {e}")
 
9
 
10
  logger = logging.getLogger(__name__)
11
 
12
+
13
  async def setup_mcp_clients():
14
  # 1. Stdio Client (e.g., Brave Search)
15
  # We'll use a placeholder command or the one requested if we can find it.
16
  # The user mentioned "Node.js MCP Server (如 Brave Search)".
17
  # Let's assume the user has npx and the package.
18
+
19
  # Check config first, then fall back to auto-discovery
20
  npx_path = settings.MCP_BRAVE_PATH or shutil.which("npx")
21
 
22
  # 2. 安全检查:如果没有安装 Node.js/npx,提前报错
23
  if not npx_path:
24
+ raise FileNotFoundError(
25
+ "未找到 npx 命令,请确保已安装 Node.js 并添加到环境变量中,或在配置中指定路径。"
26
+ )
27
 
28
  # 3. 初始化客户端
29
  brave_client = StdioMCPClient(
30
  name="brave-search",
31
  command=npx_path, # 传入绝对路径,如 "C:\...\npx.cmd"
32
+ args=["-y", "@modelcontextprotocol/server-brave-search"],
33
  )
34
  # We register it but connection happens async
35
  # await brave_client.connect() # Connect in background
36
  register_mcp_client(brave_client)
37
+
38
  # 2. SSE Client (Java Service)
39
  # Discover via Nacos
40
  # In a real app we might poll or wait for service to be available.
 
42
  # Wait, the java service is running? User said "run time query".
43
  pass
44
 
45
+
46
  async def connect_clients():
47
  # Connect Stdio
48
  try:
49
  # We need to find the client from registry
50
  from app.services.mcp_client import mcp_clients
51
+
52
  if "brave-search" in mcp_clients:
53
  await mcp_clients["brave-search"].connect()
54
  except Exception as e:
 
61
  if instances:
62
  # Pick one
63
  target = instances[0]
64
+ ip = target["ip"]
65
+ port = target["port"]
66
  url = f"http://{ip}:{port}"
67
  sse_client = SSEMCPClient(name="java-service", base_url=url)
68
  # await sse_client.connect()
69
  register_mcp_client(sse_client)
70
  logger.info(f"Registered SSE client for Java service at {url}")
71
  else:
72
+ logger.warning(
73
+ f"No {settings.NACOS_GATEWAY_SERVICE_NAME} service found in Nacos"
74
+ )
75
  except Exception as e:
76
  logger.error(f"Failed to setup SSE client: {e}")
app/core/nacos.py CHANGED
@@ -5,62 +5,114 @@ from app.core.config import settings
5
 
6
  logger = logging.getLogger(__name__)
7
 
 
8
  class NacosManager:
9
- def __init__(self, server_addr, username, password, namespace, service_name, ip=None, port=8181):
 
 
 
 
 
 
 
 
 
 
10
  self.server_addr = server_addr
11
  self.namespace = namespace
12
  self.service_name = service_name
13
  self.port = port
14
  self.ip = ip or self._get_local_ip()
15
- self.client = nacos.NacosClient(
16
- server_addr,
17
- namespace=namespace,
18
- username=username,
19
- password=password
20
- )
 
21
 
22
  def _get_local_ip(self):
23
  try:
24
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
25
- # Doesn't even have to be reachable
26
- s.connect(('10.255.255.255', 1))
27
  IP = s.getsockname()[0]
28
  except Exception:
29
- IP = '127.0.0.1'
30
  finally:
31
  s.close()
32
  return IP
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def register_service(self):
 
 
 
 
35
  try:
36
- # 🔥【关键修复】必须手动指定这两个参数,否则 0.1.15 配合 Nacos 2.x 必死
37
- self.client.add_naming_instance(self.service_name, self.ip, self.port,cluster_name="DEFAULT",
38
- heartbeat_interval=5, # <--- 加在这里!强制定义心跳间隔
39
- ephemeral=True)
40
- logger.info(f"Registered service {self.service_name} at {self.ip}:{self.port}")
 
 
 
 
 
 
 
41
  except Exception as e:
42
- logger.error(f"Failed to register service: {e}")
 
43
 
44
  def deregister_service(self):
 
 
 
45
  try:
46
  self.client.remove_naming_instance(self.service_name, self.ip, self.port)
47
- logger.info(f"Deregistered service {self.service_name}")
48
  except Exception as e:
49
  logger.error(f"Failed to deregister service: {e}")
50
-
51
  def get_service(self, service_name):
 
 
 
52
  try:
53
  return self.client.list_naming_instance(service_name)
54
  except Exception as e:
55
  logger.error(f"Failed to get service {service_name}: {e}")
56
  return []
57
 
 
58
  # Singleton instance
 
59
  nacos_manager = NacosManager(
60
  server_addr=settings.NACOS_SERVER_ADDR,
61
  namespace=settings.NACOS_NAMESPACE,
62
  username=settings.NACOS_USERNAME,
63
  password=settings.NACOS_PASSWORD,
64
  service_name=settings.SERVICE_NAME,
65
- port=settings.PORT
66
  )
 
5
 
6
  logger = logging.getLogger(__name__)
7
 
8
+
9
  class NacosManager:
10
+ def __init__(
11
+ self,
12
+ server_addr,
13
+ username,
14
+ password,
15
+ namespace,
16
+ service_name,
17
+ ip=None,
18
+ port=8181,
19
+ ):
20
+ # 1. 保存基础配置
21
  self.server_addr = server_addr
22
  self.namespace = namespace
23
  self.service_name = service_name
24
  self.port = port
25
  self.ip = ip or self._get_local_ip()
26
+
27
+ # 2. 保存凭证 (因为连接推迟了,所以必须先存起来)
28
+ self.username = username
29
+ self.password = password
30
+
31
+ # 3. 🔥 关键修改:初始化时 client 设为 None,不立即连接
32
+ self.client = None
33
 
34
  def _get_local_ip(self):
35
  try:
36
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
37
+ s.connect(("10.255.255.255", 1))
 
38
  IP = s.getsockname()[0]
39
  except Exception:
40
+ IP = "127.0.0.1"
41
  finally:
42
  s.close()
43
  return IP
44
 
45
+ def connect(self):
46
+ """
47
+ 🔥 新增方法:显式建立连接
48
+ 只有在 main.py 的 lifespan 中调用此方法时,才会真正发起网络请求
49
+ """
50
+ if self.client:
51
+ return # 已经连过了,直接返回
52
+
53
+ try:
54
+ logger.info(f"🔌 Connecting to Nacos at {self.server_addr}...")
55
+ self.client = nacos.NacosClient(
56
+ self.server_addr,
57
+ namespace=self.namespace,
58
+ username=self.username,
59
+ password=self.password,
60
+ )
61
+ logger.info("✅ Connected to Nacos successfully.")
62
+ except Exception as e:
63
+ logger.error(f"❌ Failed to connect to Nacos: {e}")
64
+ raise e # 抛出异常,让外部的重试逻辑捕获
65
+
66
  def register_service(self):
67
+ # 如果还没连接,先尝试连接
68
+ if not self.client:
69
+ self.connect()
70
+
71
  try:
72
+ # 🔥 这里的配置保持你之前的修复逻辑不变
73
+ self.client.add_naming_instance(
74
+ self.service_name,
75
+ self.ip,
76
+ self.port,
77
+ cluster_name="DEFAULT",
78
+ heartbeat_interval=10,
79
+ ephemeral=True,
80
+ )
81
+ logger.info(
82
+ f"✅ Registered service {self.service_name} at {self.ip}:{self.port}"
83
+ )
84
  except Exception as e:
85
+ logger.error(f"❌ Failed to register service: {e}")
86
+ # 这里可以选择是否抛出异常,取决于你希望注册失败是否影响启动
87
 
88
  def deregister_service(self):
89
+ if not self.client:
90
+ return
91
+
92
  try:
93
  self.client.remove_naming_instance(self.service_name, self.ip, self.port)
94
+ logger.info(f"✅ Deregistered service {self.service_name}")
95
  except Exception as e:
96
  logger.error(f"Failed to deregister service: {e}")
97
+
98
  def get_service(self, service_name):
99
+ if not self.client:
100
+ self.connect()
101
+
102
  try:
103
  return self.client.list_naming_instance(service_name)
104
  except Exception as e:
105
  logger.error(f"Failed to get service {service_name}: {e}")
106
  return []
107
 
108
+
109
  # Singleton instance
110
+ # 🔥 这里实例化现在是非常安全的,因为它只赋值变量,不发请求
111
  nacos_manager = NacosManager(
112
  server_addr=settings.NACOS_SERVER_ADDR,
113
  namespace=settings.NACOS_NAMESPACE,
114
  username=settings.NACOS_USERNAME,
115
  password=settings.NACOS_PASSWORD,
116
  service_name=settings.SERVICE_NAME,
117
+ port=settings.PORT,
118
  )
app/services/chat_graph.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Annotated, TypedDict
2
+ from langchain_core.messages import AIMessage, BaseMessage
3
+ from langgraph.graph import StateGraph, END
4
+ from langgraph.graph.message import add_messages
5
+ from app.core.database import ChatMessageModel
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class ChatState(TypedDict):
12
+ messages: Annotated[list[BaseMessage], add_messages]
13
+
14
+
15
+ # Define a simple graph
16
+ def agent_node(state: ChatState):
17
+ # Mock LLM logic for now
18
+ last_message = state["messages"][-1]
19
+ response = AIMessage(content=f"Echo: {last_message.content}")
20
+ return {"messages": [response]}
21
+
22
+
23
+ workflow = StateGraph(ChatState)
24
+ workflow.add_node("agent", agent_node)
25
+ workflow.set_entry_point("agent")
26
+ workflow.add_edge("agent", END)
27
+
28
+
29
+ async def save_chat_history(session, session_id, human_msg, ai_msg):
30
+ # session 是 SQLAlchemy 的 AsyncSession
31
+ try:
32
+ user_msg = ChatMessageModel(
33
+ session_id=session_id, role="user", content=human_msg
34
+ )
35
+ ai_msg = ChatMessageModel(session_id=session_id, role="ai", content=ai_msg)
36
+
37
+ session.add(user_msg)
38
+ session.add(ai_msg)
39
+
40
+ await session.commit() # 提交事务
41
+ except Exception as e:
42
+ await session.rollback()
43
+ raise e
main.py CHANGED
@@ -1,61 +1,18 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel
3
  import uvicorn
4
- from contextlib import asynccontextmanager
5
- from app.core.nacos import nacos_manager
6
- from app.setup import setup_mcp_clients, connect_clients
7
- from app.agent.graph import graph
8
- from langchain_core.messages import HumanMessage
9
- import logging
10
- import asyncio
11
 
12
- logging.basicConfig(level=logging.INFO)
13
- logger = logging.getLogger(__name__)
14
-
15
- # 定义一个全局集合,用来存放后台任务的引用,防止被 GC
16
- background_tasks = set()
17
-
18
- @asynccontextmanager
19
- async def lifespan(app: FastAPI):
20
- # Startup logic
21
- logger.info("Agent starting up...")
22
- nacos_manager.register_service()
23
-
24
- # Setup and connect MCP clients
25
- await setup_mcp_clients()
26
- # connect_clients needs to run after startup potentially or concurrency
27
- task = asyncio.create_task(connect_clients())
28
- background_tasks.add(task)
29
- # 当任务完成时,自动从集合中移除,避免内存泄漏
30
- task.add_done_callback(background_tasks.discard)
31
-
32
- yield
33
- # Shutdown logic
34
- logger.info("Agent shutting down...")
35
- nacos_manager.deregister_service()
36
 
37
  app = FastAPI(lifespan=lifespan)
 
 
38
 
39
  @app.get("/health")
40
  async def health():
41
  return {"status": "ok"}
42
 
43
- class ChatRequest(BaseModel):
44
- message: str
45
-
46
- @app.post("/chat")
47
- async def chat(request: ChatRequest):
48
- try:
49
- inputs = {"messages": [HumanMessage(content=request.message)]}
50
- result = await graph.ainvoke(inputs)
51
- # Extract final message
52
- last_message = result['messages'][-1]
53
- return {"response": last_message.content, "state": result}
54
- except Exception as e:
55
- logger.error(f"Error during chat: {e}")
56
- raise HTTPException(status_code=500, detail=str(e))
57
-
58
- from app.core.config import settings
59
 
60
  if __name__ == "__main__":
61
  uvicorn.run(app, host=settings.HOST, port=settings.PORT)
 
 
 
1
  import uvicorn
2
+ from fastapi import FastAPI
 
 
 
 
 
 
3
 
4
+ from app.core.config import settings
5
+ from app.core.lifecycle import lifespan
6
+ from app.api.routers import chat
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  app = FastAPI(lifespan=lifespan)
9
+ app.include_router(chat.router, tags=["chat"])
10
+
11
 
12
  @app.get("/health")
13
  async def health():
14
  return {"status": "ok"}
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  if __name__ == "__main__":
18
  uvicorn.run(app, host=settings.HOST, port=settings.PORT)
requirements.txt CHANGED
@@ -5,4 +5,9 @@ langgraph
5
  nacos-sdk-python
6
  httpx
7
  sseclient-py
8
- "mcp[sse]"
 
 
 
 
 
 
5
  nacos-sdk-python
6
  httpx
7
  sseclient-py
8
+ mcp[sse]
9
+ psycopg[binary]
10
+ sqlalchemy
11
+ langgraph-checkpoint-postgres
12
+ psycopg-pool
13
+ python-dotenv
run.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 文件名: run.py
2
+ import sys
3
+ import asyncio
4
+ import uvicorn
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+ # 🔥 1. 最关键的一步:在导入 Uvicorn 运行逻辑之前,强制修改 Windows 策略
10
+ # 这会影响当前进程
11
+ if sys.platform == "win32":
12
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
13
+
14
+ if __name__ == "__main__":
15
+ # 🔥 2. 启动 Uvicorn
16
+ # 注意:在 Windows 上使用 SelectorLoop 时,reload=True 可能会在某些情况下失效或报错
17
+ # 如果遇到子进程报错,建议暂时把 reload 改为 False 调试,或者忍受启动时的警告
18
+ print(
19
+ f"🚀 正在使用 {asyncio.get_event_loop_policy().__class__.__name__} 启动服务..."
20
+ )
21
+
22
+ uvicorn.run(
23
+ "main:app",
24
+ host="192.168.50.128",
25
+ port=8181,
26
+ reload=True, # 开发环境开启热重载
27
+ )
tests/verify_graph.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import sys
4
+ from app.core.database import engine, init_db
5
+ from app.core.config import settings
6
+ from psycopg_pool import AsyncConnectionPool
7
+ from app.agent.factory import get_graph_runnable
8
+ from langchain_core.messages import HumanMessage
9
+
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ if sys.platform == "win32":
14
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
15
+
16
+
17
+ async def verify():
18
+ print("Verifying Unified Driver Implementation...")
19
+ lg_pool = None
20
+ try:
21
+ # 1. Initialize DB Tables
22
+ await init_db()
23
+
24
+ # 2. Setup Pool for LangGraph
25
+ pg_uri = str(settings.DB_URI).replace("+asyncpg", "").replace("+psycopg", "")
26
+ lg_pool = AsyncConnectionPool(
27
+ conninfo=pg_uri, max_size=1, kwargs={"autocommit": True}
28
+ )
29
+ await lg_pool.open()
30
+
31
+ # 3. Get Runnable & Invoke
32
+ async with lg_pool.connection() as conn:
33
+ # This will internally assert that db_manager.langgraph_pool is ready
34
+ graph = await get_graph_runnable(conn)
35
+ print("Graph runnable obtained.")
36
+
37
+ # 4. Invoke Graph
38
+ print("Invoking graph...")
39
+ config = {"configurable": {"thread_id": "verify_unified_1"}}
40
+ input_message = HumanMessage(content="Hello, unified world!")
41
+
42
+ final_response = ""
43
+ async for event in graph.astream_events(
44
+ {"messages": [input_message]}, config, version="v1"
45
+ ):
46
+ kind = event["event"]
47
+ if kind == "on_chain_end":
48
+ if event["name"] == "agent":
49
+ output_messages = event["data"]["output"]["messages"]
50
+ if output_messages:
51
+ ai_message = output_messages[-1]
52
+ final_response = ai_message.content
53
+ print(f"AI Response: {final_response}")
54
+
55
+ if "Echo: Hello, unified world!" in final_response:
56
+ print("SUCCESS: Graph returned expected response.")
57
+ else:
58
+ print(f"FAILURE: Unexpected response: {final_response}")
59
+
60
+ except Exception as e:
61
+ print(f"ERROR: {e}")
62
+ import traceback
63
+
64
+ traceback.print_exc()
65
+ finally:
66
+ if lg_pool:
67
+ await lg_pool.close()
68
+ await engine.dispose()
69
+
70
+
71
+ if __name__ == "__main__":
72
+ try:
73
+ asyncio.run(verify())
74
+ except KeyboardInterrupt:
75
+ pass