diff --git a/Agent Memory/AGENTS.md b/Agent Memory/AGENTS.md new file mode 100644 index 0000000..0e68fb3 --- /dev/null +++ b/Agent Memory/AGENTS.md @@ -0,0 +1,37 @@ +# Repository Guidelines + +## Project Structure & Module Organization +- `mini_agent/`: Core package — `agent.py` (loop), `cli.py` (entrypoint), `llm/` (model clients), `tools/` (file, shell, MCP, skills), `config/` (config templates), `acp/` (ACP server bindings). +- `tests/`: Pytest suites mirroring core modules; prefer adding new tests alongside related code. +- `docs/`: Development and production guides; sync updates here when changing behavior. +- `examples/` and `scripts/`: Usage samples and setup helpers (config bootstrap, submodule init). +- `workspace/`: Local scratch/cache folder created at runtime; keep it out of commits. + +## Build, Test, and Development Commands +- Install deps: `uv sync` (preferred) or `pip install -e .` for editable installs. +- Run the agent: `uv run mini-agent --workspace ./workspace` or `uv run python -m mini_agent.cli` for debug logging. +- ACP server: `uv run mini-agent-acp` (requires config matching your editor). +- Tests: `uv run pytest tests -v` or target modules, e.g., `uv run pytest tests/test_agent.py -k tool`. +- Update skills submodule (optional): `git submodule update --init --recursive`. + +## Coding Style & Naming Conventions +- Python 3.10+; follow PEP 8 with 4-space indents and type hints. Keep functions/methods `snake_case`, classes `PascalCase`, modules/files `snake_case`. +- Use pydantic models for request/response schemas; prefer explicit dataclasses for structured data. +- Keep tools subclassing `Tool` small and declarative; document side effects in docstrings. +- Logging: use `mini_agent.logger` helpers; avoid print statements. + +## Testing Guidelines +- Framework: pytest (async supported via `pytest-asyncio`). Place tests as `test_*.py` under `tests/`. +- Aim for fast unit coverage of tools/LLM clients plus integration paths through `agent.py` and CLI. +- When adding async tools, include `@pytest.mark.asyncio` and cover error branches. Mock network/API calls; do not hit real endpoints in CI. +- Run `uv run pytest tests -v` before submitting; keep fixtures lightweight to avoid flakiness. + +## Commit & Pull Request Guidelines +- Commit messages: follow the existing `type(scope): message` pattern (`feat`, `fix`, `docs`, `test`, `chore`, `refactor`, `style`). Example: `feat(tools): add csv summarizer`. +- Branches: `feature/` or `fix/` as in CONTRIBUTING. +- PRs should include: short description of behavior change, linked issues, config/compat notes, and test evidence (`pytest -v` output or summary). Add screenshots/GIFs when CLI UX changes. +- Keep PRs focused; avoid bundling unrelated refactors with feature work. + +## Security & Configuration Tips +- Never commit API keys; store runtime config in `mini_agent/config/config.yaml` (copy from `config-example.yaml`) or `~/.mini-agent/config/`. Add placeholders in examples. +- Review scripts for hardcoded paths before running; prefer `uv run` to ensure isolated environments. diff --git "a/Agent Memory/\351\241\271\347\233\256\345\210\206\346\236\220.md" "b/Agent Memory/\351\241\271\347\233\256\345\210\206\346\236\220.md" new file mode 100644 index 0000000..06a2207 --- /dev/null +++ "b/Agent Memory/\351\241\271\347\233\256\345\210\206\346\236\220.md" @@ -0,0 +1,475 @@ +# Mini-Agent 项目分析 + +> 分析日期: 2025-12-08 +> 分析者: Claude Opus 4.5 + +--- + +## 一、项目概述 + +**Mini-Agent** 是由 MiniMax 开发的一个轻量级但功能完备的 AI Agent 演示项目。它展示了如何基于 MiniMax M2 模型(兼容 Anthropic API)构建具有完整执行循环、工具调用和持久化记忆能力的智能代理。 + +### 核心定位 + +- **教育性**: 作为构建 Agent 的最佳实践示范 +- **专业性**: 代码结构清晰、模块化程度高 +- **实用性**: 开箱即用,支持多种工具和技能 + +### 技术栈 + +| 组件 | 技术选择 | +|------|----------| +| 编程语言 | Python 3.10+ | +| 异步框架 | asyncio | +| 数据验证 | Pydantic | +| 配置管理 | PyYAML | +| HTTP 客户端 | httpx (异步) | +| 命令行界面 | prompt-toolkit | +| Token 计算 | tiktoken | +| MCP 协议 | mcp 库 | + +--- + +## 二、系统架构 + +### 整体架构图 + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ CLI (cli.py) │ +│ - 交互式命令行界面 │ +│ - 命令解析与路由 │ +└────────────────────────────┬────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ Agent (agent.py) │ +│ - 主执行循环 (run loop) │ +│ - 消息管理与历史压缩 │ +│ - Token 统计与上下文管理 │ +└────────────┬────────────────────────────────┬───────────────────┘ + │ │ + ▼ ▼ +┌────────────────────────┐ ┌─────────────────────────────────┐ +│ LLM Client │ │ Tools │ +│ (llm_wrapper.py) │ │ ┌─────────────────────────┐ │ +│ - Anthropic Client │ │ │ File Tools │ │ +│ - OpenAI Client │ │ │ (read/write/edit) │ │ +│ - 重试机制 │ │ ├─────────────────────────┤ │ +│ - Provider 自动路由 │ │ │ Bash Tools │ │ +└────────────────────────┘ │ │ (foreground/background) │ │ + │ ├─────────────────────────┤ │ + │ │ Note Tool │ │ + │ │ (session memory) │ │ + │ ├─────────────────────────┤ │ + │ │ Skill Tool │ │ + │ │ (Claude Skills) │ │ + │ ├─────────────────────────┤ │ + │ │ MCP Tools │ │ + │ │ (external servers) │ │ + │ └─────────────────────────┘ │ + └─────────────────────────────────┘ +``` + +### 目录结构 + +``` +mini_agent/ +├── __init__.py # 包初始化,导出核心类 +├── agent.py # 核心 Agent 执行循环 +├── cli.py # CLI 入口与交互界面 +├── config.py # 配置管理(Pydantic 模型) +├── logger.py # 日志系统 +├── retry.py # 重试机制(装饰器模式) +├── schema/ # 数据模型定义 +│ ├── __init__.py +│ └── schema.py # Message, ToolCall, LLMResponse 等 +├── llm/ # LLM 客户端层 +│ ├── __init__.py +│ ├── base.py # 抽象基类 LLMClientBase +│ ├── llm_wrapper.py # 统一包装器 LLMClient +│ ├── anthropic_client.py +│ └── openai_client.py +├── tools/ # 工具实现 +│ ├── __init__.py +│ ├── base.py # Tool 基类和 ToolResult +│ ├── file_tools.py # ReadTool, WriteTool, EditTool +│ ├── bash_tool.py # BashTool, BashOutputTool, BashKillTool +│ ├── note_tool.py # SessionNoteTool, RecallNoteTool +│ ├── mcp_loader.py # MCP 服务器连接与工具加载 +│ ├── skill_loader.py # Claude Skills 加载器 +│ └── skill_tool.py # GetSkillTool +├── acp/ # Agent Communication Protocol +│ ├── __init__.py +│ └── server.py +├── config/ # 配置文件模板 +│ ├── config-example.yaml +│ ├── mcp.json +│ └── system_prompt.md +├── skills/ # Claude Skills (子模块) +│ └── ... # 15+ 专业技能 +└── utils/ + ├── __init__.py + └── terminal_utils.py # 终端辅助函数 +``` + +--- + +## 三、核心模块详解 + +### 3.1 Agent 执行循环 (`agent.py`) + +Agent 是整个系统的核心,实现了完整的"思考-行动-观察"循环。 + +#### 关键流程 + +```python +async def run(self) -> str: + """执行 Agent 循环直到任务完成或达到最大步数""" + step = 0 + while step < self.max_steps: + # 1. 检查并压缩消息历史 + await self._summarize_messages() + + # 2. 调用 LLM 获取响应 + response = await self.llm.generate( + messages=self.messages, + tools=tool_list + ) + + # 3. 处理响应 + if not response.tool_calls: + return response.content # 任务完成 + + # 4. 执行工具调用 + for tool_call in response.tool_calls: + result = await tool.execute(**arguments) + # 添加工具结果到消息历史 + + step += 1 +``` + +#### 智能上下文管理 + +Agent 实现了基于 Token 的上下文压缩机制: + +1. **Token 计算**: 使用 `tiktoken` (cl100k_base 编码) 精确计算 +2. **触发条件**: 本地估算或 API 返回的 token 数超过限制 (默认 80,000) +3. **压缩策略**: 保留所有 user 消息,将执行过程压缩为摘要 + +```python +# 压缩后的结构 +system -> user1 -> summary1 -> user2 -> summary2 -> ... +``` + +### 3.2 LLM 客户端层 (`llm/`) + +#### 设计模式: 策略模式 + 工厂模式 + +``` + LLMClient (Wrapper) + │ + ▼ + ┌─────────────────────┐ + │ LLMClientBase │ (抽象基类) + │ - generate() │ + │ - _prepare_request│ + │ - _convert_messages│ + └─────────┬───────────┘ + │ + ┌─────────────┴─────────────┐ + ▼ ▼ + AnthropicClient OpenAIClient +``` + +#### 特点 + +- **自动路由**: 根据 provider 参数自动选择客户端 +- **API 端点自动拼接**: + - Anthropic: `{api_base}/anthropic` + - OpenAI: `{api_base}/v1` +- **重试机制**: 支持指数退避策略 + +### 3.3 工具系统 (`tools/`) + +#### Tool 基类设计 + +```python +class Tool: + @property + def name(self) -> str: ... # 工具名称 + @property + def description(self) -> str: ... # 工具描述 + @property + def parameters(self) -> dict: ... # JSON Schema 格式的参数定义 + + async def execute(self, **kwargs) -> ToolResult: ... # 执行方法 + + def to_schema(self) -> dict: ... # 转换为 Anthropic 格式 + def to_openai_schema(self) -> dict: # 转换为 OpenAI 格式 +``` + +#### 内置工具清单 + +| 工具名 | 功能 | 特点 | +|--------|------|------| +| `read_file` | 读取文件 | 支持行号、offset/limit 分页、Token 截断 | +| `write_file` | 写入文件 | 自动创建父目录 | +| `edit_file` | 编辑文件 | 精确字符串替换 | +| `bash` | 执行命令 | 支持前台/后台、超时控制 | +| `bash_output` | 获取后台输出 | 支持正则过滤 | +| `bash_kill` | 终止后台进程 | 优雅终止 + 强制 kill | +| `record_note` | 记录笔记 | 持久化存储到 JSON | +| `get_skill` | 加载技能 | 渐进式披露 (Progressive Disclosure) | + +### 3.4 Bash 工具深度设计 (`bash_tool.py`) + +#### 后台进程管理架构 + +``` +┌────────────────────┐ +│ BashTool │ ── 执行命令,支持前台/后台 +├────────────────────┤ +│ BashOutputTool │ ── 获取后台进程输出 +├────────────────────┤ +│ BashKillTool │ ── 终止后台进程 +└────────────────────┘ + │ + ▼ +┌────────────────────────────────────────┐ +│ BackgroundShellManager (Singleton) │ +│ - _shells: dict[bash_id, Shell] │ +│ - _monitor_tasks: dict[bash_id, Task] │ +└────────────────────────────────────────┘ + │ + ▼ +┌────────────────────────────────────────┐ +│ BackgroundShell (Data Container) │ +│ - bash_id, command, process │ +│ - output_lines, status, exit_code │ +└────────────────────────────────────────┘ +``` + +#### 跨平台支持 + +- **Unix/Linux/macOS**: 使用 bash +- **Windows**: 使用 PowerShell + +### 3.5 MCP 集成 (`mcp_loader.py`) + +MCP (Model Context Protocol) 允许 Agent 连接外部工具服务器。 + +#### 工作流程 + +``` +1. 读取 mcp.json 配置 +2. 启动 MCP 服务器进程 (stdio) +3. 建立 ClientSession 连接 +4. 获取服务器提供的工具列表 +5. 包装为 MCPTool 实例 +``` + +#### 连接管理 + +- 使用 `AsyncExitStack` 管理异步上下文 +- 全局连接注册表 `_mcp_connections` +- 程序退出时自动清理 `cleanup_mcp_connections()` + +### 3.6 Skills 系统 (`skill_tool.py`, `skill_loader.py`) + +#### 渐进式披露 (Progressive Disclosure) + +``` +Level 1 (启动时): System Prompt 中注入技能元数据 (名称+描述) + ↓ +Level 2 (按需): Agent 调用 get_skill() 加载完整技能内容 + ↓ +Level 3+ (运行时): 技能引用的脚本、模板、资源文件 +``` + +#### 内置 Claude Skills (15+) + +| 类别 | 技能 | +|------|------| +| 文档 | pdf, pptx, docx, xlsx | +| 设计 | canvas-design, algorithmic-art | +| 开发 | mcp-builder, artifacts-builder, webapp-testing | +| 品牌 | brand-guidelines, theme-factory | +| 其他 | slack-gif-creator, internal-comms, skill-creator | + +--- + +## 四、配置系统 + +### 4.1 配置文件优先级 + +``` +1. mini_agent/config/config.yaml (开发模式) +2. ~/.mini-agent/config/config.yaml (用户配置) +3. /config/config.yaml (安装包) +``` + +### 4.2 配置结构 (Pydantic 模型) + +```yaml +# LLM 配置 +api_key: "YOUR_API_KEY" +api_base: "https://api.minimax.io" +model: "MiniMax-M2" +provider: "anthropic" # 或 "openai" + +# 重试配置 +retry: + enabled: true + max_retries: 3 + initial_delay: 1.0 + max_delay: 60.0 + exponential_base: 2.0 + +# Agent 配置 +max_steps: 50 +workspace_dir: "./workspace" +system_prompt_path: "system_prompt.md" + +# 工具配置 +tools: + enable_file_tools: true + enable_bash: true + enable_note: true + enable_skills: true + skills_dir: "./skills" + enable_mcp: true + mcp_config_path: "mcp.json" +``` + +--- + +## 五、运行模式 + +### 5.1 CLI 交互模式 + +```bash +# 默认 (当前目录为工作区) +mini-agent + +# 指定工作区 +mini-agent --workspace /path/to/project +``` + +#### 内置命令 + +| 命令 | 功能 | +|------|------| +| `/help` | 显示帮助 | +| `/clear` | 清空会话历史 | +| `/history` | 显示消息数量 | +| `/stats` | 显示统计信息 | +| `/exit` | 退出程序 | + +### 5.2 ACP 服务器模式 + +支持与 Zed 等编辑器集成: + +```bash +mini-agent-acp +``` + +--- + +## 六、关键设计亮点 + +### 6.1 健壮的错误处理 + +```python +try: + result = await tool.execute(**arguments) +except Exception as e: + result = ToolResult( + success=False, + error=f"Tool execution failed: {type(e).__name__}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}" + ) +``` + +### 6.2 优雅的重试机制 + +```python +@async_retry(config=RetryConfig( + max_retries=3, + initial_delay=1.0, + exponential_base=2.0 +)) +async def call_api(): + ... +``` + +### 6.3 智能 Token 截断 + +```python +def truncate_text_by_tokens(text: str, max_tokens: int) -> str: + """保留首尾,截断中间""" + head_part + truncation_note + tail_part +``` + +### 6.4 美观的终端 UI + +- 使用 `prompt-toolkit` 实现高级交互 +- 支持命令补全、历史记录、多行输入 +- ANSI 颜色美化输出 + +--- + +## 七、扩展指南 + +### 7.1 添加新工具 + +```python +from mini_agent.tools.base import Tool, ToolResult + +class MyTool(Tool): + @property + def name(self) -> str: + return "my_tool" + + @property + def description(self) -> str: + return "My custom tool description" + + @property + def parameters(self) -> dict: + return { + "type": "object", + "properties": { + "param1": {"type": "string", "description": "..."} + }, + "required": ["param1"] + } + + async def execute(self, param1: str) -> ToolResult: + # 实现逻辑 + return ToolResult(success=True, content="Result") +``` + +### 7.2 添加新 LLM Provider + +1. 继承 `LLMClientBase` +2. 实现 `generate()`, `_prepare_request()`, `_convert_messages()` +3. 在 `LLMClient` 中添加路由逻辑 + +--- + +## 八、总结 + +Mini-Agent 是一个设计精良的 Agent 框架示例,具有以下特点: + +✅ **清晰的分层架构**: CLI → Agent → LLM + Tools +✅ **灵活的扩展性**: 工具、LLM Provider、Skills 都可扩展 +✅ **健壮的错误处理**: 重试机制、异常捕获、优雅降级 +✅ **智能的上下文管理**: Token 计算、历史压缩 +✅ **专业的代码质量**: 类型注解、Pydantic 验证、模块化设计 + +这个项目非常适合作为学习 Agent 开发的参考,也可以作为构建更复杂 Agent 系统的起点。 + +--- + +*此文档由 Claude Opus 4.5 分析生成* + diff --git a/mini_agent/cli.py b/mini_agent/cli.py index 1038870..0280b7d 100644 --- a/mini_agent/cli.py +++ b/mini_agent/cli.py @@ -494,7 +494,7 @@ def _(event): key_bindings=kb, ) - # 9. Interactive loop + # 10. Interactive loop while True: try: # Get user input using prompt_toolkit @@ -568,7 +568,7 @@ def _(event): print(f"\n{Colors.RED}❌ Error: {e}{Colors.RESET}") print(f"{Colors.DIM}{'─' * 60}{Colors.RESET}\n") - # 10. Cleanup MCP connections + # 11. Cleanup MCP connections try: print(f"{Colors.BRIGHT_CYAN}Cleaning up MCP connections...{Colors.RESET}") await cleanup_mcp_connections() diff --git a/mini_agent/config/mcp.json b/mini_agent/config/mcp.json index f618680..616e96c 100644 --- a/mini_agent/config/mcp.json +++ b/mini_agent/config/mcp.json @@ -19,11 +19,19 @@ "memory": { "description": "Memory - Knowledge graph memory system (long-term memory based on graph database)", "command": "npx", - "args": [ - "-y", - "@modelcontextprotocol/server-memory" - ], + "args": ["-y", "@modelcontextprotocol/server-memory"], "disabled": true + }, + "ticktick": { + "command": "/Users/zhangyufeng/.local/bin/uv", + "args": [ + "run", + "--directory", + "/Users/zhangyufeng/WorkSpace/CodePlace/Personal-Project/ticktick-mcp-enhanced", + "-m", + "ticktick_mcp.cli", + "run" + ] } } -} \ No newline at end of file +}