From 57ba8221fcaa0a70327f4178c48f87e7c0f8b776 Mon Sep 17 00:00:00 2001 From: KasparChen Date: Tue, 16 Dec 2025 17:57:12 +0800 Subject: [PATCH 1/3] docs: Add comprehensive Chinese documentation Added a complete set of Chinese documentation to facilitate usage for Chinese-speaking developers. Changes include: - Created 'README_ZH.md': A full translation of the main README, including architecture diagrams, benchmarks, and citations. - Created 'docs_zh/' directory: Contains translations of all core documentation. - docs_zh/QUICKSTART.md - docs_zh/CONFIGURATION.md - docs_zh/TOOLKITS.md - docs_zh/DEPLOYMENT.md - docs_zh/OBSERVABILITY.md - docs_zh/E2B_SETUP.md - prompt_optimization/README_ZH.md - tests/README_ZH.md --- README_ZH.md | 1000 ++++++++++++++++++++++++ docs_zh/CONFIGURATION.md | 1543 ++++++++++++++++++++++++++++++++++++++ docs_zh/DEPLOYMENT.md | 725 ++++++++++++++++++ docs_zh/E2B_SETUP.md | 447 +++++++++++ docs_zh/OBSERVABILITY.md | 807 ++++++++++++++++++++ docs_zh/QUICKSTART.md | 631 ++++++++++++++++ docs_zh/TOOLKITS.md | 1234 ++++++++++++++++++++++++++++++ 7 files changed, 6387 insertions(+) create mode 100644 README_ZH.md create mode 100644 docs_zh/CONFIGURATION.md create mode 100644 docs_zh/DEPLOYMENT.md create mode 100644 docs_zh/E2B_SETUP.md create mode 100644 docs_zh/OBSERVABILITY.md create mode 100644 docs_zh/QUICKSTART.md create mode 100644 docs_zh/TOOLKITS.md diff --git a/README_ZH.md b/README_ZH.md new file mode 100644 index 00000000..925faf1d --- /dev/null +++ b/README_ZH.md @@ -0,0 +1,1000 @@ +
+ alt text +

ROMA: 递归开放元智能体 (Recursive Open Meta-Agents)

+
+ +

+ 轻松构建分层高性能多智能体系统!(Beta) +

+ +

+sentient-agi%2FROMA | Trendshift +

+ +

+ + Homepage + + + GitHub + + + Hugging Face + + + +

+ + Discord + + + Twitter Follow + +
+ +

+ 技术博客 • + 论文 (即将发布) • + 构建智能体赚取收益 +

+ +--- + +## 📑 目录 +- [🧠 概念概览](#-概念概览) +- [📦 安装与设置](#-安装与设置) +- [⚡ 快速入门:端到端工作流](#-快速入门端到端工作流) +- [⚙️ 配置与存储](#%EF%B8%8F-配置与存储) +- [🎨 Agent 定义与个性化](#-agent-定义与个性化) +- [🧰 工具箱](#-工具箱) +- [🌐 REST API 与 CLI](#-rest-api-与-cli) +- [🏗️ 核心构建块:`BaseModule`](#%EF%B8%8F-核心构建块basemodule) +- [📚 模块参考](#-模块参考) + - [⚛️ Atomizer (原子化器)](#%E2%9A%9B%EF%B8%8F-atomizer-原子化器) + - [📋 Planner (规划器)](#-planner-规划器) + - [⚙️ Executor (执行器)](#%EF%B8%8F-executor-执行器) + - [🔀 Aggregator (聚合器)](#-aggregator-聚合器) + - [✅ Verifier (验证器)](#-verifier-验证器) +- [🎯 高级模式](#-高级模式) +- [🧪 测试](#-测试) +- [💡 故障排除与提示](#-故障排除与提示) +- [📖 术语表](#-术语表) +- [📊 基准测试 (Benchmarks)](#-基准测试-benchmarks) +- [🧩 基础与渊源](#-基础与渊源) +- [🙏 致谢](#-致谢) +- [📚 引用](#-引用) +- [🌟 Star 历史](#-star-历史) +- [📄 许可证](#-许可证) + +--- + +## 🎯 ROMA 是什么? + +
+ ROMA 运行演示 +
+
+ +**ROMA (Recursive Open Meta-Agents)** 是一个**元智能体框架**,利用递归分层结构解决复杂问题。通过将任务分解为可并行的组件,ROMA 使智能体能够应对复杂的推理挑战,同时保持透明度,让上下文工程和迭代变得简单直观。该框架提供: +- **并行问题解决**:智能体同时处理复杂任务的不同部分。 +- **透明开发**:清晰的结构便于调试。 +- **经验证的性能**:我们的搜索智能体在基准测试中表现出色。 + +我们已经展示了框架的有效性,但这只是开始。作为**开源且可扩展**的平台,ROMA 专为社区驱动的开发而设计,允许您根据特定需求构建和定制智能体,同时从社区的集体改进中受益。 + +--- + +## 🏗️ 工作原理 + +**ROMA** 框架通过递归的 **计划-执行 (Plan-Execute)** 循环来处理任务: + +```python +def solve(task): + if is_atomic(task): # 步骤 1: Atomizer (原子化器) + return execute(task) # 步骤 2: Executor (执行器) + else: + subtasks = plan(task) # 步骤 2: Planner (规划器) + results = [] + for subtask in subtasks: + results.append(solve(subtask)) # 递归调用 + return aggregate(results) # 步骤 3: Aggregator (聚合器) + +# 入口点: +answer = solve(initial_request) +``` + +1. **Atomizer (原子化器)** – 决定请求是**原子的**(可直接执行)还是需要**规划**。 +2. **Planner (规划器)** – 如果需要规划,任务被分解为更小的**子任务**。每个子任务都会反馈给 Atomizer,使过程具有递归性。 +3. **Executors (执行器)** – 处理原子任务。执行器可以是 **LLM、API 甚至其他智能体** — 只要它们实现了 `agent.execute()` 接口。 +4. **Aggregator (聚合器)** – 收集并整合子任务的结果。重要的是,Aggregator 生成的是**原始父任务的答案**,而不仅仅是原始子输出的堆叠。 + +#### 📐 信息流 +- **自顶向下 (Top-down)**:任务递归分解为子任务。 +- **自底向上 (Bottom-up)**:子任务结果向上聚合成父任务的解决方案。 +- **从左到右 (Left-to-right)**:如果子任务依赖于前一个子任务的输出,它会等待该子任务完成后再执行。 + +这种结构使系统具有灵活性、递归性和依赖感知能力 — 能够将复杂问题分解为更小的步骤,同时确保结果连贯地整合在一起。 + +
+点击查看系统流程图 + +```mermaid +flowchart TB + A[Your Request] --> B{Atomizer} + B -->|Plan Needed| C[Planner] + B -->|Atomic Task| D[Executor] + + %% Planner spawns subtasks + C --> E[Subtasks] + E --> G[Aggregator] + + %% Recursion + E -.-> B + + %% Execution + Aggregation + D --> F[Final Result] + G --> F + + style A fill:#e1f5fe + style F fill:#c8e6c9 + style B fill:#fff3e0 + style C fill:#ffe0b2 + style D fill:#d1c4e9 + style G fill:#c5cae9 + +``` + +

