AI助手路由工具

一个生产级的个人AI助手,利用LangGraph和GPT-4.1-mini构建,能够智能路由自然语言查询到Web搜索和GitHub,并合成单一连贯的响应。

  • by NisargKadam
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 NisargKadam/Personal_GitHub_Assistant_MCP

使用说明

Nisarg Kadam技术处理员

用LangGraph和GPT-4.1-mini构建的生产级个人人工智能助理。接受自然语言查询,并将其智能地路由到网络搜索(DuckDuckGo)和GitHub(通过MCP),然后合成一个连贯的响应。


架构概述

User Query
    |
    v
[Planner Node]        -- GPT-4.1-mini extracts intent and parameters as JSON
    |
    v
[Router Node]         -- Conditionally routes based on intent
    |
    +---> [Executor Node]   -- Runs tools concurrently via asyncio.gather
    |           |
    v           v
[Synthesizer Node]    -- GPT-4.1-mini generates a natural language response
    |
    v
[Finalizer Node]      -- Standardizes output shape for the API
    |
    v
POST /chat  ->  { response, tools_used, metadata }

LangGraph图形流

该图是一个有向结构,由 StateGraph(AgentState).

节点 角色
Planner 使用结构化JSON提示符调用GPT-4.1-mini,对意图进行分类并提取参数
路由器 读取 intent 从州-路线到 executor 如果需要工具,否则直接 synthesizer
执行器 分派工具协程 asyncio.gather --工具同时运行
合成器 将所有工具输出传递回GPT-4.1-mini以写入最终响应
Finalizer 清理输出字典,设置 response_ready: true 在元数据中

条件边:

graph.add_conditional_edges(
    "router",
    route_decision,          # returns "executor" or "synthesizer"
    {"executor": "executor", "synthesizer": "synthesizer"}
)

工具

网络搜索--DuckDuckGo(app/tools/web_search.py)

  • 使用 ddgs Python库(开源,不需要API密钥)
  • 在内部运行同步DDGS调用 asyncio.to_thread 保持非阻塞状态
  • 最多返回6个结果:标题、代码段、链接、源代码
  • 零设置——开箱即用

通过MCP访问GitHub(app/tools/github_tool.py)

  • 与官方GitHub MCP服务器通信(@modelcontextprotocol/server-github)超过stdio
  • 作为npx子进程自动生成--无需手动启动服务器
  • 支持三个操作:
    • list_repos --列出配置的GitHub用户名的所有公共存储库
    • get_repo_details(repo_name) --获取特定仓库的README和元数据
    • summarize_repo(repo_name) --从README推断技术栈并返回结构化摘要
  • 需要Node.js 18+和GitHub个人访问令牌 repo + read:user 范围

MCP客户端(app/tools/mcp_client.py)

  • 通用异步上下文管理器包装 mcp 开发包
  • 管理 stdio_client + ClientSession 具有适当生命周期 __aenter__ / __aexit__
  • 暴露: call_tool, list_tools, list_resources, read_resource
  • 可以通过更改指向任何符合MCP的服务器 command 和 args

MCP的工作原理

模型上下文协议(MCP)是一个开放标准,用于通过stdio或HTTP上的JSON-RPC协议将AI助手连接到外部工具。

在本项目中:

  1. MCPClient.__aenter__ 生成 npx -y @modelcontextprotocol/server-github 作为子流程
  2. 通过进程stdin/stdout使用MCP有线协议进行通信
  3. session.initialize() 完成握手
  4. 工具调用通过 session.call_tool(tool_name, arguments)
  5. GitHub MCP服务器通过 GITHUB_PERSONAL_ACCESS_TOKEN

此模式是可交换的——用任何其他服务器(文件系统、Jira、Slack、Notion等)替换GitHub MCP服务器,而无需接触代理逻辑。


项目结构

.
├── app/
│   ├── main.py             FastAPI app initialization and uvicorn entry point
│   ├── graph.py            LangGraph StateGraph definition and compilation
│   ├── state.py            AgentState TypedDict
│   ├── config.py           Environment config loaded via python-dotenv
│   ├── nodes/
│   │   ├── planner.py      GPT-4.1-mini intent extraction (returns structured JSON)
│   │   ├── router.py       Conditional routing logic
│   │   ├── executor.py     Concurrent tool execution via asyncio.gather
│   │   ├── synthesizer.py  GPT-4.1-mini response generation from tool outputs
│   │   └── finalizer.py    Output standardization
│   └── tools/
│       ├── web_search.py   DuckDuckGo search via ddgs library
│       ├── mcp_client.py   Generic async MCP client
│       └── github_tool.py  GitHub via MCP server (list, detail, summarize)
├── api/
│   └── routes.py           FastAPI route definitions (POST /chat, GET /health)
├── requirements.txt
├── .env.example            Template — copy to .env and fill values
└── README.md

设置

先决条件

  • Python 3.12+
  • 带npx的Node.js 18+(适用于GitHub MCP服务器)
  • 可访问的OpenAI API密钥 gpt-4.1-mini
  • GitHub个人访问令牌

安装

git clone <your-repo>
cd Anthropic_MCP_Framework

python -m venv .venv
.venv\Scripts\activate          # Windows
# source .venv/bin/activate     # macOS / Linux

pip install -r requirements.txt

配置

copy .env.example .env

打开 .env 并填写:

OPENAI_API_KEY=sk-...

GITHUB_USERNAME=your-github-username
GITHUB_TOKEN=ghp_...

GitHub令牌: github/设置/令牌 → 生成新令牌(经典)→ 范围: repo, read:user

跑

python app/main.py

服务器启动时间 http://localhost:8000 Swagger用户界面位于 http://localhost:8000/docs


API 参考

POST/聊天

请求:

{
  "query": "string"
}

答复:

{
  "response": "string",
  "tools_used": ["web_search"],
  "metadata": {
    "intent": "web_search",
    "tools_failed": [],
    "planning_reasoning": "User is asking for recent information requiring a web search."
  }
}

GET/健康

{ "status": "ok", "service": "Nisarg Kadam Tech Handler" }

示例查询

网络搜索:

{ "query": "Search latest trends in agentic AI" }

GitHub——列出所有仓库:

{ "query": "List all my GitHub repositories" }

GitHub——仓库详细信息:

{ "query": "Explain my GitHub repository called nlp-pipeline" }

GitHub——技术栈:

{ "query": "What is the tech stack of my repo called ai-automation?" }

多意图:

{ "query": "Search for LangGraph best practices and also summarize my GitHub repos" }

直接(无工具):

{ "query": "What is the difference between LangChain and LangGraph?" }

环境变量

变量 必填 描述
OPENAI_API_KEY 是 OpenAI API密钥
GITHUB_USERNAME 是 您的GitHub用户名
GITHUB_TOKEN 是 GitHub PAT与 repo + read:user 范围
MCP_GITHUB_SERVER_COMMAND 否 默认为 npx
MODEL_NAME 否 默认为 gpt-4.1-mini
MAX_TOKENS 否 默认为 4096