内容
# ZP-2025 — 平台代理和工具
本仓库包含代码生成、审核和 Docker 运行代理,工具注册,MCP 服务器,Streamlit UI 和实验性流水线。主逻辑位于 `src/`,UI 位于 `UI/`,实验位于 `experiments/`。
## 快速开始
1. 安装依赖:
```bash
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
2. 运行 Docker(执行代码所需)。
3. 运行 UI:
```bash
streamlit run UI/StreamLitLangChain.py
```
## 架构图
```mermaid
sequenceDiagram
actor User
participant UI as Streamlit UI
participant Client as MCPClient
participant Server as MCPToolServer
participant Orchestrator as AgentOrchestrator
participant Dev as DeveloperAgent
participant Conv as ConversationAgent
participant Review as ReviewerAgent
participant Exec as ExecutorAgent
participant Registry as ToolRegistry
participant Tool as GeneratedScriptTool
participant Docker as DockerExecutor
participant LLM as UnifiedLLMClient
User->>UI: Send prompt
alt Conversational prompt
UI->>Client: chat(message, reset?)
Client->>Server: chat(message, reset?)
Server->>Orchestrator: chat(message, reset?)
Orchestrator->>Conv: Build reply from history + user message
Conv->>LLM: chat(messages)
LLM-->>Conv: assistant text
Conv-->>Orchestrator: response
Orchestrator-->>Server: response
Server->>Client: response
Client->>UI: stream/render text
else Code / tool / external-fact prompt
UI->>Client: run_pipeline(prompt, mode="chat")
Client->>Server: run_agent_pipeline(prompt, mode="chat")
Server->>Orchestrator: run_pipeline(prompt, mode="chat")
Orchestrator->>Registry: load_tool_instances()
Registry-->>Orchestrator: enabled saved tools
Orchestrator->>Dev: run(prompt, tools_info)
Dev->>LLM: chat(system+user messages)
LLM-->>Dev: ReAct output or Python code
Dev-->>Orchestrator: raw output
alt ReAct selected a saved tool
Orchestrator->>Tool: run(params)
Tool->>Docker: execute(tool script with TOOL_INPUT)
Docker-->>Tool: tool output
Tool->>Orchestrator: observation
Orchestrator->>Conv: final answer from observation
Conv->>LLM: chat(messages)
LLM-->>Conv: final answer
Conv-->>Orchestrator: response
else No tool selected, generate code
Orchestrator->>Review: run(code)
Review->>LLM: chat(review prompt)
LLM-->>Review: fixed code
Review-->>Orchestrator: reviewed code
Orchestrator->>Exec: validate(code)
Exec->>LLM: chat(validation prompt)
LLM-->>Exec: final code
Exec-->>Orchestrator: validated code
Orchestrator->>Docker: execute(validated code)
Docker-->>Orchestrator: runtime output
end
opt UI can save reusable generated code
UI->>Client: save_tool(code, task_description)
Client->>Server: save_tool(code, task_description)
Server->>Registry: save_tool(code, task_description)
Registry-->>Server: saved file path + enabled flag
Server->>Client: result
Client->>UI: success / error
end
end
```
这是实际运行的更准确的映射:UI 不总是通过流水线 — 在普通对话中,它可以直接通过 `chat()` 流式传输答案。只有技术、代码或工具请求才会启动整个流水线。
## 状态图(UML 状态机)
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> ClassifyIntent: user prompt
ClassifyIntent --> ConversationResponse: no code/tool/external intent
ClassifyIntent --> DeveloperStep: pipeline required
DeveloperStep --> ToolExecution: ReAct tool selected
DeveloperStep --> CodePipeline: no tool selected
ConversationResponse --> Finalize
ToolExecution --> Finalize
CodePipeline --> Finalize
Finalize --> Idle: ready for next prompt
```
## 主要组件
| 组件 | 路径 | 角色 |
| --- | --- | --- |
| MCP stdio 服务器 | `src/mcp/mcp_stdio_server.py` | MCP 服务器,用于与工具和提示进行 stdio 交互 |
| MCP 服务器(进程内) | `src/mcp/server.py` | 用于 UI/CLI 通过 Python API 调用的服务器 |
| MCP 客户端 | `src/mcp/client.py` | 用于管理工具和运行流水线的客户端 |
| 代理编排器 | `src/langchain_module/lc_agent.py` | 工具选择、ReAct、代码生成、执行 |
| 代理 | `src/langchain_module/agents/*.py` | 开发、审核、执行、对话代理 |
| 工具注册表 | `src/tools/registry.py` | 工具存储、启用和索引 |
| 生成的工具 | `src/generated_tools/` | 按类别存储的生成代码文件 |
| Docker 执行器 | `src/executors/docker_executor.py` | 安全的代码执行 |
| UI | `UI/StreamLitLangChain.py` | Streamlit 界面 |
## Auto Agent Chat 工作原理
UI 中的“Auto Agent Chat”模式使用 `MCPClient.run_pipeline(..., mode="chat")`。行为由 `AgentOrchestrator` 确定:
1. 如果请求看起来像普通对话,UI 可以直接进入 `client.stream_chat()` 或 `client.chat()` 而无需流水线。
2. 如果请求是技术性的,包含代码意图、外部事实或类似于现有工具,则启动 `run_pipeline(..., mode="chat")`。
3. `DeveloperAgent` 返回 ReAct `Action` 或生成 Python 代码块。
4. 如果找到 `Action`,则通过 `GeneratedScriptTool` 和 `DockerExecutor` 执行选定的保存工具。
5. 如果没有选择工具,则代码通过 `ReviewerAgent` → `ExecutorAgent.validate()` → `DockerExecutor.execute()`。
## ReAct 格式和解析
开发代理必须以以下格式之一响应:
```
Thought: ...
Action: tool_name
Action Input: {"key": "value"}
```
或代码块 ` ```python ``` `。解析发生在 `src/utils/react_parsing.py` 中。
## 工具和注册表
### 工具存储位置
工具存储在 `src/generated_tools/` 中,带有子类别:`Date/`、`Math/`、`Logic/`、`General/` 等。启用状态存储在 `src/generated_tools/.enabled_tools.json` 中。
### 工具格式
工具文件是带有开头的 Python 文件。注册表读取文档字符串和可用函数以构建元数据。
### 工具输入参数
`GeneratedScriptTool` 将输入传递给 `TOOL_INPUT` 变量。输入可以是:
- 字符串(简单调用)
- 字典(带有参数的 ReAct)
### 启用或禁用工具
1. 通过 UI(“Saved tools” 部分)。
2. 通过 MCP 客户端:
```python
from src.mcp.client import create_client
client = create_client(provider="openrouter", model="google/gemma-4-26b-a4b-it:free")
client.enable_tool("Date/tool_current_time_and_data")
```
## MCP 服务器
### MCP stdio 服务器
`src/mcp/mcp_stdio_server.py` 建立在 FastMCP 上,并公开:
| 工具 | 目的 |
| --- | --- |
| `generate_code` | 通过开发代理生成代码 |
| `review_code` | 代码审查 |
| `execute_code` | 验证和在 Docker 中执行 |
| `run_full_pipeline` | 整个生成 → 审查 → 执行链 |
| `chat_with_agent` | 带上下文的对话 |
| `list_tools` | 工具列表 |
| `toggle_tool` | 启用/禁用工具 |
| `save_new_tool` | 保存新工具 |
MCP 提示:
- `solve_task`:分步场景
- `full_pipeline`:一次性运行整个流水线
### MCP 进程内服务器
`src/mcp/server.py` — 用于从 Python 代码(UI/CLI)工作的服务器。具有相同的功能,但没有 stdio 传输。
### MCP 配置
`mcp_config.json` 文件描述了如何启动 MCP 服务器:
```
{
"mcpServers": {
"zp-agents": {
"command": "/path/to/.venv/bin/python",
"args": ["/path/to/src/mcp/mcp_stdio_server.py"],
"env": {
"LLM_PROVIDER": "openrouter",
"LLM_MODEL": "google/gemma-3-27b-it:free"
}
}
}
}
```
## 提供商和模型
支持:`azure`、`openai`、`groq`、`openrouter`、`gemini`、`ollama`、`huggingface`。
| 提供商 | 环境变量 |
| --- | --- |
| Azure | `AZURE_OPENAI_KEY`、`AZURE_OPENAI_ENDPOINT`、`AZURE_OPENAI_DEPLOYMENT`、`AZURE_OPENAI_API_VERSION` |
| OpenAI | `OPENAI_API_KEY` |
| Groq | `GROQ_API_KEY`、`GROQ_BASE_URL`(可选) |
| OpenRouter | `GEMINI_GEMMA_4` 或 `OPENROUTER_API_KEY`、`OPENROUTER_BASE_URL`、`OPENROUTER_REFERER`、`OPENROUTER_TITLE` |
| Gemini | `GEMINI_API_KEY2` 或 `GEMINI_API_KEY`、`GEMINI_BASE_URL` |
| Ollama | `OLLAMA_BASE_URL` |
| HuggingFace | `HUGGINGFACE_TOKEN`(用于门控模型) |
OpenRouter 有一个备用方案:遇到 429 错误时,可以切换到 Groq 或 Ollama。
## HuggingFace 直接模式
UI 中的“HuggingFace 直接”模式绕过代理流水线,直接调用 HuggingFace 模型:
- `bigcode/tiny_starcoder_py`(~200 MB)
- `microsoft/CodeGPT-small-py`(~500 MB)
- `Salesforce/codegen-350M-mono`(~700 MB)
此模式仅返回生成的代码,而不执行也不保存到注册表中。
## UI(Streamlit)
UI 位于 `UI/StreamLitLangChain.py`。
UI 功能:
- 与代理聊天
- 运行流水线
- 切换提供商和模型
- 查看和启用工具
- 在成功执行后建议保存新工具
交互模式:
| 模式 | 发生情况 |
| --- | --- |
| 自动代理聊天 | 对话流式传输,技术请求进入流水线 |
| HuggingFace 直接 | 通过 HF 进行即时代码生成 |
## Docker 执行
代码执行通过 `DockerExecutor` 进行:
- 禁用网络
- 仅读访问文件
- 内存限制 256 MB
- CPU 1 个核心
- 默认超时 30 秒
Docker 镜像从 `Dockerfile` 构建为 `python-executor:latest`。
## 从 CLI 运行
### LangChain + Ollama
```bash
python src/runners/lc_main.py
```
### AutoGPT(实验)
```bash
PYTHONPATH=experiments python src/runners/autogpt_main.py
```
### CrewAI(实验)
```bash
PYTHONPATH=experiments python src/runners/cw_main.py
```
### 直接调用 MCP 客户端示例
```bash
python run_task.py
```
## 实验
`experiments/` 包含流水线原型:
- `autoGpt_module` — 计划器、编码器、评论家 + TaskManager
- `crewai_module` — 代理 + 任务 + Crew
这些模块默认不连接到主 UI。
## 目录结构
```
UI/ Streamlit UI
src/ 主逻辑
src/mcp/ MCP 服务器和客户端
src/langchain_module/ 代理、编排器、流水线
src/tools/ 工具注册表和包装器
src/generated_tools/ 保存的工具
src/executors/ Docker 执行
experiments/ 原型
test/ 测试
test/experiments_archive/ 存档实验 — 模型测试结果
```
## 测试
```bash
make test
make test-unit
make test-integration
```
集成测试需要实际的 API 密钥和网络访问。
## 常见问题
| 症状 | 原因 | 解决方案 |
| --- | --- | --- |
| `Execution unavailable: Docker executor is not initialized` | Docker 未运行 | 启动 Docker |
| `Missing ... API key` | `.env` 中缺少密钥 | 添加相关变量 |
| 来自 OpenRouter 的 429 | 限制或配额 | 检查密钥或等待,存在备用方案 |
| HF 模型无法加载 | 缺少令牌或磁盘空间 | 添加 `HUGGINGFACE_TOKEN` 并检查可用空间 |