+ +--- + +## 🚀 快速开始 + +### 最快方式:极简安装(推荐用于评估) + +无需基础设施,**30秒内**即可开始: + +```bash +# 使用 uv 安装 (推荐,速度快 10-100 倍) +uv pip install roma-dspy + +# 或使用 pip +pip install roma-dspy + +# 设置您的 API 密钥 (默认配置使用 OpenRouter) +export OPENROUTER_API_KEY="sk-or-v1-..." + +# 立即开始解决任务 +python -c "from roma_dspy.core.engine.solve import solve; print(solve('2+2 是多少?'))" +``` + +> **注意**:默认配置使用 OpenRouter 的 Claude Sonnet 4.5 (执行器) 和 Gemini 2.5 Flash (其他代理)。您也可以通过设置 `OPENAI_API_KEY` 并自定义配置来直接使用 OpenAI。 + +**您将获得:** +- ✅ 核心智能体框架 (Atomizer, Planner, Executor, Aggregator, Verifier) +- ✅ 所有 DSPy 预测策略 (CoT, ReAct, CodeAct 等) +- ✅ 文件存储 (无需数据库) +- ✅ 内置工具箱 (计算器, 文件操作) +- ✅ 支持任何 LLM 提供商 (OpenRouter, OpenAI, Anthropic 等) + +**无 Docker,无数据库,无复杂设置 - 安装即用!** + +### 生产设置:Docker 完整功能版 + +适用于具有持久化、可观察性和 API 服务器的生产环境: + +```bash +# 一键设置 (构建 Docker, 启动服务) +just setup + +# 或者使用特定配置文件 +just setup crypto_agent + +# 验证服务是否运行 +curl http://localhost:8000/health + +# 通过 API 解决任务 +just solve "法国的首都是哪里?" +``` + +**Docker 版额外功能:** +- 📊 PostgreSQL 持久化 (执行历史, 检查点) +- 📈 MLflow 可观察性 (实验跟踪, 可视化) +- 🌐 REST API 服务器 (FastAPI 带交互式文档) +- 📦 S3 兼容存储 (MinIO) +- 🔧 E2B 代码执行沙箱 +- 🎨 交互式 TUI 可视化 + +**可用服务:** +- 🚀 **REST API**: http://localhost:8000/docs +- 🗄️ **PostgreSQL**: 自动持久化 +- 📦 **MinIO**: S3 兼容存储 (http://localhost:9001) +- 📊 **MLflow**: http://localhost:5000 (使用 `docker-up-full`) + +详情请参阅 [快速入门指南](docs_zh/QUICKSTART.md) 和 [部署指南](docs_zh/DEPLOYMENT.md)。 + +--- + +## 🧠 概念概览 + +ROMA 的模块层将标准的 DSPy 模式封装为反映复杂任务执行生命周期的专用组件: + +1. **Atomizer (原子化器)**:决定请求是可以直接处理还是需要分解。 +2. **Planner (规划器)**:将非原子目标分解为有序的子任务图。 +3. **Executor (执行器)**:解决单个子任务,可选择通过函数/工具调用进行路由。 +4. **Aggregator (聚合器)**:将子任务输出合成为连贯的答案。 +5. **Verifier (验证器)** (可选):在交付前根据原始目标检查聚合输出。 + +每个模块共享相同的人体工程学设计:使用语言模型 (LM) 或提供商字符串实例化它,选择预测策略,然后使用特定于任务的字段调用 `.forward()` (或 `.aforward()` 用于异步)。 + +所有模块最终都委托给 `roma_dspy.core.signatures` 中定义的 DSPy 签名。这使得即使内部结构演变,接口也能保持稳定。 + +--- + +## 📦 安装与设置 + +### 选项 1:极简安装 (最快 - 推荐用于评估) + +**最适合**:评估 ROMA、开发、测试、快速原型设计 + +**30秒内安装:** + +```bash +# 使用 uv (推荐 - 快 10-100 倍) +uv pip install roma-dspy + +# 或使用 pip +pip install roma-dspy +``` + +**设置您的 API 密钥:** +```bash +export OPENROUTER_API_KEY="sk-or-v1-..." # 推荐 +# 或 +export OPENAI_API_KEY="sk-..." +export ANTHROPIC_API_KEY="sk-ant-..." +``` + +**立即开始使用:** +```python +from roma_dspy.core.engine.solve import solve + +# 解决任何任务 +result = solve("法国的首都是哪里?") +print(result) +``` + +**包含内容:** +- ✅ 所有核心模块 (Atomizer, Planner, Executor, Aggregator, Verifier) +- ✅ 所有 DSPy 预测策略 +- ✅ 基于文件的存储 (无需数据库) +- ✅ 核心工具箱 (计算器, 文件操作) +- ✅ 支持任何 LLM 提供商 + +**未包含内容 (如需请单独安装):** +- PostgreSQL 持久化 → `uv pip install roma-dspy[persistence]` +- MLflow 可观察性 → `uv pip install roma-dspy[observability]` +- E2B 代码执行 → `uv pip install roma-dspy[e2b]` +- REST API 服务器 → `uv pip install roma-dspy[api]` +- S3 存储 → `uv pip install roma-dspy[s3]` +- 所有功能 → `uv pip install roma-dspy[all]` + +--- + +### 选项 2:Docker 完整安装 (生产) + +**最适合**:生产部署、团队协作、完整可观察性 + +**先决条件**: +- Docker & Docker Compose +- Python 3.12+ (用于本地开发) +- [Just](https://github.com/casey/just) 命令运行器 (可选,推荐) + +**一键设置:** +```bash +# 交互式设置 (提示配置 E2B, S3 等) +just setup + +# 或使用特定 profile +just setup crypto_agent +``` + +**手动 Docker 启动:** +```bash +just docker-up # 基础 (PostgreSQL + MinIO + API) +just docker-up-full # 包含 MLflow 可观察性 +``` + +**环境变量** (由 `just setup` 自动配置): +```bash +# LLM 提供商 (必需) +OPENROUTER_API_KEY=... # 推荐 +# 或 +OPENAI_API_KEY=... +ANTHROPIC_API_KEY=... + +# 可选:高级功能 +E2B_API_KEY=... # 代码执行 +COINGECKO_API_KEY=... # 加密工具箱 +``` + +**Docker 额外功能:** +- 📊 PostgreSQL (执行历史, 检查点) +- 📈 MLflow (实验跟踪, 指标) +- 🌐 REST API (FastAPI 带文档) +- 📦 MinIO (S3 兼容存储) +- 🎨 TUI 可视化 + +--- + +### 选项 3:开发安装 + +**用于贡献或扩展 ROMA:** + +```bash +# 克隆仓库 +git clone https://github.com/sentient-agi/roma.git +cd roma + +# 安装开发工具 (包含 pytest, ruff, mypy) +uv pip install -e ".[dev]" + +# 运行测试 +just test + +# 格式化代码 +just format + +# 类型检查 +just typecheck +``` + +--- + +### 对比:哪种安装适合您? + +| 特性 | 极简 (`pip install roma-dspy`) | Docker (`just setup`) | +|------|-------------------------------|----------------------| +| 安装时间 | **< 30 秒** | ~5-10 分钟 | +| 基础设施需求 | **无** | Docker | +| 核心智能体框架 | ✅ | ✅ | +| 文件存储 | ✅ | ✅ | +| PostgreSQL 持久化 | ❌ (需安装 `[persistence]`) | ✅ | +| MLflow 可观察性 | ❌ (需安装 `[observability]`) | ✅ | +| REST API | ❌ (需安装 `[api]`) | ✅ | +| 适用场景 | 评估, 开发 | 生产, 团队 | + +## ⚡ 快速入门:端到端工作流 + +以下示例展示了一个典型的编排循环。它使用三个不同的提供商来展示每个模块如何轻松地与不同的模型和策略配合工作。 + +```python +import dspy +from roma_dspy import Aggregator, Atomizer, Executor, Planner, Verifier, SubTask +from roma_dspy.types import TaskType + +# 可选工具,供 Executor 调用 +def get_weather(city: str) -> str: + """返回城市的预设天气报告。""" + return f"{city} 的天气是晴朗。" + +# 针对 ReAct 策略的 Executor,使用 Fireworks 模型 +executor_lm = dspy.LM( + "fireworks_ai/accounts/fireworks/models/kimi-k2-instruct-0905", + temperature=0.7, + cache=True, +) +executor = Executor( + lm=executor_lm, + prediction_strategy="react", + tools=[get_weather], + context_defaults={"track_usage": True}, +) + +# Atomizer 决定何时进行规划分支 +atomizer = Atomizer( + lm=dspy.LM("openrouter/google/gemini-2.5-flash", temperature=0.6, cache=False), + prediction_strategy="cot", + context_defaults={"track_usage": True}, +) + +# Planner 为非原子目标生成可执行子任务 +planner = Planner( + lm=dspy.LM("openrouter/openai/gpt-4o-mini", temperature=0.85, cache=True), + prediction_strategy="cot", + context_defaults={"track_usage": True}, +) + +aggregator = Aggregator( + lm=dspy.LM("openrouter/openai/gpt-4o-mini", temperature=0.65), + prediction_strategy="cot", +) + +verifier = Verifier( + lm=dspy.LM("openrouter/openai/gpt-4o-mini", temperature=0.0), +) + +def run_pipeline(goal: str) -> str: + atomized = atomizer.forward(goal) + if atomized.is_atomic or atomized.node_type.is_execute: + execution = executor.forward(goal) + candidate = execution.output + else: + plan = planner.forward(goal) + results = [] + for idx, subtask in enumerate(plan.subtasks, start=1): + execution = executor.forward(subtask.goal) + results.append( + SubTask( + goal=subtask.goal, + task_type=subtask.task_type, + dependencies=subtask.dependencies, + ) + ) + aggregated = aggregator.forward(goal, results) + candidate = aggregated.synthesized_result + + verdict = verifier.forward(goal, candidate) + if verdict.verdict: + return candidate + return f"验证器标记了输出: {verdict.feedback or '无反馈返回'}" + +print(run_pipeline("规划一个巴塞罗那周末游并包含打包清单。")) +``` + +亮点: +- 不同模块可以在不同的 LM 和温度上运行。 +- 工具可以在构造时提供,也可以在每次调用时提供。 +- `context_defaults` 确保每个 `.forward()` 调用都在正确的 `dspy.context()` 中使用模块的 LM。 + +--- + +## ⚙️ 配置与存储 + +ROMA-DSPy 使用 **OmegaConf** 进行分层配置,并结合 **Pydantic** 验证,提供**执行范围的存储**以实现完全的任务隔离。 + +### 快速配置示例 + +```python +from roma_dspy.config import load_config + +# 加载 profile 并覆盖 +config = load_config( + profile="crypto_agent", + overrides=["agents.executor.llm.temperature=0.3"] +) +``` + +**可用 Profiles**: `general`, `crypto_agent` (通过 `just list-profiles` 查看列表) + +**参见**: [配置指南](docs_zh/CONFIGURATION.md) 获取关于 profiles、智能体配置、LLM 设置、工具箱配置和任务感知智能体映射的完整文档。 + +### 存储 + +存储是自动且基于执行范围的 - 每个任务都有一个隔离目录。大型工具箱响应 (>100KB) 自动存储为 Parquet 文件。 + +```python +from roma_dspy.core.engine.solve import solve + +# 存储自动创建于: {base_path}/executions/{execution_id}/ +result = solve("分析区块链交易") +``` + +**特性**: 执行隔离, S3 兼容, 自动 Parquet 存储, Docker 管理 + +**参见**: [部署指南](docs_zh/DEPLOYMENT.md) 了解包括 S3 集成在内的生产存储配置。 + +--- + +## 🎨 Agent 定义与个性化 + +在 ROMA 中,Agent 不再是硬编码的 Python 类,而是通过 **YAML 配置文件** 进行定义的“配置化实体”。这使得定制和扩展变得非常直观。 + +### 1. Agent 定义 = YAML 配置 +您可以像搭积木一样,通过修改 `config/profiles/*.yaml` 文件来定义 Agent 的能力边界: +- **大脑 (LLM)**:指定模型(如用 Claude 3.5 Sonnet 处理复杂逻辑,用 Gemini Flash 处理大量文本)。 +- **四肢 (Toolkits)**:挂载所需的工具箱(如搜索、代码执行、文件操作)。 +- **性格 (Params)**:调整温度、最大 Token 数等参数。 + +### 2. 个性化 Sys Prompt (系统提示词) +ROMA 使用 DSPy 框架,将传统的大段 Sys Prompt 封装为更结构化的形式,称为 `signature_instructions`。它并没有消失,而是被更好地管理了。 + +您可以通过 YAML 灵活修改 Agent 的行为: + +- **signature_instructions**:对应传统的 Sys Prompt。您可以直接在 YAML 中写字符串覆盖它,或指向一个 Python 文件中的变量(更推荐,便于复用)。 +- **demos**:Few-Shot 示例。通过提供具体问答案例,引导 Agent 的输出风格和逻辑。 + +**示例:自定义一个“严谨的金融分析师”** + +```yaml +agents: + executor: + # 1. 定义大脑 (使用强逻辑模型) + llm: + model: openrouter/anthropic/claude-3.5-sonnet + temperature: 0.1 # 低温度以保持严谨 + + # 2. 个性化 Prompt (覆盖默认指令) + signature_instructions: "你是一名华尔街顶级分析师。回答必须基于数据,风格简练犀利,拒绝模棱两可的废话。" + + # 3. 挂载工具 (赋予专业能力) + toolkits: + - class_name: BinanceToolkit + enabled: true + - class_name: ArkhamToolkit + enabled: true +``` + +--- + +## 🧰 工具箱 (Toolkits) + +ROMA-DSPy 包含 9 个内置工具箱,扩展了智能体能力: + +**核心**: FileToolkit, CalculatorToolkit, E2BToolkit (代码执行) +**加密**: CoinGeckoToolkit, BinanceToolkit, DefiLlamaToolkit, ArkhamToolkit +**搜索**: SerperToolkit (Web 搜索) +**通用**: MCPToolkit (连接到任何 [MCP 服务器](https://github.com/wong2/awesome-mcp-servers)) + +### 快速配置 + +```yaml +agents: + executor: + toolkits: + - class_name: "FileToolkit" + enabled: true + - class_name: "E2BToolkit" + enabled: true + toolkit_config: + timeout: 600 +``` + +**参见**: [工具箱参考](docs_zh/TOOLKITS.md) 获取完整的工具箱文档,包括所有工具、配置选项、MCP 集成和自定义工具箱开发。 + +--- + +## 🌐 REST API 与 CLI + +ROMA-DSPy 为生产使用提供 REST API 和 CLI。 + +### REST API + +带交互式文档的 FastAPI 服务器: + +```bash +# 随 Docker 自动启动 +just docker-up + +# API 文档: http://localhost:8000/docs +# 健康检查: http://localhost:8000/health +``` + +**端点**: 执行管理, 检查点, 可视化, 指标 + +### CLI + +```bash +# 本地任务执行 +roma-dspy solve "你的任务" --profile general + +# 服务器管理 +roma-dspy server start +roma-dspy server health + +# 执行管理 +roma-dspy exec create "Task" +roma-dspy exec status --watch + +# 交互式 TUI 可视化 (建议配合 MLflow) +just viz + +# 完整帮助 +roma-dspy --help +``` + +**参见**: `/docs` 端点处的 API 文档,获取完整的 OpenAPI 规范和交互式测试。 + +--- + +## 🏗️ 核心构建块:`BaseModule` + +所有模块都继承自 `roma_dspy/core/modules/base_module.py` 中的 `BaseModule`。它标准化了: +- 通过 DSPy 预测策略进行的签名绑定, +- LM 实例化和上下文管理, +- 工具规范化和合并, +- 带安全关键字过滤的同步/异步入口点。 + +### 上下文与 LM 管理 +实例化模块时,您可以提供现有的 `dspy.LM`,或者让模块通过提供商字符串 (`model`) 和可选关键字参数 (`model_config`) 构建一个。 + +```python +from roma_dspy import Executor + +executor = Executor( + model="openrouter/openai/gpt-4o-mini", + model_config={"temperature": 0.5, "cache": True}, +) +``` + +内部,`BaseModule` 确保每个 `.forward()` 调用都将预测器调用包装在: + +```python +with dspy.context(lm=self._lm, **context_defaults): + ... +``` + +您可以通过 `get_model_config()` 检查有效的 LM 配置,以确认提供商、缓存设置或经过清理的 kwargs。 + +### 使用工具 +工具可以作为 DSPy 的 ReAct/CodeAct 策略接受的列表、元组或可调用对象映射提供。 + +```python +executor = Executor(tools=[get_weather]) +executor.forward("安曼的天气怎么样?", tools=[another_function]) +``` + +`BaseModule` 根据对象标识自动去重工具,并将构造函数默认值与每次调用的覆盖合并。 + +### 预测策略 +ROMA 通过 `PredictionStrategy` 枚举 (`roma_dspy/types/prediction_strategy.py`) 暴露 DSPy 的策略。使用枚举或不区分大小写的字符串别名: + +```python +from roma_dspy.types import PredictionStrategy + +planner = Planner(prediction_strategy=PredictionStrategy.CHAIN_OF_THOUGHT) +executor = Executor(prediction_strategy="react") +``` + +可用选项包括 `Predict`, `ChainOfThought`, `ReAct`, `CodeAct`, `BestOfN`, `Refine`, `Parallel`, `majority` 等。需要工具的策略 (`ReAct`, `CodeAct`) 会自动接收传递给模块的任何工具。 + +### 异步执行 +每个模块都提供 `aforward()` 方法。当底层 DSPy 预测器支持异步 (`acall`/`aforward`) 时,ROMA 会异步分发;否则,它会优雅地回退到同步实现,同时保持可等待性。 + +```python +result = await executor.aforward("下载最新的销售报告") +``` + +## 📚 模块参考 + +### ⚛️ Atomizer (原子化器) +**位置**: `roma_dspy/core/modules/atomizer.py` + +**目的**: 决定目标是原子的还是需要规划。 + +**构造函数**: +```python +Atomizer( + prediction_strategy: Union[PredictionStrategy, str] = "ChainOfThought", + *, + lm: Optional[dspy.LM] = None, + model: Optional[str] = None, + model_config: Optional[Mapping[str, Any]] = None, + tools: Optional[Sequence|Mapping] = None, + **strategy_kwargs, +) +``` + +**输入** (`AtomizerSignature`): +- `goal: str` + +**输出** (`AtomizerResponse`): +- `is_atomic: bool` — 任务是否可以直接运行。 +- `node_type: NodeType` — 下游路由的 `PLAN` 或 `EXECUTE` 提示。 + +**用法**: +```python +atomized = atomizer.forward("策划一个包含餐厅预订的5天东京行程") +if atomized.is_atomic: + ... # 直接发送给 Executor +else: + ... # 转交给 Planner +``` + +Atomizer 与策略无关,但通常使用 `ChainOfThought` 或 `Predict`。您可以通过 `call_params` 传递提示 (例如 `max_tokens`): + +```python +atomizer.forward( + "总结这份 PDF", + call_params={"max_tokens": 200}, +) +``` + +### 📋 Planner (规划器) +**位置**: `roma_dspy/core/modules/planner.py` + +**目的**: 将目标分解为带有可选依赖图的有序子任务。 + +**构造函数**: 与 Atomizer 相同的模式。 + +**输入** (`PlannerSignature`): +- `goal: str` + +**输出** (`PlannerResult`): +- `subtasks: List[SubTask]` — 每个包含 `goal`, `task_type`, 和 `dependencies`。 +- `dependencies_graph: Optional[Dict[str, List[str]]]` — LM 返回时的显式邻接映射。 + +**用法**: +```python +plan = planner.forward("在6周内启动一个 B2B 网络研讨会") +for subtask in plan.subtasks: + print(subtask.goal, subtask.task_type) +``` + +`SubTask.task_type` 是一个 `TaskType` 枚举,遵循 ROMA MECE 框架 (Retrieve, Write, Think, Code Interpret, Image Generation)。 + +### ⚙️ Executor (执行器) +**位置**: `roma_dspy/core/modules/executor.py` + +**目的**: 解决原子目标,可选地通过 DSPy 的 ReAct, CodeAct 或类似策略调用工具/函数。 + +**构造函数**: 相同模式;最常用的策略是 `ReAct`, `CodeAct`, 或 `ChainOfThought`。 + +**输入** (`ExecutorSignature`): +- `goal: str` + +**输出** (`ExecutorResult`): +- `output: str | Any` +- `sources: Optional[List[str]]` — 来源或引用。 + +**用法**: +```python +execution = executor.forward( + "编制一个为期3天的滑雪旅行打包清单", + config={"temperature": 0.4}, # 每次调用的 LM 覆盖 +) +print(execution.output) +``` + +仅为某些调用暴露工具: + +```python +execution = executor.forward( + "巴黎的天气怎么样?", + tools=[get_weather], +) +``` + +### 🔀 Aggregator (聚合器) +**位置**: `roma_dspy/core/modules/aggregator.py` + +**目的**: 将多个子任务结果组合成最终的叙述或决策。 + +**构造函数**: 相同模式。 + +**输入** (`AggregatorResult` signature): +- `original_goal: str` +- `subtasks_results: List[SubTask]` — 通常是 planner 的建议加上执行输出。 + +**输出** (`AggregatorResult` base model): +- `synthesized_result: str` + +**用法**: +```python +aggregated = aggregator.forward( + original_goal="规划数据迁移", + subtasks_results=[ + SubTask(goal="清点当前数据库", task_type=TaskType.RETRIEVE), + SubTask(goal="起草迁移时间表", task_type=TaskType.WRITE), + ], +) +print(aggregated.synthesized_result) +``` + +因为它继承自 `BaseModule`,如果您的聚合策略需要外部调用,您仍然可以附加工具(例如,知识库检索函数)。 + +### ✅ Verifier (验证器) +**位置**: `roma_dspy/core/modules/verifier.py` + +**目的**: 验证合成后的输出是否满足原始目标。 + +**输入** (`VerifierSignature`): +- `goal: str` +- `candidate_output: str` + +**输出**: +- `verdict: bool` +- `feedback: Optional[str]` + +**用法**: +```python +verdict = verifier.forward( + goal="起草一份符合 GDPR 的隐私政策", + candidate_output=aggregated.synthesized_result, +) +if not verdict.verdict: + print("需要修改:", verdict.feedback) +``` + +## 🎯 高级模式 + +### 运行时交换模型 +使用 `replace_lm()` 为同一模块重用不同的 LM(用于 A/B 测试或回退)。 + +```python +fast_executor = executor.replace_lm(dspy.LM("openrouter/anthropic/claude-3-haiku")) +``` + +### 每次调用覆盖 +您可以在不重建模块的情况下改变 LM 行为或提供额外参数。 + +```python +executor.forward( + "总结会议记录", + config={"temperature": 0.1, "max_tokens": 300}, + context={"stop": ["Observation:"]}, +) +``` + +`call_params` (或关键字参数) 会被过滤以匹配 DSPy 预测器接受的 kwargs,防止意外错误。 + +### 仅工具执行 +如果您想要确定性的工具路由,可以设置一个虚拟 LM(或极低温度的模型)并传递纯 Python 可调用对象。 + +```python +from roma_dspy import Executor + +executor = Executor( + prediction_strategy="code_act", + lm=dspy.LM("openrouter/openai/gpt-4o-mini", temperature=0.0), + tools={"get_weather": get_weather, "lookup_user": lookup_user}, +) +``` + +ROMA 将确保构造函数和每次调用的工具都可供策略使用。 + +## 🧪 测试 + +```bash +# 运行所有测试 +just test + +# 运行特定测试 +pytest tests/unit/ -v +pytest tests/integration/ -v +``` + +**参见**: `justfile` 获取所有可用的测试命令。 + +## 💡 故障排除与提示 +- **`ValueError: Either provide an existing lm`** — 构造模块时提供 `lm=` 或 `model=`。 +- **`Invalid prediction strategy`** — 检查拼写;字符串不区分大小写,但必须匹配已知别名。 +- **缓存** — 在您的 LM 上传递 `cache=True` 或在 `model_config` 中设置,以重用以前的完成。 +- **异步上下文** — 混合同步和异步调用时,确保您的事件循环正在运行(例如,使用 `asyncio.run`)。 +- **工具重复** — 工具按标识去重;如果需要变体,请创建不同的函数。 + +## 📖 术语表 + +### 核心概念 +- **DSPy**: 斯坦福的用于提示、规划和工具集成的声明式框架。 +- **Prediction Strategy (预测策略)**: 驱动推理的 DSPy 类/函数 (CoT, ReAct 等)。 +- **SubTask (子任务)**: 描述分解工作单元的 Pydantic 模型 (`goal`, `task_type`, `dependencies`)。 +- **NodeType (节点类型)**: Atomizer 选定的是 `PLAN` 还是 `EXECUTE`。 +- **TaskType (任务类型)**: 子任务的 MECE 分类 (`RETRIEVE`, `WRITE`, `THINK`, `CODE_INTERPRET`, `IMAGE_GENERATION`)。 +- **Context Defaults (上下文默认值)**: 每次调用提供给 `dspy.context(...)` 的关键字参数。 + +### 配置与存储 +- **FileStorage**: 提供每个任务执行隔离目录的执行范围存储管理器。 +- **DataStorage**: 用于大型工具箱响应的自动 Parquet 存储系统(基于阈值)。 +- **Execution ID**: 每个任务执行的唯一标识符,用于存储隔离。 +- **Base Path**: 所有存储操作的根目录(本地路径或 S3 桶)。 +- **Profile**: 命名配置预设(例如 `general`, `crypto_agent`)。 +- **Configuration Override**: 运行时值,覆盖 profile/默认设置。 + +### 工具箱 +- **BaseToolkit**: 所有工具箱的抽象基类,提供存储集成和工具注册。 +- **REQUIRES_FILE_STORAGE**: 元数据标志,指示工具箱需要 FileStorage(例如 FileToolkit)。 +- **Toolkit Config**: 工具箱特定设置,如 API 密钥、超时和阈值。 +- **Tool Selection**: 包含/排除列表,用于过滤工具箱中可用的工具。 +- **Storage Threshold**: 大小限制 (KB),超过此限制响应将以 Parquet 格式存储。 + +### 架构 +- **Execution-Scoped Isolation**: 每个执行获得唯一存储目录的模式。 +- **Parquet Integration**: 大型结构化数据的自动列式存储。 +- **S3 Compatibility**: 通过 Docker 卷挂载使用 S3 兼容存储的能力。 +- **Tool Registration**: 自动发现并注册工具箱方法为可调用工具。 + +--- + +Happy building! 如果您扩展或自定义模块,请保持签名对齐,以便更高级别的编排保持稳定。 + +**额外资源:** +- [快速入门指南](docs_zh/QUICKSTART.md) - 10分钟内上手 +- [配置指南](docs_zh/CONFIGURATION.md) - 完整的配置参考 +- [工具箱参考](docs_zh/TOOLKITS.md) - 所有内置及自定义工具箱 +- [部署指南](docs_zh/DEPLOYMENT.md) - 使用 Docker 进行生产部署 +- [E2B 设置](docs_zh/E2B_SETUP.md) - 代码执行工具箱设置 +- [可观察性](docs_zh/OBSERVABILITY.md) - MLflow 跟踪与监控 +- [配置系统](config/README.md) - 配置 profiles 和示例 + +## 📊 基准测试 (Benchmarks) + +我们使用 ROMA 的一个简单搜索系统实现(称为 ROMA-Search)在三个基准测试中进行了评估:**SEAL-0**、**FRAMES** 和 **SimpleQA**。 +以下是每个基准测试的性能图表。 + +### [SEAL-0](https://huggingface.co/datasets/vtllms/sealqa) +SealQA 是一个新的具有挑战性的基准测试,用于在网络搜索产生冲突、嘈杂或无益结果时,评估搜索增强语言模型在事实寻求问题上的表现。 + +![SEAL-0 结果](assets/seal-0-full.001.jpeg) + +--- + +### [FRAMES](https://huggingface.co/datasets/google/frames-benchmark) +
+查看完整结果 + +一个全面的评估数据集,旨在测试检索增强生成 (RAG) 系统在事实性、检索准确性和推理方面的能力。 + +![FRAMES 结果](assets/FRAMES-full.001.jpeg) + +
+ +--- + +### [SimpleQA](https://openai.com/index/introducing-simpleqa/) +
+查看完整结果 + +衡量语言模型回答简短事实性问题能力的事实性基准测试。 + +![SimpleQA 结果](assets/simpleQAFull.001.jpeg) + +
+ +## 🧩 基础与渊源 + +虽然 ROMA 引入了一个用于分层任务执行的实用开源框架,但它直接建立在 [WriteHERE](https://arxiv.org/abs/2503.08275) 中引入的两个基础研究贡献之上: + +- **异构递归规划 (Heterogeneous Recursive Planning)** — ROMA 的整体架构遵循先前关于*异构递归规划*工作中引入的框架,其中复杂任务被递归分解为子任务图,每个子任务分配一个独特的认知类型。 + +- **分解中的类型规范 (Type Specification in Decomposition)** — ROMA 的“三个通用操作”(思考 THINK 🤔、写作 WRITE ✍️、搜索 SEARCH 🔍)概括了*分解中的类型规范*假设,该假设将推理、组合和检索确定为三种基本的认知类型。 + +这些贡献在 WriteHERE 仓库和论文中有详细描述。通过明确采用和扩展这一基础,ROMA 提供了一个**可通用的脚手架、智能体系统、多功能性和可扩展性**,建立在这些见解之上,并使各个领域的构建者可以使用它们。 + +## 🙏 致谢 + +如果没有这些令人惊叹的开源贡献,这个框架是不可能实现的! +- 灵感来自 Xiong 等人在 ["Beyond Outlining: Heterogeneous Recursive Planning"](https://arxiv.org/abs/2503.08275) 中描述的分层规划方法。 +- [Pydantic](https://github.com/pydantic/pydantic) - 使用 Python 类型注释的数据验证 +- [DSPy]([https://dspy.ai/)) - 编程 AI 智能体的框架 +- [E2B](https://github.com/e2b-dev/e2b) - AI 智能体的云运行时 + +## 📚 引用 + +如果您在研究中使用了 ROMA 仓库,请引用: + +```bibtex +@software{al_zubi_2025_17052592, + author = {Al-Zubi, Salah and + Nama, Baran and + Kaz, Arda and + Oh, Sewoong}, + title = {SentientResearchAgent: A Hierarchical AI Agent + Framework for Research and Analysis + }, + month = sep, + year = 2025, + publisher = {Zenodo}, + version = {ROMA}, + doi = {10.5281/zenodo.17052592}, + url = {https://doi.org/10.5281/zenodo.17052592}, + swhid = {swh:1:dir:69cd1552103e0333dd0c39fc4f53cb03196017ce + ;origin=https://doi.org/10.5281/zenodo.17052591;vi + sit=swh:1:snp:f50bf99634f9876adb80c027361aec9dff97 + 3433;anchor=swh:1:rel:afa7caa843ce1279f5b4b29b5d3d + 5e3fe85edc95;path=salzubi401-ROMA-b31c382 + }, +} +``` + +## 🌟 Star History + +
+ +[![Star History Chart](https://api.star-history.com/svg?repos=sentient-agi/roma&type=Date)](https://www.star-history.com/#sentient-agi/roma&Date) + +
+ +## 📄 许可证 + +本项目采用 Apache 2.0 许可证 - 详情请参阅 [LICENSE](LICENSE) 文件。 diff --git a/docs_zh/CONFIGURATION.md b/docs_zh/CONFIGURATION.md new file mode 100644 index 00000000..bf4d147f --- /dev/null +++ b/docs_zh/CONFIGURATION.md @@ -0,0 +1,1543 @@ +# ROMA-DSPy 配置指南 + +ROMA-DSPy 智能体、profiles、工具箱和运行时设置的完整配置参考。 + +## 目录 + +- [概览](#概览) +- [配置系统](#配置系统) +- [Profiles](#profiles) +- [智能体配置](#智能体配置) +- [任务感知智能体映射](#任务感知智能体映射) +- [工具箱配置](#工具箱配置) +- [LLM 配置](#llm-配置) +- [运行时设置](#运行时设置) +- [存储配置](#存储配置) +- [可观察性 (MLflow)](#可观察性-mlflow) +- [弹性设置](#弹性设置) +- [日志配置](#日志配置) +- [环境变量](#环境变量) +- [自定义提示词和演示](#自定义提示词和演示) +- [配置示例](#配置示例) +- [最佳实践](#最佳实践) + +--- + +## 概览 + +ROMA-DSPy 使用**分层配置系统**,结合了: +- **OmegaConf**:灵活的 YAML 配置与插值 +- **Pydantic**:类型安全验证和默认值 +- **Profiles**:针对不同用例的预配置设置 +- **环境变量**:运行时覆盖 + +### 主要特性 + +- **分层合并**:合并默认值、profiles 和覆盖 +- **类型验证**:尽早捕获配置错误 +- **环境插值**:使用 `${oc.env:API_KEY}` 获取机密信息 +- **Profile 系统**:针对不同领域的预配置智能体 +- **任务感知映射**:针对不同任务类型使用不同的执行器 + +--- + +## 配置系统 + +### 解析顺序 + +配置按以下顺序加载和合并: + +1. **Pydantic 默认值** - 来自模式 (schema) 类的基础默认值 +2. **YAML 配置** - 显式配置文件 +3. **Profile** - Profile 覆盖(如果指定) +4. **CLI/运行时覆盖** - 命令行参数 +5. **环境变量** - `ROMA__*` 变量 +6. **验证** - 通过 Pydantic 进行最终验证 + +后层配置覆盖前层配置。 + +### 使用配置 + +#### 通过 CLI +```bash +# 使用 profile +uv run python -m roma_dspy.cli solve "task" --profile crypto_agent + +# 使用自定义配置文件 +uv run python -m roma_dspy.cli solve "task" --config config/examples/basic/minimal.yaml + +# 带覆盖 +uv run python -m roma_dspy.cli solve "task" \ + --profile general \ + --override agents.executor.llm.temperature=0.5 +``` + +#### 通过 Docker (Just) +```bash +# 使用 profile +just solve "task" crypto_agent + +# 带所有参数 +just solve "task" general 2 true json +# 参数: [profile] [max_depth] [verbose] [output] +``` + +#### 通过 API +```bash +curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{ + "goal": "Your task", + "config_profile": "general", + "max_depth": 2 + }' +``` + +#### 编程方式 +```python +from roma_dspy.config.manager import ConfigManager + +# 加载 profile +config_mgr = ConfigManager() +config = config_mgr.load_config(profile="general") + +# 加载自定义配置 +config = config_mgr.load_config( + config_path="config/custom.yaml", + overrides=["runtime.max_depth=2"] +) + +# 带环境前缀 +config = config_mgr.load_config( + profile="crypto_agent", + env_prefix="ROMA_" +) +``` + +--- + +## Profiles + +Profiles 是针对不同用例的预配置智能体设置。位于 `config/profiles/`。 + +### 可用 Profiles + +| Profile | 用途 | 用例 | 模型 | +|---------|------|------|------| +| **general** | 通用智能体 | Web 研究, 代码执行, 文件操作, 计算 | Gemini Flash + Claude Sonnet 4.5 | +| **crypto_agent** | 加密货币分析 | 价格跟踪, DeFi 分析, 链上数据 | 任务感知 (Gemini Flash / Claude Sonnet 4.5) | + +### Profile 结构 + +```yaml +# config/profiles/general.yaml +agents: + atomizer: + llm: + model: openrouter/google/gemini-2.5-flash + temperature: 0.0 + max_tokens: 8000 + signature_instructions: "prompt_optimization.seed_prompts.atomizer_seed:ATOMIZER_PROMPT" + demos: "prompt_optimization.seed_prompts.atomizer_seed:ATOMIZER_DEMOS" + + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.2 + max_tokens: 32000 + prediction_strategy: react + toolkits: + - class_name: E2BToolkit + enabled: true + - class_name: FileToolkit + enabled: true + +runtime: + max_depth: 6 + enable_logging: true +``` + +### 创建自定义 Profiles + +创建 `config/profiles/my_profile.yaml`: + +```yaml +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.3 + max_tokens: 16000 + prediction_strategy: react + toolkits: + - class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: my_server + server_type: http + url: https://my-mcp-server.com + +runtime: + max_depth: 2 # 推荐: 大多数任务 1-2 + timeout: 120 + enable_logging: true +``` + +使用它: +```bash +just solve "task" my_profile +``` + +--- + +## 智能体配置 + +ROMA-DSPy 有 5 个核心智能体模块。每个都可以独立配置。 + +### 智能体类型 + +| 智能体 | 角色 | 默认策略 | 工具箱 | +|-------|------|---------|--------| +| **Atomizer** | 将任务分类为原子或可分解 | chain_of_thought | 无 | +| **Planner** | 将复杂任务分解为子任务 | chain_of_thought | 无 | +| **Executor** | 执行原子任务 | react | 所有工具箱 | +| **Aggregator** | 综合子任务结果 | chain_of_thought | 无 | +| **Verifier** | 验证输出 | chain_of_thought | 无 | + +### 智能体配置模式 + +```yaml +agents: + executor: # 智能体类型: atomizer, planner, executor, aggregator, verifier + # LLM 配置 + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.2 + max_tokens: 32000 + timeout: 30 + num_retries: 3 + cache: true + + # 预测策略 (chain_of_thought 或 react) + prediction_strategy: react + + # 自定义提示词 (可选) + signature_instructions: "module.path:VARIABLE_NAME" + demos: "module.path:DEMOS_LIST" + + # 智能体特定设置 + agent_config: + max_executions: 10 # executor 的最大迭代次数 + # max_subtasks: 12 # planner 的最大子任务数 + + # 策略特定设置 + strategy_config: + # ReAct 特定设置 + + # 工具箱 (仅 executor) + toolkits: + - class_name: E2BToolkit + enabled: true + toolkit_config: + timeout: 600 +``` + +### 每智能体默认值 + +每个智能体都有合理的默认值。仅覆盖您需要的: + +```yaml +# 最小 executor 覆盖 +agents: + executor: + llm: + temperature: 0.3 # 仅覆盖温度 + # 所有其他设置使用默认值 +``` + +### 智能体特定设置 + +#### Atomizer +```yaml +atomizer: + agent_config: + confidence_threshold: 0.8 # 原子分类的阈值 +``` + +#### Planner +```yaml +planner: + agent_config: + max_subtasks: 12 # 生成的最大子任务数 +``` + +#### Executor +```yaml +executor: + agent_config: + max_executions: 10 # 最大 ReAct 迭代次数 +``` + +#### Aggregator +```yaml +aggregator: + agent_config: + synthesis_strategy: hierarchical # 如何聚合结果 +``` + +#### Verifier +```yaml +verifier: + agent_config: + verification_depth: moderate # 验证彻底程度 +``` + +--- + +## 任务感知智能体映射 + +**高级特性**:为不同任务类型使用不同的执行器配置。 + +### 任务类型 + +ROMA-DSPy 将任务分为 5 类: + +| 任务类型 | 描述 | 示例任务 | +|---------|------|----------| +| **RETRIEVE** | 数据获取, Web 搜索 | "比特币价格", "查找文档" | +| **CODE_INTERPRET** | 代码执行, 分析 | "运行此脚本", "分析 CSV 数据" | +| **THINK** | 深度推理, 分析 | "比较方法", "分析情绪" | +| **WRITE** | 内容创作 | "写报告", "创建文档" | +| **IMAGE_GENERATION** | 图像生成 | "生成图表", "创建可视化" | + +### 映射配置 + +```yaml +# 默认智能体 (用于 atomizer, planner, aggregator, verifier) +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + prediction_strategy: react + toolkits: + - class_name: FileToolkit + enabled: true + +# 任务特定执行器配置 +agent_mapping: + executors: + # RETRIEVE: 快速模型 + Web 搜索 + RETRIEVE: + llm: + model: openrouter/google/gemini-2.5-flash # 快速且便宜 + temperature: 0.0 + max_tokens: 16000 + prediction_strategy: react + agent_config: + max_executions: 6 + toolkits: + - class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: exa + server_type: http + url: https://mcp.exa.ai/mcp + + # CODE_INTERPRET: 强大模型 + 代码执行 + CODE_INTERPRET: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 # 强大 + temperature: 0.1 + max_tokens: 32000 + agent_config: + max_executions: 15 + toolkits: + - class_name: E2BToolkit + enabled: true + - class_name: FileToolkit + enabled: true +``` + +### 优势 + +- **成本优化**:简单任务使用便宜模型 +- **质量优化**:复杂任务使用强大模型 +- **工具匹配**:每种任务类型获得适当的工具箱 +- **性能**:任务特定配置带来更快的执行速度 + +### 示例: crypto_agent Profile + +`crypto_agent` profile 使用任务感知映射: + +- **RETRIEVE**: Gemini Flash (快速, 便宜) + CoinGecko/Binance +- **CODE_INTERPRET**: Claude Sonnet 4.5 (强大) + E2B + 加密数据 +- **THINK**: Claude Sonnet 4.5 + 所有工具箱 +- **WRITE**: Claude Sonnet 4.5 (创造性) + FileToolkit + 研究 + +--- + +## 工具箱配置 + +工具箱提供智能体可以使用的工具(函数)。按智能体配置。 + +### 可用工具箱 + +#### 原生工具箱 + +ROMA-DSPy 包含这些内置工具箱: + +| 工具箱 | 用途 | API 密钥 | 配置选项 | +|-------|------|---------|----------| +| **FileToolkit** | 文件 I/O 操作 | ❌ 无 | `enable_delete`, `max_file_size` | +| **CalculatorToolkit** | 数学运算 | ❌ 无 | 无 | +| **E2BToolkit** | 代码执行沙箱 | ✅ 有 | `timeout`, `auto_reinitialize` | +| **SerperToolkit** | Web 搜索 | ✅ 有 | `num_results`, `search_type` | +| **BinanceToolkit** | 加密市场数据 | ❌ 无 | `default_market`, `enable_analysis` | +| **CoinGeckoToolkit** | 加密价格 | ❌ 无 | `use_pro_api` | +| **DefiLlamaToolkit** | DeFi 协议数据 | ❌ 无 | `enable_pro_features` | +| **ArkhamToolkit** | 区块链分析 | ❌ 无 | `enable_analysis` | + +#### MCP 工具箱 + +**MCPToolkit** 很特殊 - 它可以连接到 **任何** MCP (Model Context Protocol) 服务器,让您能够访问数千个潜在工具。 + +**两种类型的 MCP 服务器:** + +1. **HTTP MCP 服务器** (远程) + - 公共或私有 HTTP 端点 + - 无需安装 + - 示例:CoinGecko MCP, Exa MCP, 或任何自定义 HTTP MCP 服务器 + +2. **Stdio MCP 服务器** (本地) + - 作为本地子进程运行 + - 通常是 npm 包或自定义脚本 + - 示例:Filesystem, GitHub, SQLite, 或任何 npm MCP 服务器 + +**查找 MCP 服务器:** +- **Awesome MCP Servers**: https://github.com/wong2/awesome-mcp-servers (数百个服务器) +- **MCP 文档**: https://modelcontextprotocol.io/ +- **构建您自己的**: 任何实现 MCP 协议的服务器 + +### 基本工具箱配置 + +```yaml +agents: + executor: + toolkits: + # 无配置的简单工具箱 + - class_name: CalculatorToolkit + enabled: true + + # 带基本配置的工具箱 + - class_name: FileToolkit + enabled: true + toolkit_config: + enable_delete: false + max_file_size: 10485760 # 10MB +``` + +### E2B 工具箱配置 + +```yaml +- class_name: E2BToolkit + enabled: true + toolkit_config: + timeout: 600 # 执行超时 (秒) + max_lifetime_hours: 23.5 # 沙箱生命周期 + auto_reinitialize: true # 失败自动重启 +``` + +**环境变量**: +```bash +E2B_API_KEY=your_e2b_api_key +E2B_TEMPLATE_ID=roma-dspy-sandbox # 自定义模板 +STORAGE_BASE_PATH=/opt/sentient # 共享存储 +``` + +### MCP 工具箱配置 + +#### HTTP MCP 服务器 (公共) + +连接到任何公共 HTTP MCP 服务器: + +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: coingecko_mcp + server_type: http + url: "https://mcp.api.coingecko.com/sse" + use_storage: true # 将大结果存储到 Parquet + storage_threshold_kb: 10 # > 10KB 时存储 +``` + +#### HTTP MCP 服务器 (带认证) + +连接到任何经过身份验证的 HTTP MCP 服务器: + +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: exa + server_type: http + url: https://mcp.exa.ai/mcp + headers: + Authorization: Bearer ${oc.env:EXA_API_KEY} + # 添加 MCP 服务器所需的任何自定义头 + transport_type: streamable + use_storage: false + tool_timeout: 60 +``` + +#### Stdio MCP 服务器 (本地) + +连接到任何 stdio MCP 服务器(npm 包或自定义脚本): + +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: filesystem + server_type: stdio + command: npx # 或 python, node 等 + args: + - "-y" + - "@modelcontextprotocol/server-filesystem" + - "/Users/yourname/Documents" # 服务器特定参数 + env: # 服务器的可选环境变量 + CUSTOM_VAR: value + use_storage: false +``` + +**常见 Stdio 示例:** + +```yaml +# GitHub MCP 服务器 +- class_name: MCPToolkit + toolkit_config: + server_name: github + server_type: stdio + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_PERSONAL_ACCESS_TOKEN: ${oc.env:GITHUB_PERSONAL_ACCESS_TOKEN} + +# SQLite MCP 服务器 +- class_name: MCPToolkit + toolkit_config: + server_name: sqlite + server_type: stdio + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-sqlite" + - "/path/to/database.db" + +# 自定义 Python MCP 服务器 +- class_name: MCPToolkit + toolkit_config: + server_name: my_custom_server + server_type: stdio + command: python + args: + - "/path/to/my_mcp_server.py" +``` + +**Stdio 服务器先决条件**: +- npm 包: `npm install -g ` +- 自定义脚本: 确保可执行并实现 MCP 协议 + +### 加密工具箱配置 + +#### Binance + +```yaml +- class_name: BinanceToolkit + enabled: true + include_tools: # 可选: 限制特定工具 + - get_current_price + - get_ticker_stats + - get_klines + toolkit_config: + enable_analysis: true + default_market: spot # spot 或 futures +``` + +#### DefiLlama + +```yaml +- class_name: DefiLlamaToolkit + enabled: true + include_tools: + - get_protocols + - get_protocol_tvl + - get_chains + toolkit_config: + enable_analysis: true + enable_pro_features: true +``` + +### 工具过滤 + +限制工具箱中可用的工具: + +```yaml +- class_name: MCPToolkit + enabled: true + include_tools: # 仅这些工具 + - get_simple_price + - get_coins_markets + - get_search + toolkit_config: + server_name: coingecko_mcp + server_type: http + url: "https://mcp.api.coingecko.com/sse" +``` + +--- + +## LLM 配置 + +为每个智能体配置语言模型。 + +### 基本 LLM 配置 + +```yaml +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.2 + max_tokens: 32000 + timeout: 30 + num_retries: 3 + cache: true +``` + +### LLM 参数 + +| 参数 | 描述 | 范围 | 默认值 | +|------|------|------|--------| +| **model** | 模型标识符 | 提供商特定 | `gpt-4o-mini` | +| **temperature** | 随机性 (0=确定性, 2=创造性) | 0.0 - 2.0 | 0.7 | +| **max_tokens** | 最大输出 Token | 1 - 200000 | 2000 | +| **timeout** | 请求超时 (秒) | > 0 | 30 | +| **num_retries** | 失败重试次数 | 0 - 10 | 3 | +| **cache** | 启用 DSPy 缓存 | true/false | true | +| **adapter_type** | DSPy 适配器类型 | `json` 或 `chat` | `json` | +| **use_native_function_calling** | 启用原生工具调用 | true/false | `true` | + +### DSPy 适配器配置 + +ROMA-DSPy 使用 DSPy 适配器来格式化 LLM 的输入/输出。有两种适配器类型可用: + +**JSONAdapter** (默认,推荐): +- 使用结构化 JSON 进行输入/输出 +- 对 Claude 和 Gemini 模型性能更好 +- 提示词格式更清晰 + +**ChatAdapter**: +- 使用聊天消息格式 +- 对某些 OpenAI 模型性能更好 +- 更具对话风格 + +**原生函数调用** (默认启用): +- 利用 LLM 提供商的原生工具调用 API (OpenAI, Anthropic 等) +- 对不支持的模型自动回退到基于文本的解析 +- 可靠性无差异,提供商集成更清洁 + +两个参数都有合理的默认值,在配置中是**可选的**: + +```yaml +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.2 + max_tokens: 16000 + # 默认: adapter_type=json, use_native_function_calling=true + # 取消注释以覆盖: + # adapter_type: chat + # use_native_function_calling: false +``` + +### 模型命名 + +#### OpenRouter (推荐) + +所有模型使用单个 API 密钥: + +```yaml +model: openrouter/anthropic/claude-sonnet-4.5 +model: openrouter/google/gemini-2.5-flash +model: openrouter/openai/gpt-4o +``` + +**环境**: `OPENROUTER_API_KEY=your_key` + +#### 直接提供商 + +```yaml +# Anthropic +model: claude-sonnet-4.5 +# 需要: ANTHROPIC_API_KEY + +# OpenAI +model: gpt-4o +# 需要: OPENAI_API_KEY + +# Google +model: gemini-2.5-flash +# 需要: GOOGLE_API_KEY +``` + +### 温度指南 + +| 温度 | 用途 | 示例 | +|------|------|------| +| **0.0** | 确定性, 事实性 | 数据检索, 分类 | +| **0.1-0.2** | 轻微创造性 | 代码生成, 分析 | +| **0.3-0.5** | 平衡 | 通用任务, 推理 | +| **0.6-1.0** | 创造性 | 内容写作, 头脑风暴 | +| **1.0+** | 非常创造性 | 诗歌, 实验性 | + +### Token 限制 + +按智能体推荐的 `max_tokens`: + +| 智能体 | 推荐值 | 理由 | +|-------|-------|------| +| **Atomizer** | 1000-8000 | 简单分类 | +| **Planner** | 4000-32000 | 复杂任务分解 | +| **Executor** | 16000-32000 | 详细执行 | +| **Aggregator** | 5000-32000 | 结果综合 | +| **Verifier** | 3000-16000 | 验证检查 | + +### 提供商特定参数 (`extra_body`) + +通过 `extra_body` 参数传递提供商特定的特性。这对 OpenRouter 的高级功能(如 Web 搜索、模型路由和提供商偏好)特别有用。 + +**安全提示**:切勿在 `extra_body` 中包含敏感密钥 (api_key, secret, token)。请使用 `api_key` 字段。 + +#### OpenRouter Web 搜索 + +启用实时 Web 搜索以获取最新信息: + +```yaml +agents: + executor: + llm: + model: openrouter/google/gemini-2.5-flash + temperature: 0.0 + extra_body: + plugins: + - id: web + engine: exa # 选项: "exa", "native", 或省略以自动选择 + max_results: 3 +``` + +**替代方案**:使用 `:online` 后缀进行快速设置: +```yaml +model: openrouter/anthropic/claude-sonnet-4.5:online +``` + +#### 带有上下文大小的 OpenRouter 原生搜索 + +对于带有可自定义上下文的 OpenRouter 原生搜索引擎: + +```yaml +extra_body: + plugins: + - id: web + engine: native + web_search_options: + search_context_size: high # 选项: "low", "medium", "high" +``` + +#### 模型回退数组 + +自动故障转移到替代模型: + +```yaml +extra_body: + models: + - anthropic/claude-sonnet-4.5 + - openai/gpt-4o + - google/gemini-2.5-pro + route: fallback # 选项: "fallback", "lowest-cost", "lowest-latency" +``` + +#### 提供商偏好 + +控制使用哪些提供商: + +```yaml +extra_body: + provider: + order: + - Anthropic + - OpenAI + data_collection: deny # 隐私控制: "allow" 或 "deny" +``` + +#### 完整 OpenRouter Web 搜索示例 + +```yaml +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + temperature: 0.2 + max_tokens: 16000 + extra_body: + # 启用带自定义设置的 Web 搜索 + plugins: + - id: web + engine: exa + max_results: 5 + search_prompt: "Relevant information:" + # 针对可靠性的回退模型 + models: + - anthropic/claude-sonnet-4.5 + - openai/gpt-4o + route: fallback +``` + +**文档**:查看 [OpenRouter Web 搜索文档](https://openrouter.ai/docs/features/web-search) 获取所有可用选项。 + +**成本警告**:Web 搜索插件可能会显著增加每个请求的 API 成本。 + +--- + +## 运行时设置 + +控制执行行为、超时和日志记录。 + +### 运行时配置 + +```yaml +runtime: + max_depth: 6 # 递归深度 (推荐: 1-2) + max_concurrency: 5 # 并行任务限制 + timeout: 120 # 全局超时 (秒) + verbose: true # 详细输出 + enable_logging: true # 记录到文件 + log_level: INFO # DEBUG, INFO, WARNING, ERROR + + # 缓存配置 + cache: + enabled: true + enable_disk_cache: true + enable_memory_cache: true + disk_cache_dir: .cache/dspy + disk_size_limit_bytes: 30000000000 # 30GB + memory_max_entries: 1000000 +``` + +### 运行时参数 + +| 参数 | 描述 | 范围 | 默认值 | 推荐值 | +|------|------|------|--------|--------| +| **max_depth** | 最大任务分解深度 | 1-20 | 5 | **1-2** | +| **max_concurrency** | 并行子任务数 | 1-50 | 5 | 5-10 | +| **timeout** | 全局执行超时 (秒) | 1-300 | 30 | 120-300 | +| **verbose** | 打印详细输出 | bool | false | true (开发) | +| **enable_logging** | 文件日志 | bool | false | true | +| **log_level** | 日志详细程度 | DEBUG-CRITICAL | INFO | INFO | + +### 最大深度指南 + +**重要**:较低的 max_depth = 更快、更便宜、更可靠的执行。 + +| max_depth | 用例 | 权衡 | +|-----------|------|------| +| **1** | 简单原子任务 | 快速, 便宜, 有限分解 | +| **2** | 大多数生产用例 | **推荐** - 良好平衡 | +| **3-4** | 复杂多步任务 | 较慢, 较贵 | +| **5+** | 高度复杂的分层任务 | 非常慢, 昂贵, 可能失败 | + +**最佳实践**:从 `max_depth=1` 开始,仅在需要时增加。 + +--- + +## 存储配置 + +配置执行数据和工具结果的持久存储。 + +### 存储配置 + +```yaml +storage: + base_path: ${oc.env:STORAGE_BASE_PATH,/opt/sentient} + max_file_size: 104857600 # 100MB + + # PostgreSQL (执行跟踪) + postgres: + enabled: ${oc.env:POSTGRES_ENABLED,true} + connection_url: ${oc.env:DATABASE_URL,postgresql+asyncpg://localhost/roma_dspy} + pool_size: 10 + max_overflow: 20 +``` + +### 存储后端 + +#### 本地文件系统 + +```bash +# .env +STORAGE_BASE_PATH=/opt/sentient +``` + +#### S3 via goofys + +```bash +# .env +STORAGE_BASE_PATH=/opt/sentient +ROMA_S3_BUCKET=my-bucket +AWS_REGION=us-east-1 +AWS_ACCESS_KEY_ID=your_key +AWS_SECRET_ACCESS_KEY=your_secret +``` + +#### PostgreSQL + +```bash +# .env +POSTGRES_ENABLED=true +DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/roma_dspy +``` + +或通过 docker-compose (自动): + +```bash +just docker-up # 自动启动 postgres +``` + +### 工具结果存储 + +MCP 和原生工具箱可以将大结果存储到 Parquet: + +```yaml +toolkits: + - class_name: MCPToolkit + toolkit_config: + use_storage: true + storage_threshold_kb: 10 # 存储 > 10KB 的结果 +``` + +**优势**: +- 减少上下文大小 +- 启用大型数据集处理 +- 自动压缩 +- 可通过 DuckDB 查询 + +--- + +## 可观察性 (MLflow) + +使用 MLflow 跟踪执行指标、追踪和模型性能。 + +### MLflow 配置 + +```yaml +observability: + mlflow: + enabled: ${oc.env:MLFLOW_ENABLED,false} + tracking_uri: ${oc.env:MLFLOW_TRACKING_URI,http://mlflow:5000} + experiment_name: ROMA-General-Agent + log_traces: true # 记录完整执行追踪 + log_compiles: true # 记录 DSPy 编译 + log_evals: true # 记录评估 +``` + +### 环境变量 + +```bash +# .env +MLFLOW_ENABLED=true +MLFLOW_TRACKING_URI=http://mlflow:5000 +MLFLOW_EXPERIMENT=ROMA-DSPy +``` + +### 使用 MLflow + +#### 启动 MLflow 服务器 + +```bash +# 通过 Docker Compose (推荐) +just docker-up-full # 包含 MLflow + +# 访问 UI +open http://localhost:5000 +``` + +#### 跟踪执行 + +```bash +# 启用 MLflow 运行任务 +MLFLOW_ENABLED=true just solve "analyze bitcoin price" + +# 在 MLflow UI 中查看追踪 +open http://localhost:5000 +``` + +### MLflow 跟踪内容 + +- **执行指标**:持续时间、深度、Token 使用量 +- **LLM 调用**:模型、参数、延迟 +- **工具使用**:工具调用、结果、错误 +- **追踪**:带 span 的完整执行树 +- **参数**:所有配置值 +- **工件**:输出、日志、检查点 + +--- + +## 弹性设置 + +自动错误处理、重试和恢复。 + +### 弹性配置 + +```yaml +resilience: + # 重试配置 + retry: + enabled: true + max_attempts: 5 + strategy: exponential_backoff + base_delay: 2.0 # 初始延迟 (秒) + max_delay: 60.0 # 最大延迟 + + # 断路器 + circuit_breaker: + enabled: true + failure_threshold: 5 # 打开前的故障数 + recovery_timeout: 120.0 # 重试前秒数 + half_open_max_calls: 3 # 恢复时的测试调用数 + + # 检查点 + checkpoint: + enabled: true + storage_path: ${oc.env:ROMA_CHECKPOINT_PATH,.checkpoints} + max_checkpoints: 20 + max_age_hours: 48.0 + compress_checkpoints: true + verify_integrity: true +``` + +### 重试策略 + +| 策略 | 行为 | 用例 | +|------|------|------| +| **exponential_backoff** | 每次重试延迟翻倍 | 大多数情况 (默认) | +| **fixed_delay** | 每次重试延迟相同 | 可预测的时间 | +| **random_backoff** | 随机抖动 | 避免惊群效应 | + +### 断路器状态 + +- **Closed**: 正常运行 +- **Open**: 故障中,拒绝新请求 +- **Half-Open**: 测试恢复 + +### 检查点恢复 + +从故障中自动恢复: + +```python +from roma_dspy.core.engine.solve import solve + +# 执行将自动创建检查点 +result = solve("complex task", max_depth=3) + +# 如果中断,从检查点恢复 +result = solve("complex task", resume_from_checkpoint=True) +``` + +--- + +## 日志配置 + +使用 loguru 进行结构化日志记录。 + +### 日志配置 + +```yaml +logging: + level: ${oc.env:LOG_LEVEL,INFO} + log_dir: ${oc.env:LOG_DIR,logs} # null = 仅控制台 + console_format: detailed # minimal, default, detailed + file_format: json # default, detailed, json + colorize: true + serialize: true # JSON 序列化 + rotation: 500 MB # 文件轮转大小 + retention: 90 days # 保留时间 + compression: zip # 压缩轮转日志 + backtrace: true # 完整回溯 + diagnose: false # 变量值 (生产中禁用) + enqueue: true # 线程安全 +``` + +### 日志级别 + +| 级别 | 用途 | +|------|------| +| **DEBUG** | 开发, 详细追踪 | +| **INFO** | 生产, 重要事件 | +| **WARNING** | 潜在问题 | +| **ERROR** | 错误, 异常 | +| **CRITICAL** | 致命错误 | + +### 环境变量 + +```bash +# .env +LOG_LEVEL=INFO +LOG_DIR=logs # 或 null 用于仅控制台 +LOG_CONSOLE_FORMAT=detailed +LOG_FILE_FORMAT=json +``` + +### 日志格式 + +#### 控制台格式 + +- **minimal**: 级别 + 消息 +- **default**: 时间, 级别, 模块, 消息 (彩色) +- **detailed**: 包含 execution_id, 行号的完整上下文 + +#### 文件格式 + +- **default**: 标准文本格式 +- **detailed**: 包含进程/线程信息 +- **json**: 机器可解析的结构化日志 + +--- + +## 环境变量 + +环境变量覆盖配置值。 + +### LLM 提供商密钥 + +```bash +# OpenRouter (推荐 - 单个 key 用于所有模型) +OPENROUTER_API_KEY=your_key + +# 或单独的提供商 +OPENAI_API_KEY=your_key +ANTHROPIC_API_KEY=your_key +GOOGLE_API_KEY=your_key +``` + +### 工具箱密钥 + +```bash +# 代码执行 +E2B_API_KEY=your_key +E2B_TEMPLATE_ID=roma-dspy-sandbox + +# Web 搜索 +EXA_API_KEY=your_key +SERPER_API_KEY=your_key + +# 加密 API (均为可选,公共端点无需 key) +COINGECKO_API_KEY=your_key # 用于 Pro API +DEFILLAMA_API_KEY=your_key # 用于 Pro 功能 +ARKHAM_API_KEY=your_key +BINANCE_API_KEY=your_key +BINANCE_API_SECRET=your_secret + +# GitHub MCP +GITHUB_PERSONAL_ACCESS_TOKEN=your_token + +# 任何 MCP 服务器可能需要其自己的环境变量 +``` + +### 存储与数据库 + +```bash +# 存储 +STORAGE_BASE_PATH=/opt/sentient +ROMA_S3_BUCKET=my-bucket +AWS_ACCESS_KEY_ID=your_key +AWS_SECRET_ACCESS_KEY=your_secret + +# PostgreSQL +POSTGRES_ENABLED=true +DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/roma_dspy +``` + +### MLflow + +```bash +MLFLOW_ENABLED=true +MLFLOW_TRACKING_URI=http://mlflow:5000 +MLFLOW_EXPERIMENT=ROMA-DSPy +``` + +### 运行时覆盖 + +使用带双下划线的 `ROMA__` 前缀: + +```bash +# 覆盖 agents.executor.llm.temperature +ROMA__AGENTS__EXECUTOR__LLM__TEMPERATURE=0.5 + +# 覆盖 runtime.max_depth +ROMA__RUNTIME__MAX_DEPTH=2 +``` + +**格式**: `ROMA______=value` + +### Docker Compose + +在 docker-compose 中,在 `.env` 中设置: + +```bash +# .env +OPENROUTER_API_KEY=your_key +E2B_API_KEY=your_key +POSTGRES_ENABLED=true +MLFLOW_ENABLED=true +``` + +然后: +```bash +just docker-up # 自动加载 .env +``` + +--- + +## 自定义提示词和演示 + +使用优化的提示词和 Few-shot 示例增强智能体性能。 + +### 签名指令 + +自定义指令指导智能体的行为。 + +#### 三种格式 + +**1. 内联字符串** +```yaml +agents: + executor: + signature_instructions: "逐步执行任务并提供清晰的推理。" +``` + +**2. Jinja 模版文件** +```yaml +agents: + executor: + signature_instructions: "config/prompts/executor.jinja" +``` + +**3. Python 模块变量** +```yaml +agents: + executor: + signature_instructions: "prompt_optimization.seed_prompts.executor_seed:EXECUTOR_PROMPT" +``` + +#### 种子提示词 + +ROMA-DSPy 在 `prompt_optimization/seed_prompts/` 中包含优化的种子提示词: + +| 模块 | 变量 | 用途 | +|------|------|------| +| `atomizer_seed` | `ATOMIZER_PROMPT` | 任务分类 | +| `planner_seed` | `PLANNER_PROMPT` | 任务分解 | +| `executor_seed` | `EXECUTOR_PROMPT` | 通用执行 | +| `executor_retrieve_seed` | `EXECUTOR_RETRIEVE_PROMPT` | 数据检索 | +| `executor_code_seed` | `EXECUTOR_CODE_PROMPT` | 代码执行 | +| `executor_think_seed` | `EXECUTOR_THINK_PROMPT` | 深度推理 | +| `executor_write_seed` | `EXECUTOR_WRITE_PROMPT` | 内容创作 | +| `aggregator_seed` | `AGGREGATOR_PROMPT` | 结果综合 | +| `verifier_seed` | `VERIFIER_PROMPT` | 输出验证 | + +### 演示 (Few-Shot 示例) + +提供示例以指导智能体。 + +#### 格式 + +```yaml +agents: + executor: + demos: "prompt_optimization.seed_prompts.executor_seed:EXECUTOR_DEMOS" +``` + +#### 创建自定义演示 + +```python +# my_prompts/executor_demos.py +import dspy + +EXECUTOR_DEMOS = [ + dspy.Example( + goal="计算 2500 的 15%", + answer="375" + ).with_inputs("goal"), + dspy.Example( + goal="法国的首都是哪里?", + answer="巴黎" + ).with_inputs("goal") +] +``` + +在配置中使用: +```yaml +agents: + executor: + demos: "my_prompts.executor_demos:EXECUTOR_DEMOS" +``` + +### 自定义签名 + +覆盖默认 DSPy 签名: + +```yaml +agents: + executor: + signature: "goal -> answer: str, confidence: float" +``` + +**注意**:大多数用户不需要此项。请改用 `signature_instructions`。 + +--- + +## 配置示例 + +ROMA-DSPy 在 `config/examples/` 中包含全面的配置示例。这些是真实的、可工作的配置,演示了不同的概念和模式。 + +### 可用示例 + +#### 基础示例 (`config/examples/basic/`) + +| 示例 | 描述 | 使用方法 | +|------|------|----------| +| **minimal.yaml** | 最简单的可能配置 | `just solve "task" -c config/examples/basic/minimal.yaml` | +| **multi_toolkit.yaml** | 多工具箱 (E2B + File + Calculator) | `just solve "task" -c config/examples/basic/multi_toolkit.yaml` | + +**演示**:基础知识、工具箱使用、基本配置模式 + +#### MCP 示例 (`config/examples/mcp/`) + +| 示例 | 描述 | 使用方法 | +|------|------|----------| +| **http_public_server.yaml** | 公共 HTTP MCP 服务器 (CoinGecko) - 无需设置 | `just solve "task" -c config/examples/mcp/http_public_server.yaml` | +| **stdio_local_server.yaml** | 通过 npx 的本地 stdio MCP 服务器 | `just solve "task" -c config/examples/mcp/stdio_local_server.yaml` | +| **multi_server.yaml** | 多个 MCP 服务器 (HTTP + stdio) | `just solve "task" -c config/examples/mcp/multi_server.yaml` | +| **common_servers.yaml** | 常见 MCP 服务器 (GitHub, Filesystem, SQLite) | `just solve "task" -c config/examples/mcp/common_servers.yaml` | + +**演示**:HTTP vs stdio MCP 服务器、多服务器编排、存储配置 + +#### 加密示例 (`config/examples/crypto/`) + +| 示例 | 描述 | 使用方法 | +|------|------|----------| +| **crypto_agent.yaml** | 现实世界的加密分析智能体 | `just solve "task" -c config/examples/crypto/crypto_agent.yaml` | + +**演示**:特定领域智能体、结合 MCP + 原生工具箱、多源数据聚合 + +#### 高级示例 (`config/examples/advanced/`) + +| 示例 | 描述 | 使用方法 | +|------|------|----------| +| **task_aware_mapping.yaml** | 任务特定执行器配置 | `just solve "task" -c config/examples/advanced/task_aware_mapping.yaml` | +| **custom_prompts.yaml** | 自定义提示词和演示 | `just solve "task" -c config/examples/advanced/custom_prompts.yaml` | + +**演示**:任务感知智能体映射、每种任务类型的成本/质量优化、加载自定义签名指令和演示 + +### 快速参考 + +```bash +# 使用 profile (推荐) +just solve "task" general + +# 使用示例配置 +just solve "task" -c config/examples/basic/minimal.yaml + +# 带 CLI 参数 +uv run python -m roma_dspy.cli solve "task" \ + --config config/examples/basic/minimal.yaml \ + --override runtime.max_depth=1 +``` + +### 示例结构 + +每个示例包括: +- 解释每个部分的**内联注释** +- **设置要求** (API 密钥, npm 包) +- 展示如何运行的**用法示例** +- 关于示例演示内容的**关键学习点** + +### 详细指南 + +查看 **[config/examples/README.md](../config/examples/README.md)** 获取: +- 完整的示例目录结构 +- 每个示例的详细描述 +- 设置说明 +- 常见问题和解决方案 +- 成功技巧 + +--- + +## 最佳实践 + +### 1. 从简单开始 + +```yaml +# 从最小配置开始 +agents: + executor: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 + prediction_strategy: react + toolkits: + - class_name: FileToolkit + enabled: true + +runtime: + max_depth: 1 # 从 1 开始,如果需要则增加 +``` + +仅在需要时增加复杂性。 + +### 2. 使用 Profiles + +不要从头开始创建配置。从 profile 开始: + +```bash +# 使用现有 profile +just solve "task" general + +# 或复制并自定义 +cp config/profiles/general.yaml config/profiles/my_profile.yaml +# 编辑 my_profile.yaml +just solve "task" my_profile +``` + +### 3. 使用环境变量存储机密 + +切勿在配置文件中硬编码 API 密钥: + +```yaml +# ❌ 错误 +headers: + Authorization: Bearer sk-1234567890 + +# ✅ 正确 +headers: + Authorization: Bearer ${oc.env:EXA_API_KEY} +``` + +### 4. 优化 max_depth + +**大多数任务需要 max_depth=1 或 2**: + +- 从 1 开始 +- 如果任务需要分解,增加到 2 +- 仅对复杂分层任务使用 3+ +- 更高的深度 = 更慢 + 更昂贵 + +### 5. 用于成本优化的任务感知映射 + +对简单任务使用便宜模型: + +```yaml +agent_mapping: + executors: + RETRIEVE: + llm: + model: openrouter/google/gemini-2.5-flash # $0.075/1M tokens + CODE_INTERPRET: + llm: + model: openrouter/anthropic/claude-sonnet-4.5 # $3/1M tokens +``` + +### 6. 启用缓存 + +```yaml +agents: + executor: + llm: + cache: true # 启用 DSPy 缓存 + +runtime: + cache: + enabled: true + enable_disk_cache: true +``` + +省钱并提高速度。 + +### 7. 对大数据使用存储 + +```yaml +toolkits: + - class_name: MCPToolkit + toolkit_config: + use_storage: true + storage_threshold_kb: 10 # 存储 > 10KB 的结果 +``` + +防止上下文溢出。 + +### 8. 使用 MLflow 监控 + +```yaml +observability: + mlflow: + enabled: true + log_traces: true +``` + +跟踪性能、成本和错误。 + +### 9. 配置弹性 + +```yaml +resilience: + retry: + enabled: true + max_attempts: 5 + circuit_breaker: + enabled: true + checkpoint: + enabled: true +``` + +从故障中自动恢复。 + +### 10. 验证配置 + +```python +from roma_dspy.config.manager import ConfigManager + +# 使用前验证 +try: + config = ConfigManager().load_config(profile="my_profile") + print("✅ 配置有效") +except ValueError as e: + print(f"❌ 配置无效: {e}") +``` + +--- + +## 下一步 + +- **[QUICKSTART.md](QUICKSTART.md)** - 快速开始 +- **[TOOLKITS.md](TOOLKITS.md)** - 完整工具箱参考 +- **[MCP.md](MCP.md)** - MCP 集成指南 +- **[API.md](API.md)** - REST API 参考 +- **[DEPLOYMENT.md](DEPLOYMENT.md)** - 生产部署 +- **示例**: `config/examples/` - 真实世界示例 + +--- + +**有问题?** 查看 `config/examples/` 中的示例或在 GitHub 上创建 issue。 + diff --git a/docs_zh/DEPLOYMENT.md b/docs_zh/DEPLOYMENT.md new file mode 100644 index 00000000..79d31689 --- /dev/null +++ b/docs_zh/DEPLOYMENT.md @@ -0,0 +1,725 @@ +# ROMA-DSPy 部署指南 + +ROMA-DSPy 的生产部署指南。 + +## 目录 + +- [概览](#概览) +- [快速部署](#快速部署) +- [架构](#架构) +- [环境配置](#环境配置) +- [Docker 部署](#docker-部署) +- [生产检查清单](#生产检查清单) +- [监控与可观察性](#监控与可观察性) +- [扩展](#扩展) +- [安全性](#安全性) +- [故障排除](#故障排除) + +--- + +## 概览 + +ROMA-DSPy 专为使用 Docker Compose 进行生产部署而设计,提供: + +**基础设施:** +- PostgreSQL (执行/检查点持久化) +- MinIO (S3 兼容对象存储,用于 MLflow 工件) +- MLflow (可选,实验跟踪) +- ROMA API (FastAPI 服务器) + +**特性:** +- 健康检查与自动重启 +- 卷持久化 +- 网络隔离 +- 多阶段 Docker 构建 +- 非 root 容器 + +--- + +## 快速部署 + +### 先决条件 + +- Docker 24.0+ 和 Docker Compose 2.0+ +- 最小 4GB RAM (推荐 8GB) +- 20GB 磁盘空间 +- 可用端口:8000 (API), 5432 (Postgres), 9000/9001 (MinIO), 5000 (MLflow) + +### 1. 克隆仓库 + +```bash +git clone https://github.com/your-org/ROMA-DSPy.git +cd ROMA-DSPy +``` + +### 2. 配置环境 + +```bash +# 复制环境模版 +cp .env.example .env + +# 编辑 .env 并设置必需值 +nano .env +``` + +**最低要求:** +```bash +# LLM 提供商 +OPENROUTER_API_KEY=your_key_here + +# 数据库 +POSTGRES_PASSWORD=secure_password_here + +# MinIO/S3 +MINIO_ROOT_PASSWORD=secure_password_here +``` + +### 3. 启动服务 + +```bash +# 基础部署 (API + PostgreSQL + MinIO) +just docker-up + +# 完整部署 (包含 MLflow 可观察性) +just docker-up-full + +# 验证健康状态 +curl http://localhost:8000/health +``` + +### 4. 测试 + +```bash +# 通过 API +curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{"goal": "What is 2+2?", "max_depth": 1}' | jq + +# 通过 CLI (容器内) +docker exec -it roma-dspy-api roma-dspy solve "What is 2+2?" +``` + +--- + +## 架构 + +### Docker Compose 栈 + +``` +┌──────────────────────────────────────────────────────┐ +│ Docker Network │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ ROMA API │───▶│ PostgreSQL │ │ +│ │ Port: 8000 │ │ Port: 5432 │ │ +│ └──────┬───────┘ └──────────────┘ │ +│ │ │ +│ │ ┌──────────────┐ │ +│ └───────────▶│ MinIO │ │ +│ │ Port: 9000 │ │ +│ │ Console:9001 │ │ +│ └──────┬───────┘ │ +│ │ │ +│ ┌──────▼───────┐ │ +│ │ MLflow │ (可选) │ +│ │ Port: 5000 │ │ +│ └──────────────┘ │ +└──────────────────────────────────────────────────────┘ +``` + +### 服务描述 + +**roma-api:** +- FastAPI 应用服务器 +- 处理执行管理 +- 暴露 REST API +- 健康检查:`http://localhost:8000/health` + +**postgres:** +- PostgreSQL 16 Alpine +- 存储执行元数据、检查点、追踪 +- 持久卷:`postgres_data` +- 健康检查:`pg_isready` + +**minio:** +- S3 兼容对象存储 +- 存储 MLflow 工件 +- 持久卷:`minio_data` +- UI: `http://localhost:9001` + +**mlflow** (可选): +- 实验跟踪服务器 +- 需要 `--profile observability` +- UI: `http://localhost:5000` + +--- + +## 环境配置 + +### 必需变量 + +```bash +# LLM 提供商 (至少需要一个) +OPENROUTER_API_KEY=your_key_here # 推荐 +# 或 +OPENAI_API_KEY=your_key_here +ANTHROPIC_API_KEY=your_key_here +GOOGLE_API_KEY=your_key_here + +# 数据库 +POSTGRES_DB=roma_dspy # 数据库名称 +POSTGRES_USER=postgres # 数据库用户 +POSTGRES_PASSWORD=CHANGE_ME_IN_PROD # 数据库密码 +POSTGRES_PORT=5432 # 主机端口 + +# MinIO/S3 +MINIO_ROOT_USER=minioadmin # MinIO 访问密钥 +MINIO_ROOT_PASSWORD=CHANGE_ME_IN_PROD # MinIO 秘密密钥 +MINIO_PORT=9000 # S3 API 端口 +MINIO_CONSOLE_PORT=9001 # 控制台端口 + +# API +API_PORT=8000 # API 端口 +POSTGRES_ENABLED=true # 启用 PostgreSQL 存储 +``` + +### 可选变量 + +```bash +# 工具箱 API 密钥 +E2B_API_KEY=your_key_here # 代码执行 +EXA_API_KEY=your_key_here # Web 搜索 (via MCP) +SERPER_API_KEY=your_key_here # Web 搜索工具箱 +GITHUB_PERSONAL_ACCESS_TOKEN=your_token # GitHub MCP 服务器 +COINGECKO_API_KEY=your_key_here # CoinGecko Pro API + +# MLflow (用于可观察性 profile) +MLFLOW_PORT=5000 +MLFLOW_TRACKING_URI=http://mlflow:5000 + +# 存储 +STORAGE_BASE_PATH=/opt/sentient # 文件存储基础路径 + +# 安全性 +ALLOWED_ORIGINS=https://yourdomain.com # CORS 源 (逗号分隔) + +# 日志 +LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR +LOG_DIR=/app/logs # 日志目录 +``` + +--- + +## Docker 部署 + +### 构建并启动 + +**从头构建:** +```bash +# 清理构建 +just docker-build-clean + +# 启动服务 +just docker-up +``` + +**使用现有镜像启动:** +```bash +# 基础 (API + Postgres + MinIO) +just docker-up + +# 完整 (包含 MLflow) +just docker-up-full +``` + +### 验证部署 + +```bash +# 检查所有服务运行状态 +just docker-ps + +# 检查健康状态 +curl http://localhost:8000/health + +# 查看日志 +just docker-logs + +# 查看特定服务日志 +just docker-logs-service roma-api +just docker-logs-service postgres +just docker-logs-service mlflow +``` + +### 停止服务 + +```bash +# 停止 (保留数据) +just docker-down + +# 停止并移除卷 (数据丢失!) +just docker-down-clean +``` + +--- + +## 生产检查清单 + +### 安全性 + +- [ ] 更改 `.env` 中的默认密码: + - `POSTGRES_PASSWORD` + - `MINIO_ROOT_PASSWORD` + +- [ ] 为 CORS 设置 `ALLOWED_ORIGINS` (生产环境中不要使用 `*`) + +- [ ] 使用 HTTPS 反向代理 (nginx, Caddy, Traefik) + +- [ ] 在 API 上启用认证 (添加中间件) + +- [ ] 限制网络访问 (防火墙规则) + +- [ ] 使用机密管理 (Docker secrets, Vault, AWS Secrets Manager) + +- [ ] 定期更新基础镜像: + ```bash + docker-compose pull + docker-compose up -d + ``` + +### 可靠性 + +- [ ] 配置自动备份: + ```bash + # PostgreSQL 备份 + docker exec roma-dspy-postgres pg_dump -U postgres roma_dspy > backup.sql + ``` + +- [ ] 在 `docker-compose.yaml` 中设置资源限制: + ```yaml + roma-api: + deploy: + resources: + limits: + cpus: '2.0' + memory: 4G + reservations: + cpus: '1.0' + memory: 2G + ``` + +- [ ] 监控磁盘使用率: + ```bash + docker system df + docker volume ls + ``` + +- [ ] 配置日志轮转: + ```yaml + roma-api: + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + ``` + +### 可观察性 + +- [ ] 启用 MLflow 跟踪: + ```bash + just docker-up-full + ``` + +- [ ] 设置健康检查监控 (Prometheus, Datadog 等) + +- [ ] 配置日志聚合 (ELK, Grafana Loki, Datadog) + +- [ ] 监控资源使用率 (CPU, 内存, 磁盘) + +- [ ] 为服务故障设置告警 + +--- + +## 监控与可观察性 + +### 健康检查 + +**API 健康:** +```bash +curl http://localhost:8000/health +``` + +**响应:** +```json +{ + "status": "healthy", + "version": "0.1.0", + "uptime_seconds": 3600.5, + "active_executions": 2, + "storage_connected": true, + "cache_size": 5, + "timestamp": "2024-10-21T12:00:00.000Z" +} +``` + +**PostgreSQL 健康:** +```bash +docker exec roma-dspy-postgres pg_isready -U postgres +``` + +**MinIO 健康:** +```bash +curl http://localhost:9000/minio/health/live +``` + +### MLflow UI + +访问地址:http://localhost:5000 + +**特性:** +- 实验跟踪 +- 运行比较 +- 模型注册 +- 工件存储 + +**查看执行:** +1. 导航至 http://localhost:5000 +2. 按实验名称过滤 +3. 点击 execution ID 查看详情 + +### 指标端点 + +```bash +# 执行指标 +curl http://localhost:8000/api/v1/executions//metrics | jq + +# 成本摘要 +curl http://localhost:8000/api/v1/executions//costs | jq + +# 工具箱指标 +curl http://localhost:8000/api/v1/executions//toolkit-metrics | jq + +# LM 追踪 +curl http://localhost:8000/api/v1/executions//lm-traces | jq +``` + +### 日志聚合 + +**查看日志:** +```bash +# 所有服务 +just docker-logs + +# 特定服务 +just docker-logs-service roma-api + +# 跟踪日志 +docker-compose logs -f roma-api +``` + +**导出日志:** +```bash +docker-compose logs roma-api > roma-api.log +``` + +--- + +## 扩展 + +### 水平扩展 (多 API 实例) + +**docker-compose.yaml:** +```yaml +roma-api: + # ... 现有配置 ... + deploy: + replicas: 3 # 运行 3 个实例 + + # 负载均衡器 + labels: + - "traefik.enable=true" + - "traefik.http.routers.roma.rule=Host(`api.yourdomain.com`)" +``` + +**使用 nginx 负载均衡:** +```nginx +upstream roma_api { + server localhost:8001; + server localhost:8002; + server localhost:8003; +} + +server { + listen 80; + server_name api.yourdomain.com; + + location / { + proxy_pass http://roma_api; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } +} +``` + +### 垂直扩展 (资源限制) + +**docker-compose.yaml:** +```yaml +roma-api: + deploy: + resources: + limits: + cpus: '4.0' + memory: 8G + reservations: + cpus: '2.0' + memory: 4G + +postgres: + deploy: + resources: + limits: + cpus: '2.0' + memory: 4G + reservations: + cpus: '1.0' + memory: 2G +``` + +### 数据库扩展 + +**PostgreSQL 优化:** +```bash +# 连接到数据库 +docker exec -it roma-dspy-postgres psql -U postgres -d roma_dspy + +# 分析表 +ANALYZE executions; +ANALYZE checkpoints; +ANALYZE lm_traces; + +# 真空清理 +VACUUM ANALYZE; + +# 检查索引 +\di +``` + +**连接池** (如果需要,添加 PgBouncer): +```yaml +pgbouncer: + image: pgbouncer/pgbouncer:latest + environment: + DATABASE_URL: postgres://postgres:password@postgres:5432/roma_dspy + POOL_MODE: transaction + MAX_CLIENT_CONN: 1000 + DEFAULT_POOL_SIZE: 20 +``` + +--- + +## 安全性 + +### HTTPS/TLS + +**选项 1:nginx 反向代理** +```nginx +server { + listen 443 ssl; + server_name api.yourdomain.com; + + ssl_certificate /etc/nginx/ssl/cert.pem; + ssl_certificate_key /etc/nginx/ssl/key.pem; + + location / { + proxy_pass http://localhost:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` + +**选项 2:Caddy (自动 HTTPS)** +```caddy +api.yourdomain.com { + reverse_proxy localhost:8000 +} +``` + +### 认证 + +**添加 API 密钥中间件** (示例): +```python +# src/roma_dspy/api/middleware.py +from fastapi import HTTPException, Request +from starlette.middleware.base import BaseHTTPMiddleware + +class APIKeyMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + api_key = request.headers.get("X-API-Key") + if not api_key or api_key != os.getenv("API_KEY"): + raise HTTPException(status_code=401, detail="Invalid API key") + return await call_next(request) +``` + +**使用:** +```python +# src/roma_dspy/api/main.py +app.add_middleware(APIKeyMiddleware) +``` + +### 网络安全 + +**防火墙规则:** +```bash +# 仅允许特定 IP +sudo ufw allow from 203.0.113.0/24 to any port 8000 + +# 或使用 Docker 网络策略 +``` + +**仅内部网络:** +```yaml +# docker-compose.yaml +services: + postgres: + ports: [] # 不暴露给主机 + networks: + - roma-network + +networks: + roma-network: + internal: true # 无外部访问 +``` + +### 机密管理 + +**使用 Docker secrets:** +```yaml +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + openrouter_api_key: + file: ./secrets/openrouter_api_key.txt + +services: + roma-api: + secrets: + - postgres_password + - openrouter_api_key + environment: + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + OPENROUTER_API_KEY_FILE: /run/secrets/openrouter_api_key +``` + +--- + +## 故障排除 + +### 服务无法启动 + +**检查日志:** +```bash +just docker-logs-service roma-api +just docker-logs-service postgres +``` + +**常见问题:** + +1. **端口已被占用:** + ```bash + # 查找占用端口的进程 + lsof -i :8000 + + # 杀死进程或更改 .env 中的 API_PORT + ``` + +2. **数据库连接失败:** + ```bash + # 检查 postgres 健康 + docker exec roma-dspy-postgres pg_isready -U postgres + + # 验证 .env 中的 DATABASE_URL + ``` + +3. **内存不足:** + ```bash + # 检查 Docker 资源 + docker stats + + # 增加 Docker 内存限制 + # Docker Desktop → Settings → Resources → Memory + ``` + +### 数据持久化问题 + +**检查卷:** +```bash +# 列出卷 +docker volume ls | grep roma + +# 检查卷 +docker volume inspect roma-dspy_postgres_data + +# 备份卷 +docker run --rm -v roma-dspy_postgres_data:/data -v $(pwd):/backup alpine tar czf /backup/postgres_backup.tar.gz /data +``` + +### 性能问题 + +**监控资源:** +```bash +# 实时统计 +docker stats + +# 检查磁盘使用 +docker system df + +# 清理未使用数据 +docker system prune -a +``` + +**数据库慢查询:** +```bash +# 启用查询日志 +docker exec -it roma-dspy-postgres psql -U postgres -d roma_dspy + +# 显示慢查询 +SELECT query, calls, total_time, mean_time +FROM pg_stat_statements +ORDER BY total_time DESC +LIMIT 10; +``` + +### MLflow 无法访问 + +**检查服务:** +```bash +# 确保以 observability profile 启动 +just docker-up-full + +# 检查日志 +docker-compose logs mlflow + +# 验证端口 +curl http://localhost:5000 +``` + +--- + +## 额外资源 + +- **快速开始**: [QUICKSTART.md](QUICKSTART.md) +- **配置**: [CONFIGURATION.md](CONFIGURATION.md) +- **API 参考**: http://localhost:8000/docs +- **Docker Compose 文档**: https://docs.docker.com/compose/ +- **FastAPI 部署**: https://fastapi.tiangolo.com/deployment/ + +--- + +**生产就绪!** 🚀 + +如有问题,请先检查日志 (`just docker-logs`),然后查阅文档或提交 issue。 + diff --git a/docs_zh/E2B_SETUP.md b/docs_zh/E2B_SETUP.md new file mode 100644 index 00000000..080d6419 --- /dev/null +++ b/docs_zh/E2B_SETUP.md @@ -0,0 +1,447 @@ +# E2B 集成设置指南 + +## 概览 + +本指南说明如何为 ROMA-DSPy 设置带 S3 存储集成的 E2B 代码执行沙箱。此设置使智能体能够在隔离的沙箱中执行代码,同时通过 goofys 保持对共享 S3 存储的访问权限。 + +## 架构 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ 主机系统 │ +│ │ +│ ┌────────────┐ ┌─────────────────────────────┐ │ +│ │ 智能体 │────────>│ 工具箱 (如 DefiLlama) │ │ +│ └────────────┘ └─────────────────────────────┘ │ +│ │ │ │ +│ │ │ │ +│ │ ▼ │ +│ │ ┌─────────────────────┐ │ +│ │ │ FileStorage │ │ +│ │ │ (S3 via goofys) │ │ +│ │ └─────────────────────┘ │ +│ │ │ │ +│ ▼ │ │ +│ ┌────────────┐ │ │ +│ │ E2BToolkit │ │ │ +│ └────────────┘ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ ▼ │ │ +│ ┌────────────┐ │ │ +│ │ E2B API │──────────────────┘ │ +│ └────────────┘ │ +└─────────┼───────────────────────────────────────────────────┘ + │ + │ 同一个 S3 桶 (Bucket) + │ +┌─────────▼───────────────────────────────────────────────────┐ +│ E2B 沙箱 │ +│ │ +│ ┌───────────────────────────────────────────────────┐ │ +│ │ start-up.sh: 将 S3 挂载到 /opt/sentient │ │ +│ │ 通过 goofys 使用来自主机的环境变量 │ │ +│ └───────────────────────────────────────────────────┘ │ +│ │ +│ ┌───────────────────────────────────────────────────┐ │ +│ │ 智能体生成的代码执行 │ │ +│ │ - 读取 /opt/sentient/executions/... │ │ +│ │ - 写入 /opt/sentient/executions/... │ │ +│ └───────────────────────────────────────────────────┘ │ +│ │ +└───────────────────────────────────────────────────────────────┘ +``` + +## 先决条件 + +1. **E2B 账户** + - 在 [e2b.dev](https://e2b.dev) 注册 + - 从仪表板获取 API 密钥 + +2. **AWS S3 存储桶** + - 创建用于存储的 S3 桶 + - 配置具有 S3 访问权限的 AWS 凭证 + +3. **E2B CLI** (用于创建模版) + ```bash + npm install -g @e2b/cli + # 或 + yarn global add @e2b/cli + ``` + +## 步骤 1:环境配置 + +### 1.1 配置环境变量 + +复制 `.env.example` 到 `.env` 并填写: + +```bash +# 存储配置 +STORAGE_BASE_PATH=/opt/sentient +ROMA_S3_BUCKET=your-s3-bucket-name +AWS_REGION=us-east-1 + +# AWS 凭证 +AWS_ACCESS_KEY_ID=your_aws_access_key +AWS_SECRET_ACCESS_KEY=your_aws_secret_key + +# E2B 配置 +E2B_API_KEY=your_e2b_api_key +E2B_TEMPLATE_ID=roma-dspy-sandbox +``` + +### 1.2 验证配置 + +```python +from roma_dspy.config.manager import ConfigManager +import os + +config = ConfigManager().load_config() +print(f"存储路径: {config.storage.base_path}") +print(f"S3 桶: {os.getenv('ROMA_S3_BUCKET')}") +``` + +## 步骤 2:创建自定义 E2B 模版 + +E2B 模版定义了沙箱环境。我们需要一个包含 S3 挂载脚本的自定义模版。 + +### 2.1 初始化模版 + +```bash +cd /Users/barannama/ROMA-DSPy + +# 初始化 E2B 模版 +e2b template init roma-dspy-sandbox +``` + +这会创建一个包含模版配置的 `.e2b/` 目录。 + +### 2.2 添加启动脚本 + +将我们的启动脚本复制到模版: + +```bash +# 复制 start-up.sh 到模版 +cp docker/e2b/start-up.sh .e2b/start-up.sh + +# 验证脚本可执行 +chmod +x .e2b/start-up.sh +``` + +`start-up.sh` 脚本: +- 在沙箱中安装 goofys +- 将 S3 桶挂载到 `$STORAGE_BASE_PATH` +- 验证写入权限 +- 设置 Python 依赖 + +### 2.3 构建并发布模版 + +```bash +# 构建模版 (创建 Docker 镜像) +e2b template build + +# 这将输出一个模版 ID,如: +# ✓ Template built successfully +# Template ID: roma-dspy-sandbox-abc123 + +# 将模版 ID 复制到您的 .env 文件 +echo "E2B_TEMPLATE_ID=" >> .env +``` + +### 2.4 验证模版 + +```bash +# 列出您的模版 +e2b template list + +# 您应该看到 ID 与 .env 匹配的模版 +``` + +## 步骤 3:本地存储设置 + +### 3.1 运行本地设置脚本 + +```bash +# 使脚本可执行 +chmod +x scripts/setup_local.sh + +# 运行设置 (通过 goofys 将 S3 挂载到本地) +./scripts/setup_local.sh +``` + +此脚本: +1. 安装 goofys (如果不存在) +2. 将 S3 桶挂载到本地路径 +3. 如果需要,创建符号链接 +4. 验证写入权限 + +### 3.2 验证本地存储 + +```bash +# 检查挂载 +mount | grep goofys + +# 验证目录结构 +ls -la /opt/sentient/executions/ + +# 测试写入权限 +echo "test" > /opt/sentient/executions/test.txt +cat /opt/sentient/executions/test.txt +rm /opt/sentient/executions/test.txt +``` + +## 步骤 4:测试 E2B 集成 + +### 4.1 基本测试 + +```python +from roma_dspy.tools.core import E2BToolkit +from roma_dspy.config.manager import ConfigManager +from roma_dspy.core.storage import FileStorage + +# 加载配置 +config = ConfigManager().load_config() + +# 创建存储 +storage = FileStorage( + config=config.storage, + execution_id="test_e2b_001" +) + +# 在主机上写入文件 +test_data = b"Hello from host!" +await storage.put("test.txt", test_data) +print(f"写入到: {storage.get_artifacts_path('test.txt')}") + +# 创建 E2B 工具箱 +e2b = E2BToolkit() + +# 在 E2B 沙箱中读取文件 +code = f""" +import os +file_path = '{storage.get_artifacts_path('test.txt')}' +print(f'正在读取: {{file_path}}') +with open(file_path, 'r') as f: + content = f.read() + print(f'内容: {{content}}') +""" + +result = e2b.run_python_code(code) +print(result) +``` + +预期输出: +```json +{ + "success": true, + "results": [], + "stdout": [ + "正在读取: /opt/sentient/executions/test_e2b_001/artifacts/test.txt", + "内容: Hello from host!" + ], + "stderr": [], + "error": null, + "sandbox_id": "..." +} +``` + +### 4.2 运行集成测试 + +```bash +# 运行 E2B 集成测试 +pytest tests/integration/test_e2b_integration.py -v + +# 运行 E2E 存储测试 +pytest tests/integration/test_e2e_storage.py -v +``` + +## 步骤 5:生产部署 + +### 5.1 环境特定配置 + +**开发环境 (.env.development)**: +```bash +STORAGE_BASE_PATH=/opt/sentient/dev +ROMA_S3_BUCKET=roma-storage-dev +E2B_TEMPLATE_ID=roma-dspy-sandbox-dev +``` + +**生产环境 (.env.production)**: +```bash +STORAGE_BASE_PATH=/opt/sentient/prod +ROMA_S3_BUCKET=roma-storage-prod +E2B_TEMPLATE_ID=roma-dspy-sandbox-prod +``` + +### 5.2 更新模版 + +当更新启动脚本时: + +```bash +# 修改 docker/e2b/start-up.sh +# 然后更新模版: + +cp docker/e2b/start-up.sh .e2b/start-up.sh +e2b template build +``` + +## 故障排除 + +### 问题:沙箱无法访问 S3 + +**症状**:E2B 代码执行失败,出现文件未找到错误 + +**解决方案**: +1. 验证环境变量已传递给沙箱: + ```python + e2b = E2BToolkit() + status = e2b.get_sandbox_status() + print(status) # 检查环境变量 + ``` + +2. 在 E2B 仪表板中检查 start-up.sh 日志 + +3. 验证 AWS 凭证有效: + ```bash + aws s3 ls s3://$ROMA_S3_BUCKET + ``` + +### 问题:goofys 挂载失败 + +**症状**:本地设置脚本失败或挂载点为空 + +**解决方案**: +1. 检查 AWS 凭证: + ```bash + aws sts get-caller-identity + ``` + +2. 验证 S3 桶存在: + ```bash + aws s3 ls | grep $ROMA_S3_BUCKET + ``` + +3. 检查 goofys 安装: + ```bash + which goofys + goofys --version + ``` + +### 问题:主机和 E2B 之间的路径不匹配 + +**症状**:主机上写入的文件在 E2B 中不可见 + +**解决方案**: +1. 验证 `STORAGE_BASE_PATH` 在以下位置一致: + - `.env` 文件 + - 本地设置脚本输出 + - E2B start-up.sh + +2. 检查两个系统是否指向同一个 S3 桶: + ```bash + # 本地 + mount | grep goofys + + # E2B (在沙箱中运行) + mount | grep goofys + ``` + +### 问题:未找到模版 + +**症状**:E2B 工具箱失败,提示模版未找到 + +**解决方案**: +1. 验证模版存在: + ```bash + e2b template list + ``` + +2. 检查 `.env` 中的 `E2B_TEMPLATE_ID` 是否与模版 ID 匹配 + +3. 如果需要,重建模版: + ```bash + e2b template build + ``` + +## 高级配置 + +### 自定义 Goofys 选项 + +编辑 `start-up.sh` 以自定义 goofys 挂载: + +```bash +# 在 start-up.sh 中,修改 goofys 命令: +goofys \ + --region "${AWS_REGION}" \ + --stat-cache-ttl 5m \ # 更长的缓存 + --type-cache-ttl 5m \ + --max-idle-handles 1000 \ # 更多文件句柄 + --dir-mode 0755 \ + --file-mode 0644 \ + "${S3_BUCKET}" \ + "${STORAGE_BASE_PATH}" +``` + +### 多个 E2B 模版 + +创建特定环境的模版: + +```bash +# 开发模版 +e2b template init roma-dspy-dev +cp docker/e2b/start-up.sh .e2b/start-up.sh +e2b template build + +# 生产模版 (带优化) +e2b template init roma-dspy-prod +# 使用生产设置编辑 .e2b/start-up.sh +e2b template build +``` + +### 监控存储使用情况 + +```python +from roma_dspy.core.storage import FileStorage + +storage = FileStorage(config=config.storage, execution_id="exec_123") +info = await storage.get_storage_info() + +print(f"总大小: {info['total_size_mb']} MB") +print(f"文件数: {info['file_count']}") +``` + +## 最佳实践 + +1. **使用 Execution ID**:始终将存储范围限定为 execution ID 以进行隔离 + +2. **清理临时文件**:执行后使用 `cleanup_temp_files()`: + ```python + await storage.cleanup_execution_temp_files() + ``` + +3. **监控成本**:跟踪 S3 存储和 E2B 沙箱使用情况 + +4. **模版版本控制**:在生产中对 E2B 模版进行版本控制: + ```bash + e2b template build --name roma-dspy-prod-v1.0.0 + ``` + +5. **错误处理**:始终检查 E2B 执行结果: + ```python + result = e2b.run_python_code(code) + result_data = json.loads(result) + if not result_data["success"]: + logger.error(f"E2B execution failed: {result_data['error']}") + ``` + +## 参考 + +- [E2B 文档](https://e2b.dev/docs) +- [Goofys GitHub](https://github.com/kahing/goofys) +- [AWS S3 文档](https://docs.aws.amazon.com/s3/) +- [ROMA-DSPy 存储架构](/docs/STORAGE_ARCHITECTURE.md) + diff --git a/docs_zh/OBSERVABILITY.md b/docs_zh/OBSERVABILITY.md new file mode 100644 index 00000000..84af63e7 --- /dev/null +++ b/docs_zh/OBSERVABILITY.md @@ -0,0 +1,807 @@ +# 可观察性与监控 + +ROMA-DSPy 通过 MLflow 集成提供全面的可观察性,支持实验跟踪、指标记录和执行追踪。 + +## 概览 + +可观察性系统捕获: +- **执行追踪** - 任务分解和执行流程 +- **LLM 指标** - 每次 LLM 调用的 Token 使用量、成本和延迟 +- **性能指标** - 任务持续时间、深度和成功率 +- **编译工件** - 优化后的提示词和 Few-shot 示例 + +## MLflow 集成 + +### 配置 + +在配置中启用 MLflow 跟踪: + +```yaml +# config/defaults/config.yaml +observability: + mlflow: + enabled: true + tracking_uri: "http://127.0.0.1:5000" # 本地 MLflow 服务器 + experiment_name: "ROMA-DSPy" + log_traces: true + log_compiles: true + log_evals: true + log_traces_from_compile: false # 开销较大,默认禁用 +``` + +或通过环境变量: + +```bash +export MLFLOW_ENABLED=true +export MLFLOW_TRACKING_URI=http://127.0.0.1:5000 +export MLFLOW_EXPERIMENT=ROMA-DSPy +``` + +### 启动 MLflow 服务器 + +```bash +# 启动 MLflow UI +mlflow ui --port 5000 + +# 或指定后端存储 +mlflow ui --backend-store-uri sqlite:///mlflow.db --port 5000 +``` + +访问 UI:http://localhost:5000 + +## 记录内容 + +### 1. 运行级指标 + +每次求解器 (Solver) 执行都会创建一个 MLflow 运行,包含: + +**参数:** +- `task` - 原始目标/任务 +- `max_depth` - 最大分解深度 +- `config_version` - 配置版本 +- `solver_type` - RecursiveSolver 标识符 + +**指标:** +- `total_tasks` - 创建的任务总数 +- `completed_tasks` - 成功完成的任务数 +- `failed_tasks` - 失败的任务数 +- `total_cost` - LLM API 总成本 (USD) +- `total_tokens` - 消耗的总 Token 数 +- `execution_duration` - 总执行时间 (秒) +- `max_depth_reached` - 实际达到的最大深度 + +### 2. LLM 追踪 + +对于每次语言模型调用: + +**记录信息:** +- 模块名称 (atomizer, planner, executor 等) +- 模型标识符 (gpt-4, claude-3 等) +- Token 使用量 (prompt, completion, total) +- 成本明细 +- 延迟 (毫秒) +- 输入/输出 (如果启用) + +**每模块指标:** +- `{module}_calls` - 调用次数 +- `{module}_tokens` - 总 Token 数 +- `{module}_cost` - 总成本 +- `{module}_avg_latency` - 平均延迟 + +### 3. 编译工件 + +使用 DSPy 优化时: + +- 编译后的预测器签名 +- Few-shot 示例 +- 优化指标 +- 提示词模版 + +## 使用示例 + +### 基本用法 + +```python +from roma_dspy.config.manager import ConfigManager +from roma_dspy.core.engine.solve import RecursiveSolver + +# 加载启用 MLflow 的配置 +config = ConfigManager(profile="high_quality").get_config() +config.observability.mlflow.enabled = True + +# 创建求解器 +solver = RecursiveSolver(config=config) + +# 解决任务 - 自动记录到 MLflow +result = await solver.async_solve("规划巴塞罗那周末游") +``` + +### 自定义实验名称 + +```python +config.observability.mlflow.experiment_name = "Barcelona-Planning-v2" +solver = RecursiveSolver(config=config) +``` + +### 程序化访问 + +```python +from roma_dspy.observability.mlflow_manager import MLflowManager + +# 初始化 +mlflow_mgr = MLflowManager(config.observability.mlflow) +await mlflow_mgr.initialize() + +# 开始运行 +run_id = await mlflow_mgr.start_run( + run_name="custom-run", + tags={"version": "1.0", "experiment_type": "production"} +) + +# 记录指标 +await mlflow_mgr.log_metric("custom_metric", 42.0) +await mlflow_mgr.log_param("custom_param", "value") + +# 结束运行 +await mlflow_mgr.end_run(status="FINISHED") +``` + +## 查询 MLflow 数据 + +### 使用 MLflow UI + +1. 访问 http://localhost:5000 +2. 选择您的实验 +3. 比较运行、查看指标、下载工件 + +### 使用 MLflow API + +```python +import mlflow + +# 设置跟踪 URI +mlflow.set_tracking_uri("http://localhost:5000") + +# 搜索运行 +runs = mlflow.search_runs( + experiment_names=["ROMA-DSPy"], + filter_string="metrics.total_cost < 1.0", + order_by=["metrics.execution_duration ASC"] +) + +# 获取最佳运行 +best_run = runs.sort_values("metrics.total_cost").iloc[0] +print(f"最佳运行: {best_run.run_id}") +print(f"成本: ${best_run['metrics.total_cost']:.4f}") +``` + +### 分析成本 + +```python +# 获取所有运行 +runs = mlflow.search_runs(experiment_names=["ROMA-DSPy"]) + +# 成本分析 +total_cost = runs["metrics.total_cost"].sum() +avg_cost = runs["metrics.total_cost"].mean() +cost_by_depth = runs.groupby("params.max_depth")["metrics.total_cost"].mean() + +print(f"总花费: ${total_cost:.2f}") +print(f"平均单次花费: ${avg_cost:.4f}") +print("\n按深度划分的成本:") +print(cost_by_depth) +``` + +## 成本跟踪 + +### Token 成本 + +ROMA-DSPy 跟踪常见 LLM 提供商的成本: + +- **OpenAI**: gpt-4, gpt-3.5-turbo 等 +- **Anthropic**: claude-3-opus, claude-3-sonnet 等 +- **Fireworks AI**: 各种模型 +- **OpenRouter**: 透传定价 + +成本计算公式: +```python +cost = (prompt_tokens * prompt_price_per_1k / 1000) + + (completion_tokens * completion_price_per_1k / 1000) +``` + +### 成本优化 + +监控这些指标以优化成本: + +1. **每任务 Token 数** - 识别冗长的模块 +2. **失败任务成本** - 浪费在失败上的花费 +3. **模型选择** - 比较不同模型的成本 +4. **深度 vs 成本** - 找到最佳分解深度 + +## 性能监控 + +### 关键指标 + +**延迟:** +- 总执行时间 +- 每模块延迟 +- LLM 调用延迟 + +**吞吐量:** +- 每分钟任务数 +- 每次分解的子任务数 +- 成功率 + +**资源使用:** +- Token 消耗率 +- 每任务 API 调用数 +- 检查点频率 + +### 告警与阈值 + +设置告警: + +```python +# 高成本运行 +if run.metrics.total_cost > 5.0: + alert("检测到高成本运行") + +# 执行缓慢 +if run.metrics.execution_duration > 300: + alert("执行缓慢") + +# 高失败率 +failure_rate = run.metrics.failed_tasks / run.metrics.total_tasks +if failure_rate > 0.2: + alert("高失败率") +``` + +## 与 Postgres 集成 + +当同时启用 MLflow 和 Postgres 时,您将获得双重可观察性: + +**MLflow**: 实验跟踪、可视化、比较 +**Postgres**: 详细执行追踪、可查询历史、审计日志 + +```python +# 查询两个源 +import mlflow +from roma_dspy.core.storage.postgres_storage import PostgresStorage + +# MLflow - 高级指标 +runs = mlflow.search_runs(experiment_names=["ROMA-DSPy"]) + +# Postgres - 详细追踪 +storage = PostgresStorage(config.storage.postgres) +await storage.initialize() + +for _, run in runs.iterrows(): + execution_id = run["tags.execution_id"] + costs = await storage.get_execution_costs(execution_id) + print(f"Run {execution_id}: ${costs['total_cost']:.4f}") +``` + +## 最佳实践 + +1. **使用描述性实验名称** - 按项目/功能组织 +2. **适当标记运行** - 添加版本、环境、用户标签 +3. **定期监控成本** - 设置成本告警 +4. **归档旧实验** - 保持 MLflow 数据库可管理 +5. **生产环境禁用昂贵日志** - `log_traces_from_compile: false` +6. **使用远程跟踪服务器** - 用于团队协作 +7. **备份 MLflow 数据** - 尤其是工件存储 + +## 故障排除 + +### MLflow 连接问题 + +```bash +# 检查服务器是否运行 +curl http://localhost:5000/health + +# 检查环境变量 +echo $MLFLOW_TRACKING_URI + +# 测试连接 +python -c "import mlflow; print(mlflow.get_tracking_uri())" +``` + +### 缺少指标 + +```python +# 验证日志已启用 +print(config.observability.mlflow.enabled) +print(config.observability.mlflow.log_traces) + +# 检查 MLflow 管理器初始化 +print(solver.mlflow_manager._initialized) +``` + +### 存储占用高 + +```bash +# 检查工件存储大小 +du -sh ~/.mlflow + +# 清理旧运行 (谨慎使用) +mlflow gc --backend-store-uri sqlite:///mlflow.db +``` + +## 高级主题 + +### 自定义指标 + +```python +# 添加自定义指标到 MLflow +async with solver.mlflow_manager.run_context(): + await solver.mlflow_manager.log_metric("custom_score", score) + await solver.mlflow_manager.log_param("algorithm", "custom") +``` + +### 分布式跟踪 + +对于多机设置: + +```yaml +observability: + mlflow: + tracking_uri: "http://mlflow-server.company.com:5000" + # 使用 S3/GCS 存储工件 + artifact_location: "s3://my-bucket/mlflow-artifacts" +``` + +### 与其他工具集成 + +MLflow 集成: +- **Prometheus** - 运维指标 +- **Grafana** - 仪表盘 +- **Databricks** - 托管 MLflow +- **Weights & Biases** - 通过导出器 + +## 工具箱指标与可追溯性 + +ROMA-DSPy 提供全面的工具箱生命周期和工具调用指标跟踪,能够深入了解工具使用模式、性能和可靠性。 + +### 概览 + +工具箱指标系统自动跟踪: +- **工具箱生命周期** - 创建、缓存、清理操作 +- **工具调用** - 包含计时和 I/O 指标的单个工具调用 +- **性能** - 持续时间、成功率、错误模式 +- **归因** - 每个工具箱/工具的成本和使用情况 + +### 配置 + +启用工具箱指标跟踪: + +```yaml +# config/defaults/config.yaml +observability: + toolkit_metrics: + enabled: true # 启用/禁用跟踪 + track_lifecycle: true # 跟踪工具箱操作 + track_invocations: true # 跟踪工具调用 + sample_rate: 1.0 # 采样率 (0.0-1.0) + persist_to_db: true # 保存到 PostgreSQL + persist_to_mlflow: false # 保存到 MLflow + batch_size: 100 # 持久化批次大小 + async_persist: true # 异步持久化 +``` + +或通过环境变量: + +```bash +export TOOLKIT_METRICS_ENABLED=true +export TOOLKIT_TRACK_LIFECYCLE=true +export TOOLKIT_TRACK_INVOCATIONS=true +export TOOLKIT_SAMPLE_RATE=1.0 +export TOOLKIT_PERSIST_DB=true +``` + +### 跟踪内容 + +#### 1. 工具箱生命周期事件 + +**跟踪的操作:** +- `create` - 工具箱实例化 +- `cache_hit` - 从缓存检索 +- `cache_miss` - 缓存查找失败 +- `cleanup` - 工具箱处置 + +**捕获数据:** +- 操作时间戳 +- 工具箱类名 +- 持续时间 (毫秒) +- 成功/失败状态 +- 错误详情 (如果失败) +- 自定义元数据 + +#### 2. 工具调用事件 + +**每次调用的跟踪:** +- 工具名称和工具箱类 +- 调用时间戳 +- 持续时间 (毫秒) +- 输入大小 (字节) +- 输出大小 (字节) +- 成功/失败状态 +- 错误详情 (如果失败) +- 自定义元数据 + +### API 端点 + +通过 REST API 查询工具箱指标: + +#### 获取聚合摘要 + +```bash +curl http://localhost:8000/executions/{execution_id}/toolkit-metrics +``` + +**响应:** +```json +{ + "execution_id": "exec_123", + "toolkit_lifecycle": { + "total_created": 5, + "cache_hit_rate": 0.75 + }, + "tool_invocations": { + "total_calls": 50, + "successful_calls": 48, + "failed_calls": 2, + "success_rate": 0.96, + "avg_duration_ms": 125.5, + "total_duration_ms": 6275.0 + }, + "by_toolkit": { + "SerperToolkit": { + "calls": 20, + "successful": 20, + "failed": 0, + "avg_duration_ms": 150.0 + } + }, + "by_tool": { + "SerperToolkit.search_web": { + "calls": 15, + "successful": 15, + "avg_duration_ms": 145.0 + } + } +} +``` + +#### 获取原始生命周期追踪 + +```bash +# 所有生命周期追踪 +curl http://localhost:8000/executions/{execution_id}/toolkit-traces + +# 按操作过滤 +curl http://localhost:8000/executions/{execution_id}/toolkit-traces?operation=create + +# 按工具箱类过滤 +curl http://localhost:8000/executions/{execution_id}/toolkit-traces?toolkit_class=SerperToolkit + +# 限制结果 +curl http://localhost:8000/executions/{execution_id}/toolkit-traces?limit=100 +``` + +#### 获取原始工具调用 + +```bash +# 所有工具调用 +curl http://localhost:8000/executions/{execution_id}/tool-invocations + +# 按工具箱过滤 +curl http://localhost:8000/executions/{execution_id}/tool-invocations?toolkit_class=SerperToolkit + +# 按工具名称过滤 +curl http://localhost:8000/executions/{execution_id}/tool-invocations?tool_name=search_web + +# 组合过滤 +curl http://localhost:8000/executions/{execution_id}/tool-invocations?toolkit_class=SerperToolkit&tool_name=search_web +``` + +### 数据库架构 + +#### toolkit_traces 表 + +```sql +CREATE TABLE toolkit_traces ( + trace_id BIGSERIAL PRIMARY KEY, + execution_id VARCHAR(64) NOT NULL, + timestamp TIMESTAMP WITH TIME ZONE NOT NULL, + operation VARCHAR(32) NOT NULL, + toolkit_class VARCHAR(128), + duration_ms FLOAT NOT NULL, + success BOOLEAN NOT NULL, + error TEXT, + metadata JSONB NOT NULL DEFAULT '{}', + FOREIGN KEY (execution_id) REFERENCES executions(execution_id) ON DELETE CASCADE +); + +-- Indexes for query performance +CREATE INDEX idx_toolkit_traces_execution ON toolkit_traces (execution_id, timestamp); +CREATE INDEX idx_toolkit_traces_operation ON toolkit_traces (operation); +CREATE INDEX idx_toolkit_traces_toolkit_class ON toolkit_traces (toolkit_class); +CREATE INDEX idx_toolkit_traces_success ON toolkit_traces (success); +``` + +#### tool_invocation_traces 表 + +```sql +CREATE TABLE tool_invocation_traces ( + trace_id BIGSERIAL PRIMARY KEY, + execution_id VARCHAR(64) NOT NULL, + toolkit_class VARCHAR(128) NOT NULL, + tool_name VARCHAR(128) NOT NULL, + invoked_at TIMESTAMP WITH TIME ZONE NOT NULL, + duration_ms FLOAT NOT NULL, + input_size_bytes INTEGER NOT NULL, + output_size_bytes INTEGER NOT NULL, + success BOOLEAN NOT NULL, + error TEXT, + metadata JSONB NOT NULL DEFAULT '{}', + FOREIGN KEY (execution_id) REFERENCES executions(execution_id) ON DELETE CASCADE +); + +-- Indexes for query performance +CREATE INDEX idx_tool_invocations_execution ON tool_invocation_traces (execution_id, invoked_at); +CREATE INDEX idx_tool_invocations_toolkit ON tool_invocation_traces (toolkit_class); +CREATE INDEX idx_tool_invocations_tool ON tool_invocation_traces (tool_name); +CREATE INDEX idx_tool_invocations_toolkit_tool ON tool_invocation_traces (toolkit_class, tool_name); +CREATE INDEX idx_tool_invocations_success ON tool_invocation_traces (success); +``` + +### 数据库迁移 + +应用迁移以创建工具箱指标表: + +```bash +# 导航到项目根目录 +cd /path/to/ROMA-DSPy + +# 运行迁移 +alembic upgrade head +``` + +或手动: + +```bash +# 检查当前版本 +alembic current + +# 升级到工具箱指标迁移 +alembic upgrade 004_toolkit_metrics + +# 如果需要回滚 +alembic downgrade 003_add_dag_snapshot +``` + +### 使用示例 + +#### 分析工具箱性能 + +```python +from roma_dspy.core.storage.postgres_storage import PostgresStorage + +# 获取工具箱指标摘要 +summary = await storage.get_toolkit_metrics_summary("exec_123") + +print(f"总工具调用数: {summary['tool_invocations']['total_calls']}") +print(f"成功率: {summary['tool_invocations']['success_rate']:.2%}") +print(f"平均持续时间: {summary['tool_invocations']['avg_duration_ms']:.2f}ms") + +# 按工具箱分析 +for toolkit, metrics in summary['by_toolkit'].items(): + print(f"\n{toolkit}:") + print(f" 调用数: {metrics['calls']}") + print(f" 成功率: {metrics['successful'] / metrics['calls']:.2%}") + print(f" 平均持续时间: {metrics['avg_duration_ms']:.2f}ms") +``` + +#### 识别慢速工具 + +```python +# 获取所有工具调用 +invocations = await storage.get_tool_invocation_traces("exec_123") + +# 按持续时间排序 +slow_tools = sorted(invocations, key=lambda x: x.duration_ms, reverse=True)[:10] + +print("最慢的 10 个工具调用:") +for inv in slow_tools: + print(f"{inv.toolkit_class}.{inv.tool_name}: {inv.duration_ms:.2f}ms") +``` + +#### 跟踪失败 + +```python +# 获取失败的工具调用 +failed = await storage.get_tool_invocation_traces( + execution_id="exec_123", + limit=1000 +) +failed = [inv for inv in failed if not inv.success] + +# 按错误类型分组 +from collections import Counter +error_types = Counter(inv.metadata.get('error_type', 'Unknown') for inv in failed) + +print("失败分类:") +for error_type, count in error_types.most_common(): + print(f" {error_type}: {count}") +``` + +#### 缓存性能分析 + +```python +# 获取生命周期追踪 +traces = await storage.get_toolkit_traces("exec_123") + +# 计算缓存指标 +cache_hits = sum(1 for t in traces if t.operation == "cache_hit") +cache_misses = sum(1 for t in traces if t.operation == "cache_miss") +total = cache_hits + cache_misses + +if total > 0: + hit_rate = cache_hits / total + print(f"缓存命中率: {hit_rate:.2%}") + print(f"缓存命中: {cache_hits}") + print(f"缓存未命中: {cache_misses}") +``` + +### 监控与告警 + +#### 需监控的关键指标 + +1. **成功率** - 低于 95% 时告警 +2. **平均持续时间** - 显著增加时告警 +3. **错误率** - 激增时告警 +4. **缓存命中率** - 显著下降时告警 + +#### Prometheus 查询示例 + +```promql +# 按工具箱的成功率 +sum(rate(tool_invocations_success_total[5m])) by (toolkit_class) +/ +sum(rate(tool_invocations_total[5m])) by (toolkit_class) + +# P95 延迟 +histogram_quantile(0.95, sum(rate(tool_duration_ms_bucket[5m])) by (le, tool_name)) + +# 错误率 +sum(rate(tool_invocations_failed_total[5m])) by (toolkit_class, error_type) +``` + +### 性能调优 + +#### 减少存储开销 + +```yaml +# 在高容量环境中仅采样 10% 的调用 +observability: + toolkit_metrics: + sample_rate: 0.1 +``` + +#### 批量持久化 + +```yaml +# 增加批量大小以提高写入性能 +observability: + toolkit_metrics: + batch_size: 500 + async_persist: true +``` + +#### 禁用特定跟踪 + +```yaml +# 仅跟踪生命周期,跳过调用 +observability: + toolkit_metrics: + track_lifecycle: true + track_invocations: false +``` + +### 故障排除 + +#### 指标未出现 + +1. **检查 PostgreSQL 是否启用:** + ```yaml + storage: + postgres: + enabled: true + ``` + +2. **验证迁移已应用:** + ```bash + alembic current + # 应显示: 004_toolkit_metrics (head) + ``` + +3. **检查配置:** + ```python + print(config.observability.toolkit_metrics.enabled) + print(config.observability.toolkit_metrics.persist_to_db) + ``` + +#### 高存储使用率 + +```sql +-- 检查表大小 +SELECT + schemaname, + tablename, + pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS size +FROM pg_tables +WHERE tablename LIKE '%trace%' +ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC; + +-- 清理旧执行 (小心!) +DELETE FROM executions WHERE created_at < NOW() - INTERVAL '30 days'; +``` + +#### 缺少追踪 + +```python +# 检查 context 是否正确设置 +from roma_dspy.core.context import ExecutionContext + +ctx = ExecutionContext.get() +if ctx: + print(f"Execution ID: {ctx.execution_id}") + print(f"Toolkit events: {len(ctx.toolkit_events)}") + print(f"Tool invocations: {len(ctx.tool_invocations)}") +else: + print("No ExecutionContext found!") +``` + +### 最佳实践 + +1. **开发环境启用** - 使用全量跟踪 (sample_rate=1.0) +2. **生产环境采样** - 对于高容量系统使用较低的采样率 +3. **监控关键指标** - 设置成功率和延迟告警 +4. **定期清理** - 归档或删除旧的执行数据 +5. **索引管理** - 监控索引大小和查询性能 +6. **关联 LM 追踪** - 结合 LM 指标进行成本归因 + +### 与 MLflow 集成 + +```python +# 将工具箱指标记录到 MLflow +from roma_dspy.core.observability import MLflowManager + +async with mlflow_manager.run_context(): + summary = await storage.get_toolkit_metrics_summary(execution_id) + + # 记录聚合指标 + await mlflow_manager.log_metric( + "toolkit_success_rate", + summary["tool_invocations"]["success_rate"] + ) + await mlflow_manager.log_metric( + "avg_tool_duration_ms", + summary["tool_invocations"]["avg_duration_ms"] + ) + + # 记录每工具箱指标 + for toolkit, metrics in summary["by_toolkit"].items(): + await mlflow_manager.log_metric( + f"{toolkit}_calls", + metrics["calls"] + ) +``` + +## 延伸阅读 + +- [MLflow 文档](https://mlflow.org/docs/latest/index.html) +- [MLflow 跟踪指南](https://mlflow.org/docs/latest/tracking.html) +- [DSPy 可观察性](https://dspy-docs.vercel.app/) +- [PostgreSQL 性能调优](https://www.postgresql.org/docs/current/performance-tips.html) + diff --git a/docs_zh/QUICKSTART.md b/docs_zh/QUICKSTART.md new file mode 100644 index 00000000..1234081f --- /dev/null +++ b/docs_zh/QUICKSTART.md @@ -0,0 +1,631 @@ +# ROMA-DSPy 快速入门指南 + +无需任何基础设施,**30秒内**即可开始! + +## ROMA-DSPy 是什么? + +ROMA-DSPy 是一个使用 [DSPy](https://github.com/stanfordnlp/dspy) 构建生产级 AI 智能体的框架。它提供: + +- **分层任务分解** - 将复杂任务拆解为可管理的子任务 +- **模块化智能体架构** - Atomizer(原子化器)、Planner(规划器)、Executor(执行器)、Aggregator(聚合器)、Verifier(验证器) +- **丰富的工具箱系统** - 文件操作、代码执行、Web 搜索、加密数据等 +- **MCP 集成** - 连接任何模型上下文协议 (Model Context Protocol) 服务器 +- **可选的生产特性** - REST API、PostgreSQL 持久化、MLflow 可观察性、Docker 部署 + +## 先决条件 + +### 极简安装(推荐) +- **Python 3.12+** +- 来自 OpenRouter, OpenAI, Anthropic, 或 Fireworks 的 **API 密钥** + +### 完整安装(可选) +- **Docker & Docker Compose**(用于生产特性) +- **Just** 命令运行器(可选但推荐) + +--- + +## 快速开始(3条路径) + +选择您首选的设置方法: + +### 路径 A:极简安装(推荐 - 30秒启动) + +**最适合**:快速评估、开发、测试 - 无需基础设施 + +**您将获得:** +- ✅ 核心智能体框架(所有模块) +- ✅ 所有 DSPy 预测策略 +- ✅ 文件存储(无需数据库) +- ✅ 内置工具箱(计算器、文件操作) +- ✅ 支持任何 LLM 提供商 + +**您不需要:** +- ❌ Docker +- ❌ PostgreSQL +- ❌ MLflow +- ❌ 基础设施设置 + +**30秒内安装:** + +```bash +# 使用 uv 安装 (推荐,速度快 10-100 倍) +uv pip install roma-dspy + +# 或使用 pip +pip install roma-dspy + +# 设置您的 API 密钥 +export OPENROUTER_API_KEY="sk-or-v1-..." + +# 立即开始解决任务 +python -c "from roma_dspy.core.engine.solve import solve; print(solve('2+2 是多少?'))" +``` + +**Python 使用示例:** + +```python +from roma_dspy.core.engine.solve import solve + +# 简单任务 +result = solve("25 * 47 是多少?") +print(result) + +# 更复杂的任务 +result = solve("分析电动汽车的优缺点") +print(result) +``` + +**安装时间**:< 30秒 +**包大小**:~15 个核心依赖 +**就绪状态**:立即使用 + +--- + +### 路径 B:Docker 完整安装(生产特性) + +**最适合**:具有持久化、可观察性和 REST API 的生产部署 + +**额外特性:** +- ✅ REST API 服务器 +- ✅ PostgreSQL 持久化 +- ✅ MLflow 可观察性 +- ✅ S3 存储集成 +- ✅ E2B 代码执行沙箱 +- ✅ 交互式 TUI 可视化 + +1. **克隆并配置** + ```bash + git clone https://github.com/your-org/ROMA-DSPy.git + cd ROMA-DSPy + + # 复制环境模版 + cp .env.example .env + ``` + +2. **配置环境** + 编辑 `.env` 并添加您的 API 密钥: + ```bash + # 必填 + OPENROUTER_API_KEY=your_key_here + + # 可选(用于特定功能) + E2B_API_KEY=your_key_here + EXA_API_KEY=your_key_here + ``` + +3. **启动服务** + ```bash + # 构建并启动所有服务 + just docker-up + + # 或者带 MLflow 可观察性启动 + just docker-up-full + + # 检查健康状态 + curl http://localhost:8000/health + ``` + +4. **运行您的第一个任务** + ```bash + # 通过 Docker CLI + just solve "法国的首都是哪里?" + + # 或通过 REST API + curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{"goal": "法国的首都是哪里?"}' + ``` + +**运行的服务:** +- API: http://localhost:8000 +- PostgreSQL: localhost:5432 +- MinIO: http://localhost:9001 +- MLflow: http://localhost:5000 (使用 `--profile observability`) + +--- + +### 路径 C:加密货币代理(领域特定示例) + +**最适合**:加密货币分析用例 + +1. **快速设置** + ```bash + just docker-up + ``` + +2. **运行加密分析** + ```bash + # 获取比特币价格 + just solve "比特币当前价格是多少?" crypto_agent + + # 复杂分析 + just solve "对比比特币和以太坊的价格,分析7天趋势" crypto_agent + + # DeFi 分析 + just solve "显示按 TVL 排名的前 10 个 DeFi 协议" crypto_agent + ``` + +**加密货币代理包含:** +- CoinGecko (15,000+ 加密货币) +- Binance (现货/期货市场) +- DefiLlama (DeFi 协议数据) +- Arkham (链上分析) +- Exa (Web 搜索) + +--- + +## 安装对比 + +| 特性 | 极简安装 | Docker 完整版 | +|------|---------|-------------| +| **安装时间** | < 30 秒 | 2-5 分钟 | +| **先决条件** | Python 3.12+ | Docker + Docker Compose | +| **基础设施** | 无需 | PostgreSQL, MinIO, MLflow (自动部署) | +| **包大小** | ~15 依赖 | 所有功能 | +| **用例** | 快速评估, 开发, 测试 | 生产部署 | +| **核心框架** | ✅ | ✅ | +| **DSPy 策略** | ✅ | ✅ | +| **文件存储** | ✅ | ✅ | +| **内置工具箱** | ✅ | ✅ | +| **REST API** | ❌ | ✅ | +| **PostgreSQL 持久化** | ❌ | ✅ | +| **MLflow 跟踪** | ❌ | ✅ | +| **S3 存储** | ❌ | ✅ | +| **E2B 沙箱** | ❌ | ✅ | +| **TUI 可视化** | ❌ | ✅ | + +**关键区别**: +- **极简** = 仅 Python 包(无 Docker,无服务) +- **Docker** = 完整生产栈(PostgreSQL, MLflow, API,通过 docker-compose 提供所有功能) + +--- + +## 为极简安装添加功能 + +您可以安装 Python 依赖以获取可选功能: + +```bash +# 为特定功能安装依赖 +uv pip install roma-dspy[api] # REST API 依赖 +uv pip install roma-dspy[persistence] # PostgreSQL 客户端依赖 +uv pip install roma-dspy[observability] # MLflow 客户端依赖 +uv pip install roma-dspy[e2b] # E2B 代码执行 +uv pip install roma-dspy[tui] # TUI 可视化 +uv pip install roma-dspy[dev] # 开发工具 + +# 安装所有 Python 依赖 +uv pip install roma-dspy[all] +``` + +**重要**:安装 extras 仅添加 Python 依赖。PostgreSQL、MLflow 和 API 服务器等服务需要 Docker 或单独部署。 + +**如需使用所有功能的生产环境,请使用 Docker (路径 B)**。 + +--- + +## Just 命令速查表 + +### 基本用法 +```bash +just # 列出所有命令 +just solve "task" # 使用 Docker 解决任务 +just viz # 可视化执行 DAG +``` + +### Docker 管理 +```bash +just docker-up # 启动服务 +just docker-up-full # 启动并开启 MLflow +just docker-down # 停止服务 +just docker-logs # 查看日志 +just docker-ps # 检查状态 +just docker-shell # 在容器中打开 shell +``` + +### 开发 +```bash +just install # 安装依赖 +just test # 运行测试 +just lint # 检查代码质量 +just format # 格式化代码 +just clean # 清理缓存 +``` + +### 列出可用 Profiles +```bash +just list-profiles +# 输出: +# - crypto_agent +# - general +``` + +--- + +## 验证安装 + +### 1. 检查健康状态 +```bash +curl http://localhost:8000/health +``` + +预期响应: +```json +{ + "status": "healthy", + "version": "1.0.0", + "storage_connected": true, + "active_executions": 0, + "uptime_seconds": 123.45 +} +``` + +### 2. 通过 CLI 测试 +```bash +# 简单计算 +just solve "计算 2500 的 15%" + +# 从输出中获取 execution ID,然后可视化 +just viz +``` + +### 3. 通过 API 测试 +```bash +# 创建执行 (建议 max_depth=1 或 2) +curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{ + "goal": "1 到 20 之间的质数有哪些?", + "max_depth": 2 + }' | jq + +# 轮询状态 (使用响应中的 execution_id) +curl http://localhost:8000/api/v1/executions//status | jq +``` + +--- + +## 配置 Profiles + +ROMA-DSPy 使用 profiles 为不同用例预配置智能体。 + +### 可用 Profiles + +| Profile | 用途 | 模型 | 工具箱 | +|---------|------|------|--------| +| **general** | 通用任务 | Gemini Flash + Claude Sonnet | E2B, FileToolkit, CalculatorToolkit, Exa MCP | +| **crypto_agent** | 加密货币分析 | 多种 (任务感知) | CoinGecko, Binance, DefiLlama, Arkham, E2B | + +### 使用 Profile + +```bash +# 通过 CLI (如未指定默认为 'general') +just solve "你的任务" +just solve "加密任务" crypto_agent + +# 通过 API +curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{ + "goal": "你的任务", + "config_profile": "general" + }' +``` + +### 自定义 Profile + +创建 `config/profiles/my_profile.yaml`: +```yaml +agents: + executor: + llm: + model: openai/gpt-4o + temperature: 0.3 + prediction_strategy: react + toolkits: + - class_name: FileToolkit + enabled: true + - class_name: CalculatorToolkit + enabled: true + +runtime: + max_depth: 2 # 大多数任务建议 1-2 +``` + +使用它: +```bash +just solve "task" my_profile +``` + +查看 [CONFIGURATION.md](CONFIGURATION.md) 获取完整指南。 + +--- + +## 环境变量 + +### 必填 +```bash +# LLM 提供商 (选择一个或使用 OpenRouter 处理所有) +OPENROUTER_API_KEY=xxx # 推荐 (所有模型共用一个 key) +# 或单独的提供商: +OPENAI_API_KEY=xxx +ANTHROPIC_API_KEY=xxx +GOOGLE_API_KEY=xxx +``` + +### 可选特性 +```bash +# 代码执行 (E2B) +E2B_API_KEY=xxx + +# Web 搜索 (Exa MCP) +EXA_API_KEY=xxx + +# Web 搜索 (Serper Toolkit) +SERPER_API_KEY=xxx + +# 加密 API (均为公开,无需 key) +# CoinGecko, Binance, DefiLlama, Arkham 无需 key 即可工作 +``` + +### 存储与数据库 +```bash +# PostgreSQL (Docker 中自动配置) +DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/roma_dspy +POSTGRES_ENABLED=true + +# S3 存储 (可选) +STORAGE_BASE_PATH=/opt/sentient +ROMA_S3_BUCKET=your-bucket +AWS_ACCESS_KEY_ID=xxx +AWS_SECRET_ACCESS_KEY=xxx +``` + +--- + +## 常见任务 + +### 1. 解决任务 +```bash +# 简单 (默认使用 'general' profile) +just solve "2+2 是多少?" + +# 使用特定 profile +just solve "分析比特币" crypto_agent + +# 使用所有选项 +just solve "复杂任务" crypto_agent 5 true json +# 参数: [profile] [max_depth] [verbose] [output_format] +``` + +### 2. 检查执行 +```bash +# 列出所有执行 +curl http://localhost:8000/api/v1/executions | jq + +# 获取特定执行 +curl http://localhost:8000/api/v1/executions/ | jq + +# 获取执行状态 +curl http://localhost:8000/api/v1/executions//status | jq +``` + +### 3. 查看日志 +```bash +# 所有服务 +just docker-logs + +# 特定服务 +just docker-logs-service roma-api +just docker-logs-service postgres +just docker-logs-service mlflow +``` + +### 4. 交互式可视化 +```bash +# 解决任务后,获取 execution_id +just solve "Complex task" + +# 可视化执行树 +just viz +``` + +--- + +## 示例 + +### 示例 1:简单计算 +```bash +just solve "计算 10,000 美元本金、5% 年利率、10 年期的复利" +``` + +### 示例 2:Web 研究 +```bash +just solve "研究量子计算的最新进展并总结为 3 个要点" +``` + +### 示例 3:代码执行 +```bash +just solve "生成一个生成斐波那契数列至 100 的 Python 脚本,执行它并显示结果" +``` + +### 示例 4:加密分析 +```bash +just solve "对比比特币和以太坊的市值、24小时交易量和价格变化" crypto_agent +``` + +### 示例 5:文件操作 +```bash +just solve "创建一个包含前 5 种编程语言及其用例数据的 JSON 文件" +``` + +--- + +## 故障排除 + +### Docker 未启动 +```bash +# 检查 Docker 是否运行 +docker ps + +# 重建镜像 +just docker-down +just docker-build-clean +just docker-up + +# 检查日志 +just docker-logs +``` + +### API 无响应 +```bash +# 检查健康 +curl http://localhost:8000/health + +# 检查容器状态 +just docker-ps + +# 查看日志 +just docker-logs-service roma-api +``` + +### 数据库连接错误 +```bash +# 检查 postgres 是否运行 +docker ps | grep postgres + +# 检查连接 +docker exec -it roma-dspy-postgres psql -U postgres -d roma_dspy -c "SELECT 1" + +# 验证 .env 中的 DATABASE_URL 是否匹配 docker-compose.yaml +``` + +### 缺少 API 密钥 +```bash +# 验证密钥已设置 +docker exec -it roma-dspy-api env | grep API_KEY + +# 修改 .env 后重启 +just docker-restart +``` + +### E2B 不工作 +```bash +# 检查 E2B key 已设置 +echo $E2B_API_KEY + +# 测试 E2B 连接 +just e2b-test + +# 构建自定义模板 (如使用 S3 挂载) +just e2b-build +``` + +--- + +## 下一步 + +### 了解更多 +- **[配置指南](CONFIGURATION.md)** - Profiles, agents, settings +- **[工具箱参考](TOOLKITS.md)** - 所有可用工具箱 +- **[MCP 集成](MCP.md)** - 使用 MCP 服务器 +- **[API 参考](API.md)** - REST API 端点 +- **[部署指南](DEPLOYMENT.md)** - 生产部署 +- **[可观察性](OBSERVABILITY.md)** - MLflow 跟踪 + +### 探索示例 +```bash +# 查看所有示例配置 +ls config/examples/*/ + +# 尝试不同示例 +just solve "task" -c config/examples/basic/minimal.yaml +``` + +### 自定义 +1. 在 `config/profiles/` 中创建自定义 profiles +2. 添加自定义工具箱 (参见 [TOOLKITS.md](TOOLKITS.md)) +3. 按任务类型配置智能体 (参见 [CONFIGURATION.md](CONFIGURATION.md)) + +### 部署 +```bash +# 生产部署 +just deploy-full + +# 检查部署 +just health-check +``` + +--- + +## REST API + +ROMA-DSPy 包含一个用于程序化访问的生产级 REST API。 + +### 快速开始 + +```bash +# 启动 API 服务器 (通过 Docker) +just docker-up + +# 验证服务器运行 +curl http://localhost:8000/health +``` + +### API 文档 + +FastAPI 提供交互式 API 文档: + +- **Swagger UI** (交互式测试): http://localhost:8000/docs +- **ReDoc** (简洁参考): http://localhost:8000/redoc +- **OpenAPI JSON**: http://localhost:8000/openapi.json + +### 示例用法 + +```bash +# 开始执行 +curl -X POST http://localhost:8000/api/v1/executions \ + -H "Content-Type: application/json" \ + -d '{"goal": "2+2 是多少?", "max_depth": 1}' | jq + +# 获取状态 (使用响应中的 execution_id) +curl http://localhost:8000/api/v1/executions//status | jq + +# 获取指标 +curl http://localhost:8000/api/v1/executions//metrics | jq +``` + +**访问 http://localhost:8000/docs 获取包含所有端点、模式和交互式测试的完整 API 参考。** + +--- + +## 获取帮助 + +- **文档**: `docs/` 目录 +- **示例**: `config/examples/` +- **Issues**: GitHub Issues +- **Just 命令**: 运行 `just` 查看所有可用命令 + +--- + +**一切就绪!** 开始使用 ROMA-DSPy 构建吧 🚀 + diff --git a/docs_zh/TOOLKITS.md b/docs_zh/TOOLKITS.md new file mode 100644 index 00000000..3feeaf95 --- /dev/null +++ b/docs_zh/TOOLKITS.md @@ -0,0 +1,1234 @@ +# ROMA-DSPy 工具箱参考 + +在 ROMA-DSPy 智能体中使用工具箱的完整指南。 + +## 目录 + +- [概览](#概览) +- [快速开始](#快速开始) +- [原生工具箱](#原生工具箱) +- [MCP 集成](#mcp-集成) +- [配置指南](#配置指南) +- [示例](#示例) +- [创建自定义工具箱](#创建自定义工具箱) +- [最佳实践](#最佳实践) + +--- + +## 概览 + +ROMA-DSPy 提供了一个强大的工具箱系统,使智能体能够与外部系统交互、执行代码、访问数据并执行专门操作。工具箱架构支持: + +- **10 个内置工具箱** 用于常见操作(文件、数学、Web、加密货币、代码执行) +- **MCP 集成** 连接到任何模型上下文协议 (Model Context Protocol) 服务器(1000+ 可用) +- **智能数据处理** 可选的 Parquet 存储用于大数据 +- **执行隔离** 每个执行的文件作用域隔离 +- **工具指标** 跟踪调用、延迟和错误 +- **灵活配置** 通过 YAML profiles + +### 架构 + +``` +智能体 (Executor) +├── 工具箱管理器 (Toolkit Manager) +│ ├── 原生工具箱 (FileToolkit, CalculatorToolkit 等) +│ ├── MCP 工具箱 (连接外部 MCP 服务器) +│ └── 自定义工具箱 (用户定义) +├── 工具存储 (可选 Parquet 用于大数据) +└── 工具指标 (跟踪与可观察性) +``` + +每个工具箱: +- 自动向 DSPy 的工具系统注册工具 +- 为 LLM 工具选择提供完整的参数模式 (schema) +- 通过结构化响应优雅地处理错误 +- 可选地存储大型结果以减少上下文使用 + +--- + +## 快速开始 + +### 1. 使用内置工具箱 + +```yaml +# config/profiles/my_profile.yaml +agents: + executor: + llm: + model: openai/gpt-4o-mini + temperature: 0.3 + prediction_strategy: react # 工具使用必填 + toolkits: + - class_name: FileToolkit + enabled: true + - class_name: CalculatorToolkit + enabled: true + - class_name: E2BToolkit + enabled: true + toolkit_config: + timeout: 300 +``` + +**用法:** +```bash +just solve "计算 2500 的 15% 并保存到 results.txt" -c config/profiles/my_profile.yaml +``` + +### 2. 使用 MCP 服务器 + +```yaml +agents: + executor: + llm: + model: openai/gpt-4o-mini + prediction_strategy: react + toolkits: + # 公共 HTTP MCP 服务器 (无需安装) + - class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: coingecko + server_type: http + url: https://mcp.api.coingecko.com/sse + use_storage: false +``` + +**用法:** +```bash +just solve "比特币当前价格是多少?" -c config/profiles/my_profile.yaml +``` + +--- + +## 原生工具箱 + +ROMA-DSPy 包含 10 个内置工具箱,注册在 `ToolkitManager.BUILTIN_TOOLKITS` 中。 + +### 1. FileToolkit + +具有执行范围隔离的文件操作。 + +**工具:** +- `save_file(file_path: str, content: str, encoding: str = 'utf-8')` - 保存内容到文件 +- `read_file(file_path: str, encoding: str = 'utf-8')` - 读取文件内容 +- `list_files(directory: str = ".", pattern: str = "*")` - 列出匹配模式的文件 +- `search_files(query: str, directory: str = ".", extensions: list = None)` - 搜索文件内容 +- `create_directory(directory_path: str)` - 创建目录 +- `delete_file(file_path: str)` - 删除文件(需要 enable_delete=True) + +**配置:** +```yaml +- class_name: FileToolkit + enabled: true + toolkit_config: + enable_delete: false # 安全:禁用破坏性操作 + max_file_size: 10485760 # 10MB 限制 +``` + +**安全性:** +- 所有文件路径都限于执行特定的目录 +- 防止路径遍历攻击 +- 强制文件大小限制 +- 默认禁用删除操作 + +**示例:** 参见 `config/examples/basic/minimal.yaml` + +--- + +### 2. CalculatorToolkit + +具有精度控制的数学运算。 + +**工具:** +- `add(a: float, b: float)` - 加法 +- `subtract(a: float, b: float)` - 减法 +- `multiply(a: float, b: float)` - 乘法 +- `divide(a: float, b: float)` - 除法 +- `exponentiate(base: float, exponent: float)` - 幂运算 +- `factorial(n: int)` - 阶乘 +- `is_prime(n: int)` - 质数检查 +- `square_root(n: float)` - 平方根 + +**配置:** +```yaml +- class_name: CalculatorToolkit + enabled: true + toolkit_config: + precision: 10 # 小数位数 (默认: 10) +``` + +**响应格式:** +```json +{ + "success": true, + "operation": "addition", + "operands": [25, 47], + "result": 72.0 +} +``` + +**示例:** 参见 `config/examples/basic/minimal.yaml` + +--- + +### 3. E2BToolkit + +通过 [E2B](https://e2b.dev) 进行安全的沙箱代码执行。 + +**特性:** +- 隔离的 Python/Node.js 执行环境 +- 自动沙箱健康检查 +- 沙箱生命周期管理 +- 沙箱内文件系统访问 +- 用于数据获取的网络访问 + +**配置:** +```yaml +- class_name: E2BToolkit + enabled: true + toolkit_config: + timeout: 300 # 执行超时 (秒) + max_lifetime_hours: 23.5 # 24小时限制前自动重启 + template: base # E2B 模板 ID + auto_reinitialize: true # 失败时自动重启 +``` + +**环境变量:** +```bash +export E2B_API_KEY=your_key_here +export E2B_TEMPLATE_ID=base # 可选: 自定义模板 +``` + +**示例:** 参见 `config/examples/basic/multi_toolkit.yaml` + +--- + +### 4. SerperToolkit + +通过 [Serper.dev](https://serper.dev) API 进行 Web 搜索。 + +**工具:** +- `search(query: str, num_results: int = 10)` - 搜索网络 + +**配置:** +```yaml +- class_name: SerperToolkit + enabled: true + toolkit_config: + location: "United States" # 搜索位置 + language: "en" # 结果语言 + num_results: 10 # 结果数量 + date_range: null # 可选: "d" (天), "w" (周), "m" (月), "y" (年) +``` + +**环境变量:** +```bash +export SERPER_API_KEY=your_key_here +``` + +**示例:** 参见 `config/examples/basic/multi_toolkit.yaml` + +--- + +### 5. WebSearchToolkit + +使用具有 Web 搜索能力的 LLM 进行原生 Web 搜索。 + +**特性:** +- 与启用了 Web 搜索的模型进行 DSPy 原生集成 +- 支持 OpenRouter (带插件) 和 OpenAI (Responses API) +- 自动提取引用 +- 专家级搜索提示词,用于全面数据检索 +- 优先考虑可靠来源(维基百科、政府、学术) +- 可配置搜索上下文深度 + +**工具:** +- `web_search(query: str, max_results: int = None, search_context_size: str = None)` - 全面检索数据的 Web 搜索 + +**配置:** +```yaml +- class_name: WebSearchToolkit + enabled: true + toolkit_config: + model: openrouter/openai/gpt-5-mini # 根据前缀自动检测提供商 + search_engine: exa # 用于 OpenRouter (省略则使用原生搜索) + max_results: 5 # 搜索结果数量 + search_context_size: medium # low, medium, 或 high + temperature: 1.0 # 模型温度 (GPT-5 需要 1.0) + max_tokens: 16000 # 最大响应 Token (GPT-5 建议 16000+) +``` + +**提供商检测:** +- 以 `openrouter/` 开头的模型使用 OpenRouter 插件 API +- 以 `openai/` 开头的模型使用 OpenAI Responses API +- 无需单独的 provider 参数 + +**搜索行为:** +工具箱使用专家搜索者指令引导 LLM: +1. 检索完整数据集(整个表格、所有列表项、所有数据点) +2. 优先考虑可靠来源(维基百科优先,然后是政府/学术/新闻) +3. 准确呈现找到的数据(不总结) +4. 包含时间敏感查询的时间意识 + +**环境变量:** +```bash +export OPENROUTER_API_KEY=your_key_here # 用于 OpenRouter 模型 +# 或 +export OPENAI_API_KEY=your_key_here # 用于 OpenAI 模型 +``` + +**响应格式:** +```json +{ + "success": true, + "data": "包含完整数据的综合答案...", + "citations": [ + {"url": "https://en.wikipedia.org/..."}, + {"url": "https://example.com/..."} + ], + "tool": "web_search", + "model": "openrouter/openai/gpt-5-mini", + "provider": "openrouter" +} +``` + +**使用示例:** +```yaml +# OpenRouter 原生搜索 (GPT-5-mini) +- class_name: WebSearchToolkit + toolkit_config: + model: openrouter/openai/gpt-5-mini + # 无 search_engine = 原生搜索 + max_results: 5 + search_context_size: medium + temperature: 1.0 + max_tokens: 16000 + +# OpenRouter 配合 Exa 搜索引擎 +- class_name: WebSearchToolkit + toolkit_config: + model: openrouter/anthropic/claude-sonnet-4 + search_engine: exa + max_results: 10 + search_context_size: high + +# OpenAI Responses API +- class_name: WebSearchToolkit + toolkit_config: + model: openai/gpt-4o + search_context_size: medium + max_results: 5 +``` + +**示例:** 参见 `config/profiles/crypto_agent.yaml` + +--- + +### 6. BinanceToolkit + +来自 Binance 的加密货币市场数据。 + +**特性:** +- 现货、USDT 本位合约和币本位合约 +- 实时价格和 Ticker 统计 +- 订单簿深度和近期成交 +- OHLCV K线数据 +- 可选统计分析 + +**工具:** +- `get_current_price(symbol: str, market: str = "spot")` - 当前价格 +- `get_ticker_stats(symbol: str, market: str = "spot")` - 24小时统计 +- `get_book_ticker(symbol: str, market: str = "spot")` - 最佳买卖价 +- `get_klines(symbol: str, interval: str, limit: int = 100, market: str = "spot")` - K线数据 +- `get_order_book(symbol: str, limit: int = 100, market: str = "spot")` - 订单簿深度 +- `get_recent_trades(symbol: str, limit: int = 100, market: str = "spot")` - 近期成交 + +**配置:** +```yaml +- class_name: BinanceToolkit + enabled: true + toolkit_config: + default_market: spot # spot, usdm, coinm + enable_analysis: false # 统计分析 +``` + +**无需 API 密钥** - 使用公共 Binance 端点 + +**示例:** 参见 `config/profiles/crypto_agent.yaml` + +--- + +### 7. CoinGeckoToolkit + +来自 [CoinGecko](https://coingecko.com) 的全面加密货币数据。 + +**特性:** +- 17,000+ 加密货币 +- 100+ 货币计价的实时价格 +- 历史价格和市场数据 +- OHLCV K线数据 +- 市场排名和统计 +- 合约地址查找 +- 全球市场指标 + +**工具:** +- `get_coin_price(coin_name_or_id: str, vs_currency: str = "usd")` - 当前价格 +- `get_coin_market_chart(coin_name_or_id: str, vs_currency: str = "usd", days: int = 30)` - 历史数据 +- 更多工具请参阅工具箱实现 + +**配置:** +```yaml +- class_name: CoinGeckoToolkit + enabled: true + toolkit_config: + coins: null # 限制特定币种 (null = 全部) + default_vs_currency: usd # 默认计价货币 + use_pro: false # 使用 CoinGecko Pro API + enable_analysis: false # 统计分析 +``` + +**环境变量:** +```bash +export COINGECKO_API_KEY=your_key_here # 可选: 用于 Pro API +``` + +**无需 API 密钥**(对于公共端点) + +**示例:** 参见 `config/profiles/crypto_agent.yaml` + +--- + +### 8. DefiLlamaToolkit + +来自 [DefiLlama](https://defillama.com) 的 DeFi 协议分析。 + +**特性:** +- 协议 TVL (总锁仓价值) 跟踪 +- 每日费用和收入分析 +- 收益农场池和 APY 数据 (Pro) +- 用户活动指标 (Pro) +- 跨链分析 +- 统计分析 + +**工具 (公共):** +- `get_protocol_fees(protocol_name: str)` - 协议费用和收入 +- `get_protocol_tvl(protocol_name: str)` - 总锁仓价值 +- 更多公共工具可用 + +**工具 (Pro - 需要 API 密钥):** +- `get_yield_pools()` - 收益农场机会 +- `get_yield_chart(pool_id: str)` - 历史 APY 数据 +- `get_active_users(protocol_name: str)` - 用户活动 +- 更多 Pro 工具可用 + +**配置:** +```yaml +- class_name: DefiLlamaToolkit + enabled: true + toolkit_config: + enable_pro_features: false # 需要 API 密钥 + default_chain: ethereum + enable_analysis: true +``` + +**环境变量:** +```bash +export DEFILLAMA_API_KEY=your_key_here # 用于 Pro 功能 +``` + +**无需 API 密钥**(对于公共端点) + +**示例:** 参见 `config/profiles/crypto_agent.yaml` + +--- + +### 9. ArkhamToolkit + +来自 [Arkham Intelligence](https://arkhamintelligence.com) 的区块链分析。 + +**特性:** +- 代币分析(热门代币、持有者、流向) +- 实体归属的转账跟踪 +- 跨链钱包余额监控 +- 分布统计分析 +- 速率限制(标准 20 req/sec,重型 1 req/sec) + +**工具:** +- 代币分析工具 +- 转账跟踪工具 +- 钱包余额工具 +- 更多工具请参阅工具箱实现 + +**配置:** +```yaml +- class_name: ArkhamToolkit + enabled: true + toolkit_config: + default_chain: ethereum + enable_analysis: true +``` + +**环境变量:** +```bash +export ARKHAM_API_KEY=your_key_here # 必需 +``` + +**需要 API 密钥** + +--- + +### 10. CoinglassToolkit + +来自 [Coinglass](https://coinglass.com) 的衍生品市场数据。 + +**特性:** +- 持仓量加权的历史资金费率 (OHLC 数据) +- 20+ 交易所的实时资金费率 +- 资金费率套利机会检测 +- 持仓量跟踪和历史分析 +- 主动买入/卖出量比率 (市场情绪) +- 按交易所和仓位类型的清算数据 + +**工具:** +- `get_funding_rates_weighted_by_oi` - 历史资金费率 OHLC 数据 +- `get_funding_rates_per_exchange` - 各交易所当前资金费率 +- `get_arbitrage_opportunities` - 资金费率套利机会 +- `get_open_interest_by_exchange` - 各交易所当前持仓量 +- `get_open_interest_history` - 历史持仓量数据 +- `get_taker_buy_sell_volume` - 买/卖量比率 +- `get_liquidations_by_exchange` - 清算数据 + +**配置:** +```yaml +- class_name: CoinglassToolkit + enabled: true + toolkit_config: + symbols: ["BTC", "ETH", "SOL"] # 限制特定品种 (null = 全部) + default_symbol: BTC + storage_threshold_kb: 500 # 自动存储 > 500KB 的响应 +``` + +**环境变量:** +```bash +export COINGLASS_API_KEY=your_key_here # 必需 +``` + +**需要 API 密钥** - 在 [Coinglass API](https://coinglass.com/api) 获取 + +**示例:** 参见 `config/profiles/crypto_agent.yaml` + +--- + +### 11. MCPToolkit + +模型上下文协议 (Model Context Protocol) 服务器的通用连接器。 + +**特性:** MCPToolkit 可以连接到 **任何** MCP 服务器 - 有 1000+ 可用! + +请参阅下方的 [MCP 集成](#mcp-集成) 部分了解完整详情。 + +--- + +## MCP 集成 + +**MCPToolkit** 使 ROMA-DSPy 智能体能够使用来自 **任何** MCP 服务器的工具。这提供了超越 10 个内置工具箱的无限扩展性。 + +### 什么是 MCP? + +MCP 是用于将 AI 应用程序连接到数据源和工具的开放协议。就像 AI 的 USB-C 接口一样通用。 + +**资源:** +- **Awesome MCP Servers**: [700+ 服务器](https://github.com/wong2/awesome-mcp-servers) +- **MCP 文档**: [modelcontextprotocol.io](https://modelcontextprotocol.io/) +- **构建您自己的**: 任何实现 MCP 协议的服务器 + +### 连接类型 + +#### 1. HTTP/SSE 服务器 (远程) + +**最适合:** 公共 API,云服务,无需安装 + +**示例 - CoinGecko 公共服务器:** +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: coingecko + server_type: http + url: https://mcp.api.coingecko.com/sse + use_storage: false +``` + +**示例 - Exa 搜索 (带 API 密钥):** +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: exa + server_type: http + url: https://mcp.exa.ai/mcp + headers: + Authorization: "Bearer ${oc.env:EXA_API_KEY}" + use_storage: true # Exa 返回大量搜索结果 + storage_threshold_kb: 50 +``` + +**无需安装** - 通过 HTTP 连接 + +#### 2. Stdio 服务器 (本地子进程) + +**最适合:** 本地工具,文件系统访问,数据库,git 操作 + +**示例 - GitHub 操作:** +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: github + server_type: stdio + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_PERSONAL_ACCESS_TOKEN: "${oc.env:GITHUB_PERSONAL_ACCESS_TOKEN}" + use_storage: false +``` + +**示例 - 文件系统访问:** +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: filesystem + server_type: stdio + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-filesystem" + - "/Users/yourname/Documents" # 允许的目录 + use_storage: false +``` + +**需要安装:** +```bash +npm install -g @modelcontextprotocol/server-github +npm install -g @modelcontextprotocol/server-filesystem +``` + +### 存储配置 + +MCP 工具可能会返回大型数据集(搜索结果、数据库查询等)。工具箱提供智能数据处理: + +**小数据 (默认):** +```yaml +use_storage: false # 直接返回原始文本/JSON +``` + +**大数据 (带存储):** +```yaml +use_storage: true # 数据存入 Parquet,返回引用 +storage_threshold_kb: 100 # 存储 > 100KB 的结果 (默认) +``` + +**工作原理:** +1. 工具执行并返回数据 +2. 如果数据大小 > 阈值,保存到 Parquet 文件 +3. 返回文件引用而不是完整数据 +4. 减少大型数据集的上下文占用 + +### 查找 MCP 服务器 + +**热门类别:** + +| 类别 | 示例 | +|------|------| +| **Web 搜索** | Exa, Brave Search, Google Search | +| **开发** | GitHub, GitLab, Linear, Sentry | +| **数据** | PostgreSQL, SQLite, MongoDB, Redis | +| **云** | AWS, Google Cloud, Kubernetes | +| **生产力** | Google Drive, Slack, Notion, Confluence | +| **金融** | Stripe, QuickBooks | +| **AI/ML** | OpenAI, Anthropic, Hugging Face | + +**浏览全部:** +- [awesome-mcp-servers](https://github.com/wong2/awesome-mcp-servers) - 700+ 服务器 +- [MCP Server Registry](https://modelcontextprotocol.io/servers) - 官方注册表 + +### 多个 MCP 服务器 + +您可以在一个智能体中使用 **多个** MCP 服务器: + +```yaml +agents: + executor: + llm: + model: openai/gpt-4o-mini + prediction_strategy: react + toolkits: + # GitHub 用于代码 + - class_name: MCPToolkit + toolkit_config: + server_name: github + server_type: stdio + command: npx + args: ["-y", "@modelcontextprotocol/server-github"] + env: + GITHUB_PERSONAL_ACCESS_TOKEN: "${oc.env:GITHUB_TOKEN}" + + # Exa 用于 Web 搜索 + - class_name: MCPToolkit + toolkit_config: + server_name: exa + server_type: http + url: https://mcp.exa.ai/mcp + headers: + Authorization: "Bearer ${oc.env:EXA_API_KEY}" + use_storage: true + + # Filesystem 用于本地文件 + - class_name: MCPToolkit + toolkit_config: + server_name: filesystem + server_type: stdio + command: npx + args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"] +``` + +**示例:** 参见 `config/examples/mcp/multi_server.yaml` + +--- + +## 配置指南 + +### 基本结构 + +```yaml +agents: + executor: + llm: + model: openai/gpt-4o-mini + temperature: 0.3 + prediction_strategy: react # 工具使用必需 + toolkits: + - class_name: ToolkitName + enabled: true + include_tools: null # 可选: 白名单特定工具 + exclude_tools: null # 可选: 黑名单特定工具 + toolkit_config: + # 工具箱特定设置 +``` + +### 工具过滤 + +**仅包含特定工具:** +```yaml +- class_name: CalculatorToolkit + enabled: true + include_tools: + - add + - subtract + - multiply + # 只有这 3 个工具可用 +``` + +**排除特定工具:** +```yaml +- class_name: FileToolkit + enabled: true + exclude_tools: + - delete_file # 安全:禁用删除 + # 除 delete_file 外的所有工具可用 +``` + +### 环境变量 + +**通过 OmegaConf:** +```yaml +toolkit_config: + api_key: "${oc.env:MY_API_KEY}" # 从环境读取 + timeout: "${oc.env:TIMEOUT,300}" # 默认值: 300 +``` + +**通过 .env 文件:** +```bash +# .env +E2B_API_KEY=your_key +SERPER_API_KEY=your_key +GITHUB_PERSONAL_ACCESS_TOKEN=your_token +``` + +### 存储集成 + +一些工具箱支持可选的 Parquet 存储用于大数据: + +```yaml +- class_name: MCPToolkit + enabled: true + toolkit_config: + server_name: database + server_type: stdio + command: npx + args: ["-y", "@modelcontextprotocol/server-sqlite", "/path/to/db.db"] + use_storage: true # 启用存储包装器 + storage_threshold_kb: 100 # 存储 > 100KB 的结果 +``` + +**支持存储的工具箱:** +- MCPToolkit +- DefiLlamaToolkit +- ArkhamToolkit +- BinanceToolkit (用于大型响应) +- CoinGeckoToolkit (用于大型响应) +- CoinglassToolkit (用于大型响应) + +--- + +## 示例 + +所有示例均可在 `config/examples/` 中找到。请参阅 `config/examples/README.md` 获取完整指南。 + +### 示例 1:极简配置 + +**文件:** `config/examples/basic/minimal.yaml` + +包含 FileToolkit 和 CalculatorToolkit 的简单智能体。 + +**用法:** +```bash +just solve "计算 2500 的 15% 并保存到 results.txt" -c config/examples/basic/minimal.yaml +``` + +--- + +### 示例 2:多工具箱 + +**文件:** `config/examples/basic/multi_toolkit.yaml` + +结合 E2B(代码执行)、FileToolkit、CalculatorToolkit 和 SerperToolkit。 + +**用法:** +```bash +just solve "搜索 Python 斐波那契实现,执行它,并保存结果" \ + -c config/examples/basic/multi_toolkit.yaml +``` + +--- + +### 示例 3:公共 HTTP MCP 服务器 + +**文件:** `config/examples/mcp/http_public_server.yaml` + +使用 CoinGecko 公共 MCP 服务器 - **无需安装或 API 密钥!** + +**用法:** +```bash +just solve "比特币当前价格是多少?" \ + -c config/examples/mcp/http_public_server.yaml +``` + +--- + +### 示例 4:本地 Stdio MCP 服务器 + +**文件:** `config/examples/mcp/stdio_local_server.yaml` + +使用本地 Exa MCP 服务器进行 Web 搜索。 + +**设置:** +```bash +export EXA_API_KEY=your_key +npm install -g @exa-labs/exa-mcp-server +``` + +**用法:** +```bash +just solve "搜索最新的 LLM 研究论文" \ + -c config/examples/mcp/stdio_local_server.yaml +``` + +--- + +### 示例 5:多个 MCP 服务器 + +**文件:** `config/examples/mcp/multi_server.yaml` + +结合 GitHub、Exa(Web 搜索)和 CoinGecko MCP 服务器。 + +**用法:** +```bash +just solve "搜索最近的 AI 新闻,检查比特币价格,并创建 GitHub issue 摘要" \ + -c config/examples/mcp/multi_server.yaml +``` + +--- + +### 示例 6:加密货币代理(领域特定) + +**文件:** `config/profiles/crypto_agent.yaml` + +全面的加密分析,包含: +- CoinGeckoToolkit (17,000+ 币种) +- CoinglassToolkit (衍生品市场数据) +- BinanceToolkit (现货 + 期货) +- DefiLlamaToolkit (DeFi 协议) +- ArkhamToolkit (链上分析) +- Exa MCP (Web 搜索) + +**用法:** +```bash +just solve "对比比特币和以太坊:价格、市值、24小时成交量,并分析趋势" \ + crypto_agent +``` + +--- + +## 创建自定义工具箱 + +### 步骤 1:创建工具箱类 + +```python +# my_custom_toolkit.py +from roma_dspy.tools.base.base import BaseToolkit +from typing import Optional, List + +class MyCustomToolkit(BaseToolkit): + """用于 XYZ 操作的自定义工具箱。""" + + def __init__( + self, + enabled: bool = True, + include_tools: Optional[List[str]] = None, + exclude_tools: Optional[List[str]] = None, + **config, + ): + super().__init__( + enabled=enabled, + include_tools=include_tools, + exclude_tools=exclude_tools, + **config, + ) + + # 您的初始化 + self.api_key = config.get("api_key") + + def _setup_dependencies(self) -> None: + """设置外部依赖。""" + # 可选:验证 API 密钥,初始化客户端 + pass + + def _initialize_tools(self) -> None: + """初始化工具箱特定配置。""" + # 可选:额外设置 + pass + + # 工具方法 (由 BaseToolkit 自动注册) + + async def my_tool(self, param1: str, param2: int) -> str: + """ + LLM 将看到的工具描述。 + + Args: + param1: param1 的描述 + param2: param2 的描述 + + Returns: + 结果描述 + """ + # 您的工具实现 + result = f"Processed {param1} with {param2}" + return result + + async def another_tool(self, query: str) -> dict: + """另一个返回结构化数据的工具。""" + return { + "success": True, + "query": query, + "results": ["result1", "result2"] + } +``` + +### 步骤 2:注册工具箱 + +添加到 `src/roma_dspy/tools/base/manager.py`: + +```python +BUILTIN_TOOLKITS = { + # ... 现有工具箱 ... + "MyCustomToolkit": "path.to.my_custom_toolkit", +} +``` + +### 步骤 3:在配置中使用 + +```yaml +agents: + executor: + llm: + model: openai/gpt-4o-mini + prediction_strategy: react + toolkits: + - class_name: MyCustomToolkit + enabled: true + toolkit_config: + api_key: "${oc.env:MY_API_KEY}" +``` + +### 最佳实践 + +1. **工具设计:** + - 清晰、描述性的工具名称 + - 全面的文档字符串(LLM 会看到这些) + - 所有参数的类型提示 + - 返回结构化数据(JSON 字典或字符串) + +2. **错误处理:** + ```python + async def my_tool(self, param: str) -> dict: + try: + result = await self._do_something(param) + return {"success": True, "data": result} + except Exception as e: + logger.error(f"Tool failed: {e}") + return {"success": False, "error": str(e)} + ``` + +3. **大型数据存储:** + ```python + class MyToolkit(BaseToolkit): + REQUIRES_FILE_STORAGE = False # 可选存储 + + def __init__(self, use_storage: bool = False, **config): + super().__init__(**config) + self.use_storage = use_storage + + async def big_data_tool(self, query: str) -> str: + result = await self._fetch_large_dataset(query) + + if self.use_storage and len(result) > threshold: + # 存储到 Parquet 并返回引用 + path = await self.file_storage.save_tool_result(...) + return f"Data stored at: {path}" + + return result + ``` + +4. **测试:** + ```python + # tests/test_my_toolkit.py + import pytest + from my_custom_toolkit import MyCustomToolkit + + @pytest.mark.asyncio + async def test_my_tool(): + toolkit = MyCustomToolkit() + result = await toolkit.my_tool("test", 42) + assert "Processed" in result + ``` + +--- + +## 最佳实践 + +### 1. 工具箱选择 + +**为任务选择正确的工具:** +```yaml +# 用于文件操作 + 数学 +toolkits: + - class_name: FileToolkit + - class_name: CalculatorToolkit + +# 用于 Web 研究 +toolkits: + - class_name: SerperToolkit # 原生 + # 或 + - class_name: MCPToolkit # MCP (Exa, Brave 等) + toolkit_config: + server_name: exa + server_type: http + url: https://mcp.exa.ai/mcp + +# 用于代码执行 +toolkits: + - class_name: E2BToolkit +``` + +### 2. 安全性 + +**文件操作:** +```yaml +- class_name: FileToolkit + toolkit_config: + enable_delete: false # 禁用破坏性操作 + max_file_size: 10485760 # 10MB 限制 +``` + +**MCP 服务器:** +- 仅使用受信任的 MCP 服务器 +- 验证服务器 URL 和签名 +- 对敏感数据使用环境变量 + +### 3. 性能 + +**对大数据使用存储:** +```yaml +- class_name: MCPToolkit + toolkit_config: + use_storage: true + storage_threshold_kb: 50 # 激进的阈值以加快响应 +``` + +**限制工具范围:** +```yaml +- class_name: CalculatorToolkit + include_tools: + - add + - multiply + # 更少的选项使工具选择更快 +``` + +### 4. 成本优化 + +**使用任务感知映射**为不同任务类型分配不同的工具箱: + +```yaml +agent_mapping: + executors: + RETRIEVE: + # 便宜的模型 + Web 搜索 + llm: + model: openrouter/google/gemini-2.0-flash-exp:free + toolkits: + - class_name: SerperToolkit + + CODE_INTERPRET: + # 强大的模型 + 代码执行 + llm: + model: openrouter/anthropic/claude-sonnet-4 + toolkits: + - class_name: E2BToolkit + - class_name: FileToolkit +``` + +**示例:** 参见 `config/examples/advanced/task_aware_mapping.yaml` + +### 5. 可观察性 + +**启用日志:** +```yaml +runtime: + enable_logging: true +``` + +**跟踪工具指标:** +- 自动记录工具调用 +- 延迟跟踪 +- 错误率 +- 在 MLflow 中查看(如果启用了可观察性) + +### 6. API 密钥管理 + +**切勿硬编码密钥:** +```yaml +# ❌ 错误 +toolkit_config: + api_key: "sk-1234567890abcdef" + +# ✅ 正确 +toolkit_config: + api_key: "${oc.env:MY_API_KEY}" +``` + +**使用 .env 文件:** +```bash +# .env +E2B_API_KEY=your_key +SERPER_API_KEY=your_key +GITHUB_PERSONAL_ACCESS_TOKEN=your_token +``` + +--- + +## 故障排除 + +### "Unknown toolkit class: XYZ" + +**原因:** 工具箱未注册或 class_name 拼写错误 + +**修复:** +```bash +# 检查可用工具箱 +python -c "from roma_dspy.tools.base.manager import ToolkitManager; print(ToolkitManager.BUILTIN_TOOLKITS.keys())" + +# 验证拼写是否完全匹配(区分大小写) +``` + +### "Tools don't support strategy: chain_of_thought" + +**原因:** Chain-of-thought 策略不支持工具使用 + +**修复:** +```yaml +agents: + executor: + prediction_strategy: react # 使用 react 或 codeact 以支持工具 +``` + +### MCP 服务器连接失败 + +**HTTP 服务器:** +```bash +# 测试连接 +curl -I https://mcp.api.coingecko.com/sse + +# 检查 headers/auth +curl -H "Authorization: Bearer YOUR_KEY" https://mcp.exa.ai/mcp +``` + +**Stdio 服务器:** +```bash +# 验证安装 +npx @modelcontextprotocol/server-github --version + +# 手动测试 +npx -y @modelcontextprotocol/server-github +``` + +### E2B 不工作 + +```bash +# 验证 API 密钥 +echo $E2B_API_KEY + +# 测试连接 +python -c "from e2b import Sandbox; s = Sandbox(); print(s.is_running())" + +# 检查模板 +export E2B_TEMPLATE_ID=base +``` + +### 大数据超时 + +**启用存储:** +```yaml +toolkit_config: + use_storage: true + storage_threshold_kb: 50 # 降低阈值 +``` + +--- + +## 额外资源 + +- **配置指南**: [CONFIGURATION.md](CONFIGURATION.md) +- **MCP 深入解析**: [MCP.md](MCP.md) +- **示例配置**: `config/examples/` +- **Awesome MCP Servers**: https://github.com/wong2/awesome-mcp-servers +- **MCP 文档**: https://modelcontextprotocol.io/ +- **E2B 文档**: https://e2b.dev/docs + +--- + +**准备好构建了吗?** 从 `config/examples/` 中的示例开始,并根据您的用例进行定制! 🚀 + From fa33ed0f6b815e3d6f3b087c1c6ef10ddd260642 Mon Sep 17 00:00:00 2001 From: KasparChen Date: Tue, 16 Dec 2025 18:01:52 +0800 Subject: [PATCH 2/3] docs: Add Chinese READMEs for prompt_optimization and tests --- prompt_optimization/README_ZH.md | 187 ++++++++++++++++++++++ tests/README_ZH.md | 260 +++++++++++++++++++++++++++++++ 2 files changed, 447 insertions(+) create mode 100644 prompt_optimization/README_ZH.md create mode 100644 tests/README_ZH.md diff --git a/prompt_optimization/README_ZH.md b/prompt_optimization/README_ZH.md new file mode 100644 index 00000000..b6762934 --- /dev/null +++ b/prompt_optimization/README_ZH.md @@ -0,0 +1,187 @@ +# 提示词优化 (Prompt Optimization) + +基于 GEPA (Generative Expectation-Maximization Prompt Optimization with Adversarial Examples) 的模块化工具包,用于优化 ROMA-DSPy 提示词。 + +## 目录结构 + +``` +prompt_optimization/ +├── config.py # 配置管理 (dataclasses) +├── datasets.py # 数据集加载器 (AIMO, AIME) +├── solver_setup.py # Solver 工厂与指令常量 +├── judge.py # 用于评估组件的 LLM 裁判 +├── metrics/ # 指标实现 (基础, 搜索, 数字, 反馈) +│ ├── __init__.py +│ ├── base.py +│ ├── metric_with_feedback.py +│ ├── number_metric.py +│ └── search_metric.py +├── selectors.py # 组件选择策略 +├── optimizer.py # GEPA 优化器工厂 +└── run_optimization.py # 主 CLI 脚本 +``` + +## 快速开始 + +### 基本用法 + +```bash +# 使用默认值运行 (5 训练, 5 验证, 15 测试) +python -m prompt_optimization.run_optimization + +# 自定义数据集大小 +python -m prompt_optimization.run_optimization --train-size 10 --val-size 10 --test-size 30 + +# 使用不同的组件选择器 +python -m prompt_optimization.run_optimization --selector round_robin + +# 保存优化后的程序 +python -m prompt_optimization.run_optimization --output optimized_solver.json + +# 启用详细日志 +python -m prompt_optimization.run_optimization --verbose +``` + +### 可用选择器 (Selectors) + +- `planner_only` (默认) - 仅优化规划器 (planner) 组件 +- `atomizer_only` - 仅优化原子化器 (atomizer) 组件 +- `executor_only` - 仅优化执行器 (executor) 组件 +- `aggregator_only` - 仅优化聚合器 (aggregator) 组件 +- `round_robin` - 循环优化所有组件 + +### 编程方式使用 + +```python +from prompt_optimization import ( + get_default_config, + load_aimo_datasets, + create_solver_module, + ComponentJudge, + MetricWithFeedback, + create_optimizer +) + +# 加载配置 +config = get_default_config() +config.train_size = 10 +config.max_metric_calls = 20 + +# 加载数据集 +train, val, test = load_aimo_datasets( + train_size=config.train_size, + val_size=config.val_size, + test_size=config.test_size +) + +# 创建 solver +solver = create_solver_module(config) + +# 创建裁判和指标 +judge = ComponentJudge(config.judge_lm) +# 包装评分指标 (如果省略,默认为基本整数比较) +metric = MetricWithFeedback(judge) + +# 创建优化器 +optimizer = create_optimizer(config, metric, component_selector="planner_only") + +# 替代方案:插入自定义评分指标 (例如,搜索准确性) +# from prompt_optimization.metrics import NumberMetric +# metric = MetricWithFeedback(judge, scoring_metric=NumberMetric()) + +# 运行优化 +optimized = optimizer.compile(solver, trainset=train, valset=val) +``` + +### 异步用法 + +裁判 (judge) 和指标 (metrics) 均支持异步执行以提高性能: + +```python +import asyncio +from prompt_optimization import ComponentJudge, MetricWithFeedback, get_default_config + +config = get_default_config() + +# 创建裁判 +judge = ComponentJudge(config.judge_lm) + +# 同步用法 +feedback = judge( + component_name="planner", + component_trace={"subtasks": [...], "dependencies_graph": {...}}, + prediction_trace="完整追踪..." +) + +# 异步用法 +async def evaluate_async(): + feedback = await judge.__acall__( + component_name="planner", + component_trace={"subtasks": [...], "dependencies_graph": {...}}, + prediction_trace="完整追踪..." + ) + return feedback + +# 运行异步 +feedback = asyncio.run(evaluate_async()) + +# 指标也支持异步 +metric = MetricWithFeedback(judge) + +# 异步指标评估 +async def evaluate_metric(): + result = await metric.aforward( + example=example, + prediction=prediction, + pred_name="planner", + pred_trace=trace + ) + return result +``` + +## 配置 + +所有配置集中在 `config.py` 中。关键参数: + +- **LM Configs**: 每个组件的模型名称、温度、最大 token 数 +- **Dataset**: 训练/验证/测试集大小,随机种子 +- **Execution**: 最大并行执行数,并发限制 +- **GEPA**: 最大指标调用数,线程数,反思小批量 (minibatch) 大小 +- **Solver**: 最大深度,日志设置 + +## CLI 选项 + +``` +usage: run_optimization.py [-h] [--train-size TRAIN_SIZE] [--val-size VAL_SIZE] + [--test-size TEST_SIZE] [--max-parallel MAX_PARALLEL] + [--concurrency CONCURRENCY] [--max-metric-calls MAX_METRIC_CALLS] + [--num-threads NUM_THREADS] + [--selector {planner_only,atomizer_only,executor_only,aggregator_only,round_robin}] + [--output OUTPUT] [--verbose] [--skip-eval] +``` + +## 核心特性 + +- ✅ **无全局状态** - 所有组件均正确初始化并作为依赖项传递 +- ✅ **使用 AsyncParallelExecutor** - 利用 `roma_dspy.utils` 中现有的异步工具 +- ✅ **异步支持** - 裁判和指标支持同步 (`forward`) 和异步 (`aforward`) 执行 +- ✅ **完全可配置** - 基于 dataclass 的配置,支持 CLI 覆盖 +- ✅ **模块化** - 每个组件都可独立测试和重用 +- ✅ **类型安全** - 全程使用正确的类型提示 +- ✅ **简洁 CLI** - 可通过 `python -m prompt_optimization.run_optimization` 运行 + +## 从 Notebook 迁移 + +重构将 `prompt_optimization.ipynb` 中的所有逻辑提取了出来: + +| Notebook 单元格 | 新位置 | +|---------------|--------------| +| LM 配置 | `config.py:LMConfig` | +| 模块初始化 | `solver_setup.py:create_solver_module()` | +| 指令 | `solver_setup.py` (常量) | +| 数据集加载 | `datasets.py:load_aimo_datasets()` | +| 裁判设置 | `judge.py:ComponentJudge` | +| 指标 | `metrics/__init__.py:basic_metric`, `metrics/metric_with_feedback.py:MetricWithFeedback` | +| 选择器 | `selectors.py:*_selector` | +| GEPA 优化器 | `optimizer.py:create_optimizer()` | +| 执行 | `run_optimization.py:main()` | diff --git a/tests/README_ZH.md b/tests/README_ZH.md new file mode 100644 index 00000000..7bd207ff --- /dev/null +++ b/tests/README_ZH.md @@ -0,0 +1,260 @@ +# ROMA-DSPy 测试套件 + +本目录包含 ROMA-DSPy 的测试套件,按测试类型组织,并使用 pytest 标记进行分类,以实现灵活的测试执行。 + +## 测试组织 + +``` +tests/ +├── unit/ # 快速、隔离的单元测试 +├── integration/ # 包含外部服务的集成测试 +├── tools/ # 工具箱特定测试 +├── validation/ # 验证和确认测试 +├── performance/ # 性能基准测试 (未来) +└── fixtures/ # 共享测试固件 (fixtures) +``` + +## 测试标记 (Markers) + +测试使用 pytest 标记进行分类。使用标记来运行特定的测试子集: + +### 主要类别 +- `unit` - 无外部依赖的快速单元测试 +- `integration` - 需要外部服务的集成测试 +- `e2e` - 端到端系统测试 + +### 需求标记 +- `requires_db` - 需要 PostgreSQL 数据库 +- `requires_llm` - 需要 LLM API 密钥 (OpenAI 等) +- `requires_e2b` - 需要 E2B 沙箱环境 + +### 功能标记 +- `checkpoint` - 检查点/恢复功能测试 +- `error_handling` - 错误传播测试 +- `tools` - 工具箱集成测试 +- `performance` - 性能基准测试 +- `slow` - 耗时较长的测试 + +## 运行测试 + +### 运行所有测试 +```bash +pytest +``` + +### 仅运行单元测试 (快速) +```bash +pytest -m unit +``` + +### 运行集成测试 (需要服务) +```bash +pytest -m integration +``` + +### 运行需要 PostgreSQL 的测试 +```bash +# 先启动 Postgres +docker-compose up -d postgres + +# 运行数据库测试 +pytest -m requires_db + +# 清理 +docker-compose down +``` + +### 运行需要 LLM API 的测试 +```bash +# 设置 API 密钥 +export OPENAI_API_KEY=your_key_here + +# 运行 LLM 测试 +pytest -m requires_llm +``` + +### 运行特定测试类别 +```bash +# 仅检查点测试 +pytest -m checkpoint + +# 仅工具箱测试 +pytest -m tools + +# 不需要数据库的集成测试 +pytest -m "integration and not requires_db" + +# 包含所有需求的 E2E 测试 +pytest -m "e2e and requires_db and requires_llm" +``` + +### 按目录运行测试 +```bash +# 所有单元测试 +pytest tests/unit/ + +# 特定测试文件 +pytest tests/unit/test_dag_serialization.py + +# 特定测试函数 +pytest tests/unit/test_dag_serialization.py::test_serialize_task_node +``` + +### 测试覆盖率 +```bash +# 运行并生成覆盖率报告 +pytest --cov=src/roma_dspy --cov-report=html + +# 打开覆盖率报告 +open htmlcov/index.html +``` + +## 设置测试环境 + +### 1. 安装开发依赖 +```bash +pip install -e ".[dev]" +``` + +### 2. 启动 PostgreSQL (用于 DB 测试) +```bash +docker-compose up -d postgres + +# 验证是否运行 +docker-compose ps + +# 检查日志 +docker-compose logs postgres +``` + +### 3. 设置环境变量 +```bash +# LLM 测试必需 +export OPENAI_API_KEY=sk-... +export FIREWORKS_API_KEY=... + +# DB 测试必需 (docker-compose 默认值) +export DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost/roma_dspy_test + +# 可选:E2B 沙箱 +export E2B_API_KEY=... +``` + +### 4. 运行数据库迁移 (首次) +```bash +# 将迁移应用到测试数据库 +uv run alembic upgrade head +``` + +## 编写测试 + +### 测试结构 +```python +import pytest + +@pytest.mark.unit +def test_my_unit_test(): + """测试描述。""" + # 无外部依赖的快速测试 + assert True + +@pytest.mark.integration +@pytest.mark.requires_db +async def test_my_integration_test(postgres_storage): + """测试描述。""" + # 使用 fixtures 的集成测试 + result = await postgres_storage.get_execution("exec_123") + assert result is not None +``` + +### 使用标记 +```python +# 单个标记 +@pytest.mark.unit + +# 多个标记 +@pytest.mark.integration +@pytest.mark.slow +@pytest.mark.requires_db + +# 带条件的跳过 +@pytest.mark.skipif( + not os.getenv("OPENAI_API_KEY"), + reason="需要 OPENAI_API_KEY 环境变量" +) +``` + +### Fixtures +常用 fixtures 可在 `tests/conftest.py` 和 `tests/fixtures/` 中找到: + +- `postgres_storage` - 初始化的 PostgresStorage 实例 +- `postgres_config` - 用于测试的 PostgresConfig +- `temp_checkpoint_dir` - 用于检查点测试的临时目录 +- 针对 LM 和外部服务的 Mock fixtures + +## 持续集成 (CI) + +测试自动运行于: +- Pull requests (单元测试 + 无外部依赖的集成测试) +- Main 分支提交 (带服务的完整套件) + +查看 `.github/workflows/ci.yml` 获取 CI 配置。 + +## 故障排除 + +### 测试超时 +```bash +# 增加慢速测试的超时时间 +pytest --timeout=300 +``` + +### 数据库连接错误 +```bash +# 检查 Postgres 是否运行 +docker-compose ps + +# 重置数据库 +docker-compose down -v +docker-compose up -d postgres +``` + +### 导入错误 +```bash +# 以可编辑模式重新安装 +pip install -e . +``` + +### 跳过的测试 +```bash +# 查看测试被跳过的原因 +pytest -v -rs + +# 强制运行跳过的测试 (危险!) +pytest --runxfail +``` + +## 测试最佳实践 + +1. **保持单元测试快速** - 无 I/O,无网络,无外部服务 +2. **使用适当的标记** - 准确标记测试以进行选择性运行 +3. **Mock 外部依赖** - 在单元测试中 mock LLM +4. **清理资源** - 使用 fixtures 进行 setup/teardown +5. **测试边缘情况** - 无效输入、错误条件、边界值 +6. **记录测试目的** - 清晰的文档字符串解释测试内容 + +## 性能测试 + +性能测试计划在未来开发: + +```bash +# 运行性能基准测试 (未来) +pytest -m performance --benchmark-only +``` + +## 测试数据 + +测试数据和 fixtures 位于: +- `tests/fixtures/` - 可重用的测试数据 +- 单个测试文件 - 测试特定的数据 + +避免将敏感数据(API 密钥、凭证)提交到测试文件中。 From 02cf6745016126b090de14d171d020f0cd78ac08 Mon Sep 17 00:00:00 2001 From: KasparChen Date: Tue, 16 Dec 2025 18:06:17 +0800 Subject: [PATCH 3/3] docs: modify wording --- README_ZH.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README_ZH.md b/README_ZH.md index 925faf1d..8e3d2e00 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -1,10 +1,10 @@
alt text -

ROMA: 递归开放元智能体 (Recursive Open Meta-Agents)

+

ROMA: 开源递归式元智能体 (Recursive Open Meta-Agents)

- 轻松构建分层高性能多智能体系统!(Beta) + 轻松构建分层高性能多智能体系统(Beta)

@@ -35,7 +35,7 @@

技术博客论文 (即将发布) • - 构建智能体赚取收益 + 构建智能体赚取赏金

---