受限环境中基于 Copilot API 构建 ReAct MCP Agent
在银行等金融 IT 环境中,LLM 应用落地往往面临着严苛的限制。最典型的一道坎是:我们只能使用公司内部提供的 LLM API(如 Copilot API),而这些 API 往往是不完整的。
本文将复盘一次真实的架构演进:当我们的基础模型不支持标准的 Function Calling (bind_tools) 时,如何通过 ReAct 模式 和 Model Context Protocol (MCP),手动构建一个强大的、支持工具调用的智能 Agent。
1. 交互全景图 (Architecture Overview)
在深入代码细节之前,让我们先通过一张时序图来俯瞰整个系统的请求流转过程。
MCP Server (GitHub) -> Copilot API (BaseChatModel) -> GithubReactAgent (Expert) -> MainAgent (Router)
PostgreSQL <- ChatService <- ChatRouter (FastAPI) <- 前端用户
第一阶段:请求接收与上下文加载
POST /chat ("列出我的 repo")
初始化 (Inject GithubAgent)
stream_chat_response(request, MainAgent)
INSERT User Message ("列出我的 repo")
SELECT Chat History (limit=20)
History Records
去重 (Remove Duplicate User Input)
第二阶段:主 Agent 路由思考
astream("列出我的 repo", history)
System Prompt (Tools Def) + History + InputChunk: ```json { "action": "delegate_to_github" } ```
拦截 JSON,生成友好提示
Yield: "[System: Asking GitHub Agent...]"
第三阶段:子 Agent 执行与工具调用
astream("列出我的 repo")
System Prompt (GitHub Tools) + InputChunk: ```json { "action": "get_repo_list" } ```
拦截 JSON
Yield: "[Thinking: Calling get_repo_list...]"
call_tool("get_repo_list", args)
Tool Result (JSON List)
Observation: Tool Result
第四阶段:响应持久化
Final Answer ("这里是您的仓库列表...")
Yield Final Answer
Yield Final Answer
Stream Response Token Token
Assistant Message ( Response)

