{
  "canonical_name": "stanfordnlp/dspy",
  "compilation_id": "pack_10c230ff44554d868aec04bd32229bcd",
  "created_at": "2026-05-16T05:02:41.318098+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=prompt, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=prompt, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install dspy` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install dspy",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_41d25b1a08194ea1ad7674ae5f703325"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_593837c1f4222a8b8a6cba41aaf921ee",
    "canonical_name": "stanfordnlp/dspy",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/stanfordnlp/dspy",
    "slug": "dspy",
    "source_packet_id": "phit_446a59c66ef947ada16d70a91501b82b",
    "source_validation_id": "dval_61d8d0f5194148c490bf2613b11dd059"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 local_cli的用户",
    "github_forks": 2892,
    "github_stars": 34450,
    "one_liner_en": "DSPy: The framework for programming—not prompting—language models",
    "one_liner_zh": "DSPy: The framework for programming—not prompting—language models",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "medium",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:git, cli"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "dspy",
    "title_zh": "dspy 能力包",
    "visible_tags": [
      {
        "label_en": "MCP Tools",
        "label_zh": "MCP 工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-mcp-tools",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Structured Extraction",
        "label_zh": "结构化提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Verifiable Workflow",
        "label_zh": "可验证工作流",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-verifiable-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_446a59c66ef947ada16d70a91501b82b",
  "page_model": {
    "artifacts": {
      "artifact_slug": "dspy",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install dspy",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/stanfordnlp/dspy#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "结构化提取",
        "可验证工作流",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "DSPy: The framework for programming—not prompting—language models"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "local_cli",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "prompt, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_43291e191b234ac883662982bf693e18 | https://github.com/stanfordnlp/dspy/issues/9749 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.0.4b1",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_76f47f2d6cbc4f299fe2a852b20617ef | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b1 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.0.4b1",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.2",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_3733e2d7817440638629959030da2ddb | https://github.com/stanfordnlp/dspy/releases/tag/3.1.2 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.1.2",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.3",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_2b7f0c4a046840b4b453167ce581b80a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.1.3",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.2.0",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_976a3edffce44ac3984c9da4a10a2575 | https://github.com/stanfordnlp/dspy/releases/tag/3.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.2.0",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Use Tool functions that require external libaries in CodeAct",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_3c605227d53e42b69651c46c3e76c162 | https://github.com/stanfordnlp/dspy/issues/8839 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Use Tool functions that require external libaries in CodeAct",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:587050620 | https://github.com/stanfordnlp/dspy | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_d192b20b863c476ca31d4ba476cec875 | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.0.4",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4b2",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_392f60c647b74a6592f1692bcdc0070f | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.0.4b2",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_364bbccd7d4241c9b6841303fefb5a85 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.1.0",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0b1",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_4599cbf0d1fd41b4b3c47e5c1aae247a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.1.0b1",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.1",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_5656ac7c80214b9fb410d129ccec33d2 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.1.1",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.2.1",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_e2250d3118a04c5e8d213eb2fce4e68d | https://github.com/stanfordnlp/dspy/releases/tag/3.2.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：3.2.1",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 19 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 425,
        "forks": 2892,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 34450
      },
      "source_url": "https://github.com/stanfordnlp/dspy",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "DSPy: The framework for programming—not prompting—language models",
      "title": "dspy 能力包",
      "trial_prompt": "# dspy - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 dspy 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的软件开发与交付任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 示例引导, 判断线索。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 安装前能力预览: DSPy: The framework for programming—not prompting—language models 输入：用户任务, 当前 AI 对话上下文；输出：示例引导, 判断线索。\n\n【必须安装后才可验证的能力】\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. page-overview：DSPy概述。围绕“DSPy概述”模拟一次用户任务，不展示安装或运行结果。\n2. page-installation：安装与快速开始。围绕“安装与快速开始”模拟一次用户任务，不展示安装或运行结果。\n3. page-signatures：签名（Signatures）。围绕“签名（Signatures）”模拟一次用户任务，不展示安装或运行结果。\n4. page-modules：内置模块参考。围绕“内置模块参考”模拟一次用户任务，不展示安装或运行结果。\n5. page-primitives：原语与数据结构。围绕“原语与数据结构”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. page-overview\n输入：用户提供的“DSPy概述”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. page-installation\n输入：用户提供的“安装与快速开始”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. page-signatures\n输入：用户提供的“签名（Signatures）”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. page-modules\n输入：用户提供的“内置模块参考”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. page-primitives\n输入：用户提供的“原语与数据结构”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / page-overview：Step 1 必须围绕“DSPy概述”形成一个小中间产物，并等待用户确认。\n- Step 2 / page-installation：Step 2 必须围绕“安装与快速开始”形成一个小中间产物，并等待用户确认。\n- Step 3 / page-signatures：Step 3 必须围绕“签名（Signatures）”形成一个小中间产物，并等待用户确认。\n- Step 4 / page-modules：Step 4 必须围绕“内置模块参考”形成一个小中间产物，并等待用户确认。\n- Step 5 / page-primitives：Step 5 必须围绕“原语与数据结构”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/stanfordnlp/dspy\n- https://github.com/stanfordnlp/dspy#readme\n- dspy/__init__.py\n- dspy/__metadata__.py\n- README.md\n- dspy/primitives/module.py\n- dspy/primitives/base_module.py\n- pyproject.toml\n- dspy/utils/__init__.py\n- dspy/signatures/__init__.py\n- dspy/signatures/signature.py\n- dspy/signatures/field.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 dspy 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: PythonInterpreter: paths containing commas are silently misparsed by Den（https://github.com/stanfordnlp/dspy/issues/9749）；github/github_issue: [Bug] PythonInterpreter fails with default setup due to missing Deno rea（https://github.com/stanfordnlp/dspy/issues/9501）；github/github_issue: Use Tool functions that require external libaries in CodeAct（https://github.com/stanfordnlp/dspy/issues/8839）；github/github_release: 3.2.1（https://github.com/stanfordnlp/dspy/releases/tag/3.2.1）；github/github_release: 3.2.0（https://github.com/stanfordnlp/dspy/releases/tag/3.2.0）；github/github_release: 3.1.3（https://github.com/stanfordnlp/dspy/releases/tag/3.1.3）；github/github_release: 3.1.2（https://github.com/stanfordnlp/dspy/releases/tag/3.1.2）；github/github_release: 3.1.1（https://github.com/stanfordnlp/dspy/releases/tag/3.1.1）；github/github_release: 3.1.0（https://github.com/stanfordnlp/dspy/releases/tag/3.1.0）；github/github_release: 3.1.0b1（https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1）；github/github_release: 3.0.4（https://github.com/stanfordnlp/dspy/releases/tag/3.0.4）；github/github_release: 3.0.4b2（https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "PythonInterpreter: paths containing commas are silently misparsed by Den",
              "url": "https://github.com/stanfordnlp/dspy/issues/9749"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug] PythonInterpreter fails with default setup due to missing Deno rea",
              "url": "https://github.com/stanfordnlp/dspy/issues/9501"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Use Tool functions that require external libaries in CodeAct",
              "url": "https://github.com/stanfordnlp/dspy/issues/8839"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.2.1",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.2.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.2.0",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.2.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.1.3",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.1.3"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.1.2",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.1.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.1.1",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.1.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.1.0",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.1.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.1.0b1",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.0.4",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.0.4"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "3.0.4b2",
              "url": "https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "DSPy: The framework for programming—not prompting—language models",
      "effort": "安装已验证",
      "forks": 2892,
      "icon": "code",
      "name": "dspy 能力包",
      "risk": "可发布",
      "slug": "dspy",
      "stars": 34450,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "结构化提取",
        "可验证工作流",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "Prompt Preview"
    },
    "manual": {
      "markdown": "# https://github.com/stanfordnlp/dspy 项目说明书\n\n生成时间：2026-05-16 04:11:08 UTC\n\n## 目录\n\n- [DSPy概述](#page-overview)\n- [安装与快速开始](#page-installation)\n- [签名（Signatures）](#page-signatures)\n- [内置模块参考](#page-modules)\n- [原语与数据结构](#page-primitives)\n- [优化器详解](#page-optimizers)\n- [语言模型客户端](#page-lm-clients)\n- [适配器系统](#page-adapters)\n- [检索增强模块](#page-retrieval)\n- [评估与指标](#page-evaluation)\n\n<a id='page-overview'></a>\n\n## DSPy概述\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [内置模块参考](#page-modules), [语言模型客户端](#page-lm-clients)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.md)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n- [dspy/adapters/types/document.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/document.py)\n- [dspy/adapters/types/citation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/citation.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# DSPy概述\n\nDSPy（Declarative Self-Improving Python）是一个用于构建和优化基于语言模型（LM）复杂管道的框架。该框架由斯坦福NLP团队开发，旨在通过声明式编程范式简化大型语言模型应用的开发和优化过程。\n\n## 核心定位与价值\n\nDSPy的核心价值在于将语言模型调用从硬编码的提示词转变为可声明式定义、可自动优化的程序组件。根据项目文档，DSPy能够\"将声明式语言模型调用编译成自我改进的管道\"，这使得开发者可以专注于程序逻辑而非提示工程细节。\n\n## 系统架构\n\n### 整体架构图\n\n```mermaid\ngraph TD\n    A[用户程序] --> B[DSPy Module]\n    B --> C[Signature定义]\n    B --> D[Predict组件]\n    B --> E[ChainOfThought组件]\n    C --> F[InputField/OutputField]\n    D --> G[语言模型 LM]\n    E --> G\n    G --> H[优化器 Teleprompter]\n    H --> I[训练集 Trainset]\n    I --> H\n    H --> B\n    G --> J[检索模型 RM]\n    J --> K[外部知识库]\n```\n\n### 核心组件层次\n\n| 层级 | 组件 | 说明 |\n|------|------|------|\n| 用户层 | DSPy Module | 自定义程序模块，继承`dspy.Module` |\n| 定义层 | Signature | 声明输入输出字段及其描述 |\n| 执行层 | Predict/ChainOfThought | 执行语言模型调用 |\n| 优化层 | Teleprompter | 自动优化提示和参数 |\n| 集成层 | LM/RM Adapter | 支持多种语言模型和检索器 |\n\n## 核心抽象\n\n### Module基类\n\nDSPy的`Module`是所有程序组件的基类，提供了语言模型管理和预测组件发现功能：\n\n```python\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n```\n\nModule类提供以下关键方法：\n\n| 方法 | 功能 | 资料来源 |\n|------|------|----------|\n| `named_predictors()` | 返回所有Predict组件的(名称, 实例)元组列表 | [module.py:92-100]() |\n| `predictors()` | 返回所有Predict实例的列表 | [module.py:103-120]() |\n| `set_lm(lm)` | 为所有Predict设置语言模型 | [module.py:128-143]() |\n| `get_lm()` | 获取当前使用的语言模型 | [module.py:145-152]() |\n\n### Signature系统\n\nSignature用于声明模块的输入输出字段语义，是DSPy中连接程序逻辑与语言模型的关键抽象：\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField(desc=\"用户问题\")\n    answer: str = dspy.OutputField(desc=\"模型回答\")\n```\n\nSignature支持动态修改：\n\n- `prepend()`: 在输入字段前插入新字段\n- `append()`: 在输出字段后追加新字段\n- `delete()`: 删除指定字段\n\n## 数据模型\n\n### Example类\n\n`dspy.Example`是DSPy中用于表示训练样本和测试样本的核心数据结构：\n\n```python\nexample = dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\")\n```\n\n**主要方法：**\n\n| 方法 | 功能 | 示例 |\n|------|------|------|\n| `with_inputs(*keys)` | 标记输入字段 | `.with_inputs(\"question\")` |\n| `inputs()` | 获取仅包含输入字段的新Example | `example.inputs()` |\n| `labels()` | 获取仅包含标签字段的新Example | `example.labels()` |\n| `toDict()` | 递归转换为JSON友好字典 | `example.toDict()` |\n| `copy(**kwargs)` | 创建副本并覆盖指定字段 | `ex.copy(answer=\"5\")` |\n| `without(*keys)` | 返回移除指定字段的副本 | `ex.without(\"source\")` |\n\n资料来源：[example.py:1-250]()\n\n### 特殊类型\n\nDSPy提供了多种适配不同场景的特殊数据类型：\n\n#### History类型\n\n用于会话历史管理，允许在提示中包含多轮对话上下文：\n\n```python\nhistory = dspy.History(messages=[\n    {\"question\": \"法国的首都是什么？\", \"answer\": \"巴黎\"},\n    {\"question\": \"德国的首都是什么？\", \"answer\": \"柏林\"}\n])\n```\n\n资料来源：[history.py:1-60]()\n\n#### Document类型\n\n支持文档格式的数据，可用于检索增强生成（RAG）场景：\n\n```python\ndoc = Document(\n    data=\"水的沸点是100°C\",\n    title=\"物理基础\",\n    context=\"标准大气压下\"\n)\n```\n\n资料来源：[document.py:1-100]()\n\n#### Citation类型\n\n支持引用信息，用于需要标注来源的场景：\n\n```python\nclass Citations(dspy.Signature):\n    documents: list[Document] = dspy.InputField()\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n    citations: list[Citation] = dspy.OutputField()\n```\n\n资料来源：[citation.py:1-80]()\n\n## 回调系统\n\nDSPy提供了灵活的回调机制用于监控和调试程序执行：\n\n```python\nclass LoggingCallback(dspy.Callback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"Module started: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"Module finished: {outputs}\")\n```\n\n| 回调方法 | 触发时机 |\n|----------|----------|\n| `on_module_start()` | Module的forward方法被调用时 |\n| `on_module_end()` | Module的forward方法完成时 |\n| `on_lm_start()` | 语言模型开始生成时 |\n| `on_lm_end()` | 语言模型生成完成时 |\n\n资料来源：[callback.py:1-100]()\n\n## 安装与使用\n\n### 安装方式\n\n```bash\npip install dspy\n```\n\n安装最新开发版本：\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:1-20]()\n\n### 基础使用流程\n\n```mermaid\ngraph LR\n    A[定义Signature] --> B[创建Module]\n    B --> C[配置LM]\n    C --> D[准备Trainset]\n    D --> E[编译优化]\n    E --> F[执行预测]\n```\n\n## Teleprompter优化系统\n\nDSPy的优化器（Teleprompter）负责自动优化程序的提示和参数：\n\n| 优化器 | 用途 |\n|--------|------|\n| `BootstrapFewShotWithRandomSearch` | 小样本引导+随机搜索 |\n| `BootstrapFinetune` | 引导微调 |\n| `BetterTogether` | 组合优化策略 |\n\n`BetterTogether`是一个典型的组合优化器，可同时执行提示优化（p阶段）和权重优化（w阶段）：\n\n```python\noptimizer = BetterTogether(\n    metric=metric,\n    p=GEPA(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric)\n)\n```\n\n资料来源：[bettertogether.py:1-100]()\n\n## 嵌入与检索\n\n### Embedder组件\n\n支持自定义嵌入函数和批量处理：\n\n```python\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\n关键参数：\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `model` | str, Callable | 必填 | 嵌入模型或函数 |\n| `batch_size` | int | 200 | 批处理大小 |\n| `caching` | bool | True | 是否启用缓存 |\n\n资料来源：[embedding.py:1-100]()\n\n### 检索器支持\n\nDSPy支持多种检索器后端，包括Weaviate等向量数据库：\n\n```python\nretriever_model = WeaviateRM(\"my_collection_name\", weaviate_client=client)\ndspy.configure(lm=llm, rm=retriever_model)\n```\n\n## 典型应用模式\n\n### 问答系统\n\n```python\nclass QAModule(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nqa = QAModule()\nqa.set_lm(lm)\nresult = qa(question=\"什么是DSPy?\")\n```\n\n### 带推理链的问答\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"1+1等于几？\")\n```\n\n### 检索增强生成\n\n```python\nretrieve = dspy.Retrieve(k=3)\npassages = retrieve(\"机器学习基础\").passages\n```\n\n## 开发环境配置\n\nDSPy要求Python 3.10或更高版本。使用`uv`进行环境管理：\n\n```bash\nuv venv --python 3.10\nuv sync --extra dev\n```\n\n运行测试：\n\n```bash\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:1-100]()\n\n## 相关研究\n\nDSPy基于以下核心研究论文：\n\n- **[2025年7月]** GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning\n- **[2024年6月]** Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs\n- **[2023年10月]** DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines\n\n## 总结\n\nDSPy通过声明式编程范式和自动优化机制，大大简化了基于语言模型应用的开发流程。其核心组件包括：\n\n- **Module系统**：提供程序结构的统一抽象\n- **Signature机制**：声明式定义输入输出语义\n- **Teleprompter优化器**：自动化提示和参数优化\n- **Adapter适配层**：支持多种语言模型和工具集成\n\n这套架构使得开发者可以专注于业务逻辑，而将提示工程的具体实现交给DSPy的优化系统自动处理。\n\n---\n\n<a id='page-installation'></a>\n\n## 安装与快速开始\n\n### 相关页面\n\n相关主题：[DSPy概述](#page-overview), [语言模型客户端](#page-lm-clients)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/stanfordnlp/dspy/blob/main/CONTRIBUTING.md)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/clients/embedding.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/embedding.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# 安装与快速开始\n\n## 概述\n\nDSPy（Declarative Self-Improving Language Model Programs）是一个用于编译声明式语言模型调用的框架，使语言模型程序能够自我改进。本节介绍如何安装 DSPy 框架以及如何快速上手使用该框架进行开发。\n\nDSPy 的设计理念是将语言模型调用声明化，通过优化器和签名系统自动优化提示和演示，从而提升程序性能。\n\n## 环境要求\n\n| 要求项 | 最低版本 | 说明 |\n|--------|----------|------|\n| Python | 3.10+ | 必须使用 Python 3.10 或更高版本 |\n| 包管理器 | pip/uv | 用于安装 DSPy 包 |\n\n资料来源：[CONTRIBUTING.md:1]()\n\n## 安装方式\n\n### 使用 pip 安装（推荐）\n\n通过 pip 直接安装稳定版本：\n\n```bash\npip install dspy\n```\n\n资料来源：[README.md:7]()\n\n### 安装最新开发版本\n\n如需安装最新的开发版本（从 main 分支），可使用以下命令：\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:12]()\n\n### 开发环境安装\n\n如需参与 DSPy 开发，推荐使用 uv 或 conda 进行环境管理。\n\n#### 使用 uv 设置开发环境\n\n```shell\ngit clone {url-to-your-fork}\ncd dspy\nuv sync\n```\n\n验证安装是否成功：\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:20-45]()\n\n#### 使用 conda 设置开发环境\n\n```shell\nconda create -n dspy-dev python=3.10\nconda activate dspy-dev\npip install -e \".[dev]\"\n```\n\n验证安装：\n\n```shell\npytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:47-56]()\n\n## 快速开始\n\n### 基本概念\n\n在使用 DSPy 之前，需要了解以下核心概念：\n\n| 概念 | 类名 | 用途 |\n|------|------|------|\n| 示例 | `dspy.Example` | 表示训练或评估数据，包含输入字段和标签字段 |\n| 模块 | `dspy.Module` | 自定义语言模型程序的基类 |\n| 预测器 | `dspy.Predict` | 执行语言模型调用的核心组件 |\n| 语言模型 | `dspy.LM` | 与各种语言模型提供商交互的接口 |\n\n### 创建 Example 对象\n\n`Example` 是 DSPy 中表示数据的基本单元。可以通过关键字参数创建：\n\n```python\nimport dspy\n\n# 创建包含问题答案的示例\nexample = dspy.Example(question=\"1+1 等于多少？\", answer=\"2\")\n```\n\n资料来源：[dspy/primitives/example.py:31-32]()\n\n### 标记输入字段\n\n使用 `with_inputs()` 方法标记哪些字段是输入字段：\n\n```python\nexample = dspy.Example(\n    question=\"今天天气如何？\",\n    answer=\"晴天\"\n).with_inputs(\"question\")\n```\n\n标记后，可以使用方法分离输入和标签：\n\n```python\nexample.inputs().toDict()  # {'question': '今天天气如何？'}\nexample.labels().toDict()  # {'answer': '晴天'}\n```\n\n资料来源：[dspy/primitives/example.py:87-97]()\n\n### 定义模块和预测器\n\n创建一个简单的问答模块：\n\n```python\nclass SimpleQA(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n### 设置语言模型\n\n使用 `set_lm()` 方法为模块设置语言模型：\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nqa = SimpleQA()\nqa.set_lm(lm)\n```\n\n资料来源：[dspy/primitives/module.py:67-78]()\n\n### 执行推理\n\n设置好语言模型后，可以执行推理：\n\n```python\nresult = qa(question=\"法国的首都是什么？\")\nprint(result.answer)\n```\n\n### 使用回调监控执行\n\nDSPy 支持通过回调函数监控模块和语言模型的调用：\n\n```python\nfrom dspy.utils.callback import BaseCallback\n\nclass LoggingCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"模块调用: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"模块输出: {outputs}\")\n\n# 在语言模型中使用回调\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n资料来源：[dspy/utils/callback.py:1-60]()\n\n### 构建训练集\n\n将多个 Example 组合成训练集用于优化：\n\n```python\ntrainset = [\n    dspy.Example(question=\"2+2 等于多少？\", answer=\"4\").with_inputs(\"question\"),\n    dspy.Example(question=\"3+3 等于多少？\", answer=\"6\").with_inputs(\"question\"),\n]\n```\n\n资料来源：[dspy/primitives/example.py:98-102]()\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[创建 Example 数据] --> B[定义 Module]\n    B --> C[设置 Language Model]\n    C --> D[执行推理]\n    D --> E{是否需要优化?}\n    E -->|是| F[创建训练集和验证集]\n    F --> G[选择 Teleprompter 优化器]\n    G --> H[编译优化程序]\n    H --> I[使用优化后的程序]\n    E -->|否| I\n    I --> J[最终部署使用]\n```\n\n## 下一步\n\n- 了解更多 DSPy 核心概念，请参阅签名（Signature）文档\n- 学习高级优化技术，请参阅 Teleprompter 相关文档\n- 了解支持的语言模型提供商，请参阅 LM 配置文档\n\n## 相关文档\n\n| 文档 | 说明 |\n|------|------|\n| [DSPy Docs](https://dspy.ai) | 官方完整文档 |\n| [GEPA](https://arxiv.org/abs/2507.19457) | 反思式提示进化算法论文 |\n| [DSPy 论文](https://arxiv.org/abs/2310.03714) | 框架核心论文 |\n\n---\n\n<a id='page-signatures'></a>\n\n## 签名（Signatures）\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/signatures/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/__init__.py)\n- [dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n- [dspy/signatures/field.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/field.py)\n- [dspy/signatures/utils.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/utils.py)\n</details>\n\n# 签名（Signatures）\n\n## 概述\n\n签名（Signature）是 DSPy 框架中定义模块输入输出接口的核心抽象。一个签名描述了语言模型程序的输入字段（InputField）和输出字段（OutputField），以及附加的指令说明。签名作为 DSPy 程序的结构化蓝图，定义了数据如何流入和流出各个模块。\n\n签名的主要作用包括：\n\n- **接口定义**：明确指定模块的输入和输出字段\n- **提示词构建**：自动生成结构化的提示词给语言模型\n- **数据验证**：确保输入输出数据的结构正确性\n- **元编程支持**：支持签名的动态组合、修改和转换\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n## 核心概念\n\n### 字段类型\n\nDSPy 提供两种基本字段类型来定义签名中的数据：\n\n| 字段类型 | 用途 | 说明 |\n|---------|------|------|\n| `InputField` | 输入字段 | 描述语言模型需要接收的输入数据 |\n| `OutputField` | 输出字段 | 描述语言模型需要生成的输出数据 |\n\n每个字段都可以通过 `desc` 参数添加描述文本，这些描述会被纳入提示词中，帮助语言模型理解字段的含义。\n\n资料来源：[dspy/signatures/field.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/field.py)\n\n### 签名结构\n\n```mermaid\ngraph TD\n    A[签名 Signature] --> B[instructions 说明]\n    A --> C[fields 字段集合]\n    C --> D[InputField 输入字段]\n    C --> E[OutputField 输出字段]\n    D --> F[field_name 字段名]\n    D --> G[annotation 类型注解]\n    D --> H[desc 描述文本]\n    E --> F2[field_name 字段名]\n    E --> G2[annotation 类型注解]\n    E --> H2[desc 描述文本]\n```\n\n## Signature 类 API\n\n### 主要方法\n\n| 方法名 | 用途 | 返回类型 |\n|-------|------|---------|\n| `with_instructions(instructions)` | 创建带新指令的签名副本 | `type[Signature]` |\n| `with_updated_fields(name, **kwargs)` | 更新指定字段的属性 | `type[Signature]` |\n| `prepend(name, field, type_=None)` | 在签名开头插入新字段 | `type[Signature]` |\n| `append(name, field, type_=None)` | 在签名末尾追加新字段 | `type[Signature]` |\n| `insert(pos, name, field, type_=None)` | 在指定位置插入字段 | `type[Signature]` |\n| `delete(name)` | 删除指定字段 | `type[Signature]` |\n\n资料来源：[dspy/signatures/signature.py:1-200](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### with_instructions 方法\n\n创建具有新指令文本的签名类副本：\n\n```python\nclass MySig(dspy.Signature):\n    input_text: str = dspy.InputField(desc=\"Input text\")\n    output_text: str = dspy.OutputField(desc=\"Output text\")\n\nNewSig = MySig.with_instructions(\"Translate to French.\")\n# NewSig.instructions == \"Translate to French.\"\n```\n\n此方法不会修改原签名，而是返回一个新的签名类。\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### with_updated_fields 方法\n\n更新指定字段的元数据属性：\n\n```python\nclass MySig(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nUpdatedSig = MySig.with_updated_fields(\n    \"answer\",\n    desc=\"The final answer\",\n    prefix=\"Result: \"\n)\n```\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### 字段操作方法\n\n```mermaid\ngraph LR\n    A[原 Signature] -->|prepend| B[在开头插入]\n    A -->|append| C[在末尾追加]\n    A -->|insert| D[在指定位置]\n    A -->|delete| E[删除字段]\n    B --> F[new Signature]\n    C --> F\n    D --> F\n    E --> F\n```\n\n**prepend 方法** - 在输入字段部分的开头插入新字段：\n\n```python\nNewSig = MySig.prepend(\"context\", dspy.InputField(desc=\"Context for translation\"))\n```\n\n**append 方法** - 在输出字段部分的末尾追加新字段：\n\n```python\nNewSig = MySig.append(\"confidence\", dspy.OutputField(desc=\"Translation confidence\"))\n```\n\n**delete 方法** - 返回移除指定字段后的新签名：\n\n```python\nNewSig = MySig.delete(\"unnecessary_field\")\n```\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n## make_signature 函数\n\n除了使用类语法定义签名外，DSPy 还提供了 `make_signature` 工具函数，支持多种签名定义格式：\n\n### 函数签名\n\n```python\ndef make_signature(\n    signature: str | dict,\n    *,\n    fresh_fields: bool = True,\n    check_args: bool = True,\n    custom_types: dict[str, type] | None = None,\n) -> dict[str, FieldInfo]:\n```\n\n### 支持的格式\n\n| 格式类型 | 示例 | 说明 |\n|---------|------|------|\n| 字符串格式 | `\"question -> answer\"` | 使用 `->` 分隔输入输出 |\n| 字典格式 | `{\"question\": str, \"answer\": str}` | 键值对形式 |\n| 元组格式 | `{\"q\": (str, InputField())}` | 指定类型和字段 |\n\n```python\n# 字符串格式\nsig1 = make_signature(\"question, context -> answer\")\n\n# 字典格式\nsig2 = make_signature({\n    \"question\": (str, InputField()),\n    \"answer\": (str, OutputField())\n})\n\n# 使用自定义类型\nclass MyType:\n    pass\n\nsig3 = make_signature(\n    \"input: MyType -> output\",\n    custom_types={\"MyType\": MyType}\n)\n```\n\n资料来源：[dspy/signatures/utils.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/utils.py)\n\n## 使用示例\n\n### 基本用法\n\n```python\nimport dspy\n\nclass RAGSignature(dspy.Signature):\n    \"\"\"回答基于给定上下文的问题\"\"\"\n    context: str = dspy.InputField(desc=\"用于回答问题的上下文信息\")\n    question: str = dspy.InputField(desc=\"需要回答的问题\")\n    answer: str = dspy.OutputField(desc=\"基于上下文得出的答案\")\n\n# 使用签名创建预测器\npredict = dspy.Predict(RAGSignature)\nresult = predict(context=\"巴黎是法国的首都。\", question=\"法国的首都是哪里？\")\nprint(result.answer)  # 输出生成的答案\n```\n\n### 与 Example 类集成\n\n签名与 `Example` 类紧密配合使用：\n\n```python\nimport dspy\n\n# 创建带输入标记的示例\nexample = dspy.Example(\n    question=\"What is 2+2?\",\n    answer=\"4\"\n).with_inputs(\"question\")\n\n# example.inputs() 返回只包含 question 的示例\n# example.labels() 返回只包含 answer 的示例\n```\n\n资料来源：[dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n\n### 在模块中使用\n\n签名可以被 DSPy 模块继承和组合：\n\n```python\nimport dspy\n\nclass MyModule(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n    \n    def forward(self, question: str) -> dspy.Prediction:\n        return self.qa(question=question)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 高级用法\n\n### 动态签名构建\n\n通过组合方法动态构建复杂签名：\n\n```python\nbase_sig = dspy.make_signature(\"input_text -> output_text\")\n\n# 链式调用添加字段\nenhanced_sig = (\n    base_sig\n    .prepend(\"system_prompt\", dspy.InputField(desc=\"系统提示词\"))\n    .append(\"confidence\", dspy.OutputField(desc=\"置信度\"))\n)\n\nclass EnhancedPredictor(dspy.Signature):\n    pass\n\nEnhancedPredictor.__signature__ = enhanced_sig\n```\n\n### 签名字段更新\n\n修改现有签名的字段描述：\n\n```python\noriginal = dspy.make_signature(\"query -> result\")\n\n# 更新字段描述\nrefined = original.with_updated_fields(\n    \"query\",\n    desc=\"搜索查询词\",\n    prefix=\"查询: \"\n)\nrefined = refined.with_updated_fields(\n    \"result\",\n    desc=\"搜索结果\",\n    prefix=\"结果: \"\n)\n```\n\n## 最佳实践\n\n### 1. 清晰的字段描述\n\n为每个字段提供准确的 `desc` 描述，这会直接影响语言模型的理解和输出质量：\n\n```python\nclass GoodSignature(dspy.Signature):\n    email_content: str = dspy.InputField(\n        desc=\"完整的电子邮件内容，包括发件人、主题和正文\"\n    )\n    sentiment: str = dspy.OutputField(\n        desc=\"情感分类结果，必须是 'positive'、'negative' 或 'neutral' 之一\"\n    )\n```\n\n### 2. 类型注解\n\n使用适当的类型注解可以增强代码可读性和 IDE 支持：\n\n```python\nclass TypedSignature(dspy.Signature):\n    user_id: int = dspy.InputField(desc=\"用户唯一标识符\")\n    query: str = dspy.InputField(desc=\"用户查询文本\")\n    response: str = dspy.OutputField(desc=\"生成的响应文本\")\n    confidence: float = dspy.OutputField(desc=\"响应置信度，范围 0-1\")\n```\n\n### 3. 签名组合策略\n\n当构建复杂流水线时，考虑按功能拆分签名：\n\n```mermaid\ngraph TD\n    subgraph 预处理阶段\n        A1[TextInput] --> A2[PreprocessedText]\n    end\n    subgraph 处理阶段\n        A2 --> B1[AnalyzeText]\n        B1 --> B2[AnalysisResult]\n    end\n    subgraph 生成阶段\n        B2 --> C1[GenerateResponse]\n        C1 --> C2[FinalOutput]\n    end\n```\n\n## 相关模块\n\n| 模块 | 路径 | 用途 |\n|-----|------|------|\n| signatures/signature.py | `dspy/signatures/signature.py` | Signature 类定义 |\n| signatures/field.py | `dspy/signatures/field.py` | InputField 和 OutputField |\n| signatures/utils.py | `dspy/signatures/utils.py` | make_signature 工具函数 |\n| signatures/\\_signature_do_not_use_directly.py | `dspy/signatures/` | 内部实现 |\n\n## 参考链接\n\n- [DSPy 官方文档](https://dspy.ai)\n- [签名模块源码](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/)\n- [Example 原语文档](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n\n---\n\n<a id='page-modules'></a>\n\n## 内置模块参考\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [优化器详解](#page-optimizers), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/predict/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/__init__.py)\n- [dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n- [dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n- [dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n- [dspy/predict/program_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/program_of_thought.py)\n- [dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n- [dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n- [dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n- [dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n- [dspy/predict/code_act.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/code_act.py)\n- [dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n</details>\n\n# 内置模块参考\n\n## 概述\n\nDSPy 内置模块是框架提供的核心组件，用于构建和执行语言模型程序。这些模块封装了常见的提示词工程模式，包括思维链推理、工具调用、并行处理等，使开发者能够以声明式的方式组合复杂的 LLM 应用。\n\n内置模块均继承自 `dspy.Module` 基类，提供了统一的接口和行为规范。每个模块都可以通过签名（Signature）定义输入输出字段，并支持与优化器（Teleprompter）配合使用进行自动优化。\n\n资料来源：[dspy/primitives/module.py:1-50](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 模块体系架构\n\nDSPy 的内置模块遵循分层设计架构，核心模块为 `Predict`，其他高级模块在其基础上组合扩展。\n\n```mermaid\ngraph TD\n    A[dspy.Module 基类] --> B[Predict 基础模块]\n    B --> C1[ChainOfThought 思维链]\n    B --> C2[Parallel 并行预测]\n    B --> C3[Retry 重试机制]\n    B --> C4[BestOfN N选一]\n    C1 --> D1[ReAct 推理+行动]\n    C1 --> D2[ProgramOfThought 程序思维]\n    C1 --> D3[MultiChainComparison 多链比较]\n    D1 --> E[CodeAct 代码行动]\n    B --> F[Refine 细化迭代]\n    B --> G[RLM 推理语言模型]\n```\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n## 模块基类\n\n`dspy.Module` 是所有内置模块的基类，提供了通用功能支持。\n\n### 核心方法\n\n| 方法名 | 说明 | 返回值 |\n|--------|------|--------|\n| `named_predictors()` | 返回所有命名预测器元组列表 | `list[tuple[str, Predict]]` |\n| `predictors()` | 返回所有 Predict 实例 | `list[Predict]` |\n| `set_lm(lm)` | 为所有预测器设置语言模型 | `None` |\n| `get_lm()` | 获取模块使用的语言模型 | `LM` 实例 |\n| `map_named_predictors(func)` | 对所有预测器应用转换函数 | `self` |\n| `inspect_history(n)` | 查看最近 n 次 LM 调用历史 | `None` |\n\n### 设置语言模型\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = dspy.Predict(\"question -> answer\")\nprogram.set_lm(lm)\n```\n\n资料来源：[dspy/primitives/module.py:45-75](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 基础模块\n\n### Predict\n\n`Predict` 是 DSPy 最核心的模块，用于基于签名执行语言模型调用。\n\n#### 基本用法\n\n```python\nimport dspy\n\n# 简单签名\npredict = dspy.Predict(\"question -> answer\")\nresult = predict(question=\"What is 1+1?\")\n\n# 使用类签名\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\npredict = dspy.Predict(MySignature)\n```\n\n#### 初始化参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `signature` | `str \\| Signature` | 输入输出字段定义 | 必填 |\n| `lm` | `LM \\| None` | 语言模型实例 | `None` |\n| `remote_cache` | `dict \\| None` | 远程缓存字典 | `None` |\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n## 推理模块\n\n### ChainOfThought（思维链）\n\n`ChainOfThought` 在 Predict 基础上自动加入推理步骤，要求模型先输出思考过程再给出最终答案。\n\n#### 工作原理\n\n1. 修改签名，在输出字段前添加 `reasoning` 字段\n2. 生成提示词引导模型进行逐步推理\n3. 提取并返回最终答案\n\n```python\nimport dspy\n\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"What is the capital of France?\")\nprint(result.reasoning)  # 中间推理过程\nprint(result.answer)     # 最终答案\n```\n\n#### 继承链\n\n```\nModule -> Predict -> ChainOfThought\n```\n\n资料来源：[dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n\n### MultiChainComparison（多链比较）\n\n`MultiChainComparison` 允许多个推理链并行执行，并对结果进行比较以选出最优答案。\n\n#### 工作流程\n\n```mermaid\ngraph TD\n    A[输入问题] --> B1[推理链1]\n    A --> B2[推理链2]\n    A --> B3[推理链3]\n    B1 --> C[比较结果]\n    B2 --> C\n    B3 --> C\n    C --> D[最优答案]\n```\n\n```python\nimport dspy\n\nmcc = dspy.MultiChainComparison(n=3)\nresult = mcc(question=\"Explain quantum entanglement\")\n```\n\n资料来源：[dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n\n## 工具调用模块\n\n### ReAct（推理与行动）\n\n`ReAct` 结合了推理（Reasoning）和行动（Acting）能力，支持模型使用工具与环境交互。\n\n#### 特性\n\n- 支持定义自定义工具\n- 自动管理工具调用循环\n- 推理过程透明可见\n\n```python\nimport dspy\n\nreact = dspy.ReAct(\"question -> answer\")\nresult = react(question=\"最新科技新闻有哪些？\")\n```\n\n资料来源：[dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n\n### CodeAct（代码行动）\n\n`CodeAct` 扩展了 ReAct 模式，专门用于生成和执行 Python 代码来解决复杂问题。\n\n```python\nimport dspy\n\ncode_act = dspy.CodeAct(\"problem -> solution\")\nresult = code_act(problem=\"计算斐波那契数列前20项的和\")\n```\n\n#### 执行流程\n\n```mermaid\ngraph LR\n    A[问题] --> B[生成代码]\n    B --> C[执行代码]\n    C --> D{结果正确?}\n    D -->|是| E[返回结果]\n    D -->|否| B\n```\n\n资料来源：[dspy/predict/code_act.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/code_act.py)\n\n## 迭代优化模块\n\n### Refine（细化迭代）\n\n`Refine` 通过迭代方式逐步细化答案，每次迭代基于前一次的结果进行调整。\n\n```python\nimport dspy\n\nrefine = dspy.Refine(\"question -> answer\", max_iters=3)\nresult = refine(question=\"解释机器学习原理\")\n```\n\n#### 迭代过程\n\n1. 初始化：生成初始答案\n2. 评估：检查当前答案质量\n3. 细化：根据反馈更新答案\n4. 重复：直到满足条件或达到最大迭代次数\n\n资料来源：[dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n\n### Retry（重试机制）\n\n`Retry` 在预测失败时自动重试，并可选择性地向模型提供错误信息以引导修正。\n\n```python\nimport dspy\n\nretry_predict = dspy.Retry(\"question -> answer\")\nresult = retry_predict(question=\"What is 1+1?\")\n```\n\n#### 重试策略\n\n| 参数 | 说明 | 默认值 |\n|------|------|--------|\n| `max_retries` | 最大重试次数 | `3` |\n| `on_error` | 错误处理回调 | 内置格式化 |\n\n资料来源：[dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n\n## 并行与选择模块\n\n### Parallel（并行预测）\n\n`Parallel` 允许同时执行多个预测器，适合需要并行处理多种推理路径的场景。\n\n```python\nimport dspy\n\nparallel = dspy.Parallel(\n    dspy.Predict(\"input -> output_a\"),\n    dspy.Predict(\"input -> output_b\"),\n    dspy.ChainOfThought(\"input -> output_c\")\n)\nresults = parallel(input=\"some text\")\n```\n\n资料来源：[dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n\n### BestOfN（N选一）\n\n`BestOfN` 生成 N 个候选答案，并使用指定的选择标准选出最优结果。\n\n```python\nimport dspy\n\nbon = dspy.BestOfN(\"question -> answer\", n=5)\nresult = bon(question=\"最佳编程语言是什么？\")\n```\n\n#### 选择机制\n\n```mermaid\ngraph TD\n    A[生成N个候选] --> B[应用评分函数]\n    B --> C[排序候选结果]\n    C --> D[返回最优答案]\n```\n\n资料来源：[dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n\n## Program of Thought\n\n`ProgramOfThought` 采用代码作为中间推理表示，通过生成和执行 Python 代码片段来解决问题。\n\n```python\nimport dspy\n\npot = dspy.ProgramOfThought(\"problem -> answer\")\nresult = pot(problem=\"求解微分方程 dy/dx = 2x\")\n```\n\n#### 与 CodeAct 的区别\n\n| 特性 | ProgramOfThought | CodeAct |\n|------|------------------|---------|\n| 交互方式 | 生成代码片段 | 生成并执行完整代码 |\n| 执行环境 | 隔离的解释器 | 完整 Python 环境 |\n| 适用场景 | 数学计算、逻辑推理 | 复杂系统操作 |\n\n资料来源：[dspy/predict/program_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/program_of_thought.py)\n\n## RLM（推理语言模型）\n\n`RLM` 是底层的语言模型封装模块，提供对各种 LLM 提供商的统一接口。\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nresult = lm(question=\"What is the meaning of life?\")\n```\n\n#### 支持的模型格式\n\n- `provider/model-name`（如 `openai/gpt-4o-mini`）\n- 支持的提供商包括 OpenAI、Anthropic、Google、本地模型等\n\n资料来源：[dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n\n## 模块导出清单\n\n所有内置模块可通过 `dspy.predict` 命名空间访问：\n\n| 模块 | 导入路径 | 说明 |\n|------|----------|------|\n| `Predict` | `dspy.Predict` | 基础预测模块 |\n| `ChainOfThought` | `dspy.ChainOfThought` | 思维链推理 |\n| `CoT` | `dspy.CoT` | ChainOfThought 别名 |\n| `ReAct` | `dspy.ReAct` | 推理+行动 |\n| `ProgramOfThought` | `dspy.ProgramOfThought` | 程序思维 |\n| `MultiChainComparison` | `dspy.MultiChainComparison` | 多链比较 |\n| `Parallel` | `dspy.Parallel` | 并行预测 |\n| `Refine` | `dspy.Refine` | 迭代细化 |\n| `BestOfN` | `dspy.BestOfN` | N选一 |\n| `CodeAct` | `dspy.CodeAct` | 代码行动 |\n| `Retry` | `dspy.Retry` | 重试机制 |\n\n资料来源：[dspy/predict/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/__init__.py)\n\n## 组合使用示例\n\n### 构建复杂管道\n\n```python\nimport dspy\n\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.cot = dspy.ChainOfThought(\"question -> reasoning, answer\")\n        self.refine = dspy.Refine(\"initial_answer -> refined_answer\")\n        self.verify = dspy.Predict(\"question, answer -> is_correct\")\n    \n    def forward(self, question):\n        cot_result = self.cot(question=question)\n        refined = self.refine(initial_answer=cot_result.answer)\n        verification = self.verify(question=question, answer=refined.refined_answer)\n        return {\n            \"reasoning\": cot_result.reasoning,\n            \"answer\": refined.refined_answer,\n            \"verified\": verification.is_correct\n        }\n\nprogram = MyProgram()\nresult = program(question=\"What is the square root of 144?\")\n```\n\n### 与优化器结合\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\n# 使用内置模块构建程序\nstudent = dspy.ChainOfThought(\"question -> answer\")\n\n# 编译优化\noptimizer = BootstrapFewShot(metric=your_metric)\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n## 最佳实践\n\n### 1. 选择合适的模块\n\n| 场景 | 推荐模块 |\n|------|----------|\n| 简单问答 | `Predict` |\n| 需要推理过程 | `ChainOfThought` |\n| 多角度分析 | `MultiChainComparison` |\n| 需要工具交互 | `ReAct` |\n| 代码生成执行 | `CodeAct` / `ProgramOfThought` |\n| 提高可靠性 | `Retry` / `BestOfN` |\n\n### 2. 性能考虑\n\n- `Parallel` 适用于可并行的独立任务\n- `BestOfN` 会增加 N 倍的 API 调用，应根据延迟要求选择\n- `Refine` 的 `max_iters` 参数需权衡质量与成本\n\n### 3. 调试技巧\n\n```python\n# 检查模块的 LM 调用历史\nprogram.inspect_history(n=5)\n\n# 查看当前使用的语言模型\nlm = program.get_lm()\n\n# 批量替换预测器\nprogram.map_named_predictors(lambda p: dspy.Retry(p.signature))\n```\n\n资料来源：[dspy/primitives/module.py:90-120](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n<a id='page-primitives'></a>\n\n## 原语与数据结构\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [内置模块参考](#page-modules), [评估与指标](#page-evaluation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/primitives/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/__init__.py)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/primitives/prediction.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/prediction.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/python_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/python_interpreter.py)\n- [dspy/primitives/code_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/code_interpreter.py)\n- [dspy/primitives/repl_types.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/repl_types.py)\n</details>\n\n# 原语与数据结构\n\n## 概述\n\nDSPy 框架的**原语（Primitives）与数据结构**构成了整个框架的核心抽象层。这些基础组件定义了如何表示数据、执行程序、管理模块间的通信，以及实现代码的沙箱执行能力。\n\nDSPy 的原语系统主要包括以下几个核心组件：\n\n| 组件 | 文件路径 | 职责 |\n|------|----------|------|\n| `Example` | `dspy/primitives/example.py` | 数据样本表示与输入/输出字段管理 |\n| `Prediction` | `dspy/primitives/prediction.py` | 程序执行结果的容器 |\n| `Module` | `dspy/primitives/module.py` | 所有 DSPy 程序的基类 |\n| `PythonInterpreter` | `dspy/primitives/python_interpreter.py` | Python 代码的安全执行环境 |\n| `CodeInterpreter` | `dspy/primitives/code_interpreter.py` | 代码解释器与 REPL 支持 |\n\n资料来源：[dspy/primitives/__init__.py]()\n\n## 核心数据结构\n\n### Example 类\n\n`Example` 是 DSPy 中用于表示数据样本的基础数据结构，类似于字典但提供了更丰富的语义支持。\n\n#### 基本功能\n\n```python\nimport dspy\n\n# 创建 Example 实例\nexample = dspy.Example(question=\"巴黎是哪国的首都？\", answer=\"法国\").with_inputs(\"question\")\n\n# 访问字段\nprint(example.question)  # 输出: 巴黎是哪国的首都？\nprint(example.answer)    # 输出: 法国\n```\n\n#### 字段分类系统\n\nExample 类通过 `with_inputs()` 方法将字段分为两类：\n\n- **输入字段（Inputs）**：程序执行时需要提供的外部数据\n- **标签字段（Labels）**：期望的输出结果，用于评估和训练\n\n```python\n# 使用 inputs() 和 labels() 方法分离字段\ninput_fields = example.inputs()    # 只包含 question\nlabel_fields = example.labels()    # 只包含 answer\n```\n\n资料来源：[dspy/primitives/example.py:1-200]()\n\n#### 常用方法\n\n| 方法 | 功能 | 返回类型 |\n|------|------|----------|\n| `with_inputs(*keys)` | 标记输入字段 | `Example` |\n| `inputs()` | 获取输入字段子集 | `Example` |\n| `labels()` | 获取标签字段子集 | `Example` |\n| `copy(**kwargs)` | 创建带修改的副本 | `Example` |\n| `without(*keys)` | 移除指定字段 | `Example` |\n| `toDict()` | 转换为字典格式 | `dict` |\n| `get(key, default)` | 安全获取字段值 | 任意类型 |\n| `keys()` / `values()` / `items()` | 字典式访问 | `list` |\n\n#### 序列化支持\n\n`toDict()` 方法支持递归序列化，能够处理嵌套的 Example 对象、Pydantic 模型、列表和字典，确保输出为 JSON 友好的格式：\n\n```python\ndef convert_to_serializable(value):\n    if hasattr(value, \"toDict\"):\n        return value.toDict()\n    elif isinstance(value, BaseModel):\n        return value.model_dump()\n    elif isinstance(value, list):\n        return [convert_to_serializable(item) for item in value]\n    elif isinstance(value, dict):\n        return {k: convert_to_serializable(v) for k, v in value.items()}\n```\n\n资料来源：[dspy/primitives/example.py:80-120]()\n\n---\n\n### Prediction 类\n\n`Prediction` 是程序执行后产生的结果容器，封装了模型的实际输出。\n\n#### 与 Example 的区别\n\n| 特性 | Example | Prediction |\n|------|---------|------------|\n| 用途 | 表示训练/测试数据 | 表示程序输出 |\n| 字段来源 | 人工标注或外部数据 | 模型推理结果 |\n| 典型使用 | 构造 trainset、valset | 接收 `cot()` 等模块返回值 |\n\n```python\n# Prediction 通常由 DSPy 模块自动生成\npred = dspy.Prediction(answer=\"2\")\n```\n\n资料来源：[dspy/primitives/prediction.py]()\n\n---\n\n## Module 基类\n\n`Module` 是所有 DSPy 程序的基类，提供了程序结构管理、语言模型设置等核心功能。\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[Predict]\n    A --> C[ChainOfThought]\n    A --> D[Program]\n    A --> E[自定义模块]\n    \n    F[named_predictors] --> G[获取所有 Predict 实例]\n    H[set_lm] --> I[递归设置 LM]\n```\n\n#### 核心方法\n\n| 方法 | 功能说明 |\n|------|----------|\n| `named_predictors()` | 返回所有 Predict 模块的 (名称, 实例) 元组列表 |\n| `predictors()` | 返回所有 Predict 实例的列表 |\n| `set_lm(lm)` | 递归为所有 Predict 模块设置语言模型 |\n| `get_lm()` | 获取当前使用的语言模型 |\n\n```python\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n    \n    def forward(self, question):\n        return self.qa(question=question)\n\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(f\"模块: {name}, 类型: {type(predictor)}\")\n```\n\n资料来源：[dspy/primitives/module.py:1-100]()\n\n---\n\n## 代码执行原语\n\n### PythonInterpreter\n\n`PythonInterpreter` 提供了一个安全的 Python 代码执行环境，用于在 DSPy 管道中动态执行生成的代码。\n\n```mermaid\ngraph LR\n    A[LLM 生成代码] --> B[PythonInterpreter]\n    B --> C[受限执行环境]\n    C --> D[结果提取]\n    D --> E[返回给下游模块]\n```\n\n#### 设计原则\n\n- **沙箱隔离**：限制可访问的内置函数和模块\n- **安全执行**：防止危险操作的代码执行\n- **结果捕获**：自动提取代码执行的输出\n\n资料来源：[dspy/primitives/python_interpreter.py]()\n\n---\n\n### CodeInterpreter\n\n`CodeInterpreter` 是更高级的代码解释器，支持 REPL（Read-Eval-Print Loop）模式的交互执行。\n\n#### REPLTypes\n\nREPL 相关的类型定义位于 `repl_types.py`，定义了代码块、超时控制等执行上下文：\n\n```python\n# 典型使用场景\nfrom dspy.primitives.repl_types import CodeBlock, REPLContext\n\ncontext = REPLContext(timeout=30)\nresult = interpreter.execute(code_block, context=context)\n```\n\n资料来源：[dspy/primitives/code_interpreter.py]()\n资料来源：[dspy/primitives/repl_types.py]()\n\n---\n\n## 数据流架构\n\n```mermaid\ngraph TD\n    subgraph \"数据输入层\"\n        A1[Example 数据集]\n        A2[用户输入]\n    end\n    \n    subgraph \"程序执行层\"\n        B1[Module.forward]\n        B2[Predict 模块]\n        B3[签名验证]\n    end\n    \n    subgraph \"输出层\"\n        C1[Prediction]\n        C2[Example.labels]\n    end\n    \n    subgraph \"优化层\"\n        D1[Teleprompter]\n        D2[Metrics]\n    end\n    \n    A1 --> B1\n    A2 --> B1\n    B1 --> B2\n    B2 --> B3\n    B3 --> C1\n    A1 --> D1\n    C1 --> D2\n    D1 --> B2\n```\n\n---\n\n## 最佳实践\n\n### 构造 Example 的规范\n\n```python\n# ✅ 推荐：显式指定输入字段\ntrain_example = dspy.Example(\n    question=\"1+1 等于多少？\",\n    answer=\"2\"\n).with_inputs(\"question\")\n\n# ✅ 副本创建用于数据增强\naugmented = train_example.copy(answer=\"答案是 2\")\n\n# ✅ 使用 base 参数高效构建\nbase_record = {\"question\": \"旧问题\", \"answer\": \"旧答案\"}\nnew_example = dspy.Example(base=base_record, question=\"新问题\").with_inputs(\"question\")\n```\n\n### 模块继承模式\n\n```python\nclass MyPipeline(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        # 初始化所有 Predict 子模块\n        self.retrieve = dspy.ColBERTv2(k=3)\n        self.answer = dspy.Predict(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.answer(context=context, question=question)\n```\n\n---\n\n## 模块导出清单\n\n`dspy/primitives/__init__.py` 负责导出以下核心组件：\n\n| 导出名称 | 来源模块 | 用途 |\n|----------|----------|------|\n| `Example` | `example.py` | 数据样本管理 |\n| `Prediction` | `prediction.py` | 结果封装 |\n| `Module` | `module.py` | 程序基类 |\n| `PythonInterpreter` | `python_interpreter.py` | 代码执行 |\n| `CodeInterpreter` | `code_interpreter.py` | 交互式解释器 |\n\n资料来源：[dspy/primitives/__init__.py]()\n\n---\n\n## 相关文档\n\n- [签名系统（Signatures）](../signatures/signature.md) - 了解如何定义模块的输入输出规范\n- [预测模块（Predict）](../predict/predict.md) - 核心预测组件的使用方法\n- [评估系统（Evaluate）](../learn/evaluation/evaluation.md) - 使用 Example 和 Metrics 进行程序评估\n\n---\n\n<a id='page-optimizers'></a>\n\n## 优化器详解\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [评估与指标](#page-evaluation), [签名（Signatures）](#page-signatures)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/teleprompt/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/__init__.py)\n- [dspy/teleprompt/bootstrap.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap.py)\n- [dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n- [dspy/teleprompt/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n- [dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n- [dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n- [dspy/teleprompt/simba.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/simba.py)\n- [dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n- [dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n- [dspy/teleprompt/knn_fewshot.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/knn_fewshot.py)\n- [dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n- [dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n</details>\n\n# 优化器详解\n\n## 概述\n\nDSPy 的优化器（Optimizer，亦称 Teleprompter）是框架的核心组件，负责自动优化程序中的提示词（Prompt）和演示示例（Demos），以提升语言模型在特定任务上的表现。优化器通过编译（Compile）过程，将声明式的 DSPy 程序转换为经过优化的自改进流水线。\n\nDSPy 优化器的工作机制遵循\"Bootstrap\"范式：先用初始配置运行程序，收集失败的案例，再利用语言模型自动生成改进的提示词或演示示例，如此迭代优化直到达到满意的性能水平。 资料来源：[dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n\n## 架构设计\n\n### 优化器继承体系\n\n所有 DSPy 优化器均继承自 `dspy.teleprompt.Teleprompter` 基类。基类定义了 `compile()` 接口，各子类实现具体的优化策略。\n\n```mermaid\ngraph TD\n    A[Teleprompter 基类] --> B[BootstrapFewShot]\n    A --> C[BootstrapFewShotWithRandomSearch]\n    A --> D[BootstrapFinetune]\n    A --> E[MIPROv2]\n    A --> F[GEPA]\n    A --> G[BetterTogether]\n    A --> H[Ensemble]\n    A --> I[COPRO]\n    A --> J[KNNFewShot]\n    A --> K[SimBA]\n    A --> L[GRPO]\n    \n    G --> |组合多个优化器| M[元优化器]\n```\n\n### 核心编译流程\n\n```mermaid\ngraph LR\n    A[Program] --> B[初始化运行]\n    B --> C[收集轨迹]\n    C --> D{评估指标}\n    D --> |未达标| E[生成候选]\n    E --> F[评估候选]\n    F --> G[选择最优]\n    G --> D\n    D --> |达标| H[优化后程序]\n```\n\n## 内置优化器详解\n\n### 1. BootstrapFewShotWithRandomSearch\n\n这是 DSPy 中最基础的优化器，结合了 Bootstrap 演示生成和随机搜索策略。它会生成多个候选配置（不同的提示词和演示组合），然后在验证集上评估选择最优方案。 资料来源：[dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数，签名 `metric(example, pred, trace) -> bool` | 必填 |\n| `max_bootstrapped_demos` | int | 每个预测模块最多保留的演示数量 | 4 |\n| `max_rounds` | int | 最大优化轮次 | 1 |\n| `num_candidates` | int | 随机搜索的候选数量 | 10 |\n| `num_threads` | int | 并行线程数 | 1 |\n\n#### 使用示例\n\n```python\nimport dspy\n\n# 定义评估指标\ndef metric(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 创建优化器\noptimizer = BootstrapFewShotWithRandomSearch(\n    metric=metric,\n    max_bootstrapped_demos=4,\n    num_candidates=10\n)\n\n# 编译程序\ncompiled_program = optimizer.compile(\n    student=program,\n    trainset=trainset,\n    valset=valset\n)\n```\n\n### 2. BootstrapFinetune\n\nBootstrapFinetune 是 DSPy 的微调优化器，通过 Bootstrap 生成的优质数据对语言模型进行微调。它先生成高质量的演示示例，然后利用这些数据对轻量级语言模型进行微调。 资料来源：[dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `teacher_settings` | dict | 教师模型的设置 | None |\n| `finetune_settings` | dict | 微调设置（如训练轮数、学习率） | {} |\n| `max_bootstrapped_demos` | int | Bootstrap 演示数量上限 | 8 |\n\n### 3. MIPROv2 (Multi-Instruction Prompt Optimization v2)\n\nMIPROv2 是先进的提示优化器，采用贝叶斯优化策略同时优化指令和演示。它通过考虑指令与演示之间的交互作用，实现更高效的提示词优化。 资料来源：[dspy/teleprompt/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `num_trials` | int | 贝叶斯优化试验次数 | 20 |\n| `max_bootstrapped_demos` | int | 演示数量上限 | 4 |\n| `num_examples` | int | 每轮使用的训练样本数 | 200 |\n| `auto` | str | 自动模式级别：\"light\"、\"medium\"、\"heavy\" | None |\n| `bootstrap_dataset_size` | int | Bootstrap 数据集大小 | None |\n\n#### 优化策略\n\nMIPROv2 的核心创新在于将指令优化与演示选择联合考虑：\n\n```mermaid\ngraph TD\n    A[贝叶斯优化器] --> B[指令提议器]\n    A --> C[演示采样器]\n    B --> D[候选指令集合]\n    C --> E[候选演示集合]\n    D --> F[笛卡尔积组合]\n    E --> F\n    F --> G[评估函数]\n    G --> H[更新贝叶斯模型]\n    H --> A\n```\n\n### 4. GEPA (Generalized Evolved Prompt Agent)\n\nGEPA 是基于进化算法的提示优化器，通过反思性提示进化策略实现自动优化。它在多阶段语言模型程序的优化中表现出色。 资料来源：[dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `auto` | str | 自动模式：\"light\"、\"medium\"、\"full\" | None |\n| `num_prompt_instructions` | int | 基础指令数量 | 10 |\n| `max_bootstrap两会` | int | Bootstrap 演示上限 | 4 |\n\n### 5. BetterTogether (元优化器)\n\nBetterTogether 是 DSPy 的元优化器框架，可以将多个优化器组合成流水线。它支持自定义优化器组合策略，实现复杂的优化流程。 资料来源：[dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n\n#### 设计理念\n\nBetterTogether 将优化过程分解为两个阶段：\n\n1. **提示优化阶段 (Prompt Optimization, p)**：优化指令和提示词\n2. **权重优化阶段 (Weight Optimization, w)**：通过 Bootstrap Finetune 优化权重\n\n#### 使用示例\n\n```python\nfrom dspy.teleprompt import BetterTogether, MIPROv2, BootstrapFinetune\n\n# 方式一：使用自定义优化器组合\noptimizer = BetterTogether(\n    metric=metric,\n    p=MIPROv2(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric)\n)\n\n# 方式二：使用默认优化器\noptimizer = BetterTogether(metric=metric)\n\n# 编译并指定策略\ncompiled = optimizer.compile(\n    student=program,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\"  # 提示优化后接权重优化\n)\n```\n\n#### 策略配置\n\n| 策略字符串 | 说明 |\n|-----------|------|\n| `\"p\"` | 仅执行提示优化 |\n| `\"w\"` | 仅执行权重优化 |\n| `\"p -> w\"` | 先提示优化后权重优化 |\n| `\"w -> p\"` | 先权重优化后提示优化 |\n| `\"p -> w -> p\"` | 交替优化 |\n\n### 6. COPRO (Coordinate Prompt Optimization)\n\nCOPRO 是一种协同提示优化方法，通过分析程序结构来优化各个模块的提示词。 资料来源：[dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n\n### 7. SimBA (Simple Bootstrap Agent)\n\nSimBA 是轻量级的 Bootstrap 优化器，适用于资源受限场景。它简化了优化流程，同时保持较好的优化效果。 资料来源：[dspy/teleprompt/simba.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/simba.py)\n\n### 8. KNNFewShot (K-Nearest Neighbors Few-Shot)\n\nKNNFewShot 利用 K 近邻算法为每个测试样本选择最相关的演示示例，实现动态演示选择。 资料来源：[dspy/teleprompt/knn_fewshot.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/knn_fewshot.py)\n\n### 9. Ensemble\n\nEnsemble 优化器通过集成多个不同配置的预测模块来提升整体性能，适用于需要高稳定性的生产环境。 资料来源：[dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n\n### 10. GRPO (Group Relative Policy Optimization)\n\nGRPO 是一种基于强化学习的优化方法，通过组内相对策略优化来提升语言模型程序性能。 资料来源：[dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n\n## 优化器选择指南\n\n```mermaid\ngraph TD\n    A[开始选择] --> B{场景类型}\n    B -->|快速原型开发| C[BootstrapFewShotWithRandomSearch]\n    B -->|高质量演示| D[BootstrapFinetune]\n    B -->|联合优化| E[MIPROv2]\n    B -->|进化策略| F[GEPA]\n    B -->|复杂流水线| G[BetterTogether]\n    B -->|动态演示| H[KNNFewShot]\n    B -->|集成预测| I[Ensemble]\n    \n    C --> J[性能基准]\n    D --> J\n    E --> J\n    F --> J\n    G --> J\n    H --> J\n    I --> J\n```\n\n### 场景推荐\n\n| 场景 | 推荐优化器 | 理由 |\n|------|-----------|------|\n| 快速实验 | BootstrapFewShotWithRandomSearch | 配置简单、速度快 |\n| 资源充足追求最优 | MIPROv2 | 贝叶斯优化效果好 |\n| 多阶段流水线 | GEPA / BetterTogether | 支持复杂优化策略 |\n| 边缘部署 | SimBA | 轻量级实现 |\n| 高稳定性需求 | Ensemble | 多模型集成 |\n\n## Teleprompter 基类接口\n\n所有优化器都实现以下核心接口：\n\n```python\nclass Teleprompter:\n    def compile(\n        self,\n        student: Module,\n        *,\n        trainset: list[Example],\n        valset: list[Example] = None,\n        **kwargs\n    ) -> Module:\n        \"\"\"编译学生程序\"\"\"\n        raise NotImplementedError\n```\n\n### compile 方法参数\n\n| 参数 | 类型 | 必填 | 说明 |\n|------|------|------|------|\n| `student` | Module | 是 | 待优化的 DSPy 程序 |\n| `trainset` | list[Example] | 是 | 训练数据集 |\n| `valset` | list[Example] | 否 | 验证数据集，部分优化器需要 |\n| `max_bootstrapped_demos` | int | 否 | Bootstrap 演示上限 |\n| `max_rounds` | int | 否 | 最大优化轮次 |\n| `num_threads` | int | 否 | 并行线程数 |\n\n## 评估指标设计\n\n优化器依赖高质量的评估指标函数。指标函数应满足以下签名：\n\n```python\ndef metric(example: Example, pred: Prediction, trace=None) -> bool | float:\n    \"\"\"\n    参数:\n        example: 测试样本\n        pred: 模型预测结果\n        trace: 轨迹信息（可选，用于 Bootstrap 过程\n    返回:\n        bool 或 float: 评估结果\n    \"\"\"\n```\n\n### 指标函数示例\n\n```python\n# 精确匹配指标\ndef exact_match(example, pred, trace=None):\n    return example.answer.lower().strip() == pred.answer.lower().strip()\n\n# 带权重的复合指标\ndef weighted_metric(example, pred, trace=None):\n    exact = example.answer.lower() == pred.answer.lower()\n    confidence = pred.get(\"confidence\", 1.0)\n    return exact * confidence\n\n# 使用 trace 信息（用于 Bootstrap）\ndef bootstrap_metric(example, pred, trace):\n    if trace is None:\n        return example.answer.lower() == pred.answer.lower()\n    # Bootstrap 过程中可使用更多上下文信息\n    return int(trace.get(\"cost\", 1)) < 10\n```\n\n## 最佳实践\n\n### 1. 数据集划分\n\n```python\n# 正确划分数据集\ntrainset = [example.with_inputs(\"question\") for example in train_examples]\nvalset = [example.with_inputs(\"question\") for example in val_examples]\n\n# 确保 valset 有足够的样本用于可靠评估\nassert len(valset) >= 20, \"验证集应至少包含 20 个样本\"\n```\n\n### 2. 指标设计原则\n\n- **可量化**：指标应能客观衡量输出质量\n- **稳定可靠**：多次运行应产生一致结果\n- **与任务目标一致**：指标应反映实际业务需求\n\n### 3. 优化器配置建议\n\n| 配置项 | 建议值 | 说明 |\n|--------|--------|------|\n| `max_bootstrapped_demos` | 4-8 | 过多演示可能增加上下文负担 |\n| `num_trials` (MIPROv2) | 20-50 | 试验次数越多效果越好但耗时增加 |\n| `num_candidates` | 10-20 | 候选数量影响搜索空间大小 |\n\n### 4. 性能调优\n\n```python\n# 使用并行化加速\noptimizer = BootstrapFewShotWithRandomSearch(\n    metric=metric,\n    num_threads=8  # 利用多核 CPU\n)\n\n# 控制资源使用\noptimizer = MIPROv2(\n    metric=metric,\n    num_trials=20,  # 限制试验次数\n    num_examples=100  # 限制样本数\n)\n```\n\n## 常见问题\n\n### Q1: 优化器编译失败怎么办？\n\n检查以下几点：\n1. 确认 `metric` 函数签名正确且可调用\n2. 确保 `trainset` 和 `valset` 非空且格式正确\n3. 验证 `Example` 对象已通过 `with_inputs()` 设置输入字段\n\n### Q2: 如何选择合适的优化器？\n\n参考\"优化器选择指南\"章节，从场景复杂度、可用资源和性能要求三个维度考量。\n\n### Q3: 优化后的性能不理想怎么办？\n\n- 尝试更换优化器类型\n- 调整优化器参数（如增加试验次数）\n- 改进评估指标函数\n- 检查数据集质量和规模\n\n### Q4: 如何调试优化过程？\n\n```python\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n# 启用详细输出\noptimizer = MIPROv2(metric=metric, verbose=True)\n```\n\n## 参考链接\n\n- [DSPy 官方文档](https://dspy.ai)\n- [DSPy 论文: Compiling Declarative Language Model Calls](https://arxiv.org/abs/2310.03714)\n- [MIPRO 论文: Optimizing Instructions and Demonstrations](https://arxiv.org/abs/2406.11695)\n- [GEPA 论文: Reflective Prompt Evolution](https://arxiv.org/abs/2507.19457)\n\n---\n\n<a id='page-lm-clients'></a>\n\n## 语言模型客户端\n\n### 相关页面\n\n相关主题：[DSPy概述](#page-overview), [适配器系统](#page-adapters)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/clients/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/__init__.py)\n- [dspy/clients/lm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/lm.py)\n- [dspy/clients/base_lm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/base_lm.py)\n- [dspy/clients/openai.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/openai.py)\n- [dspy/clients/_litellm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/_litellm.py)\n- [dspy/clients/databricks.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/databricks.py)\n- [dspy/clients/lm_local.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/lm_local.py)\n- [dspy/clients/embedding.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/embedding.py)\n- [dspy/clients/cache.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/cache.py)\n- [dspy/clients/provider.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/provider.py)\n</details>\n\n# 语言模型客户端\n\n## 概述\n\nDSPy 的语言模型客户端是框架与各种大语言模型（LLM）交互的核心抽象层。它提供了统一的接口，使开发者能够通过简洁的 API 调用不同的语言模型提供商，同时支持缓存、回调、批处理等高级功能。\n\n语言模型客户端在 DSPy 架构中扮演着至关重要的角色：它被 `dspy.Module` 中的预测器（如 `dspy.Predict`、`dspy.ChainOfThought` 等）调用，为整个程序提供推理能力。\n\n## 架构设计\n\n### 模块层次结构\n\nDSPy 的语言模型客户端采用分层架构设计：\n\n```mermaid\ngraph TD\n    A[dspy.LM 统一入口] --> B[BaseLM 抽象基类]\n    B --> C[OpenAI 客户端]\n    B --> D[LiteLLM 客户端]\n    B --> E[Databricks 客户端]\n    B --> F[Local LM 客户端]\n    G[Embedding 嵌入客户端] --> H[Embedder 类]\n    G --> I[缓存层 Cache]\n```\n\n### 核心组件\n\n| 组件 | 文件路径 | 职责 |\n|------|----------|------|\n| `dspy.LM` | `dspy/clients/lm.py` | 统一入口，支持多种模型提供商 |\n| `BaseLM` | `dspy/clients/base_lm.py` | 抽象基类，定义接口规范 |\n| `OpenAI` | `dspy/clients/openai.py` | OpenAI API 专用客户端 |\n| `_LiteLLM` | `dspy/clients/_litellm.py` | LiteLLM 封装，支持 100+ 模型 |\n| `Databricks` | `dspy/clients/databricks.py` | Databricks 模型服务 |\n| `LocalLM` | `dspy/clients/lm_local.py` | 本地部署模型 |\n| `Embedder` | `dspy/clients/embedding.py` | 文本嵌入模型客户端 |\n| `Cache` | `dspy/clients/cache.py` | 请求缓存管理 |\n| `Provider` | `dspy/clients/provider.py` | 模型提供商配置 |\n\n## 使用方式\n\n### 基本初始化\n\n```python\nimport dspy\n\n# 使用 OpenAI 模型\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# 使用本地模型\nlm = dspy.LM(\"ollama/llama3\")\n\n# 配置回调函数\nfrom dspy.utils.callback import LoggingCallback\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n### 在模块中使用\n\n语言模型客户端通过 `dspy.Module` 的 `set_lm()` 方法与预测器关联：\n\n```python\nimport dspy\n\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n\n# 创建程序并设置语言模型\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = MyProgram()\nprogram.set_lm(lm)\n```\n\n获取模块当前使用的语言模型：\n\n```python\ncurrent_lm = program.get_lm()\n```\n\n## Embedder 嵌入客户端\n\n`Embedder` 类是 DSPy 中用于处理文本嵌入的专用客户端，支持自定义嵌入函数和多种模型。\n\n### 核心参数\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `model` | `str \\| Callable` | - | 模型名称或自定义嵌入函数 |\n| `batch_size` | `int` | `200` | 批处理大小 |\n| `caching` | `bool` | `True` | 是否启用缓存 |\n| `**kwargs` | `dict` | - | 传递给模型的额外参数 |\n\n### 使用示例\n\n```python\nimport dspy\nimport numpy as np\n\n# 示例 1：使用预定义模型\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\")\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\nassert embeddings.shape == (2, 1536)\n\n# 示例 2：使用自定义函数\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\nassert embeddings.shape == (2, 10)\n```\n\n### 内部处理流程\n\n`Embedder` 的 `_preprocess()` 方法负责输入预处理：\n\n```python\ndef _preprocess(self, inputs, batch_size=None, caching=None, **kwargs):\n    # 1. 处理单个字符串输入\n    if isinstance(inputs, str):\n        is_single_input = True\n        inputs = [inputs]\n    else:\n        is_single_input = False\n    \n    # 2. 验证所有输入为字符串\n    if not all(isinstance(inp, str) for inp in inputs):\n        raise ValueError(\"All inputs must be strings.\")\n    \n    # 3. 合并默认参数与自定义参数\n    batch_size = batch_size or self.batch_size\n    caching = caching if caching is not None else self.caching\n    merged_kwargs = self.default_kwargs.copy()\n    merged_kwargs.update(kwargs)\n    \n    # 4. 分批处理\n    input_batches = []\n    for i in range(0, len(inputs), batch_size):\n        input_batches.append(inputs[i : i + batch_size])\n    \n    return input_batches, caching, merged_kwargs, is_single_input\n```\n\n## 回调机制\n\nDSPy 提供回调系统用于监控和调试语言模型调用。回调通过 `BaseCallback` 抽象类定义：\n\n```python\nfrom dspy.utils.callback import BaseCallback\n\nclass LoggingCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"LM is called with inputs: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"LM is finished with outputs: {outputs}\")\n```\n\n回调使用方式：\n\n```python\n# 方式 1：全局配置\ndspy.configure(callbacks=[LoggingCallback()])\n\n# 方式 2：组件级别配置\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n## 缓存机制\n\nDSPy 的缓存层位于 `dspy/clients/cache.py`，用于存储和检索已计算的模型响应，避免重复 API 调用。\n\n缓存的主要特性：\n\n- 基于请求参数的内容寻址\n- 支持配置 TTL（生存时间）\n- 可与各种模型客户端无缝集成\n\n## 模型提供商\n\n### 支持的提供商类型\n\n| 提供商 | 客户端类 | 说明 |\n|--------|----------|------|\n| OpenAI | `OpenAI` | OpenAI API 原生支持 |\n| Azure | 通过 `OpenAI` | Azure OpenAI Service |\n| Anthropic | 通过 `_LiteLLM` | Claude 系列模型 |\n| Google | 通过 `_LiteLLM` | Gemini 系列 |\n| Meta | 通过 `_LiteLLM` | Llama 系列 |\n| Databricks | `Databricks` | Databricks 模型服务 |\n| Ollama | `LocalLM` | 本地部署模型 |\n| LM Studio | `LocalLM` | 本地部署模型 |\n\n### 模型标识符格式\n\n```python\n# OpenAI 格式\ndspy.LM(\"openai/gpt-4o\")\ndspy.LM(\"openai/gpt-4o-mini\")\n\n# 自定义格式\ndspy.LM(\"ollama/llama3\")\ndspy.LM(\"local/my-model\")\n```\n\n## 最佳实践\n\n### 1. 全局配置 vs 组件配置\n\n```python\n# 全局配置：所有组件共享同一语言模型\ndspy.configure(lm=dspy.LM(\"gpt-4o\"))\n\n# 组件配置：特定组件使用特定模型\nlm_special = dspy.LM(\"gpt-4o\")\nprogram.set_lm(lm_special)\n```\n\n### 2. 回调用于调试\n\n```python\nclass DebugCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        logger.debug(f\"Calling LM with: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        logger.debug(f\"LM returned: {outputs}\")\n\nlm = dspy.LM(\"gpt-4o\", callbacks=[DebugCallback()])\n```\n\n### 3. 嵌入模型批处理优化\n\n```python\n# 大批量处理时使用较大 batch_size\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\", batch_size=100)\n```\n\n## 相关文档\n\n- [DSPy 文档首页](https://dspy.ai)\n- [预测器 (Predict)](./predict.md)\n- [模块系统](./module.md)\n- [示例系统](./example.md)\n- [评估系统](./evaluation.md)\n\n## 源码索引\n\n| 文件 | 功能描述 |\n|------|----------|\n| `dspy/clients/__init__.py` | 客户端模块入口，导出 `LM`、`Embedder` 等 |\n| `dspy/clients/lm.py` | `LM` 类实现，支持多种提供商 |\n| `dspy/clients/base_lm.py` | `BaseLM` 抽象基类 |\n| `dspy/clients/openai.py` | OpenAI 专用客户端 |\n| `dspy/clients/_litellm.py` | LiteLLM 封装 |\n| `dspy/clients/databricks.py` | Databricks 客户端 |\n| `dspy/clients/lm_local.py` | 本地模型客户端 |\n| `dspy/clients/embedding.py` | 嵌入模型客户端 `Embedder` |\n| `dspy/clients/cache.py` | 缓存实现 |\n| `dspy/clients/provider.py` | 提供商配置 |\n| `dspy/primitives/module.py` | 模块的 `set_lm`/`get_lm` 方法 |\n| `dspy/utils/callback.py` | 回调系统实现 |\n\n---\n\n<a id='page-adapters'></a>\n\n## 适配器系统\n\n### 相关页面\n\n相关主题：[语言模型客户端](#page-lm-clients), [内置模块参考](#page-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/adapters/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/__init__.py)\n- [dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n- [dspy/adapters/chat_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/chat_adapter.py)\n- [dspy/adapters/json_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/json_adapter.py)\n- [dspy/adapters/xml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/xml_adapter.py)\n- [dspy/adapters/two_step_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/two_step_adapter.py)\n- [dspy/adapters/baml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/baml_adapter.py)\n- [dspy/adapters/types/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/__init__.py)\n</details>\n\n# 适配器系统\n\n## 概述\n\nDSPy 的适配器系统（Adapter System）是框架中负责将程序签名（Signature）转换为语言模型可处理的格式化消息的核心组件。适配器充当 DSPy 程序与底层语言模型 API 之间的桥梁，负责处理输入输出的结构化转换、字段序列化以及响应解析等关键任务。\n\n适配器系统的主要职责包括：\n\n- **消息格式化**：将 DSPy 签名中的输入字段转换为语言模型 API 可接受的格式\n- **响应解析**：将语言模型的输出解析回 DSPy 的结构化数据结构\n- **自定义类型支持**：处理复杂数据类型（如图像、历史对话等）的序列化与反序列化\n- **多格式支持**：支持多种输出格式规范（如 JSON、XML、Chat 格式等）\n\n资料来源：[dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n\n## 系统架构\n\n### 核心组件层次\n\n```mermaid\ngraph TD\n    A[DSPy 程序] --> B[签名 Signature]\n    B --> C[适配器 Adapter]\n    C --> D{适配器类型}\n    D --> E[ChatAdapter]\n    D --> F[JSONAdapter]\n    D --> G[XMLAdapter]\n    D --> H[TwoStepAdapter]\n    D --> I[BAMLAdapter]\n    C --> J[语言模型 LM API]\n    J --> K[响应 Response]\n    K --> C\n    C --> L[Prediction]\n```\n\n### 适配器类型对比\n\n| 适配器类型 | 输出格式 | 解析方式 | 使用场景 |\n|-----------|---------|---------|---------|\n| ChatAdapter | Chat Messages | 结构化解析 | 通用对话场景 |\n| JSONAdapter | JSON | JSON 解析 | 结构化数据输出 |\n| XMLAdapter | XML | XML 解析 | XML 格式要求 |\n| TwoStepAdapter | 两阶段格式 | 两步解析 | 复杂推理任务 |\n| BAMLAdapter | BAML | BAML 解析器 | 类型安全生成 |\n\n资料来源：[dspy/adapters/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/__init__.py)\n\n## 基础适配器接口\n\n### BaseAdapter 抽象基类\n\n所有适配器都继承自 `BaseAdapter` 抽象基类，定义了适配器的核心接口规范：\n\n```python\nclass BaseAdapter(ABC):\n    \"\"\"适配器基类，定义所有适配器必须实现的接口\"\"\"\n    \n    @abstractmethod\n    def format(self, signature, demos, inputs):\n        \"\"\"将签名和输入格式化为模型消息\"\"\"\n        pass\n    \n    @abstractmethod\n    def parse(self, signature, response):\n        \"\"\"解析模型响应为预测结果\"\"\"\n        pass\n```\n\n### 适配器核心方法\n\n| 方法 | 参数 | 返回值 | 说明 |\n|-----|------|-------|-----|\n| format | signature, demos, inputs | list[dict] | 格式化输入消息 |\n| parse | signature, response | Prediction | 解析输出响应 |\n| format_field_value | value, field | str | 格式化单个字段值 |\n| post_save_hook | output, signature | None | 保存后钩子 |\n\n资料来源：[dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n\n## Chat 适配器\n\n`ChatAdapter` 是 DSPy 默认的适配器实现，专门用于处理对话格式的语言模型 API（如 OpenAI ChatGPT、Google Gemini 等）。\n\n### 消息格式转换\n\nChatAdapter 将 DSPy 的签名转换为标准的聊天消息格式：\n\n```mermaid\ngraph LR\n    A[Signature<br/>InputFields] --> B[ChatAdapter]\n    C[Demos<br/>Few-Shot] --> B\n    B --> D[System Message<br/>历史指令]\n    B --> E[User Messages<br/>输入+演示]\n    B --> F[Assistant Messages<br/>历史响应]\n```\n\n### 核心实现逻辑\n\n```python\ndef format(self, signature, demos, inputs):\n    # 构建系统消息（包含指令）\n    messages = [self._build_system_message(signature)]\n    \n    # 添加演示示例\n    for demo in demos:\n        messages.extend(self._format_demo(demo))\n    \n    # 添加当前输入\n    messages.append(self._build_user_message(inputs))\n    \n    return messages\n```\n\n资料来源：[dspy/adapters/chat_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/chat_adapter.py)\n\n## JSON 适配器\n\n`JSONAdapter` 专为需要结构化 JSON 输出的场景设计，适用于需要机器解析输出的应用。\n\n### 工作流程\n\n```mermaid\ngraph TD\n    A[输入字段] --> B[构建Prompt]\n    B --> C[添加JSON Schema说明]\n    C --> D[调用LM]\n    D --> E{响应格式}\n    E -->|有效JSON| F[json.loads解析]\n    E -->|无效JSON| G[尝试修复格式]\n    F --> H[Prediction]\n    G --> H\n```\n\n### 格式控制机制\n\nJSONAdapter 通过在提示词中嵌入 JSON Schema 来指导模型生成符合规范的输出：\n\n```python\njson_schema = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"field_name\": {\"type\": \"string\", \"description\": \"...\"}\n    },\n    \"required\": [\"field_name\"]\n}\n```\n\n资料来源：[dspy/adapters/json_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/json_adapter.py)\n\n## XML 适配器\n\n`XMLAdapter` 使用 XML 标签格式封装输出字段，适用于需要明确结构化层次的场景。\n\n### 标签规范\n\n| 组件 | 标签格式 | 说明 |\n|-----|---------|-----|\n| 输出块 | `<answer>` ... `</answer>` | 包含整个输出 |\n| 字段 | `<field_name>` 值 `</field_name>` | 单个输出字段 |\n| 嵌套 | 层级嵌套标签 | 复杂数据结构 |\n\n### 解析机制\n\nXMLAdapter 使用正则表达式匹配提取字段值：\n\n```python\npattern = rf\"<{field_name}>(.*?)</{field_name}>\"\nmatch = re.search(pattern, response)\n```\n\n资料来源：[dspy/adapters/xml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/xml_adapter.py)\n\n## TwoStep 适配器\n\n`TwoStepAdapter` 实现两阶段推理模式，适用于需要\"思考-回答\"分离的复杂任务。\n\n### 两阶段流程\n\n```mermaid\ngraph LR\n    A[问题] --> B[第一阶段<br/>推理/分析]\n    B --> C[中间推理结果]\n    C --> D[第二阶段<br/>生成答案]\n    D --> E[最终答案]\n```\n\n### 配置参数\n\n| 参数 | 类型 | 默认值 | 说明 |\n|-----|------|-------|-----|\n| reasoning_field | str | \"reasoning\" | 推理字段名 |\n| answer_field | str | \"answer\" | 答案字段名 |\n| reasoning_type | str | \"chain_of_thought\" | 推理类型 |\n\n资料来源：[dspy/adapters/two_step_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/two_step_adapter.py)\n\n## 自定义类型系统\n\n### 类型注册机制\n\nDSPy 适配器系统支持自定义复杂类型的处理，通过标识符分割内容：\n\n```mermaid\ngraph TD\n    A[消息内容] --> B{包含自定义类型?}\n    B -->|是| C[查找标识符]\n    C --> D[<<CUSTOM-TYPE-START-IDENTIFIER>>]\n    D --> E[提取JSON内容]\n    E --> F[解析自定义类型]\n    F --> G[重建消息结构]\n    B -->|否| H[纯文本处理]\n```\n\n### 类型标识符\n\n| 标识符 | 用途 |\n|-------|-----|\n| `<<CUSTOM-TYPE-START-IDENTIFIER>>` | 自定义类型内容开始 |\n| `<<CUSTOM-TYPE-END-IDENTIFIER>>` | 自定义类型内容结束 |\n\n资料来源：[dspy/adapters/types/base_type.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/base_type.py)\n\n### 内置自定义类型\n\n#### History 类型\n\n`History` 类型用于管理多轮对话历史：\n\n```python\nclass History(BaseModel):\n    \"\"\"对话历史类\"\"\"\n    messages: list[dict]  # 消息列表，每条消息包含历史对话内容\n```\n\n**使用示例：**\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField()\n    history: dspy.History = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nhistory = dspy.History(messages=[\n    {\"question\": \"法国的首都是什么？\", \"answer\": \"巴黎\"},\n    {\"question\": \"德国的首都是什么？\", \"answer\": \"柏林\"},\n])\n```\n\n资料来源：[dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n\n#### Image 类型\n\n`Image` 类型支持图像输入处理：\n\n```python\nclass Image(BaseModel):\n    \"\"\"图像类型，支持URL和本地文件\"\"\"\n    url: str  # base64数据URI或URL\n```\n\n**支持的数据格式：**\n\n| 格式 | 说明 | 适用场景 |\n|-----|------|---------|\n| http://... | 网络URL | 公开图像 |\n| https://... | 安全URL | 公开图像 |\n| data:image/...;base64,... | Base64编码 | 本地/内联图像 |\n| file://... | 本地文件路径 | 本地图像 |\n\n**图像处理方法：**\n\n| 方法 | 说明 |\n|-----|-----|\n| `encode_image()` | 编码图像为可传输格式 |\n| `format()` | 格式化为 API 消息格式 |\n| `from_url()` | 从URL创建（已废弃） |\n| `from_file()` | 从文件创建 |\n\n资料来源：[dspy/adapters/types/image.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/image.py)\n\n## 使用指南\n\n### 选择合适的适配器\n\n```mermaid\ngraph TD\n    A[开始] --> B{输出需求?}\n    B -->|通用对话| C[ChatAdapter]\n    B -->|结构化数据| D{数据复杂度?}\n    D -->|简单| E[JSONAdapter]\n    D -->|复杂| F[TwoStepAdapter]\n    B -->|XML格式要求| G[XMLAdapter]\n    B -->|类型安全| H[BAMLAdapter]\n```\n\n### 配置默认适配器\n\n```python\nimport dspy\n\n# 全局配置\ndspy.settings.configure(adapter=dspy.ChatAdapter())\n\n# 或在程序中指定\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        self.predict = dspy.Predict(\n            \"question -> answer\",\n            adapter=dspy.JSONAdapter()\n        )\n```\n\n### 自定义适配器\n\n```python\nfrom dspy.adapters import BaseAdapter\n\nclass MyCustomAdapter(BaseAdapter):\n    def format(self, signature, demos, inputs):\n        # 自定义格式化逻辑\n        return messages\n    \n    def parse(self, signature, response):\n        # 自定义解析逻辑\n        return dspy.Prediction(...)\n```\n\n## 最佳实践\n\n### 1. 适配器选择建议\n\n| 场景 | 推荐适配器 | 原因 |\n|-----|----------|-----|\n| 通用应用 | ChatAdapter | 灵活、通用 |\n| API 数据提取 | JSONAdapter | 结构化、机器可读 |\n| 文档生成 | XMLAdapter | 层次清晰 |\n| 推理任务 | TwoStepAdapter | 分离思考与答案 |\n| 生产系统 | BAMLAdapter | 类型安全 |\n\n### 2. 性能优化\n\n- **批处理**：使用 `batch_size` 参数控制批处理大小\n- **缓存**：启用缓存机制减少重复计算\n- **类型选择**：根据输出复杂度选择最合适的适配器\n\n### 3. 错误处理\n\n适配器应处理以下常见错误：\n\n| 错误类型 | 处理策略 |\n|---------|---------|\n| 解析失败 | 回退到备用解析器或提示重试 |\n| 格式不匹配 | 尝试自动修复或抛出明确错误 |\n| 超限 | 截断或分片处理 |\n\n## 总结\n\nDSPy 的适配器系统为框架提供了灵活的消息格式化和解析能力，通过统一的接口抽象支持多种输出格式规范。适配器的模块化设计使得开发者可以轻松扩展新的格式支持，同时内置的多种适配器覆盖了大多数常见使用场景。自定义类型系统的支持进一步增强了框架的表达能力，使得复杂的数据结构处理变得简单可控。\n\n---\n\n<a id='page-retrieval'></a>\n\n## 检索增强模块\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [评估与指标](#page-evaluation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/retrievers/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/__init__.py)\n- [dspy/retrievers/retrieve.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/retrieve.py)\n- [dspy/retrievers/embeddings.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/embeddings.py)\n- [dspy/retrievers/databricks_rm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/databricks_rm.py)\n- [dspy/retrievers/weaviate_rm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/weaviate_rm.py)\n- [dspy/dsp/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/__init__.py)\n- [dspy/dsp/colbertv2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/colbertv2.py)\n- [dspy/dsp/utils/dpr.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/utils/dpr.py)\n</details>\n\n# 检索增强模块\n\n## 概述\n\nDSPy的检索增强模块（Retrieval Augmentation Module）是框架中负责从外部知识源获取相关文档或段落的核心组件。该模块通过检索模型（Retriever Model）实现语义搜索功能，使语言模型能够在生成回答时利用外部知识库中的相关信息。\n\n检索增强模块的主要职责包括：\n\n- 与向量数据库或检索服务集成，实现语义相似度搜索\n- 提供统一的检索接口，支持多种后端实现\n- 将检索结果格式化为可被签名（Signature）处理的数据结构\n- 支持自定义嵌入模型和检索策略\n\n## 架构设计\n\n### 模块层级结构\n\nDSPy的检索增强系统采用分层架构设计，从底层到顶层依次为：\n\n| 层级 | 组件 | 职责 |\n|------|------|------|\n| 嵌入层 | `Embedder` | 将文本转换为向量表示 |\n| 检索层 | 各类RM实现 | 执行向量相似度搜索 |\n| 接口层 | `Retrieve` | 提供统一的模块化调用接口 |\n| 配置层 | `dspy.configure()` | 全局配置检索模型 |\n\n### 核心类关系\n\n```mermaid\ngraph TD\n    A[dspy.configure] --> B[RM Retriever Model]\n    B --> C[weaviate_rm.WeaviateRM]\n    B --> D[databricks_rm.DatabricksRM]\n    B --> E[colbertv2.ColBERTv2]\n    F[Retrieve模块] --> B\n    G[Embedder] --> H[嵌入服务]\n    B --> G\n```\n\n## Retrieve 模块\n\n`Retrieve`是DSPy中用于执行检索的核心模块，继承自`Module`基类。它作为检索系统的统一入口点，将用户的查询转换为检索请求并返回相关文档。\n\n### 基本用法\n\n```python\nimport dspy\n\n# 配置语言模型和检索模型\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\ndspy.configure(rm=WeaviateRM(\"my_collection\", weaviate_client=client))\n\n# 创建Retrieve模块\nretrieve = dspy.Retrieve(k=5)\nresults = retrieve(\"什么是机器学习\")\n```\n\n### API 参数说明\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| k | int | 3 | 返回的最相关文档数量 |\n| force_by_id | bool | False | 是否强制按ID检索 |\n\n### 工作流程\n\n```mermaid\nsequenceDiagram\n    用户 ->> Retrieve: 调用retrieve(query)\n    Retrieve ->> RM: query(query_str, k)\n    RM ->> 向量数据库: 相似度搜索\n    向量数据库 ->> RM: 返回Top-K文档\n    RM ->> Retrieve: 格式化检索结果\n    Retrieve ->> 用户: 返回Passages对象\n```\n\n## 检索模型（Retriever Model）\n\n检索模型是实际执行向量搜索的后端实现。DSPy支持多种检索后端，每种实现都遵循统一的接口规范。\n\n### Retriever 基类接口\n\n所有检索模型都需要实现以下核心方法：\n\n| 方法 | 返回类型 | 说明 |\n|------|----------|------|\n| `forward(query)` | list[str] | 根据查询返回相关文档列表 |\n| `query(query_str, k)` | list | 执行检索并返回k个结果 |\n| `__call__(*args, **kwargs)` | list[str] | 模块调用接口 |\n\n### WeaviateRM 实现\n\n`WeaviateRM`是与Weaviate向量数据库集成的检索模型实现。\n\n**构造函数参数：**\n\n| 参数 | 类型 | 必填 | 说明 |\n|------|------|------|------|\n| weaviate_collection_name | str | 是 | Weaviate集合名称 |\n| weaviate_client | WeaviateClient | 是 | Weaviate客户端实例 |\n| weaviate_collection_text_key | str | 否 | 集合中存储文本的字段名，默认\"content\" |\n| k | int | 否 | 检索结果数量，默认3 |\n| tenant_id | str | 否 | 多租户支持 |\n\n**配置示例：**\n\n```python\nimport dspy\nimport weaviate\n\nllm = dspy.Cohere(model=\"command-r-plus\", api_key=api_key)\nweaviate_client = weaviate.connect_to_local(\"your-path-here\")\nretriever_model = WeaviateRM(\"my_collection_name\", weaviate_client=weaviate_client)\ndspy.configure(lm=llm, rm=retriever_model)\n\nretrieve = dspy.Retrieve(k=1)\ntopK_passages = retrieve(\"what are the stages in planning\").passages\n```\n\n**内部机制：**\n\n该实现通过`weaviate_client.collections.get()`获取集合对象，然后使用集合的查询接口执行向量相似度搜索。文本内容通过`weaviate_collection_text_key`字段提取。\n\n### DatabricksRM 实现\n\n`DatabricksRM`是专门为Databricks平台设计的检索模型，利用Databricks向量搜索服务进行语义检索。\n\n### ColBERTv2 实现\n\n`ColBERTv2`是基于ColBERT算法的延迟交互式检索实现，适用于需要细粒度语义匹配的场景。\n\n```python\nfrom dspy.dsp.colbertv2 import ColBERTv2\n\nretriever = ColBERTv2()\nresults = retriever(\"query text\", k=5)\n```\n\n### DPR 实现\n\nDSPy还提供了基于Dense Passage Retrieval（DPR）的工具函数，位于`dspy/dsp/utils/dpr.py`中，用于处理双塔模型的检索逻辑。\n\n## 嵌入模块\n\n### Embedder 类\n\n`Embedder`是封装嵌入模型的统一接口，支持自定义嵌入函数和批量处理。\n\n**构造函数参数：**\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| model | str \\| Callable | 必填 | 嵌入模型名称或自定义函数 |\n| batch_size | int | 200 | 批处理大小 |\n| caching | bool | True | 是否启用结果缓存 |\n| kwargs | dict | {} | 传递给嵌入服务的额外参数 |\n\n**使用示例：**\n\n```python\nimport dspy\nimport numpy as np\n\n# 使用自定义嵌入函数\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\n### 预处理与后处理\n\nEmbedder类包含两个关键内部方法：\n\n- `_preprocess()`：处理输入数据，支持单个字符串或字符串列表，自动进行批量分割\n- `_postprocess()`：处理嵌入结果，支持返回原始格式或批量格式\n\n## 数据结构\n\n### Passages 数据结构\n\n检索结果以`Passages`对象形式返回，包含以下属性：\n\n| 属性 | 类型 | 说明 |\n|------|------|------|\n| passages | list[str] | 检索到的文档段落列表 |\n\n```python\nresult = retrieve(\"查询内容\")\nprint(result.passages)  # ['文档1内容', '文档2内容', ...]\n```\n\n### 示例数据结构\n\n`Example`类用于组织训练数据和评估数据，支持与检索系统配合使用：\n\n```python\nexample = dspy.Example(\n    question=\"什么是检索增强生成?\",\n    answer=\"检索增强生成是一种结合检索系统和语言模型的技术。\"\n).with_inputs(\"question\")\n\n# 检索相关文档\ncontext = example.inputs().toDict()\n```\n\n## 配置管理\n\n### 全局配置\n\n通过`dspy.configure()`进行全局配置：\n\n```python\nimport dspy\n\ndspy.configure(\n    lm=dspy.LM(\"openai/gpt-4o-mini\"),  # 语言模型\n    rm=WeaviateRM(...)                   # 检索模型\n)\n```\n\n### 模块级配置\n\n也可以在模块级别设置语言模型：\n\n```python\nclass MyRAG(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.qa = dspy.Predict(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.qa(context=context, question=question)\n```\n\n## 最佳实践\n\n### 检索参数调优\n\n| 场景 | 建议配置 |\n|------|----------|\n| 快速原型开发 | k=3, 使用轻量级嵌入模型 |\n| 生产环境 | k=5-10, 启用缓存, 使用高精度嵌入 |\n| 长文档检索 | 设置合适的chunk_size, 使用rerank |\n\n### 性能优化建议\n\n1. **启用缓存**：对于重复查询较多的场景，设置`caching=True`\n2. **批量处理**：合理设置`batch_size`参数，平衡内存和吞吐量\n3. **连接池复用**：在生产环境中复用向量数据库连接\n\n## 相关模块\n\n| 模块 | 文件路径 | 用途 |\n|------|----------|------|\n| Module基类 | `dspy/primitives/module.py` | 所有DSPy模块的基类，包含`set_lm()`和`get_lm()`方法 |\n| Predict | `dspy/predict/predict.py` | 预测模块，可与Retrieve组合使用 |\n| Example | `dspy/primitives/example.py` | 数据示例类，用于组织训练和评估数据 |\n| History | `dspy/adapters/types/history.py` | 对话历史类型，支持多轮检索场景 |\n\n## 扩展开发\n\n### 自定义检索模型\n\n要实现自定义检索模型，需要继承相关基类并实现核心接口：\n\n```python\nclass MyRetriever(dspy.Module):\n    def __init__(self, collection_name, k=3):\n        self.collection_name = collection_name\n        self.k = k\n    \n    def forward(self, query):\n        # 实现检索逻辑\n        results = self._search_vector_db(query, self.k)\n        return results\n    \n    def _search_vector_db(self, query, k):\n        # 向量搜索实现\n        pass\n```\n\n### 集成新向量数据库\n\n在`dspy/retrievers/`目录下创建新的RM实现文件，参考`weaviate_rm.py`的结构，确保实现统一的`__call__`接口和检索参数规范。\n\n---\n\n<a id='page-evaluation'></a>\n\n## 评估与指标\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [优化器详解](#page-optimizers), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/evaluate/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/__init__.py)\n- [dspy/evaluate/evaluate.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/evaluate.py)\n- [dspy/evaluate/metrics.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/metrics.py)\n- [dspy/evaluate/auto_evaluation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/auto_evaluation.py)\n- [dspy/datasets/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/__init__.py)\n- [dspy/datasets/dataloader.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/dataloader.py)\n- [dspy/datasets/dataset.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/dataset.py)\n</details>\n\n# 评估与指标\n\n## 概述\n\nDSPy 框架的评估与指标系统是验证和优化语言模型程序的核心组件。该系统提供了标准化的评估接口、灵活的指标定义机制，以及与 DSPy 优化器（Teleprompter）深度集成的评估流程。评估系统的设计遵循模块化原则，允许开发者自定义评估逻辑，同时保持与框架其他部分的一致性。\n\n在 DSPy 中，评估主要通过 `dspy.Evaluate` 类驱动，而指标（Metrics）则是用于衡量预测质量的回调函数。两者结合构成了完整的程序性能评估体系，支持从简单的精确匹配到复杂的语义相似度等多种评估场景。\n\n## 核心架构\n\n### 评估系统组件关系\n\n```mermaid\ngraph TD\n    A[用户程序 dspy.Module] --> B[dspy.Evaluate 评估器]\n    B --> C[评估指标 Metric 函数]\n    C --> D[Example 测试集]\n    B --> E[Prediction 预测结果]\n    E --> C\n    C --> F[评估分数 Score]\n    B --> G[Teleprompter 优化器]\n    G --> H[BootstrapFewShot / MIPROv2 等]\n```\n\n### 关键类结构\n\n| 类名 | 文件位置 | 职责 |\n|------|----------|------|\n| `Evaluate` | `dspy/evaluate/evaluate.py` | 评估引擎，协调评估流程 |\n| `Metric` | `dspy/evaluate/metrics.py` | 指标基类与预置指标 |\n| `AutoEvaluation` | `dspy/evaluate/auto_evaluation.py` | 自动评估支持 |\n| `Example` | `dspy/primitives/example.py` | 测试样本数据结构 |\n| `Prediction` | `dspy/primitives/prediction.py` | 预测结果数据结构 |\n\n## Example 数据结构\n\n`Example` 是 DSPy 中用于表示测试样本的基础数据结构，它将输入字段和标签字段分离，为评估提供标准化的数据格式。 资料来源：[dspy/primitives/example.py:1-50]()\n\n### 创建与使用 Example\n\n```python\nimport dspy\n\n# 创建带标签的示例\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# 提取输入字段\ninputs = example.inputs()\n# Example({'question': 'What is the capital of France?'}) (input_keys={'question'})\n\n# 提取标签字段\nlabels = example.labels()\n# Example({'answer': 'Paris'}) (input_keys={'question'})\n```\n\n### Example 核心方法\n\n| 方法 | 说明 | 返回值 |\n|------|------|--------|\n| `with_inputs(*keys)` | 标记输入字段 | 新的 Example 实例 |\n| `inputs()` | 获取输入部分 | 仅包含输入字段的 Example |\n| `labels()` | 获取标签部分 | 仅包含标签字段的 Example |\n| `toDict()` | 转换为字典 | 递归可序列化的字典 |\n| `copy(**kwargs)` | 复制并覆盖字段 | 新的 Example 实例 |\n| `without(*keys)` | 移除指定字段 | 新的 Example 实例 |\n\n`toDict()` 方法支持递归序列化嵌套的 `Example` 对象、Pydantic 模型、列表和字典，确保评估结果可以JSON化输出。 资料来源：[dspy/primitives/example.py:80-120]()\n\n## 评估器（Evaluate）\n\n### Evaluate 类概述\n\n`dspy.Evaluate` 是评估系统的核心类，负责执行整个评估流程。它接受待评估的程序、测试集和指标函数，并返回聚合的评估分数。\n\n### 基本用法\n\n```python\nimport dspy\n\n# 定义评估指标\ndef exact_match_metric(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 准备测试集\ntestset = [\n    dspy.Example(question=\"What is 1+1?\", answer=\"2\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\"),\n]\n\n# 创建评估器\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=exact_match_metric,\n    num_threads=1,\n)\n\n# 执行评估\nscore = evaluate(your_program)\n```\n\n### Evaluate 参数配置\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `dev` | list[Example] | 必需 | 开发/测试集 |\n| `metric` | Callable | 必需 | 评估指标函数 |\n| `num_threads` | int | 1 | 并行评估线程数 |\n| `max_errors` | int | -1 | 最大允许错误数 |\n| `return_outputs` | bool | False | 是否返回详细输出 |\n| `display` | bool | True | 是否显示进度 |\n\n### 评估流程\n\n```mermaid\nsequenceDiagram\n    participant User as 用户\n    participant Eval as Evaluate\n    participant Module as dspy.Module\n    participant Metric as Metric函数\n    participant Example as Example数据\n    \n    User->>Eval: evaluate(program)\n    Loop 遍历测试集\n        Eval->>Module: forward(example.inputs())\n        Module-->>Eval: Prediction\n        Eval->>Metric: metric(example, pred, trace)\n        Metric-->>Eval: score (bool/float)\n    End\n    Eval->>Eval: 聚合分数\n    Eval-->>User: 平均分数\n```\n\n## 指标函数（Metrics）\n\n### 指标函数签名\n\n指标函数是评估的核心，它们接受三个参数并返回布尔值或浮点数：\n\n```python\ndef metric(\n    example: Example,  # 测试样本，包含输入和标签\n    pred: Prediction,  # 模型预测结果\n    trace: Trace | None  # 可选的执行轨迹（用于优化器）\n) -> bool | float\n```\n\n### 预置指标\n\nDSPy 在 `dspy.evaluate.metrics` 模块中提供了一些常用的预置指标。开发者也可以根据需求自定义指标函数。 资料来源：[dspy/evaluate/metrics.py:1-50]()\n\n### 自定义指标示例\n\n#### 精确匹配指标\n\n```python\ndef exact_match_metric(example, pred, trace=None):\n    \"\"\"检查预测答案是否与标签完全匹配（忽略大小写）\"\"\"\n    return example.answer.lower() == pred.answer.lower()\n\n# 使用示例\ngold = dspy.Example(question=\"What is 1+1?\", answer=\"2\").with_inputs(\"question\")\npred = dspy.Prediction(answer=\"2\")\nexact_match_metric(gold, pred)  # True\n```\n\n#### 包含检查指标\n\n```python\ndef answer_contains_metric(example, pred, trace=None):\n    \"\"\"检查标签是否被预测答案包含\"\"\"\n    return example.answer.lower() in pred.answer.lower()\n```\n\n#### 带权重的复合指标\n\n```python\ndef composite_metric(example, pred, trace=None):\n    \"\"\"组合多个子指标\"\"\"\n    exact_match = example.answer.lower() == pred.answer.lower()\n    length_penalty = len(pred.answer) > 0\n    return float(exact_match) * 0.8 + float(length_penalty) * 0.2\n```\n\n## 自动评估（Auto Evaluation）\n\nDSPy 提供了自动评估功能，支持在没有人工标注标签的情况下进行程序评估。这对于迭代优化过程中的快速反馈特别有用。 资料来源：[dspy/evaluate/auto_evaluation.py:1-30]()\n\n### 自动评估工作流\n\n```mermaid\ngraph LR\n    A[程序输出] --> B[Auto Evaluator]\n    B --> C{是否有参考标签}\n    C -->|是| D[使用参考指标]\n    C -->|否| E[使用LLM评判]\n    D --> F[评估分数]\n    E --> F\n```\n\n### LLM 作为评估器\n\n当没有预定义标签时，可以使用大语言模型本身来评估输出质量：\n\n```python\nimport dspy\n\n# 使用LLM进行自动评估\ndef llm_judge_metric(example, pred, trace=None):\n    lm = dspy.LM(\"openai/gpt-4\")\n    prompt = f\"\"\"评估以下回答的质量：\n    \n    问题: {example.question}\n    回答: {pred.answer}\n    \n    回答是否准确、完整且相关？只需回答 '是' 或 '否'。\"\"\"\n    \n    response = lm(prompt)\n    return \"是\" in response.lower()\n\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=llm_judge_metric,\n)\n```\n\n## 数据集（datasets）\n\nDSPy 的数据集模块提供了加载和管理评估数据的功能。`Dataset` 类是数据管理的基础抽象，支持多种数据格式和加载方式。 资料来源：[dspy/datasets/__init__.py:1-30]()\n\n### 加载内置数据集\n\n```python\nimport dspy\nfrom dspy.datasets import GSM8K, HotPotQA\n\n# 加载 GSM8K 数学数据集\ngsm8k = GSM8K()\ntrainset = gsm8k.train\ndevset = gsm8k.dev\n\n# 加载 HotPotQA 问答数据集\nhotpot = HotPotQA()\ntestset = hotpot.dev\n```\n\n### DataLoader API\n\n`DataLoader` 提供了标准化的数据加载接口，支持训练集、验证集和测试集的划分： 资料来源：[dspy/datasets/dataloader.py:1-50]()\n\n| 方法 | 说明 |\n|------|------|\n| `from Hub` | 从模型Hub加载数据集 |\n| `from_jsonl` | 从JSONL文件加载 |\n| `from_dicts` | 从字典列表加载 |\n| `train_test_split` | 划分训练集和测试集 |\n\n### 自定义数据集\n\n```python\nfrom dspy.datasets import Dataset\n\nclass MyDataset(Dataset):\n    def __init__(self, path):\n        super().__init__()\n        self._data = self._load_from_file(path)\n    \n    def _load_from_file(self, path):\n        # 自定义加载逻辑\n        pass\n\n# 使用自定义数据集\ndataset = MyDataset(\"path/to/data.jsonl\")\ntrainset = dataset.train\ndevset = dataset.dev\n```\n\n## 与优化器的集成\n\n评估系统与 DSPy 的 Teleprompter 优化器紧密集成。优化器使用评估指标来引导搜索最优的程序配置（提示词、示例选择等）。\n\n```mermaid\ngraph LR\n    A[BootstrapFewShot] --> B[评估指标]\n    C[MIPROv2] --> B\n    D[GEPA] --> B\n    B --> E[优化搜索]\n    E --> F[最优配置]\n```\n\n### 完整优化流程\n\n```python\nimport dspy\n\n# 1. 定义程序\nprogram = dspy.ChainOfThought(\"question -> answer\")\n\n# 2. 准备数据集\ntrainset = [\n    dspy.Example(question=q, answer=a).with_inputs(\"question\")\n    for q, a in question_answer_pairs\n]\n\n# 3. 定义指标\ndef exact_match(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 4. 使用优化器（内部使用评估）\noptimizer = dspy.MIPROv2(metric=exact_match)\ncompiled_program = optimizer.compile(\n    program,\n    trainset=trainset,\n    max_bootstrapped_demos=4,\n)\n```\n\n## 最佳实践\n\n### 指标设计原则\n\n1. **确定性**：相同输入应产生相同分数，避免随机性\n2. **高效性**：指标函数会被频繁调用，应尽量轻量\n3. **可解释性**：分数应能清晰反映输出质量\n4. **可组合性**：支持复合指标以评估多个维度\n\n### 评估执行建议\n\n| 场景 | 建议 |\n|------|------|\n| 快速原型开发 | 使用 `num_threads=-1` 启用所有CPU核心 |\n| 调试 | 设置 `return_outputs=True` 获取详细输出 |\n| 生产环境 | 设置合理的 `max_errors` 避免无限等待 |\n| 大规模评估 | 分批评估并保存中间结果 |\n\n### 常见问题处理\n\n**处理评估超时**：\n```python\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=my_metric,\n    max_errors=10,  # 跳过有问题的样本\n    num_threads=4,\n)\n```\n\n**获取详细评估日志**：\n```python\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=my_metric,\n    return_outputs=True,\n    display=True,\n)\nresults = evaluate(program)\nfor i, (example, pred, score) in enumerate(results.outputs):\n    print(f\"[{i}] Score: {score}\")\n```\n\n## 相关模块\n\n- [预测模块 (Predict)](./predict.md) - 生成预测的模块\n- [优化器 (Teleprompter)](./teleprompt.md) - 优化程序配置的优化器\n- [示例模块 (Example)](./primitives.md) - 数据结构基础\n\n## 参考链接\n\n- DSPy 官方文档：https://dspy.ai\n- 评估指标文档：[dspy.evaluate.metrics](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/metrics.py)\n- 数据集模块：[dspy.datasets](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/__init__.py)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：stanfordnlp/dspy\n\n摘要：发现 19 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read。\n\n## 1. 安全/权限坑 · 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_43291e191b234ac883662982bf693e18 | https://github.com/stanfordnlp/dspy/issues/9749 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：3.0.4b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.0.4b1\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_76f47f2d6cbc4f299fe2a852b20617ef | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：3.1.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.2\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3733e2d7817440638629959030da2ddb | https://github.com/stanfordnlp/dspy/releases/tag/3.1.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：3.1.3\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.3\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b7f0c4a046840b4b453167ce581b80a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：3.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.2.0\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_976a3edffce44ac3984c9da4a10a2575 | https://github.com/stanfordnlp/dspy/releases/tag/3.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：Use Tool functions that require external libaries in CodeAct\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Use Tool functions that require external libaries in CodeAct\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c605227d53e42b69651c46c3e76c162 | https://github.com/stanfordnlp/dspy/issues/8839 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:587050620 | https://github.com/stanfordnlp/dspy | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：3.0.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d192b20b863c476ca31d4ba476cec875 | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：3.0.4b2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4b2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_392f60c647b74a6592f1692bcdc0070f | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 13. 安全/权限坑 · 来源证据：3.1.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364bbccd7d4241c9b6841303fefb5a85 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：3.1.0b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0b1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4599cbf0d1fd41b4b3c47e5c1aae247a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. 安全/权限坑 · 来源证据：3.1.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5656ac7c80214b9fb410d129ccec33d2 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：3.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.2.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2250d3118a04c5e8d213eb2fce4e68d | https://github.com/stanfordnlp/dspy/releases/tag/3.2.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安全/权限坑 · 来源证据：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bb4eb14c9ce944f0a7654217c34b1d1d | https://github.com/stanfordnlp/dspy/issues/9501 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 18. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | issue_or_pr_quality=unknown\n\n## 19. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | release_recency=unknown\n\n<!-- canonical_name: stanfordnlp/dspy; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "dspy",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:587050620",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/stanfordnlp/dspy"
        },
        {
          "evidence_id": "art_b540deff7f9b4421a5df3ced549d6930",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/stanfordnlp/dspy#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "dspy 说明书",
      "toc": [
        "https://github.com/stanfordnlp/dspy 项目说明书",
        "目录",
        "DSPy概述",
        "核心定位与价值",
        "系统架构",
        "核心抽象",
        "数据模型",
        "回调系统",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "621c3a6140e3da1622127fc75c775e1f6fe37129",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "uv.lock",
      "docs/mkdocs.yml",
      "docs/vercel.json",
      "docs/README.md",
      "docs/docs/index.md",
      "docs/docs/roadmap.md",
      "docs/docs/cheatsheet.md",
      "docs/docs/faqs.md",
      "docs/scripts/generate_api_summary.py",
      "docs/scripts/generate_api_docs.py",
      "docs/docs/api/index.md",
      "docs/docs/js/copy-as-markdown.js",
      "docs/docs/js/tutorial-nav.js",
      "docs/docs/js/runllm-widget.js",
      "docs/docs/tutorials/index.md",
      "docs/docs/community/built-with-dspy.md",
      "docs/docs/community/community-resources.md",
      "docs/docs/community/how-to-contribute.md",
      "docs/docs/community/use-cases.md",
      "docs/docs/production/index.md",
      "docs/docs/learn/index.md",
      "docs/docs/api/experimental/Citations.md",
      "docs/docs/api/experimental/Document.md",
      "docs/docs/api/models/Embedder.md",
      "docs/docs/api/models/LM.md",
      "docs/docs/api/tools/ColBERTv2.md",
      "docs/docs/api/tools/PythonInterpreter.md",
      "docs/docs/api/tools/Embeddings.md",
      "docs/docs/api/adapters/XMLAdapter.md",
      "docs/docs/api/adapters/JSONAdapter.md",
      "docs/docs/api/adapters/Adapter.md",
      "docs/docs/api/adapters/ChatAdapter.md",
      "docs/docs/api/adapters/TwoStepAdapter.md",
      "docs/docs/api/utils/asyncify.md",
      "docs/docs/api/utils/context.md",
      "docs/docs/api/utils/configure.md",
      "docs/docs/api/utils/enable_logging.md",
      "docs/docs/api/utils/StreamListener.md"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# dspy - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 dspy 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **AI 研究者或研究型 Agent 构建者**：README 明确围绕研究、实验或论文工作流展开。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install dspy` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `pip install git+https://github.com/stanfordnlp/dspy.git` 证据：`README.md` Claim：`clm_0004` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做角色匹配试用\n- **为什么**：这个项目更像角色库，核心风险是选错角色或把角色文案当执行能力；先用 Prompt Preview 试角色匹配，再决定是否沙盒导入。\n\n### 30 秒判断\n\n- **现在怎么做**：先做角色匹配试用\n- **最小安全下一步**：先用 Prompt Preview 试角色匹配；满意后再隔离导入\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：AI 研究者或研究型 Agent 构建者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **角色质量和任务匹配不能直接相信。**（unverified）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0005` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0006` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：457\n- 重要文件覆盖：40/457\n- 证据索引条目：80\n- 角色 / Skill 条目：79\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 dspy 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 dspy 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 dspy 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 79 个角色 / Skill / 项目文档条目。\n\n- **Modifying the DSPy Documentation**（project_doc）：If you're looking to understand the framework, please go to the DSPy Docs at dspy.ai https://dspy.ai 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/README.md`\n- **DSPy: Programming —not prompting—Foundation Models**（project_doc）：DSPy: Programming —not prompting—Foundation Models 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Readme**（project_doc）：The tests in this directory are primarily concerned with code correctness and Adapter reliability. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/README.md`\n- **DSPy Reliability Tests**（project_doc）：This directory contains reliability tests for DSPy programs. The purpose of these tests is to verify that DSPy programs reliably produce expected outputs across multiple large language models LLMs , regardless of model size or capability. These tests are designed to ensure that DSPy programs maintain robustness and accuracy across diverse LLM configurations. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/reliability/README.md`\n- **Contribution Guide**（project_doc）：DSPy is an actively growing project and community! We welcome your contributions and involvement. Below are instructions for how to contribute to DSPy. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **dspy.Adapter**（project_doc）：::: dspy.Adapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format system message - format task description - format user message content - parse show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object ful… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/adapters/Adapter.md`\n- **dspy.ChatAdapter**（project_doc）：::: dspy.ChatAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading:… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/adapters/ChatAdapter.md`\n- **dspy.JSONAdapter**（project_doc）：::: dspy.JSONAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading:… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/adapters/JSONAdapter.md`\n- **dspy.TwoStepAdapter**（project_doc）：::: dspy.TwoStepAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format system message - format task description - format user message content - parse show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show obj… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/adapters/TwoStepAdapter.md`\n- **dspy.XMLAdapter**（project_doc）：::: dspy.XMLAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading:… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/adapters/XMLAdapter.md`\n- **dspy.evaluate.CompleteAndGrounded**（project_doc）：::: dspy.evaluate.CompleteAndGrounded handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: tru… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/CompleteAndGrounded.md`\n- **dspy.Evaluate**（project_doc）：::: dspy.Evaluate handler: python options: members: - call show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/Evaluate.md`\n- **dspy.evaluate.EvaluationResult**（project_doc）：::: dspy.evaluate.EvaluationResult handler: python options: members: - copy - from completions - get - get lm usage - inputs - items - keys - labels - set lm usage - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/EvaluationResult.md`\n- **dspy.evaluate.SemanticF1**（project_doc）：::: dspy.evaluate.SemanticF1 handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show ob… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/SemanticF1.md`\n- **dspy.evaluate.answer exact match**（project_doc）：::: dspy.evaluate.answer exact match handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/answer_exact_match.md`\n- **dspy.evaluate.answer passage match**（project_doc）：::: dspy.evaluate.answer passage match handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/evaluation/answer_passage_match.md`\n- **dspy.experimental.Citations**（project_doc）：::: dspy.experimental.Citations handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from dict list - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signatu… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/experimental/Citations.md`\n- **dspy.experimental.Document**（project_doc）：::: dspy.experimental.Document handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherite… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/experimental/Document.md`\n- **API Reference**（project_doc）：Welcome to the DSPy API reference documentation. This section provides detailed information about DSPy's classes, modules, and functions. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/index.md`\n- **dspy.Embedder**（project_doc）：!!! note \"Requires numpy\" dspy.Embedder requires numpy. Install it with pip install dspy numpy . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/models/Embedder.md`\n- **dspy.LM**（project_doc）：::: dspy.LM handler: python options: members: - call - acall - aforward - copy - dump state - finetune - forward - infer provider - inspect history - kill - launch - reinforce - update history show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/models/LM.md`\n- **dspy.BestOfN**（project_doc）：::: dspy.BestOfN handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full pa… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/BestOfN.md`\n- **dspy.ChainOfThought**（project_doc）：::: dspy.ChainOfThought handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true s… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/ChainOfThought.md`\n- **dspy.CodeAct**（project_doc）：::: dspy.CodeAct handler: python options: members: - call - batch - deepcopy - dump state - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/CodeAct.md`\n- **dspy.Module**（project_doc）：::: dspy.Module handler: python options: members: - call - acall - batch - deepcopy - dump state - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false s… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/Module.md`\n- **dspy.MultiChainComparison**（project_doc）：::: dspy.MultiChainComparison handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show o… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/MultiChainComparison.md`\n- **dspy.Parallel**（project_doc）：::: dspy.Parallel handler: python options: members: - call - forward show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/Parallel.md`\n- **dspy.Predict**（project_doc）：::: dspy.Predict handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get config - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset - reset copy - save - set lm - update config show source: true show root heading: true heading level: 2 docstring style: goog… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/Predict.md`\n- **dspy.ProgramOfThought**（project_doc）：::: dspy.ProgramOfThought handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show objec… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/ProgramOfThought.md`\n- **dspy.RLM**（project_doc）：RLM Recursive Language Model is a DSPy module that lets LLMs programmatically explore large contexts through a sandboxed Python REPL. Instead of feeding huge contexts directly into the prompt, RLM treats context as external data that the LLM examines via code execution and recursive sub-LLM calls. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/RLM.md`\n- **dspy.ReAct**（project_doc）：::: dspy.ReAct handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm - truncate trajectory show source: true show root heading: true heading level: 2 docstring style: google show root full… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/ReAct.md`\n- **dspy.Refine**（project_doc）：::: dspy.Refine handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full pat… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/modules/Refine.md`\n- **dspy.BetterTogether**（project_doc）：BetterTogether is a meta-optimizer proposed in the paper Fine-Tuning and Prompt Optimization: Two Great Steps that Work Better Together https://arxiv.org/abs/2407.10930 by Dilara Soylu, Christopher Potts, and Omar Khattab. It combines prompt optimization and weight optimization fine-tuning by applying them in a configurable sequence, allowing a student program to iteratively improve both its prompts and model parame… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/BetterTogether.md`\n- **dspy.BootstrapFewShot**（project_doc）：::: dspy.BootstrapFewShot handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/BootstrapFewShot.md`\n- **dspy.BootstrapFewShotWithRandomSearch**（project_doc）：dspy.BootstrapFewShotWithRandomSearch 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/BootstrapFewShotWithRandomSearch.md`\n- **dspy.BootstrapFinetune**（project_doc）：::: dspy.BootstrapFinetune handler: python options: members: - compile - convert to lm dict - finetune lms - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/BootstrapFinetune.md`\n- **dspy.BootstrapRS**（project_doc）：::: dspy.BootstrapRS handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/BootstrapRS.md`\n- **dspy.COPRO**（project_doc）：::: dspy.COPRO handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/COPRO.md`\n- **dspy.Ensemble**（project_doc）：::: dspy.Ensemble handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/Ensemble.md`\n- **dspy.GEPA - Advanced Features**（project_doc）：The instruction proposer is the component responsible for invoking the reflection lm and proposing new prompts during GEPA optimization. When GEPA identifies underperforming components in your DSPy program, the instruction proposer analyzes execution traces, feedback, and failures to generate improved instructions tailored to the observed issues. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/GEPA/GEPA_Advanced.md`\n- **dspy.GEPA: Reflective Prompt Optimizer**（project_doc）：dspy.GEPA: Reflective Prompt Optimizer 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/GEPA/overview.md`\n- **dspy.InferRules**（project_doc）：::: dspy.InferRules handler: python options: members: - compile - evaluate program - format examples - get params - get predictor demos - induce natural language rules - update program instructions show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/InferRules.md`\n- **dspy.KNN**（project_doc）：!!! note \"Requires numpy\" dspy.KNN requires numpy. Install it with pip install dspy numpy . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/KNN.md`\n- **dspy.KNNFewShot**（project_doc）：!!! note \"Requires numpy\" dspy.KNNFewShot requires numpy. Install it with pip install dspy numpy . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/KNNFewShot.md`\n- **dspy.LabeledFewShot**（project_doc）：::: dspy.LabeledFewShot handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/LabeledFewShot.md`\n- **dspy.MIPROv2**（project_doc）：MIPROv2 M ultiprompt I nstruction PR oposal O ptimizer Version 2 is an prompt optimizer capable of optimizing both instructions and few-shot examples jointly. It does this by bootstrapping few-shot example candidates, proposing instructions grounded in different dynamics of the task, and finding an optimized combination of these options using Bayesian Optimization. It can be used for optimizing few-shot examples & i… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/MIPROv2.md`\n- **dspy.SIMBA**（project_doc）：!!! note \"Requires numpy\" dspy.SIMBA requires numpy. Install it with pip install dspy numpy . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/optimizers/SIMBA.md`\n- **dspy.Audio**（project_doc）：::: dspy.Audio handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from array - from file - from url - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signa… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Audio.md`\n- **dspy.Code**（project_doc）：::: dspy.Code handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Code.md`\n- **dspy.Example**（project_doc）：::: dspy.Example handler: python options: members: - copy - get - inputs - items - keys - labels - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Example.md`\n- **dspy.History**（project_doc）：::: dspy.History handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/History.md`\n- **dspy.Image**（project_doc）：::: dspy.Image handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from PIL - from file - from url - is streamable - parse lm response - parse stream chunk - serialize model show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherit… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Image.md`\n- **dspy.Prediction**（project_doc）：::: dspy.Prediction handler: python options: members: - copy - from completions - get - get lm usage - inputs - items - keys - labels - set lm usage - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Prediction.md`\n- **dspy.Tool**（project_doc）：::: dspy.Tool handler: python options: members: - call - acall - adapt to native lm feature - description - extract custom type from annotation - format - format as litellm function call - from langchain - from mcp tool - is streamable - parse lm response - parse stream chunk - serialize model show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object ful… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/Tool.md`\n- **dspy.ToolCalls**（project_doc）：::: dspy.ToolCalls handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from dict list - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inh… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/primitives/ToolCalls.md`\n- **dspy.InputField**（project_doc）：::: dspy.InputField handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/signatures/InputField.md`\n- **dspy.OutputField**（project_doc）：::: dspy.OutputField handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/signatures/OutputField.md`\n- **dspy.Signature**（project_doc）：::: dspy.Signature handler: python options: members: - append - delete - dump state - equals - insert - load state - prepend - with instructions - with updated fields show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/signatures/Signature.md`\n- **dspy.ColBERTv2**（project_doc）：::: dspy.ColBERTv2 handler: python options: members: - call show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/tools/ColBERTv2.md`\n- **dspy.retrievers.Embeddings**（project_doc）：!!! note \"Requires numpy\" dspy.retrievers.Embeddings requires numpy. Install it with pip install dspy numpy . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/tools/Embeddings.md`\n- **dspy.PythonInterpreter**（project_doc）：::: dspy.PythonInterpreter handler: python options: members: - call - execute - shutdown - start show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/tools/PythonInterpreter.md`\n- **dspy.streaming.StatusMessage**（project_doc）：::: dspy.streaming.StatusMessage handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/StatusMessage.md`\n- **dspy.streaming.StatusMessageProvider**（project_doc）：dspy.streaming.StatusMessageProvider 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/StatusMessageProvider.md`\n- **dspy.streaming.StreamListener**（project_doc）：::: dspy.streaming.StreamListener handler: python options: members: - finalize - flush - receive show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/StreamListener.md`\n- **dspy.asyncify**（project_doc）：::: dspy.asyncify handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/asyncify.md`\n- **dspy.configure**（project_doc）：Set the default language model, adapter, and other settings for DSPy. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/configure.md`\n- **dspy.configure cache**（project_doc）：::: dspy.configure cache handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/configure_cache.md`\n- **dspy.context**（project_doc）：Override DSPy settings inside one with block. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/context.md`\n- **dspy.disable litellm logging**（project_doc）：::: dspy.disable litellm logging handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/disable_litellm_logging.md`\n- **dspy.disable logging**（project_doc）：::: dspy.disable logging handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/disable_logging.md`\n- **dspy.enable litellm logging**（project_doc）：::: dspy.enable litellm logging handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/enable_litellm_logging.md`\n- **dspy.enable logging**（project_doc）：::: dspy.enable logging handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/enable_logging.md`\n- **dspy.inspect history**（project_doc）：::: dspy.inspect history handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/inspect_history.md`\n- **dspy.load**（project_doc）：::: dspy.load handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/load.md`\n- **dspy.streamify**（project_doc）：::: dspy.streamify handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/api/utils/streamify.md`\n- **DSPy Cheatsheet**（project_doc）：This page will contain snippets for frequent usage patterns. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/cheatsheet.md`\n- **Built with DSPy**（project_doc）：Open-source projects, research papers, language ports, and integrations from the wider DSPy ecosystem. Community-maintained; to add yours, please open a PR https://github.com/stanfordnlp/dspy/edit/main/docs/docs/community/built-with-dspy.md . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/community/built-with-dspy.md`\n- **Resources**（project_doc）：This is the list of tutorials and blog posts on DSPy. If you would like to add your own tutorial, please make a PR. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/community/community-resources.md`\n- **Contributing**（project_doc）：DSPy is an actively growing project and community, and we welcome your contributions and involvement! Please read the contributing guide https://github.com/stanfordnlp/dspy/blob/main/CONTRIBUTING.md for how to contribute to DSPy. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/community/how-to-contribute.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Modifying the DSPy Documentation**（documentation）：If you're looking to understand the framework, please go to the DSPy Docs at dspy.ai https://dspy.ai 证据：`docs/README.md`\n- **DSPy: Programming —not prompting—Foundation Models**（documentation）：DSPy: Programming —not prompting—Foundation Models 证据：`README.md`\n- **Readme**（documentation）：The tests in this directory are primarily concerned with code correctness and Adapter reliability. 证据：`tests/README.md`\n- **DSPy Reliability Tests**（documentation）：This directory contains reliability tests for DSPy programs. The purpose of these tests is to verify that DSPy programs reliably produce expected outputs across multiple large language models LLMs , regardless of model size or capability. These tests are designed to ensure that DSPy programs maintain robustness and accuracy across diverse LLM configurations. 证据：`tests/reliability/README.md`\n- **Contribution Guide**（documentation）：DSPy is an actively growing project and community! We welcome your contributions and involvement. Below are instructions for how to contribute to DSPy. 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Copyright c 2023 Stanford Future Data Systems 证据：`LICENSE`\n- **dspy.Adapter**（documentation）：::: dspy.Adapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format system message - format task description - format user message content - parse show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/adapters/Adapter.md`\n- **dspy.ChatAdapter**（documentation）：::: dspy.ChatAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/adapters/ChatAdapter.md`\n- **dspy.JSONAdapter**（documentation）：::: dspy.JSONAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/adapters/JSONAdapter.md`\n- **dspy.TwoStepAdapter**（documentation）：::: dspy.TwoStepAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format system message - format task description - format user message content - parse show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/adapters/TwoStepAdapter.md`\n- **dspy.XMLAdapter**（documentation）：::: dspy.XMLAdapter handler: python options: members: - call - acall - format - format assistant message content - format conversation history - format demos - format field description - format field structure - format field with value - format finetune data - format system message - format task description - format user message content - parse - user message output requirements show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/adapters/XMLAdapter.md`\n- **dspy.evaluate.CompleteAndGrounded**（documentation）：::: dspy.evaluate.CompleteAndGrounded handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/CompleteAndGrounded.md`\n- **dspy.Evaluate**（documentation）：::: dspy.Evaluate handler: python options: members: - call show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/Evaluate.md`\n- **dspy.evaluate.EvaluationResult**（documentation）：::: dspy.evaluate.EvaluationResult handler: python options: members: - copy - from completions - get - get lm usage - inputs - items - keys - labels - set lm usage - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/EvaluationResult.md`\n- **dspy.evaluate.SemanticF1**（documentation）：::: dspy.evaluate.SemanticF1 handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/SemanticF1.md`\n- **dspy.evaluate.answer exact match**（documentation）：::: dspy.evaluate.answer exact match handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/answer_exact_match.md`\n- **dspy.evaluate.answer passage match**（documentation）：::: dspy.evaluate.answer passage match handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/evaluation/answer_passage_match.md`\n- **dspy.experimental.Citations**（documentation）：::: dspy.experimental.Citations handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from dict list - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/experimental/Citations.md`\n- **dspy.experimental.Document**（documentation）：::: dspy.experimental.Document handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/experimental/Document.md`\n- **API Reference**（documentation）：Welcome to the DSPy API reference documentation. This section provides detailed information about DSPy's classes, modules, and functions. 证据：`docs/docs/api/index.md`\n- **dspy.Embedder**（documentation）：!!! note \"Requires numpy\" dspy.Embedder requires numpy. Install it with pip install dspy numpy . 证据：`docs/docs/api/models/Embedder.md`\n- **dspy.LM**（documentation）：::: dspy.LM handler: python options: members: - call - acall - aforward - copy - dump state - finetune - forward - infer provider - inspect history - kill - launch - reinforce - update history show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/models/LM.md`\n- **dspy.BestOfN**（documentation）：::: dspy.BestOfN handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/BestOfN.md`\n- **dspy.ChainOfThought**（documentation）：::: dspy.ChainOfThought handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/ChainOfThought.md`\n- **dspy.CodeAct**（documentation）：::: dspy.CodeAct handler: python options: members: - call - batch - deepcopy - dump state - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/CodeAct.md`\n- **dspy.Module**（documentation）：::: dspy.Module handler: python options: members: - call - acall - batch - deepcopy - dump state - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/Module.md`\n- **dspy.MultiChainComparison**（documentation）：::: dspy.MultiChainComparison handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/MultiChainComparison.md`\n- **dspy.Parallel**（documentation）：::: dspy.Parallel handler: python options: members: - call - forward show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/Parallel.md`\n- **dspy.Predict**（documentation）：::: dspy.Predict handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get config - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset - reset copy - save - set lm - update config show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/Predict.md`\n- **dspy.ProgramOfThought**（documentation）：::: dspy.ProgramOfThought handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/ProgramOfThought.md`\n- **dspy.RLM**（documentation）：RLM Recursive Language Model is a DSPy module that lets LLMs programmatically explore large contexts through a sandboxed Python REPL. Instead of feeding huge contexts directly into the prompt, RLM treats context as external data that the LLM examines via code execution and recursive sub-LLM calls. 证据：`docs/docs/api/modules/RLM.md`\n- **dspy.ReAct**（documentation）：::: dspy.ReAct handler: python options: members: - call - acall - aforward - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm - truncate trajectory show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/ReAct.md`\n- **dspy.Refine**（documentation）：::: dspy.Refine handler: python options: members: - call - acall - batch - deepcopy - dump state - forward - get lm - inspect history - load - load state - map named predictors - named parameters - named predictors - named sub modules - parameters - predictors - reset copy - save - set lm show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/modules/Refine.md`\n- **dspy.BetterTogether**（documentation）：BetterTogether is a meta-optimizer proposed in the paper Fine-Tuning and Prompt Optimization: Two Great Steps that Work Better Together https://arxiv.org/abs/2407.10930 by Dilara Soylu, Christopher Potts, and Omar Khattab. It combines prompt optimization and weight optimization fine-tuning by applying them in a configurable sequence, allowing a student program to iteratively improve both its prompts and model parameters. The core insight is that prompt and weight optimization can complement each other: prompt optimization can potentially discover effective task decompositions and reasoning strategies, while weight optimization can specialize the model to execute these patterns more efficien… 证据：`docs/docs/api/optimizers/BetterTogether.md`\n- **dspy.BootstrapFewShot**（documentation）：::: dspy.BootstrapFewShot handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/BootstrapFewShot.md`\n- **dspy.BootstrapFewShotWithRandomSearch**（documentation）：dspy.BootstrapFewShotWithRandomSearch 证据：`docs/docs/api/optimizers/BootstrapFewShotWithRandomSearch.md`\n- **dspy.BootstrapFinetune**（documentation）：::: dspy.BootstrapFinetune handler: python options: members: - compile - convert to lm dict - finetune lms - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/BootstrapFinetune.md`\n- **dspy.BootstrapRS**（documentation）：::: dspy.BootstrapRS handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/BootstrapRS.md`\n- **dspy.COPRO**（documentation）：::: dspy.COPRO handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/COPRO.md`\n- **dspy.Ensemble**（documentation）：::: dspy.Ensemble handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/Ensemble.md`\n- **dspy.GEPA - Advanced Features**（documentation）：The instruction proposer is the component responsible for invoking the reflection lm and proposing new prompts during GEPA optimization. When GEPA identifies underperforming components in your DSPy program, the instruction proposer analyzes execution traces, feedback, and failures to generate improved instructions tailored to the observed issues. 证据：`docs/docs/api/optimizers/GEPA/GEPA_Advanced.md`\n- **dspy.GEPA: Reflective Prompt Optimizer**（documentation）：dspy.GEPA: Reflective Prompt Optimizer 证据：`docs/docs/api/optimizers/GEPA/overview.md`\n- **dspy.InferRules**（documentation）：::: dspy.InferRules handler: python options: members: - compile - evaluate program - format examples - get params - get predictor demos - induce natural language rules - update program instructions show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/InferRules.md`\n- **dspy.KNN**（documentation）：!!! note \"Requires numpy\" dspy.KNN requires numpy. Install it with pip install dspy numpy . 证据：`docs/docs/api/optimizers/KNN.md`\n- **dspy.KNNFewShot**（documentation）：!!! note \"Requires numpy\" dspy.KNNFewShot requires numpy. Install it with pip install dspy numpy . 证据：`docs/docs/api/optimizers/KNNFewShot.md`\n- **dspy.LabeledFewShot**（documentation）：::: dspy.LabeledFewShot handler: python options: members: - compile - get params show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/optimizers/LabeledFewShot.md`\n- **dspy.MIPROv2**（documentation）：MIPROv2 M ultiprompt I nstruction PR oposal O ptimizer Version 2 is an prompt optimizer capable of optimizing both instructions and few-shot examples jointly. It does this by bootstrapping few-shot example candidates, proposing instructions grounded in different dynamics of the task, and finding an optimized combination of these options using Bayesian Optimization. It can be used for optimizing few-shot examples & instructions jointly, or just instructions for 0-shot optimization. 证据：`docs/docs/api/optimizers/MIPROv2.md`\n- **dspy.SIMBA**（documentation）：!!! note \"Requires numpy\" dspy.SIMBA requires numpy. Install it with pip install dspy numpy . 证据：`docs/docs/api/optimizers/SIMBA.md`\n- **dspy.Audio**（documentation）：::: dspy.Audio handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from array - from file - from url - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Audio.md`\n- **dspy.Code**（documentation）：::: dspy.Code handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Code.md`\n- **dspy.Example**（documentation）：::: dspy.Example handler: python options: members: - copy - get - inputs - items - keys - labels - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Example.md`\n- **dspy.History**（documentation）：::: dspy.History handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/History.md`\n- **dspy.Image**（documentation）：::: dspy.Image handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from PIL - from file - from url - is streamable - parse lm response - parse stream chunk - serialize model show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Image.md`\n- **dspy.Prediction**（documentation）：::: dspy.Prediction handler: python options: members: - copy - from completions - get - get lm usage - inputs - items - keys - labels - set lm usage - toDict - values - with inputs - without show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Prediction.md`\n- **dspy.Tool**（documentation）：::: dspy.Tool handler: python options: members: - call - acall - adapt to native lm feature - description - extract custom type from annotation - format - format as litellm function call - from langchain - from mcp tool - is streamable - parse lm response - parse stream chunk - serialize model show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/Tool.md`\n- **dspy.ToolCalls**（documentation）：::: dspy.ToolCalls handler: python options: members: - adapt to native lm feature - description - extract custom type from annotation - format - from dict list - is streamable - parse lm response - parse stream chunk - serialize model - validate input show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/primitives/ToolCalls.md`\n- **dspy.InputField**（documentation）：::: dspy.InputField handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/signatures/InputField.md`\n- **dspy.OutputField**（documentation）：::: dspy.OutputField handler: python options: show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/signatures/OutputField.md`\n- **dspy.Signature**（documentation）：::: dspy.Signature handler: python options: members: - append - delete - dump state - equals - insert - load state - prepend - with instructions - with updated fields show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/signatures/Signature.md`\n- **dspy.ColBERTv2**（documentation）：::: dspy.ColBERTv2 handler: python options: members: - call show source: true show root heading: true heading level: 2 docstring style: google show root full path: true show object full path: false separate signature: false inherited members: true 证据：`docs/docs/api/tools/ColBERTv2.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/README.md`, `README.md`, `tests/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/README.md`, `README.md`, `tests/README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **DSPy概述**：importance `high`\n  - source_paths: dspy/__init__.py, dspy/__metadata__.py, README.md, dspy/primitives/module.py, dspy/primitives/base_module.py\n- **安装与快速开始**：importance `high`\n  - source_paths: pyproject.toml, dspy/utils/__init__.py\n- **签名（Signatures）**：importance `high`\n  - source_paths: dspy/signatures/__init__.py, dspy/signatures/signature.py, dspy/signatures/field.py, dspy/signatures/utils.py\n- **内置模块参考**：importance `high`\n  - source_paths: dspy/predict/__init__.py, dspy/predict/predict.py, dspy/predict/chain_of_thought.py, dspy/predict/react.py, dspy/predict/program_of_thought.py\n- **原语与数据结构**：importance `high`\n  - source_paths: dspy/primitives/__init__.py, dspy/primitives/example.py, dspy/primitives/prediction.py, dspy/primitives/module.py, dspy/primitives/python_interpreter.py\n- **优化器详解**：importance `high`\n  - source_paths: dspy/teleprompt/__init__.py, dspy/teleprompt/bootstrap.py, dspy/teleprompt/copro_optimizer.py, dspy/teleprompt/mipro_optimizer_v2.py, dspy/teleprompt/ensemble.py\n- **语言模型客户端**：importance `high`\n  - source_paths: dspy/clients/__init__.py, dspy/clients/lm.py, dspy/clients/base_lm.py, dspy/clients/openai.py, dspy/clients/_litellm.py\n- **适配器系统**：importance `medium`\n  - source_paths: dspy/adapters/__init__.py, dspy/adapters/base.py, dspy/adapters/chat_adapter.py, dspy/adapters/json_adapter.py, dspy/adapters/xml_adapter.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `621c3a6140e3da1622127fc75c775e1f6fe37129`\n- inspected_files: `pyproject.toml`, `README.md`, `uv.lock`, `docs/mkdocs.yml`, `docs/vercel.json`, `docs/README.md`, `docs/docs/index.md`, `docs/docs/roadmap.md`, `docs/docs/cheatsheet.md`, `docs/docs/faqs.md`, `docs/scripts/generate_api_summary.py`, `docs/scripts/generate_api_docs.py`, `docs/docs/api/index.md`, `docs/docs/js/copy-as-markdown.js`, `docs/docs/js/tutorial-nav.js`, `docs/docs/js/runllm-widget.js`, `docs/docs/tutorials/index.md`, `docs/docs/community/built-with-dspy.md`, `docs/docs/community/community-resources.md`, `docs/docs/community/how-to-contribute.md`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_43291e191b234ac883662982bf693e18 | https://github.com/stanfordnlp/dspy/issues/9749 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：3.0.4b1\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.0.4b1\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_76f47f2d6cbc4f299fe2a852b20617ef | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b1 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：3.1.2\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.2\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_3733e2d7817440638629959030da2ddb | https://github.com/stanfordnlp/dspy/releases/tag/3.1.2 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：3.1.3\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.3\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_2b7f0c4a046840b4b453167ce581b80a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：3.2.0\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.2.0\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_976a3edffce44ac3984c9da4a10a2575 | https://github.com/stanfordnlp/dspy/releases/tag/3.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：Use Tool functions that require external libaries in CodeAct\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Use Tool functions that require external libaries in CodeAct\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_3c605227d53e42b69651c46c3e76c162 | https://github.com/stanfordnlp/dspy/issues/8839 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:587050620 | https://github.com/stanfordnlp/dspy | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：stanfordnlp/dspy\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：local_cli\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：3.0.4b1（medium）：可能阻塞安装或首次运行。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：3.1.2（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：3.1.3（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：3.2.0（medium）：可能阻塞安装或首次运行。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/stanfordnlp/dspy 项目说明书\n\n生成时间：2026-05-16 04:11:08 UTC\n\n## 目录\n\n- [DSPy概述](#page-overview)\n- [安装与快速开始](#page-installation)\n- [签名（Signatures）](#page-signatures)\n- [内置模块参考](#page-modules)\n- [原语与数据结构](#page-primitives)\n- [优化器详解](#page-optimizers)\n- [语言模型客户端](#page-lm-clients)\n- [适配器系统](#page-adapters)\n- [检索增强模块](#page-retrieval)\n- [评估与指标](#page-evaluation)\n\n<a id='page-overview'></a>\n\n## DSPy概述\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [内置模块参考](#page-modules), [语言模型客户端](#page-lm-clients)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.md)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n- [dspy/adapters/types/document.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/document.py)\n- [dspy/adapters/types/citation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/citation.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# DSPy概述\n\nDSPy（Declarative Self-Improving Python）是一个用于构建和优化基于语言模型（LM）复杂管道的框架。该框架由斯坦福NLP团队开发，旨在通过声明式编程范式简化大型语言模型应用的开发和优化过程。\n\n## 核心定位与价值\n\nDSPy的核心价值在于将语言模型调用从硬编码的提示词转变为可声明式定义、可自动优化的程序组件。根据项目文档，DSPy能够\"将声明式语言模型调用编译成自我改进的管道\"，这使得开发者可以专注于程序逻辑而非提示工程细节。\n\n## 系统架构\n\n### 整体架构图\n\n```mermaid\ngraph TD\n    A[用户程序] --> B[DSPy Module]\n    B --> C[Signature定义]\n    B --> D[Predict组件]\n    B --> E[ChainOfThought组件]\n    C --> F[InputField/OutputField]\n    D --> G[语言模型 LM]\n    E --> G\n    G --> H[优化器 Teleprompter]\n    H --> I[训练集 Trainset]\n    I --> H\n    H --> B\n    G --> J[检索模型 RM]\n    J --> K[外部知识库]\n```\n\n### 核心组件层次\n\n| 层级 | 组件 | 说明 |\n|------|------|------|\n| 用户层 | DSPy Module | 自定义程序模块，继承`dspy.Module` |\n| 定义层 | Signature | 声明输入输出字段及其描述 |\n| 执行层 | Predict/ChainOfThought | 执行语言模型调用 |\n| 优化层 | Teleprompter | 自动优化提示和参数 |\n| 集成层 | LM/RM Adapter | 支持多种语言模型和检索器 |\n\n## 核心抽象\n\n### Module基类\n\nDSPy的`Module`是所有程序组件的基类，提供了语言模型管理和预测组件发现功能：\n\n```python\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n```\n\nModule类提供以下关键方法：\n\n| 方法 | 功能 | 资料来源 |\n|------|------|----------|\n| `named_predictors()` | 返回所有Predict组件的(名称, 实例)元组列表 | [module.py:92-100]() |\n| `predictors()` | 返回所有Predict实例的列表 | [module.py:103-120]() |\n| `set_lm(lm)` | 为所有Predict设置语言模型 | [module.py:128-143]() |\n| `get_lm()` | 获取当前使用的语言模型 | [module.py:145-152]() |\n\n### Signature系统\n\nSignature用于声明模块的输入输出字段语义，是DSPy中连接程序逻辑与语言模型的关键抽象：\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField(desc=\"用户问题\")\n    answer: str = dspy.OutputField(desc=\"模型回答\")\n```\n\nSignature支持动态修改：\n\n- `prepend()`: 在输入字段前插入新字段\n- `append()`: 在输出字段后追加新字段\n- `delete()`: 删除指定字段\n\n## 数据模型\n\n### Example类\n\n`dspy.Example`是DSPy中用于表示训练样本和测试样本的核心数据结构：\n\n```python\nexample = dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\")\n```\n\n**主要方法：**\n\n| 方法 | 功能 | 示例 |\n|------|------|------|\n| `with_inputs(*keys)` | 标记输入字段 | `.with_inputs(\"question\")` |\n| `inputs()` | 获取仅包含输入字段的新Example | `example.inputs()` |\n| `labels()` | 获取仅包含标签字段的新Example | `example.labels()` |\n| `toDict()` | 递归转换为JSON友好字典 | `example.toDict()` |\n| `copy(**kwargs)` | 创建副本并覆盖指定字段 | `ex.copy(answer=\"5\")` |\n| `without(*keys)` | 返回移除指定字段的副本 | `ex.without(\"source\")` |\n\n资料来源：[example.py:1-250]()\n\n### 特殊类型\n\nDSPy提供了多种适配不同场景的特殊数据类型：\n\n#### History类型\n\n用于会话历史管理，允许在提示中包含多轮对话上下文：\n\n```python\nhistory = dspy.History(messages=[\n    {\"question\": \"法国的首都是什么？\", \"answer\": \"巴黎\"},\n    {\"question\": \"德国的首都是什么？\", \"answer\": \"柏林\"}\n])\n```\n\n资料来源：[history.py:1-60]()\n\n#### Document类型\n\n支持文档格式的数据，可用于检索增强生成（RAG）场景：\n\n```python\ndoc = Document(\n    data=\"水的沸点是100°C\",\n    title=\"物理基础\",\n    context=\"标准大气压下\"\n)\n```\n\n资料来源：[document.py:1-100]()\n\n#### Citation类型\n\n支持引用信息，用于需要标注来源的场景：\n\n```python\nclass Citations(dspy.Signature):\n    documents: list[Document] = dspy.InputField()\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n    citations: list[Citation] = dspy.OutputField()\n```\n\n资料来源：[citation.py:1-80]()\n\n## 回调系统\n\nDSPy提供了灵活的回调机制用于监控和调试程序执行：\n\n```python\nclass LoggingCallback(dspy.Callback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"Module started: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"Module finished: {outputs}\")\n```\n\n| 回调方法 | 触发时机 |\n|----------|----------|\n| `on_module_start()` | Module的forward方法被调用时 |\n| `on_module_end()` | Module的forward方法完成时 |\n| `on_lm_start()` | 语言模型开始生成时 |\n| `on_lm_end()` | 语言模型生成完成时 |\n\n资料来源：[callback.py:1-100]()\n\n## 安装与使用\n\n### 安装方式\n\n```bash\npip install dspy\n```\n\n安装最新开发版本：\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:1-20]()\n\n### 基础使用流程\n\n```mermaid\ngraph LR\n    A[定义Signature] --> B[创建Module]\n    B --> C[配置LM]\n    C --> D[准备Trainset]\n    D --> E[编译优化]\n    E --> F[执行预测]\n```\n\n## Teleprompter优化系统\n\nDSPy的优化器（Teleprompter）负责自动优化程序的提示和参数：\n\n| 优化器 | 用途 |\n|--------|------|\n| `BootstrapFewShotWithRandomSearch` | 小样本引导+随机搜索 |\n| `BootstrapFinetune` | 引导微调 |\n| `BetterTogether` | 组合优化策略 |\n\n`BetterTogether`是一个典型的组合优化器，可同时执行提示优化（p阶段）和权重优化（w阶段）：\n\n```python\noptimizer = BetterTogether(\n    metric=metric,\n    p=GEPA(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric)\n)\n```\n\n资料来源：[bettertogether.py:1-100]()\n\n## 嵌入与检索\n\n### Embedder组件\n\n支持自定义嵌入函数和批量处理：\n\n```python\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\n关键参数：\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `model` | str, Callable | 必填 | 嵌入模型或函数 |\n| `batch_size` | int | 200 | 批处理大小 |\n| `caching` | bool | True | 是否启用缓存 |\n\n资料来源：[embedding.py:1-100]()\n\n### 检索器支持\n\nDSPy支持多种检索器后端，包括Weaviate等向量数据库：\n\n```python\nretriever_model = WeaviateRM(\"my_collection_name\", weaviate_client=client)\ndspy.configure(lm=llm, rm=retriever_model)\n```\n\n## 典型应用模式\n\n### 问答系统\n\n```python\nclass QAModule(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nqa = QAModule()\nqa.set_lm(lm)\nresult = qa(question=\"什么是DSPy?\")\n```\n\n### 带推理链的问答\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"1+1等于几？\")\n```\n\n### 检索增强生成\n\n```python\nretrieve = dspy.Retrieve(k=3)\npassages = retrieve(\"机器学习基础\").passages\n```\n\n## 开发环境配置\n\nDSPy要求Python 3.10或更高版本。使用`uv`进行环境管理：\n\n```bash\nuv venv --python 3.10\nuv sync --extra dev\n```\n\n运行测试：\n\n```bash\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:1-100]()\n\n## 相关研究\n\nDSPy基于以下核心研究论文：\n\n- **[2025年7月]** GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning\n- **[2024年6月]** Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs\n- **[2023年10月]** DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines\n\n## 总结\n\nDSPy通过声明式编程范式和自动优化机制，大大简化了基于语言模型应用的开发流程。其核心组件包括：\n\n- **Module系统**：提供程序结构的统一抽象\n- **Signature机制**：声明式定义输入输出语义\n- **Teleprompter优化器**：自动化提示和参数优化\n- **Adapter适配层**：支持多种语言模型和工具集成\n\n这套架构使得开发者可以专注于业务逻辑，而将提示工程的具体实现交给DSPy的优化系统自动处理。\n\n---\n\n<a id='page-installation'></a>\n\n## 安装与快速开始\n\n### 相关页面\n\n相关主题：[DSPy概述](#page-overview), [语言模型客户端](#page-lm-clients)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/stanfordnlp/dspy/blob/main/CONTRIBUTING.md)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/clients/embedding.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/embedding.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# 安装与快速开始\n\n## 概述\n\nDSPy（Declarative Self-Improving Language Model Programs）是一个用于编译声明式语言模型调用的框架，使语言模型程序能够自我改进。本节介绍如何安装 DSPy 框架以及如何快速上手使用该框架进行开发。\n\nDSPy 的设计理念是将语言模型调用声明化，通过优化器和签名系统自动优化提示和演示，从而提升程序性能。\n\n## 环境要求\n\n| 要求项 | 最低版本 | 说明 |\n|--------|----------|------|\n| Python | 3.10+ | 必须使用 Python 3.10 或更高版本 |\n| 包管理器 | pip/uv | 用于安装 DSPy 包 |\n\n资料来源：[CONTRIBUTING.md:1]()\n\n## 安装方式\n\n### 使用 pip 安装（推荐）\n\n通过 pip 直接安装稳定版本：\n\n```bash\npip install dspy\n```\n\n资料来源：[README.md:7]()\n\n### 安装最新开发版本\n\n如需安装最新的开发版本（从 main 分支），可使用以下命令：\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:12]()\n\n### 开发环境安装\n\n如需参与 DSPy 开发，推荐使用 uv 或 conda 进行环境管理。\n\n#### 使用 uv 设置开发环境\n\n```shell\ngit clone {url-to-your-fork}\ncd dspy\nuv sync\n```\n\n验证安装是否成功：\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:20-45]()\n\n#### 使用 conda 设置开发环境\n\n```shell\nconda create -n dspy-dev python=3.10\nconda activate dspy-dev\npip install -e \".[dev]\"\n```\n\n验证安装：\n\n```shell\npytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:47-56]()\n\n## 快速开始\n\n### 基本概念\n\n在使用 DSPy 之前，需要了解以下核心概念：\n\n| 概念 | 类名 | 用途 |\n|------|------|------|\n| 示例 | `dspy.Example` | 表示训练或评估数据，包含输入字段和标签字段 |\n| 模块 | `dspy.Module` | 自定义语言模型程序的基类 |\n| 预测器 | `dspy.Predict` | 执行语言模型调用的核心组件 |\n| 语言模型 | `dspy.LM` | 与各种语言模型提供商交互的接口 |\n\n### 创建 Example 对象\n\n`Example` 是 DSPy 中表示数据的基本单元。可以通过关键字参数创建：\n\n```python\nimport dspy\n\n# 创建包含问题答案的示例\nexample = dspy.Example(question=\"1+1 等于多少？\", answer=\"2\")\n```\n\n资料来源：[dspy/primitives/example.py:31-32]()\n\n### 标记输入字段\n\n使用 `with_inputs()` 方法标记哪些字段是输入字段：\n\n```python\nexample = dspy.Example(\n    question=\"今天天气如何？\",\n    answer=\"晴天\"\n).with_inputs(\"question\")\n```\n\n标记后，可以使用方法分离输入和标签：\n\n```python\nexample.inputs().toDict()  # {'question': '今天天气如何？'}\nexample.labels().toDict()  # {'answer': '晴天'}\n```\n\n资料来源：[dspy/primitives/example.py:87-97]()\n\n### 定义模块和预测器\n\n创建一个简单的问答模块：\n\n```python\nclass SimpleQA(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n### 设置语言模型\n\n使用 `set_lm()` 方法为模块设置语言模型：\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nqa = SimpleQA()\nqa.set_lm(lm)\n```\n\n资料来源：[dspy/primitives/module.py:67-78]()\n\n### 执行推理\n\n设置好语言模型后，可以执行推理：\n\n```python\nresult = qa(question=\"法国的首都是什么？\")\nprint(result.answer)\n```\n\n### 使用回调监控执行\n\nDSPy 支持通过回调函数监控模块和语言模型的调用：\n\n```python\nfrom dspy.utils.callback import BaseCallback\n\nclass LoggingCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"模块调用: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"模块输出: {outputs}\")\n\n# 在语言模型中使用回调\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n资料来源：[dspy/utils/callback.py:1-60]()\n\n### 构建训练集\n\n将多个 Example 组合成训练集用于优化：\n\n```python\ntrainset = [\n    dspy.Example(question=\"2+2 等于多少？\", answer=\"4\").with_inputs(\"question\"),\n    dspy.Example(question=\"3+3 等于多少？\", answer=\"6\").with_inputs(\"question\"),\n]\n```\n\n资料来源：[dspy/primitives/example.py:98-102]()\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[创建 Example 数据] --> B[定义 Module]\n    B --> C[设置 Language Model]\n    C --> D[执行推理]\n    D --> E{是否需要优化?}\n    E -->|是| F[创建训练集和验证集]\n    F --> G[选择 Teleprompter 优化器]\n    G --> H[编译优化程序]\n    H --> I[使用优化后的程序]\n    E -->|否| I\n    I --> J[最终部署使用]\n```\n\n## 下一步\n\n- 了解更多 DSPy 核心概念，请参阅签名（Signature）文档\n- 学习高级优化技术，请参阅 Teleprompter 相关文档\n- 了解支持的语言模型提供商，请参阅 LM 配置文档\n\n## 相关文档\n\n| 文档 | 说明 |\n|------|------|\n| [DSPy Docs](https://dspy.ai) | 官方完整文档 |\n| [GEPA](https://arxiv.org/abs/2507.19457) | 反思式提示进化算法论文 |\n| [DSPy 论文](https://arxiv.org/abs/2310.03714) | 框架核心论文 |\n\n---\n\n<a id='page-signatures'></a>\n\n## 签名（Signatures）\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/signatures/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/__init__.py)\n- [dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n- [dspy/signatures/field.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/field.py)\n- [dspy/signatures/utils.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/utils.py)\n</details>\n\n# 签名（Signatures）\n\n## 概述\n\n签名（Signature）是 DSPy 框架中定义模块输入输出接口的核心抽象。一个签名描述了语言模型程序的输入字段（InputField）和输出字段（OutputField），以及附加的指令说明。签名作为 DSPy 程序的结构化蓝图，定义了数据如何流入和流出各个模块。\n\n签名的主要作用包括：\n\n- **接口定义**：明确指定模块的输入和输出字段\n- **提示词构建**：自动生成结构化的提示词给语言模型\n- **数据验证**：确保输入输出数据的结构正确性\n- **元编程支持**：支持签名的动态组合、修改和转换\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n## 核心概念\n\n### 字段类型\n\nDSPy 提供两种基本字段类型来定义签名中的数据：\n\n| 字段类型 | 用途 | 说明 |\n|---------|------|------|\n| `InputField` | 输入字段 | 描述语言模型需要接收的输入数据 |\n| `OutputField` | 输出字段 | 描述语言模型需要生成的输出数据 |\n\n每个字段都可以通过 `desc` 参数添加描述文本，这些描述会被纳入提示词中，帮助语言模型理解字段的含义。\n\n资料来源：[dspy/signatures/field.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/field.py)\n\n### 签名结构\n\n```mermaid\ngraph TD\n    A[签名 Signature] --> B[instructions 说明]\n    A --> C[fields 字段集合]\n    C --> D[InputField 输入字段]\n    C --> E[OutputField 输出字段]\n    D --> F[field_name 字段名]\n    D --> G[annotation 类型注解]\n    D --> H[desc 描述文本]\n    E --> F2[field_name 字段名]\n    E --> G2[annotation 类型注解]\n    E --> H2[desc 描述文本]\n```\n\n## Signature 类 API\n\n### 主要方法\n\n| 方法名 | 用途 | 返回类型 |\n|-------|------|---------|\n| `with_instructions(instructions)` | 创建带新指令的签名副本 | `type[Signature]` |\n| `with_updated_fields(name, **kwargs)` | 更新指定字段的属性 | `type[Signature]` |\n| `prepend(name, field, type_=None)` | 在签名开头插入新字段 | `type[Signature]` |\n| `append(name, field, type_=None)` | 在签名末尾追加新字段 | `type[Signature]` |\n| `insert(pos, name, field, type_=None)` | 在指定位置插入字段 | `type[Signature]` |\n| `delete(name)` | 删除指定字段 | `type[Signature]` |\n\n资料来源：[dspy/signatures/signature.py:1-200](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### with_instructions 方法\n\n创建具有新指令文本的签名类副本：\n\n```python\nclass MySig(dspy.Signature):\n    input_text: str = dspy.InputField(desc=\"Input text\")\n    output_text: str = dspy.OutputField(desc=\"Output text\")\n\nNewSig = MySig.with_instructions(\"Translate to French.\")\n# NewSig.instructions == \"Translate to French.\"\n```\n\n此方法不会修改原签名，而是返回一个新的签名类。\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### with_updated_fields 方法\n\n更新指定字段的元数据属性：\n\n```python\nclass MySig(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nUpdatedSig = MySig.with_updated_fields(\n    \"answer\",\n    desc=\"The final answer\",\n    prefix=\"Result: \"\n)\n```\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n### 字段操作方法\n\n```mermaid\ngraph LR\n    A[原 Signature] -->|prepend| B[在开头插入]\n    A -->|append| C[在末尾追加]\n    A -->|insert| D[在指定位置]\n    A -->|delete| E[删除字段]\n    B --> F[new Signature]\n    C --> F\n    D --> F\n    E --> F\n```\n\n**prepend 方法** - 在输入字段部分的开头插入新字段：\n\n```python\nNewSig = MySig.prepend(\"context\", dspy.InputField(desc=\"Context for translation\"))\n```\n\n**append 方法** - 在输出字段部分的末尾追加新字段：\n\n```python\nNewSig = MySig.append(\"confidence\", dspy.OutputField(desc=\"Translation confidence\"))\n```\n\n**delete 方法** - 返回移除指定字段后的新签名：\n\n```python\nNewSig = MySig.delete(\"unnecessary_field\")\n```\n\n资料来源：[dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n\n## make_signature 函数\n\n除了使用类语法定义签名外，DSPy 还提供了 `make_signature` 工具函数，支持多种签名定义格式：\n\n### 函数签名\n\n```python\ndef make_signature(\n    signature: str | dict,\n    *,\n    fresh_fields: bool = True,\n    check_args: bool = True,\n    custom_types: dict[str, type] | None = None,\n) -> dict[str, FieldInfo]:\n```\n\n### 支持的格式\n\n| 格式类型 | 示例 | 说明 |\n|---------|------|------|\n| 字符串格式 | `\"question -> answer\"` | 使用 `->` 分隔输入输出 |\n| 字典格式 | `{\"question\": str, \"answer\": str}` | 键值对形式 |\n| 元组格式 | `{\"q\": (str, InputField())}` | 指定类型和字段 |\n\n```python\n# 字符串格式\nsig1 = make_signature(\"question, context -> answer\")\n\n# 字典格式\nsig2 = make_signature({\n    \"question\": (str, InputField()),\n    \"answer\": (str, OutputField())\n})\n\n# 使用自定义类型\nclass MyType:\n    pass\n\nsig3 = make_signature(\n    \"input: MyType -> output\",\n    custom_types={\"MyType\": MyType}\n)\n```\n\n资料来源：[dspy/signatures/utils.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/utils.py)\n\n## 使用示例\n\n### 基本用法\n\n```python\nimport dspy\n\nclass RAGSignature(dspy.Signature):\n    \"\"\"回答基于给定上下文的问题\"\"\"\n    context: str = dspy.InputField(desc=\"用于回答问题的上下文信息\")\n    question: str = dspy.InputField(desc=\"需要回答的问题\")\n    answer: str = dspy.OutputField(desc=\"基于上下文得出的答案\")\n\n# 使用签名创建预测器\npredict = dspy.Predict(RAGSignature)\nresult = predict(context=\"巴黎是法国的首都。\", question=\"法国的首都是哪里？\")\nprint(result.answer)  # 输出生成的答案\n```\n\n### 与 Example 类集成\n\n签名与 `Example` 类紧密配合使用：\n\n```python\nimport dspy\n\n# 创建带输入标记的示例\nexample = dspy.Example(\n    question=\"What is 2+2?\",\n    answer=\"4\"\n).with_inputs(\"question\")\n\n# example.inputs() 返回只包含 question 的示例\n# example.labels() 返回只包含 answer 的示例\n```\n\n资料来源：[dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n\n### 在模块中使用\n\n签名可以被 DSPy 模块继承和组合：\n\n```python\nimport dspy\n\nclass MyModule(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n    \n    def forward(self, question: str) -> dspy.Prediction:\n        return self.qa(question=question)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 高级用法\n\n### 动态签名构建\n\n通过组合方法动态构建复杂签名：\n\n```python\nbase_sig = dspy.make_signature(\"input_text -> output_text\")\n\n# 链式调用添加字段\nenhanced_sig = (\n    base_sig\n    .prepend(\"system_prompt\", dspy.InputField(desc=\"系统提示词\"))\n    .append(\"confidence\", dspy.OutputField(desc=\"置信度\"))\n)\n\nclass EnhancedPredictor(dspy.Signature):\n    pass\n\nEnhancedPredictor.__signature__ = enhanced_sig\n```\n\n### 签名字段更新\n\n修改现有签名的字段描述：\n\n```python\noriginal = dspy.make_signature(\"query -> result\")\n\n# 更新字段描述\nrefined = original.with_updated_fields(\n    \"query\",\n    desc=\"搜索查询词\",\n    prefix=\"查询: \"\n)\nrefined = refined.with_updated_fields(\n    \"result\",\n    desc=\"搜索结果\",\n    prefix=\"结果: \"\n)\n```\n\n## 最佳实践\n\n### 1. 清晰的字段描述\n\n为每个字段提供准确的 `desc` 描述，这会直接影响语言模型的理解和输出质量：\n\n```python\nclass GoodSignature(dspy.Signature):\n    email_content: str = dspy.InputField(\n        desc=\"完整的电子邮件内容，包括发件人、主题和正文\"\n    )\n    sentiment: str = dspy.OutputField(\n        desc=\"情感分类结果，必须是 'positive'、'negative' 或 'neutral' 之一\"\n    )\n```\n\n### 2. 类型注解\n\n使用适当的类型注解可以增强代码可读性和 IDE 支持：\n\n```python\nclass TypedSignature(dspy.Signature):\n    user_id: int = dspy.InputField(desc=\"用户唯一标识符\")\n    query: str = dspy.InputField(desc=\"用户查询文本\")\n    response: str = dspy.OutputField(desc=\"生成的响应文本\")\n    confidence: float = dspy.OutputField(desc=\"响应置信度，范围 0-1\")\n```\n\n### 3. 签名组合策略\n\n当构建复杂流水线时，考虑按功能拆分签名：\n\n```mermaid\ngraph TD\n    subgraph 预处理阶段\n        A1[TextInput] --> A2[PreprocessedText]\n    end\n    subgraph 处理阶段\n        A2 --> B1[AnalyzeText]\n        B1 --> B2[AnalysisResult]\n    end\n    subgraph 生成阶段\n        B2 --> C1[GenerateResponse]\n        C1 --> C2[FinalOutput]\n    end\n```\n\n## 相关模块\n\n| 模块 | 路径 | 用途 |\n|-----|------|------|\n| signatures/signature.py | `dspy/signatures/signature.py` | Signature 类定义 |\n| signatures/field.py | `dspy/signatures/field.py` | InputField 和 OutputField |\n| signatures/utils.py | `dspy/signatures/utils.py` | make_signature 工具函数 |\n| signatures/\\_signature_do_not_use_directly.py | `dspy/signatures/` | 内部实现 |\n\n## 参考链接\n\n- [DSPy 官方文档](https://dspy.ai)\n- [签名模块源码](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/)\n- [Example 原语文档](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n\n---\n\n<a id='page-modules'></a>\n\n## 内置模块参考\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [优化器详解](#page-optimizers), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/predict/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/__init__.py)\n- [dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n- [dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n- [dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n- [dspy/predict/program_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/program_of_thought.py)\n- [dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n- [dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n- [dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n- [dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n- [dspy/predict/code_act.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/code_act.py)\n- [dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n</details>\n\n# 内置模块参考\n\n## 概述\n\nDSPy 内置模块是框架提供的核心组件，用于构建和执行语言模型程序。这些模块封装了常见的提示词工程模式，包括思维链推理、工具调用、并行处理等，使开发者能够以声明式的方式组合复杂的 LLM 应用。\n\n内置模块均继承自 `dspy.Module` 基类，提供了统一的接口和行为规范。每个模块都可以通过签名（Signature）定义输入输出字段，并支持与优化器（Teleprompter）配合使用进行自动优化。\n\n资料来源：[dspy/primitives/module.py:1-50](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 模块体系架构\n\nDSPy 的内置模块遵循分层设计架构，核心模块为 `Predict`，其他高级模块在其基础上组合扩展。\n\n```mermaid\ngraph TD\n    A[dspy.Module 基类] --> B[Predict 基础模块]\n    B --> C1[ChainOfThought 思维链]\n    B --> C2[Parallel 并行预测]\n    B --> C3[Retry 重试机制]\n    B --> C4[BestOfN N选一]\n    C1 --> D1[ReAct 推理+行动]\n    C1 --> D2[ProgramOfThought 程序思维]\n    C1 --> D3[MultiChainComparison 多链比较]\n    D1 --> E[CodeAct 代码行动]\n    B --> F[Refine 细化迭代]\n    B --> G[RLM 推理语言模型]\n```\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n## 模块基类\n\n`dspy.Module` 是所有内置模块的基类，提供了通用功能支持。\n\n### 核心方法\n\n| 方法名 | 说明 | 返回值 |\n|--------|------|--------|\n| `named_predictors()` | 返回所有命名预测器元组列表 | `list[tuple[str, Predict]]` |\n| `predictors()` | 返回所有 Predict 实例 | `list[Predict]` |\n| `set_lm(lm)` | 为所有预测器设置语言模型 | `None` |\n| `get_lm()` | 获取模块使用的语言模型 | `LM` 实例 |\n| `map_named_predictors(func)` | 对所有预测器应用转换函数 | `self` |\n| `inspect_history(n)` | 查看最近 n 次 LM 调用历史 | `None` |\n\n### 设置语言模型\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = dspy.Predict(\"question -> answer\")\nprogram.set_lm(lm)\n```\n\n资料来源：[dspy/primitives/module.py:45-75](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n## 基础模块\n\n### Predict\n\n`Predict` 是 DSPy 最核心的模块，用于基于签名执行语言模型调用。\n\n#### 基本用法\n\n```python\nimport dspy\n\n# 简单签名\npredict = dspy.Predict(\"question -> answer\")\nresult = predict(question=\"What is 1+1?\")\n\n# 使用类签名\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\npredict = dspy.Predict(MySignature)\n```\n\n#### 初始化参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `signature` | `str \\| Signature` | 输入输出字段定义 | 必填 |\n| `lm` | `LM \\| None` | 语言模型实例 | `None` |\n| `remote_cache` | `dict \\| None` | 远程缓存字典 | `None` |\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n## 推理模块\n\n### ChainOfThought（思维链）\n\n`ChainOfThought` 在 Predict 基础上自动加入推理步骤，要求模型先输出思考过程再给出最终答案。\n\n#### 工作原理\n\n1. 修改签名，在输出字段前添加 `reasoning` 字段\n2. 生成提示词引导模型进行逐步推理\n3. 提取并返回最终答案\n\n```python\nimport dspy\n\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"What is the capital of France?\")\nprint(result.reasoning)  # 中间推理过程\nprint(result.answer)     # 最终答案\n```\n\n#### 继承链\n\n```\nModule -> Predict -> ChainOfThought\n```\n\n资料来源：[dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n\n### MultiChainComparison（多链比较）\n\n`MultiChainComparison` 允许多个推理链并行执行，并对结果进行比较以选出最优答案。\n\n#### 工作流程\n\n```mermaid\ngraph TD\n    A[输入问题] --> B1[推理链1]\n    A --> B2[推理链2]\n    A --> B3[推理链3]\n    B1 --> C[比较结果]\n    B2 --> C\n    B3 --> C\n    C --> D[最优答案]\n```\n\n```python\nimport dspy\n\nmcc = dspy.MultiChainComparison(n=3)\nresult = mcc(question=\"Explain quantum entanglement\")\n```\n\n资料来源：[dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n\n## 工具调用模块\n\n### ReAct（推理与行动）\n\n`ReAct` 结合了推理（Reasoning）和行动（Acting）能力，支持模型使用工具与环境交互。\n\n#### 特性\n\n- 支持定义自定义工具\n- 自动管理工具调用循环\n- 推理过程透明可见\n\n```python\nimport dspy\n\nreact = dspy.ReAct(\"question -> answer\")\nresult = react(question=\"最新科技新闻有哪些？\")\n```\n\n资料来源：[dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n\n### CodeAct（代码行动）\n\n`CodeAct` 扩展了 ReAct 模式，专门用于生成和执行 Python 代码来解决复杂问题。\n\n```python\nimport dspy\n\ncode_act = dspy.CodeAct(\"problem -> solution\")\nresult = code_act(problem=\"计算斐波那契数列前20项的和\")\n```\n\n#### 执行流程\n\n```mermaid\ngraph LR\n    A[问题] --> B[生成代码]\n    B --> C[执行代码]\n    C --> D{结果正确?}\n    D -->|是| E[返回结果]\n    D -->|否| B\n```\n\n资料来源：[dspy/predict/code_act.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/code_act.py)\n\n## 迭代优化模块\n\n### Refine（细化迭代）\n\n`Refine` 通过迭代方式逐步细化答案，每次迭代基于前一次的结果进行调整。\n\n```python\nimport dspy\n\nrefine = dspy.Refine(\"question -> answer\", max_iters=3)\nresult = refine(question=\"解释机器学习原理\")\n```\n\n#### 迭代过程\n\n1. 初始化：生成初始答案\n2. 评估：检查当前答案质量\n3. 细化：根据反馈更新答案\n4. 重复：直到满足条件或达到最大迭代次数\n\n资料来源：[dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n\n### Retry（重试机制）\n\n`Retry` 在预测失败时自动重试，并可选择性地向模型提供错误信息以引导修正。\n\n```python\nimport dspy\n\nretry_predict = dspy.Retry(\"question -> answer\")\nresult = retry_predict(question=\"What is 1+1?\")\n```\n\n#### 重试策略\n\n| 参数 | 说明 | 默认值 |\n|------|------|--------|\n| `max_retries` | 最大重试次数 | `3` |\n| `on_error` | 错误处理回调 | 内置格式化 |\n\n资料来源：[dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n\n## 并行与选择模块\n\n### Parallel（并行预测）\n\n`Parallel` 允许同时执行多个预测器，适合需要并行处理多种推理路径的场景。\n\n```python\nimport dspy\n\nparallel = dspy.Parallel(\n    dspy.Predict(\"input -> output_a\"),\n    dspy.Predict(\"input -> output_b\"),\n    dspy.ChainOfThought(\"input -> output_c\")\n)\nresults = parallel(input=\"some text\")\n```\n\n资料来源：[dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n\n### BestOfN（N选一）\n\n`BestOfN` 生成 N 个候选答案，并使用指定的选择标准选出最优结果。\n\n```python\nimport dspy\n\nbon = dspy.BestOfN(\"question -> answer\", n=5)\nresult = bon(question=\"最佳编程语言是什么？\")\n```\n\n#### 选择机制\n\n```mermaid\ngraph TD\n    A[生成N个候选] --> B[应用评分函数]\n    B --> C[排序候选结果]\n    C --> D[返回最优答案]\n```\n\n资料来源：[dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n\n## Program of Thought\n\n`ProgramOfThought` 采用代码作为中间推理表示，通过生成和执行 Python 代码片段来解决问题。\n\n```python\nimport dspy\n\npot = dspy.ProgramOfThought(\"problem -> answer\")\nresult = pot(problem=\"求解微分方程 dy/dx = 2x\")\n```\n\n#### 与 CodeAct 的区别\n\n| 特性 | ProgramOfThought | CodeAct |\n|------|------------------|---------|\n| 交互方式 | 生成代码片段 | 生成并执行完整代码 |\n| 执行环境 | 隔离的解释器 | 完整 Python 环境 |\n| 适用场景 | 数学计算、逻辑推理 | 复杂系统操作 |\n\n资料来源：[dspy/predict/program_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/program_of_thought.py)\n\n## RLM（推理语言模型）\n\n`RLM` 是底层的语言模型封装模块，提供对各种 LLM 提供商的统一接口。\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nresult = lm(question=\"What is the meaning of life?\")\n```\n\n#### 支持的模型格式\n\n- `provider/model-name`（如 `openai/gpt-4o-mini`）\n- 支持的提供商包括 OpenAI、Anthropic、Google、本地模型等\n\n资料来源：[dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n\n## 模块导出清单\n\n所有内置模块可通过 `dspy.predict` 命名空间访问：\n\n| 模块 | 导入路径 | 说明 |\n|------|----------|------|\n| `Predict` | `dspy.Predict` | 基础预测模块 |\n| `ChainOfThought` | `dspy.ChainOfThought` | 思维链推理 |\n| `CoT` | `dspy.CoT` | ChainOfThought 别名 |\n| `ReAct` | `dspy.ReAct` | 推理+行动 |\n| `ProgramOfThought` | `dspy.ProgramOfThought` | 程序思维 |\n| `MultiChainComparison` | `dspy.MultiChainComparison` | 多链比较 |\n| `Parallel` | `dspy.Parallel` | 并行预测 |\n| `Refine` | `dspy.Refine` | 迭代细化 |\n| `BestOfN` | `dspy.BestOfN` | N选一 |\n| `CodeAct` | `dspy.CodeAct` | 代码行动 |\n| `Retry` | `dspy.Retry` | 重试机制 |\n\n资料来源：[dspy/predict/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/__init__.py)\n\n## 组合使用示例\n\n### 构建复杂管道\n\n```python\nimport dspy\n\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.cot = dspy.ChainOfThought(\"question -> reasoning, answer\")\n        self.refine = dspy.Refine(\"initial_answer -> refined_answer\")\n        self.verify = dspy.Predict(\"question, answer -> is_correct\")\n    \n    def forward(self, question):\n        cot_result = self.cot(question=question)\n        refined = self.refine(initial_answer=cot_result.answer)\n        verification = self.verify(question=question, answer=refined.refined_answer)\n        return {\n            \"reasoning\": cot_result.reasoning,\n            \"answer\": refined.refined_answer,\n            \"verified\": verification.is_correct\n        }\n\nprogram = MyProgram()\nresult = program(question=\"What is the square root of 144?\")\n```\n\n### 与优化器结合\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\n# 使用内置模块构建程序\nstudent = dspy.ChainOfThought(\"question -> answer\")\n\n# 编译优化\noptimizer = BootstrapFewShot(metric=your_metric)\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n## 最佳实践\n\n### 1. 选择合适的模块\n\n| 场景 | 推荐模块 |\n|------|----------|\n| 简单问答 | `Predict` |\n| 需要推理过程 | `ChainOfThought` |\n| 多角度分析 | `MultiChainComparison` |\n| 需要工具交互 | `ReAct` |\n| 代码生成执行 | `CodeAct` / `ProgramOfThought` |\n| 提高可靠性 | `Retry` / `BestOfN` |\n\n### 2. 性能考虑\n\n- `Parallel` 适用于可并行的独立任务\n- `BestOfN` 会增加 N 倍的 API 调用，应根据延迟要求选择\n- `Refine` 的 `max_iters` 参数需权衡质量与成本\n\n### 3. 调试技巧\n\n```python\n# 检查模块的 LM 调用历史\nprogram.inspect_history(n=5)\n\n# 查看当前使用的语言模型\nlm = program.get_lm()\n\n# 批量替换预测器\nprogram.map_named_predictors(lambda p: dspy.Retry(p.signature))\n```\n\n资料来源：[dspy/primitives/module.py:90-120](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n<a id='page-primitives'></a>\n\n## 原语与数据结构\n\n### 相关页面\n\n相关主题：[签名（Signatures）](#page-signatures), [内置模块参考](#page-modules), [评估与指标](#page-evaluation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/primitives/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/__init__.py)\n- [dspy/primitives/example.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/example.py)\n- [dspy/primitives/prediction.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/prediction.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/python_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/python_interpreter.py)\n- [dspy/primitives/code_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/code_interpreter.py)\n- [dspy/primitives/repl_types.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/repl_types.py)\n</details>\n\n# 原语与数据结构\n\n## 概述\n\nDSPy 框架的**原语（Primitives）与数据结构**构成了整个框架的核心抽象层。这些基础组件定义了如何表示数据、执行程序、管理模块间的通信，以及实现代码的沙箱执行能力。\n\nDSPy 的原语系统主要包括以下几个核心组件：\n\n| 组件 | 文件路径 | 职责 |\n|------|----------|------|\n| `Example` | `dspy/primitives/example.py` | 数据样本表示与输入/输出字段管理 |\n| `Prediction` | `dspy/primitives/prediction.py` | 程序执行结果的容器 |\n| `Module` | `dspy/primitives/module.py` | 所有 DSPy 程序的基类 |\n| `PythonInterpreter` | `dspy/primitives/python_interpreter.py` | Python 代码的安全执行环境 |\n| `CodeInterpreter` | `dspy/primitives/code_interpreter.py` | 代码解释器与 REPL 支持 |\n\n资料来源：[dspy/primitives/__init__.py]()\n\n## 核心数据结构\n\n### Example 类\n\n`Example` 是 DSPy 中用于表示数据样本的基础数据结构，类似于字典但提供了更丰富的语义支持。\n\n#### 基本功能\n\n```python\nimport dspy\n\n# 创建 Example 实例\nexample = dspy.Example(question=\"巴黎是哪国的首都？\", answer=\"法国\").with_inputs(\"question\")\n\n# 访问字段\nprint(example.question)  # 输出: 巴黎是哪国的首都？\nprint(example.answer)    # 输出: 法国\n```\n\n#### 字段分类系统\n\nExample 类通过 `with_inputs()` 方法将字段分为两类：\n\n- **输入字段（Inputs）**：程序执行时需要提供的外部数据\n- **标签字段（Labels）**：期望的输出结果，用于评估和训练\n\n```python\n# 使用 inputs() 和 labels() 方法分离字段\ninput_fields = example.inputs()    # 只包含 question\nlabel_fields = example.labels()    # 只包含 answer\n```\n\n资料来源：[dspy/primitives/example.py:1-200]()\n\n#### 常用方法\n\n| 方法 | 功能 | 返回类型 |\n|------|------|----------|\n| `with_inputs(*keys)` | 标记输入字段 | `Example` |\n| `inputs()` | 获取输入字段子集 | `Example` |\n| `labels()` | 获取标签字段子集 | `Example` |\n| `copy(**kwargs)` | 创建带修改的副本 | `Example` |\n| `without(*keys)` | 移除指定字段 | `Example` |\n| `toDict()` | 转换为字典格式 | `dict` |\n| `get(key, default)` | 安全获取字段值 | 任意类型 |\n| `keys()` / `values()` / `items()` | 字典式访问 | `list` |\n\n#### 序列化支持\n\n`toDict()` 方法支持递归序列化，能够处理嵌套的 Example 对象、Pydantic 模型、列表和字典，确保输出为 JSON 友好的格式：\n\n```python\ndef convert_to_serializable(value):\n    if hasattr(value, \"toDict\"):\n        return value.toDict()\n    elif isinstance(value, BaseModel):\n        return value.model_dump()\n    elif isinstance(value, list):\n        return [convert_to_serializable(item) for item in value]\n    elif isinstance(value, dict):\n        return {k: convert_to_serializable(v) for k, v in value.items()}\n```\n\n资料来源：[dspy/primitives/example.py:80-120]()\n\n---\n\n### Prediction 类\n\n`Prediction` 是程序执行后产生的结果容器，封装了模型的实际输出。\n\n#### 与 Example 的区别\n\n| 特性 | Example | Prediction |\n|------|---------|------------|\n| 用途 | 表示训练/测试数据 | 表示程序输出 |\n| 字段来源 | 人工标注或外部数据 | 模型推理结果 |\n| 典型使用 | 构造 trainset、valset | 接收 `cot()` 等模块返回值 |\n\n```python\n# Prediction 通常由 DSPy 模块自动生成\npred = dspy.Prediction(answer=\"2\")\n```\n\n资料来源：[dspy/primitives/prediction.py]()\n\n---\n\n## Module 基类\n\n`Module` 是所有 DSPy 程序的基类，提供了程序结构管理、语言模型设置等核心功能。\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[Predict]\n    A --> C[ChainOfThought]\n    A --> D[Program]\n    A --> E[自定义模块]\n    \n    F[named_predictors] --> G[获取所有 Predict 实例]\n    H[set_lm] --> I[递归设置 LM]\n```\n\n#### 核心方法\n\n| 方法 | 功能说明 |\n|------|----------|\n| `named_predictors()` | 返回所有 Predict 模块的 (名称, 实例) 元组列表 |\n| `predictors()` | 返回所有 Predict 实例的列表 |\n| `set_lm(lm)` | 递归为所有 Predict 模块设置语言模型 |\n| `get_lm()` | 获取当前使用的语言模型 |\n\n```python\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.qa = dspy.Predict(\"question -> answer\")\n        self.summarize = dspy.Predict(\"text -> summary\")\n    \n    def forward(self, question):\n        return self.qa(question=question)\n\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(f\"模块: {name}, 类型: {type(predictor)}\")\n```\n\n资料来源：[dspy/primitives/module.py:1-100]()\n\n---\n\n## 代码执行原语\n\n### PythonInterpreter\n\n`PythonInterpreter` 提供了一个安全的 Python 代码执行环境，用于在 DSPy 管道中动态执行生成的代码。\n\n```mermaid\ngraph LR\n    A[LLM 生成代码] --> B[PythonInterpreter]\n    B --> C[受限执行环境]\n    C --> D[结果提取]\n    D --> E[返回给下游模块]\n```\n\n#### 设计原则\n\n- **沙箱隔离**：限制可访问的内置函数和模块\n- **安全执行**：防止危险操作的代码执行\n- **结果捕获**：自动提取代码执行的输出\n\n资料来源：[dspy/primitives/python_interpreter.py]()\n\n---\n\n### CodeInterpreter\n\n`CodeInterpreter` 是更高级的代码解释器，支持 REPL（Read-Eval-Print Loop）模式的交互执行。\n\n#### REPLTypes\n\nREPL 相关的类型定义位于 `repl_types.py`，定义了代码块、超时控制等执行上下文：\n\n```python\n# 典型使用场景\nfrom dspy.primitives.repl_types import CodeBlock, REPLContext\n\ncontext = REPLContext(timeout=30)\nresult = interpreter.execute(code_block, context=context)\n```\n\n资料来源：[dspy/primitives/code_interpreter.py]()\n资料来源：[dspy/primitives/repl_types.py]()\n\n---\n\n## 数据流架构\n\n```mermaid\ngraph TD\n    subgraph \"数据输入层\"\n        A1[Example 数据集]\n        A2[用户输入]\n    end\n    \n    subgraph \"程序执行层\"\n        B1[Module.forward]\n        B2[Predict 模块]\n        B3[签名验证]\n    end\n    \n    subgraph \"输出层\"\n        C1[Prediction]\n        C2[Example.labels]\n    end\n    \n    subgraph \"优化层\"\n        D1[Teleprompter]\n        D2[Metrics]\n    end\n    \n    A1 --> B1\n    A2 --> B1\n    B1 --> B2\n    B2 --> B3\n    B3 --> C1\n    A1 --> D1\n    C1 --> D2\n    D1 --> B2\n```\n\n---\n\n## 最佳实践\n\n### 构造 Example 的规范\n\n```python\n# ✅ 推荐：显式指定输入字段\ntrain_example = dspy.Example(\n    question=\"1+1 等于多少？\",\n    answer=\"2\"\n).with_inputs(\"question\")\n\n# ✅ 副本创建用于数据增强\naugmented = train_example.copy(answer=\"答案是 2\")\n\n# ✅ 使用 base 参数高效构建\nbase_record = {\"question\": \"旧问题\", \"answer\": \"旧答案\"}\nnew_example = dspy.Example(base=base_record, question=\"新问题\").with_inputs(\"question\")\n```\n\n### 模块继承模式\n\n```python\nclass MyPipeline(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        # 初始化所有 Predict 子模块\n        self.retrieve = dspy.ColBERTv2(k=3)\n        self.answer = dspy.Predict(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.answer(context=context, question=question)\n```\n\n---\n\n## 模块导出清单\n\n`dspy/primitives/__init__.py` 负责导出以下核心组件：\n\n| 导出名称 | 来源模块 | 用途 |\n|----------|----------|------|\n| `Example` | `example.py` | 数据样本管理 |\n| `Prediction` | `prediction.py` | 结果封装 |\n| `Module` | `module.py` | 程序基类 |\n| `PythonInterpreter` | `python_interpreter.py` | 代码执行 |\n| `CodeInterpreter` | `code_interpreter.py` | 交互式解释器 |\n\n资料来源：[dspy/primitives/__init__.py]()\n\n---\n\n## 相关文档\n\n- [签名系统（Signatures）](../signatures/signature.md) - 了解如何定义模块的输入输出规范\n- [预测模块（Predict）](../predict/predict.md) - 核心预测组件的使用方法\n- [评估系统（Evaluate）](../learn/evaluation/evaluation.md) - 使用 Example 和 Metrics 进行程序评估\n\n---\n\n<a id='page-optimizers'></a>\n\n## 优化器详解\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [评估与指标](#page-evaluation), [签名（Signatures）](#page-signatures)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/teleprompt/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/__init__.py)\n- [dspy/teleprompt/bootstrap.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap.py)\n- [dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n- [dspy/teleprompt/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n- [dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n- [dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n- [dspy/teleprompt/simba.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/simba.py)\n- [dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n- [dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n- [dspy/teleprompt/knn_fewshot.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/knn_fewshot.py)\n- [dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n- [dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n</details>\n\n# 优化器详解\n\n## 概述\n\nDSPy 的优化器（Optimizer，亦称 Teleprompter）是框架的核心组件，负责自动优化程序中的提示词（Prompt）和演示示例（Demos），以提升语言模型在特定任务上的表现。优化器通过编译（Compile）过程，将声明式的 DSPy 程序转换为经过优化的自改进流水线。\n\nDSPy 优化器的工作机制遵循\"Bootstrap\"范式：先用初始配置运行程序，收集失败的案例，再利用语言模型自动生成改进的提示词或演示示例，如此迭代优化直到达到满意的性能水平。 资料来源：[dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n\n## 架构设计\n\n### 优化器继承体系\n\n所有 DSPy 优化器均继承自 `dspy.teleprompt.Teleprompter` 基类。基类定义了 `compile()` 接口，各子类实现具体的优化策略。\n\n```mermaid\ngraph TD\n    A[Teleprompter 基类] --> B[BootstrapFewShot]\n    A --> C[BootstrapFewShotWithRandomSearch]\n    A --> D[BootstrapFinetune]\n    A --> E[MIPROv2]\n    A --> F[GEPA]\n    A --> G[BetterTogether]\n    A --> H[Ensemble]\n    A --> I[COPRO]\n    A --> J[KNNFewShot]\n    A --> K[SimBA]\n    A --> L[GRPO]\n    \n    G --> |组合多个优化器| M[元优化器]\n```\n\n### 核心编译流程\n\n```mermaid\ngraph LR\n    A[Program] --> B[初始化运行]\n    B --> C[收集轨迹]\n    C --> D{评估指标}\n    D --> |未达标| E[生成候选]\n    E --> F[评估候选]\n    F --> G[选择最优]\n    G --> D\n    D --> |达标| H[优化后程序]\n```\n\n## 内置优化器详解\n\n### 1. BootstrapFewShotWithRandomSearch\n\n这是 DSPy 中最基础的优化器，结合了 Bootstrap 演示生成和随机搜索策略。它会生成多个候选配置（不同的提示词和演示组合），然后在验证集上评估选择最优方案。 资料来源：[dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数，签名 `metric(example, pred, trace) -> bool` | 必填 |\n| `max_bootstrapped_demos` | int | 每个预测模块最多保留的演示数量 | 4 |\n| `max_rounds` | int | 最大优化轮次 | 1 |\n| `num_candidates` | int | 随机搜索的候选数量 | 10 |\n| `num_threads` | int | 并行线程数 | 1 |\n\n#### 使用示例\n\n```python\nimport dspy\n\n# 定义评估指标\ndef metric(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 创建优化器\noptimizer = BootstrapFewShotWithRandomSearch(\n    metric=metric,\n    max_bootstrapped_demos=4,\n    num_candidates=10\n)\n\n# 编译程序\ncompiled_program = optimizer.compile(\n    student=program,\n    trainset=trainset,\n    valset=valset\n)\n```\n\n### 2. BootstrapFinetune\n\nBootstrapFinetune 是 DSPy 的微调优化器，通过 Bootstrap 生成的优质数据对语言模型进行微调。它先生成高质量的演示示例，然后利用这些数据对轻量级语言模型进行微调。 资料来源：[dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `teacher_settings` | dict | 教师模型的设置 | None |\n| `finetune_settings` | dict | 微调设置（如训练轮数、学习率） | {} |\n| `max_bootstrapped_demos` | int | Bootstrap 演示数量上限 | 8 |\n\n### 3. MIPROv2 (Multi-Instruction Prompt Optimization v2)\n\nMIPROv2 是先进的提示优化器，采用贝叶斯优化策略同时优化指令和演示。它通过考虑指令与演示之间的交互作用，实现更高效的提示词优化。 资料来源：[dspy/teleprompt/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `num_trials` | int | 贝叶斯优化试验次数 | 20 |\n| `max_bootstrapped_demos` | int | 演示数量上限 | 4 |\n| `num_examples` | int | 每轮使用的训练样本数 | 200 |\n| `auto` | str | 自动模式级别：\"light\"、\"medium\"、\"heavy\" | None |\n| `bootstrap_dataset_size` | int | Bootstrap 数据集大小 | None |\n\n#### 优化策略\n\nMIPROv2 的核心创新在于将指令优化与演示选择联合考虑：\n\n```mermaid\ngraph TD\n    A[贝叶斯优化器] --> B[指令提议器]\n    A --> C[演示采样器]\n    B --> D[候选指令集合]\n    C --> E[候选演示集合]\n    D --> F[笛卡尔积组合]\n    E --> F\n    F --> G[评估函数]\n    G --> H[更新贝叶斯模型]\n    H --> A\n```\n\n### 4. GEPA (Generalized Evolved Prompt Agent)\n\nGEPA 是基于进化算法的提示优化器，通过反思性提示进化策略实现自动优化。它在多阶段语言模型程序的优化中表现出色。 资料来源：[dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n\n#### 核心参数\n\n| 参数 | 类型 | 说明 | 默认值 |\n|------|------|------|--------|\n| `metric` | Callable | 评估指标函数 | 必填 |\n| `auto` | str | 自动模式：\"light\"、\"medium\"、\"full\" | None |\n| `num_prompt_instructions` | int | 基础指令数量 | 10 |\n| `max_bootstrap两会` | int | Bootstrap 演示上限 | 4 |\n\n### 5. BetterTogether (元优化器)\n\nBetterTogether 是 DSPy 的元优化器框架，可以将多个优化器组合成流水线。它支持自定义优化器组合策略，实现复杂的优化流程。 资料来源：[dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n\n#### 设计理念\n\nBetterTogether 将优化过程分解为两个阶段：\n\n1. **提示优化阶段 (Prompt Optimization, p)**：优化指令和提示词\n2. **权重优化阶段 (Weight Optimization, w)**：通过 Bootstrap Finetune 优化权重\n\n#### 使用示例\n\n```python\nfrom dspy.teleprompt import BetterTogether, MIPROv2, BootstrapFinetune\n\n# 方式一：使用自定义优化器组合\noptimizer = BetterTogether(\n    metric=metric,\n    p=MIPROv2(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric)\n)\n\n# 方式二：使用默认优化器\noptimizer = BetterTogether(metric=metric)\n\n# 编译并指定策略\ncompiled = optimizer.compile(\n    student=program,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\"  # 提示优化后接权重优化\n)\n```\n\n#### 策略配置\n\n| 策略字符串 | 说明 |\n|-----------|------|\n| `\"p\"` | 仅执行提示优化 |\n| `\"w\"` | 仅执行权重优化 |\n| `\"p -> w\"` | 先提示优化后权重优化 |\n| `\"w -> p\"` | 先权重优化后提示优化 |\n| `\"p -> w -> p\"` | 交替优化 |\n\n### 6. COPRO (Coordinate Prompt Optimization)\n\nCOPRO 是一种协同提示优化方法，通过分析程序结构来优化各个模块的提示词。 资料来源：[dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n\n### 7. SimBA (Simple Bootstrap Agent)\n\nSimBA 是轻量级的 Bootstrap 优化器，适用于资源受限场景。它简化了优化流程，同时保持较好的优化效果。 资料来源：[dspy/teleprompt/simba.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/simba.py)\n\n### 8. KNNFewShot (K-Nearest Neighbors Few-Shot)\n\nKNNFewShot 利用 K 近邻算法为每个测试样本选择最相关的演示示例，实现动态演示选择。 资料来源：[dspy/teleprompt/knn_fewshot.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/knn_fewshot.py)\n\n### 9. Ensemble\n\nEnsemble 优化器通过集成多个不同配置的预测模块来提升整体性能，适用于需要高稳定性的生产环境。 资料来源：[dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n\n### 10. GRPO (Group Relative Policy Optimization)\n\nGRPO 是一种基于强化学习的优化方法，通过组内相对策略优化来提升语言模型程序性能。 资料来源：[dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n\n## 优化器选择指南\n\n```mermaid\ngraph TD\n    A[开始选择] --> B{场景类型}\n    B -->|快速原型开发| C[BootstrapFewShotWithRandomSearch]\n    B -->|高质量演示| D[BootstrapFinetune]\n    B -->|联合优化| E[MIPROv2]\n    B -->|进化策略| F[GEPA]\n    B -->|复杂流水线| G[BetterTogether]\n    B -->|动态演示| H[KNNFewShot]\n    B -->|集成预测| I[Ensemble]\n    \n    C --> J[性能基准]\n    D --> J\n    E --> J\n    F --> J\n    G --> J\n    H --> J\n    I --> J\n```\n\n### 场景推荐\n\n| 场景 | 推荐优化器 | 理由 |\n|------|-----------|------|\n| 快速实验 | BootstrapFewShotWithRandomSearch | 配置简单、速度快 |\n| 资源充足追求最优 | MIPROv2 | 贝叶斯优化效果好 |\n| 多阶段流水线 | GEPA / BetterTogether | 支持复杂优化策略 |\n| 边缘部署 | SimBA | 轻量级实现 |\n| 高稳定性需求 | Ensemble | 多模型集成 |\n\n## Teleprompter 基类接口\n\n所有优化器都实现以下核心接口：\n\n```python\nclass Teleprompter:\n    def compile(\n        self,\n        student: Module,\n        *,\n        trainset: list[Example],\n        valset: list[Example] = None,\n        **kwargs\n    ) -> Module:\n        \"\"\"编译学生程序\"\"\"\n        raise NotImplementedError\n```\n\n### compile 方法参数\n\n| 参数 | 类型 | 必填 | 说明 |\n|------|------|------|------|\n| `student` | Module | 是 | 待优化的 DSPy 程序 |\n| `trainset` | list[Example] | 是 | 训练数据集 |\n| `valset` | list[Example] | 否 | 验证数据集，部分优化器需要 |\n| `max_bootstrapped_demos` | int | 否 | Bootstrap 演示上限 |\n| `max_rounds` | int | 否 | 最大优化轮次 |\n| `num_threads` | int | 否 | 并行线程数 |\n\n## 评估指标设计\n\n优化器依赖高质量的评估指标函数。指标函数应满足以下签名：\n\n```python\ndef metric(example: Example, pred: Prediction, trace=None) -> bool | float:\n    \"\"\"\n    参数:\n        example: 测试样本\n        pred: 模型预测结果\n        trace: 轨迹信息（可选，用于 Bootstrap 过程\n    返回:\n        bool 或 float: 评估结果\n    \"\"\"\n```\n\n### 指标函数示例\n\n```python\n# 精确匹配指标\ndef exact_match(example, pred, trace=None):\n    return example.answer.lower().strip() == pred.answer.lower().strip()\n\n# 带权重的复合指标\ndef weighted_metric(example, pred, trace=None):\n    exact = example.answer.lower() == pred.answer.lower()\n    confidence = pred.get(\"confidence\", 1.0)\n    return exact * confidence\n\n# 使用 trace 信息（用于 Bootstrap）\ndef bootstrap_metric(example, pred, trace):\n    if trace is None:\n        return example.answer.lower() == pred.answer.lower()\n    # Bootstrap 过程中可使用更多上下文信息\n    return int(trace.get(\"cost\", 1)) < 10\n```\n\n## 最佳实践\n\n### 1. 数据集划分\n\n```python\n# 正确划分数据集\ntrainset = [example.with_inputs(\"question\") for example in train_examples]\nvalset = [example.with_inputs(\"question\") for example in val_examples]\n\n# 确保 valset 有足够的样本用于可靠评估\nassert len(valset) >= 20, \"验证集应至少包含 20 个样本\"\n```\n\n### 2. 指标设计原则\n\n- **可量化**：指标应能客观衡量输出质量\n- **稳定可靠**：多次运行应产生一致结果\n- **与任务目标一致**：指标应反映实际业务需求\n\n### 3. 优化器配置建议\n\n| 配置项 | 建议值 | 说明 |\n|--------|--------|------|\n| `max_bootstrapped_demos` | 4-8 | 过多演示可能增加上下文负担 |\n| `num_trials` (MIPROv2) | 20-50 | 试验次数越多效果越好但耗时增加 |\n| `num_candidates` | 10-20 | 候选数量影响搜索空间大小 |\n\n### 4. 性能调优\n\n```python\n# 使用并行化加速\noptimizer = BootstrapFewShotWithRandomSearch(\n    metric=metric,\n    num_threads=8  # 利用多核 CPU\n)\n\n# 控制资源使用\noptimizer = MIPROv2(\n    metric=metric,\n    num_trials=20,  # 限制试验次数\n    num_examples=100  # 限制样本数\n)\n```\n\n## 常见问题\n\n### Q1: 优化器编译失败怎么办？\n\n检查以下几点：\n1. 确认 `metric` 函数签名正确且可调用\n2. 确保 `trainset` 和 `valset` 非空且格式正确\n3. 验证 `Example` 对象已通过 `with_inputs()` 设置输入字段\n\n### Q2: 如何选择合适的优化器？\n\n参考\"优化器选择指南\"章节，从场景复杂度、可用资源和性能要求三个维度考量。\n\n### Q3: 优化后的性能不理想怎么办？\n\n- 尝试更换优化器类型\n- 调整优化器参数（如增加试验次数）\n- 改进评估指标函数\n- 检查数据集质量和规模\n\n### Q4: 如何调试优化过程？\n\n```python\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n# 启用详细输出\noptimizer = MIPROv2(metric=metric, verbose=True)\n```\n\n## 参考链接\n\n- [DSPy 官方文档](https://dspy.ai)\n- [DSPy 论文: Compiling Declarative Language Model Calls](https://arxiv.org/abs/2310.03714)\n- [MIPRO 论文: Optimizing Instructions and Demonstrations](https://arxiv.org/abs/2406.11695)\n- [GEPA 论文: Reflective Prompt Evolution](https://arxiv.org/abs/2507.19457)\n\n---\n\n<a id='page-lm-clients'></a>\n\n## 语言模型客户端\n\n### 相关页面\n\n相关主题：[DSPy概述](#page-overview), [适配器系统](#page-adapters)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/clients/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/__init__.py)\n- [dspy/clients/lm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/lm.py)\n- [dspy/clients/base_lm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/base_lm.py)\n- [dspy/clients/openai.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/openai.py)\n- [dspy/clients/_litellm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/_litellm.py)\n- [dspy/clients/databricks.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/databricks.py)\n- [dspy/clients/lm_local.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/lm_local.py)\n- [dspy/clients/embedding.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/embedding.py)\n- [dspy/clients/cache.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/cache.py)\n- [dspy/clients/provider.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/provider.py)\n</details>\n\n# 语言模型客户端\n\n## 概述\n\nDSPy 的语言模型客户端是框架与各种大语言模型（LLM）交互的核心抽象层。它提供了统一的接口，使开发者能够通过简洁的 API 调用不同的语言模型提供商，同时支持缓存、回调、批处理等高级功能。\n\n语言模型客户端在 DSPy 架构中扮演着至关重要的角色：它被 `dspy.Module` 中的预测器（如 `dspy.Predict`、`dspy.ChainOfThought` 等）调用，为整个程序提供推理能力。\n\n## 架构设计\n\n### 模块层次结构\n\nDSPy 的语言模型客户端采用分层架构设计：\n\n```mermaid\ngraph TD\n    A[dspy.LM 统一入口] --> B[BaseLM 抽象基类]\n    B --> C[OpenAI 客户端]\n    B --> D[LiteLLM 客户端]\n    B --> E[Databricks 客户端]\n    B --> F[Local LM 客户端]\n    G[Embedding 嵌入客户端] --> H[Embedder 类]\n    G --> I[缓存层 Cache]\n```\n\n### 核心组件\n\n| 组件 | 文件路径 | 职责 |\n|------|----------|------|\n| `dspy.LM` | `dspy/clients/lm.py` | 统一入口，支持多种模型提供商 |\n| `BaseLM` | `dspy/clients/base_lm.py` | 抽象基类，定义接口规范 |\n| `OpenAI` | `dspy/clients/openai.py` | OpenAI API 专用客户端 |\n| `_LiteLLM` | `dspy/clients/_litellm.py` | LiteLLM 封装，支持 100+ 模型 |\n| `Databricks` | `dspy/clients/databricks.py` | Databricks 模型服务 |\n| `LocalLM` | `dspy/clients/lm_local.py` | 本地部署模型 |\n| `Embedder` | `dspy/clients/embedding.py` | 文本嵌入模型客户端 |\n| `Cache` | `dspy/clients/cache.py` | 请求缓存管理 |\n| `Provider` | `dspy/clients/provider.py` | 模型提供商配置 |\n\n## 使用方式\n\n### 基本初始化\n\n```python\nimport dspy\n\n# 使用 OpenAI 模型\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# 使用本地模型\nlm = dspy.LM(\"ollama/llama3\")\n\n# 配置回调函数\nfrom dspy.utils.callback import LoggingCallback\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n### 在模块中使用\n\n语言模型客户端通过 `dspy.Module` 的 `set_lm()` 方法与预测器关联：\n\n```python\nimport dspy\n\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predict = dspy.Predict(\"question -> answer\")\n    \n    def forward(self, question):\n        return self.predict(question=question)\n\n# 创建程序并设置语言模型\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = MyProgram()\nprogram.set_lm(lm)\n```\n\n获取模块当前使用的语言模型：\n\n```python\ncurrent_lm = program.get_lm()\n```\n\n## Embedder 嵌入客户端\n\n`Embedder` 类是 DSPy 中用于处理文本嵌入的专用客户端，支持自定义嵌入函数和多种模型。\n\n### 核心参数\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `model` | `str \\| Callable` | - | 模型名称或自定义嵌入函数 |\n| `batch_size` | `int` | `200` | 批处理大小 |\n| `caching` | `bool` | `True` | 是否启用缓存 |\n| `**kwargs` | `dict` | - | 传递给模型的额外参数 |\n\n### 使用示例\n\n```python\nimport dspy\nimport numpy as np\n\n# 示例 1：使用预定义模型\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\")\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\nassert embeddings.shape == (2, 1536)\n\n# 示例 2：使用自定义函数\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\nassert embeddings.shape == (2, 10)\n```\n\n### 内部处理流程\n\n`Embedder` 的 `_preprocess()` 方法负责输入预处理：\n\n```python\ndef _preprocess(self, inputs, batch_size=None, caching=None, **kwargs):\n    # 1. 处理单个字符串输入\n    if isinstance(inputs, str):\n        is_single_input = True\n        inputs = [inputs]\n    else:\n        is_single_input = False\n    \n    # 2. 验证所有输入为字符串\n    if not all(isinstance(inp, str) for inp in inputs):\n        raise ValueError(\"All inputs must be strings.\")\n    \n    # 3. 合并默认参数与自定义参数\n    batch_size = batch_size or self.batch_size\n    caching = caching if caching is not None else self.caching\n    merged_kwargs = self.default_kwargs.copy()\n    merged_kwargs.update(kwargs)\n    \n    # 4. 分批处理\n    input_batches = []\n    for i in range(0, len(inputs), batch_size):\n        input_batches.append(inputs[i : i + batch_size])\n    \n    return input_batches, caching, merged_kwargs, is_single_input\n```\n\n## 回调机制\n\nDSPy 提供回调系统用于监控和调试语言模型调用。回调通过 `BaseCallback` 抽象类定义：\n\n```python\nfrom dspy.utils.callback import BaseCallback\n\nclass LoggingCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        print(f\"LM is called with inputs: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        print(f\"LM is finished with outputs: {outputs}\")\n```\n\n回调使用方式：\n\n```python\n# 方式 1：全局配置\ndspy.configure(callbacks=[LoggingCallback()])\n\n# 方式 2：组件级别配置\nlm = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n```\n\n## 缓存机制\n\nDSPy 的缓存层位于 `dspy/clients/cache.py`，用于存储和检索已计算的模型响应，避免重复 API 调用。\n\n缓存的主要特性：\n\n- 基于请求参数的内容寻址\n- 支持配置 TTL（生存时间）\n- 可与各种模型客户端无缝集成\n\n## 模型提供商\n\n### 支持的提供商类型\n\n| 提供商 | 客户端类 | 说明 |\n|--------|----------|------|\n| OpenAI | `OpenAI` | OpenAI API 原生支持 |\n| Azure | 通过 `OpenAI` | Azure OpenAI Service |\n| Anthropic | 通过 `_LiteLLM` | Claude 系列模型 |\n| Google | 通过 `_LiteLLM` | Gemini 系列 |\n| Meta | 通过 `_LiteLLM` | Llama 系列 |\n| Databricks | `Databricks` | Databricks 模型服务 |\n| Ollama | `LocalLM` | 本地部署模型 |\n| LM Studio | `LocalLM` | 本地部署模型 |\n\n### 模型标识符格式\n\n```python\n# OpenAI 格式\ndspy.LM(\"openai/gpt-4o\")\ndspy.LM(\"openai/gpt-4o-mini\")\n\n# 自定义格式\ndspy.LM(\"ollama/llama3\")\ndspy.LM(\"local/my-model\")\n```\n\n## 最佳实践\n\n### 1. 全局配置 vs 组件配置\n\n```python\n# 全局配置：所有组件共享同一语言模型\ndspy.configure(lm=dspy.LM(\"gpt-4o\"))\n\n# 组件配置：特定组件使用特定模型\nlm_special = dspy.LM(\"gpt-4o\")\nprogram.set_lm(lm_special)\n```\n\n### 2. 回调用于调试\n\n```python\nclass DebugCallback(BaseCallback):\n    def on_module_start(self, call_id, instance, inputs):\n        logger.debug(f\"Calling LM with: {inputs}\")\n    \n    def on_module_end(self, call_id, outputs):\n        logger.debug(f\"LM returned: {outputs}\")\n\nlm = dspy.LM(\"gpt-4o\", callbacks=[DebugCallback()])\n```\n\n### 3. 嵌入模型批处理优化\n\n```python\n# 大批量处理时使用较大 batch_size\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\", batch_size=100)\n```\n\n## 相关文档\n\n- [DSPy 文档首页](https://dspy.ai)\n- [预测器 (Predict)](./predict.md)\n- [模块系统](./module.md)\n- [示例系统](./example.md)\n- [评估系统](./evaluation.md)\n\n## 源码索引\n\n| 文件 | 功能描述 |\n|------|----------|\n| `dspy/clients/__init__.py` | 客户端模块入口，导出 `LM`、`Embedder` 等 |\n| `dspy/clients/lm.py` | `LM` 类实现，支持多种提供商 |\n| `dspy/clients/base_lm.py` | `BaseLM` 抽象基类 |\n| `dspy/clients/openai.py` | OpenAI 专用客户端 |\n| `dspy/clients/_litellm.py` | LiteLLM 封装 |\n| `dspy/clients/databricks.py` | Databricks 客户端 |\n| `dspy/clients/lm_local.py` | 本地模型客户端 |\n| `dspy/clients/embedding.py` | 嵌入模型客户端 `Embedder` |\n| `dspy/clients/cache.py` | 缓存实现 |\n| `dspy/clients/provider.py` | 提供商配置 |\n| `dspy/primitives/module.py` | 模块的 `set_lm`/`get_lm` 方法 |\n| `dspy/utils/callback.py` | 回调系统实现 |\n\n---\n\n<a id='page-adapters'></a>\n\n## 适配器系统\n\n### 相关页面\n\n相关主题：[语言模型客户端](#page-lm-clients), [内置模块参考](#page-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/adapters/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/__init__.py)\n- [dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n- [dspy/adapters/chat_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/chat_adapter.py)\n- [dspy/adapters/json_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/json_adapter.py)\n- [dspy/adapters/xml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/xml_adapter.py)\n- [dspy/adapters/two_step_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/two_step_adapter.py)\n- [dspy/adapters/baml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/baml_adapter.py)\n- [dspy/adapters/types/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/__init__.py)\n</details>\n\n# 适配器系统\n\n## 概述\n\nDSPy 的适配器系统（Adapter System）是框架中负责将程序签名（Signature）转换为语言模型可处理的格式化消息的核心组件。适配器充当 DSPy 程序与底层语言模型 API 之间的桥梁，负责处理输入输出的结构化转换、字段序列化以及响应解析等关键任务。\n\n适配器系统的主要职责包括：\n\n- **消息格式化**：将 DSPy 签名中的输入字段转换为语言模型 API 可接受的格式\n- **响应解析**：将语言模型的输出解析回 DSPy 的结构化数据结构\n- **自定义类型支持**：处理复杂数据类型（如图像、历史对话等）的序列化与反序列化\n- **多格式支持**：支持多种输出格式规范（如 JSON、XML、Chat 格式等）\n\n资料来源：[dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n\n## 系统架构\n\n### 核心组件层次\n\n```mermaid\ngraph TD\n    A[DSPy 程序] --> B[签名 Signature]\n    B --> C[适配器 Adapter]\n    C --> D{适配器类型}\n    D --> E[ChatAdapter]\n    D --> F[JSONAdapter]\n    D --> G[XMLAdapter]\n    D --> H[TwoStepAdapter]\n    D --> I[BAMLAdapter]\n    C --> J[语言模型 LM API]\n    J --> K[响应 Response]\n    K --> C\n    C --> L[Prediction]\n```\n\n### 适配器类型对比\n\n| 适配器类型 | 输出格式 | 解析方式 | 使用场景 |\n|-----------|---------|---------|---------|\n| ChatAdapter | Chat Messages | 结构化解析 | 通用对话场景 |\n| JSONAdapter | JSON | JSON 解析 | 结构化数据输出 |\n| XMLAdapter | XML | XML 解析 | XML 格式要求 |\n| TwoStepAdapter | 两阶段格式 | 两步解析 | 复杂推理任务 |\n| BAMLAdapter | BAML | BAML 解析器 | 类型安全生成 |\n\n资料来源：[dspy/adapters/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/__init__.py)\n\n## 基础适配器接口\n\n### BaseAdapter 抽象基类\n\n所有适配器都继承自 `BaseAdapter` 抽象基类，定义了适配器的核心接口规范：\n\n```python\nclass BaseAdapter(ABC):\n    \"\"\"适配器基类，定义所有适配器必须实现的接口\"\"\"\n    \n    @abstractmethod\n    def format(self, signature, demos, inputs):\n        \"\"\"将签名和输入格式化为模型消息\"\"\"\n        pass\n    \n    @abstractmethod\n    def parse(self, signature, response):\n        \"\"\"解析模型响应为预测结果\"\"\"\n        pass\n```\n\n### 适配器核心方法\n\n| 方法 | 参数 | 返回值 | 说明 |\n|-----|------|-------|-----|\n| format | signature, demos, inputs | list[dict] | 格式化输入消息 |\n| parse | signature, response | Prediction | 解析输出响应 |\n| format_field_value | value, field | str | 格式化单个字段值 |\n| post_save_hook | output, signature | None | 保存后钩子 |\n\n资料来源：[dspy/adapters/base.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/base.py)\n\n## Chat 适配器\n\n`ChatAdapter` 是 DSPy 默认的适配器实现，专门用于处理对话格式的语言模型 API（如 OpenAI ChatGPT、Google Gemini 等）。\n\n### 消息格式转换\n\nChatAdapter 将 DSPy 的签名转换为标准的聊天消息格式：\n\n```mermaid\ngraph LR\n    A[Signature<br/>InputFields] --> B[ChatAdapter]\n    C[Demos<br/>Few-Shot] --> B\n    B --> D[System Message<br/>历史指令]\n    B --> E[User Messages<br/>输入+演示]\n    B --> F[Assistant Messages<br/>历史响应]\n```\n\n### 核心实现逻辑\n\n```python\ndef format(self, signature, demos, inputs):\n    # 构建系统消息（包含指令）\n    messages = [self._build_system_message(signature)]\n    \n    # 添加演示示例\n    for demo in demos:\n        messages.extend(self._format_demo(demo))\n    \n    # 添加当前输入\n    messages.append(self._build_user_message(inputs))\n    \n    return messages\n```\n\n资料来源：[dspy/adapters/chat_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/chat_adapter.py)\n\n## JSON 适配器\n\n`JSONAdapter` 专为需要结构化 JSON 输出的场景设计，适用于需要机器解析输出的应用。\n\n### 工作流程\n\n```mermaid\ngraph TD\n    A[输入字段] --> B[构建Prompt]\n    B --> C[添加JSON Schema说明]\n    C --> D[调用LM]\n    D --> E{响应格式}\n    E -->|有效JSON| F[json.loads解析]\n    E -->|无效JSON| G[尝试修复格式]\n    F --> H[Prediction]\n    G --> H\n```\n\n### 格式控制机制\n\nJSONAdapter 通过在提示词中嵌入 JSON Schema 来指导模型生成符合规范的输出：\n\n```python\njson_schema = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"field_name\": {\"type\": \"string\", \"description\": \"...\"}\n    },\n    \"required\": [\"field_name\"]\n}\n```\n\n资料来源：[dspy/adapters/json_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/json_adapter.py)\n\n## XML 适配器\n\n`XMLAdapter` 使用 XML 标签格式封装输出字段，适用于需要明确结构化层次的场景。\n\n### 标签规范\n\n| 组件 | 标签格式 | 说明 |\n|-----|---------|-----|\n| 输出块 | `<answer>` ... `</answer>` | 包含整个输出 |\n| 字段 | `<field_name>` 值 `</field_name>` | 单个输出字段 |\n| 嵌套 | 层级嵌套标签 | 复杂数据结构 |\n\n### 解析机制\n\nXMLAdapter 使用正则表达式匹配提取字段值：\n\n```python\npattern = rf\"<{field_name}>(.*?)</{field_name}>\"\nmatch = re.search(pattern, response)\n```\n\n资料来源：[dspy/adapters/xml_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/xml_adapter.py)\n\n## TwoStep 适配器\n\n`TwoStepAdapter` 实现两阶段推理模式，适用于需要\"思考-回答\"分离的复杂任务。\n\n### 两阶段流程\n\n```mermaid\ngraph LR\n    A[问题] --> B[第一阶段<br/>推理/分析]\n    B --> C[中间推理结果]\n    C --> D[第二阶段<br/>生成答案]\n    D --> E[最终答案]\n```\n\n### 配置参数\n\n| 参数 | 类型 | 默认值 | 说明 |\n|-----|------|-------|-----|\n| reasoning_field | str | \"reasoning\" | 推理字段名 |\n| answer_field | str | \"answer\" | 答案字段名 |\n| reasoning_type | str | \"chain_of_thought\" | 推理类型 |\n\n资料来源：[dspy/adapters/two_step_adapter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/two_step_adapter.py)\n\n## 自定义类型系统\n\n### 类型注册机制\n\nDSPy 适配器系统支持自定义复杂类型的处理，通过标识符分割内容：\n\n```mermaid\ngraph TD\n    A[消息内容] --> B{包含自定义类型?}\n    B -->|是| C[查找标识符]\n    C --> D[<<CUSTOM-TYPE-START-IDENTIFIER>>]\n    D --> E[提取JSON内容]\n    E --> F[解析自定义类型]\n    F --> G[重建消息结构]\n    B -->|否| H[纯文本处理]\n```\n\n### 类型标识符\n\n| 标识符 | 用途 |\n|-------|-----|\n| `<<CUSTOM-TYPE-START-IDENTIFIER>>` | 自定义类型内容开始 |\n| `<<CUSTOM-TYPE-END-IDENTIFIER>>` | 自定义类型内容结束 |\n\n资料来源：[dspy/adapters/types/base_type.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/base_type.py)\n\n### 内置自定义类型\n\n#### History 类型\n\n`History` 类型用于管理多轮对话历史：\n\n```python\nclass History(BaseModel):\n    \"\"\"对话历史类\"\"\"\n    messages: list[dict]  # 消息列表，每条消息包含历史对话内容\n```\n\n**使用示例：**\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField()\n    history: dspy.History = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nhistory = dspy.History(messages=[\n    {\"question\": \"法国的首都是什么？\", \"answer\": \"巴黎\"},\n    {\"question\": \"德国的首都是什么？\", \"answer\": \"柏林\"},\n])\n```\n\n资料来源：[dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n\n#### Image 类型\n\n`Image` 类型支持图像输入处理：\n\n```python\nclass Image(BaseModel):\n    \"\"\"图像类型，支持URL和本地文件\"\"\"\n    url: str  # base64数据URI或URL\n```\n\n**支持的数据格式：**\n\n| 格式 | 说明 | 适用场景 |\n|-----|------|---------|\n| http://... | 网络URL | 公开图像 |\n| https://... | 安全URL | 公开图像 |\n| data:image/...;base64,... | Base64编码 | 本地/内联图像 |\n| file://... | 本地文件路径 | 本地图像 |\n\n**图像处理方法：**\n\n| 方法 | 说明 |\n|-----|-----|\n| `encode_image()` | 编码图像为可传输格式 |\n| `format()` | 格式化为 API 消息格式 |\n| `from_url()` | 从URL创建（已废弃） |\n| `from_file()` | 从文件创建 |\n\n资料来源：[dspy/adapters/types/image.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/image.py)\n\n## 使用指南\n\n### 选择合适的适配器\n\n```mermaid\ngraph TD\n    A[开始] --> B{输出需求?}\n    B -->|通用对话| C[ChatAdapter]\n    B -->|结构化数据| D{数据复杂度?}\n    D -->|简单| E[JSONAdapter]\n    D -->|复杂| F[TwoStepAdapter]\n    B -->|XML格式要求| G[XMLAdapter]\n    B -->|类型安全| H[BAMLAdapter]\n```\n\n### 配置默认适配器\n\n```python\nimport dspy\n\n# 全局配置\ndspy.settings.configure(adapter=dspy.ChatAdapter())\n\n# 或在程序中指定\nclass MyProgram(dspy.Module):\n    def __init__(self):\n        self.predict = dspy.Predict(\n            \"question -> answer\",\n            adapter=dspy.JSONAdapter()\n        )\n```\n\n### 自定义适配器\n\n```python\nfrom dspy.adapters import BaseAdapter\n\nclass MyCustomAdapter(BaseAdapter):\n    def format(self, signature, demos, inputs):\n        # 自定义格式化逻辑\n        return messages\n    \n    def parse(self, signature, response):\n        # 自定义解析逻辑\n        return dspy.Prediction(...)\n```\n\n## 最佳实践\n\n### 1. 适配器选择建议\n\n| 场景 | 推荐适配器 | 原因 |\n|-----|----------|-----|\n| 通用应用 | ChatAdapter | 灵活、通用 |\n| API 数据提取 | JSONAdapter | 结构化、机器可读 |\n| 文档生成 | XMLAdapter | 层次清晰 |\n| 推理任务 | TwoStepAdapter | 分离思考与答案 |\n| 生产系统 | BAMLAdapter | 类型安全 |\n\n### 2. 性能优化\n\n- **批处理**：使用 `batch_size` 参数控制批处理大小\n- **缓存**：启用缓存机制减少重复计算\n- **类型选择**：根据输出复杂度选择最合适的适配器\n\n### 3. 错误处理\n\n适配器应处理以下常见错误：\n\n| 错误类型 | 处理策略 |\n|---------|---------|\n| 解析失败 | 回退到备用解析器或提示重试 |\n| 格式不匹配 | 尝试自动修复或抛出明确错误 |\n| 超限 | 截断或分片处理 |\n\n## 总结\n\nDSPy 的适配器系统为框架提供了灵活的消息格式化和解析能力，通过统一的接口抽象支持多种输出格式规范。适配器的模块化设计使得开发者可以轻松扩展新的格式支持，同时内置的多种适配器覆盖了大多数常见使用场景。自定义类型系统的支持进一步增强了框架的表达能力，使得复杂的数据结构处理变得简单可控。\n\n---\n\n<a id='page-retrieval'></a>\n\n## 检索增强模块\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [评估与指标](#page-evaluation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/retrievers/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/__init__.py)\n- [dspy/retrievers/retrieve.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/retrieve.py)\n- [dspy/retrievers/embeddings.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/embeddings.py)\n- [dspy/retrievers/databricks_rm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/databricks_rm.py)\n- [dspy/retrievers/weaviate_rm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/retrievers/weaviate_rm.py)\n- [dspy/dsp/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/__init__.py)\n- [dspy/dsp/colbertv2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/colbertv2.py)\n- [dspy/dsp/utils/dpr.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/dsp/utils/dpr.py)\n</details>\n\n# 检索增强模块\n\n## 概述\n\nDSPy的检索增强模块（Retrieval Augmentation Module）是框架中负责从外部知识源获取相关文档或段落的核心组件。该模块通过检索模型（Retriever Model）实现语义搜索功能，使语言模型能够在生成回答时利用外部知识库中的相关信息。\n\n检索增强模块的主要职责包括：\n\n- 与向量数据库或检索服务集成，实现语义相似度搜索\n- 提供统一的检索接口，支持多种后端实现\n- 将检索结果格式化为可被签名（Signature）处理的数据结构\n- 支持自定义嵌入模型和检索策略\n\n## 架构设计\n\n### 模块层级结构\n\nDSPy的检索增强系统采用分层架构设计，从底层到顶层依次为：\n\n| 层级 | 组件 | 职责 |\n|------|------|------|\n| 嵌入层 | `Embedder` | 将文本转换为向量表示 |\n| 检索层 | 各类RM实现 | 执行向量相似度搜索 |\n| 接口层 | `Retrieve` | 提供统一的模块化调用接口 |\n| 配置层 | `dspy.configure()` | 全局配置检索模型 |\n\n### 核心类关系\n\n```mermaid\ngraph TD\n    A[dspy.configure] --> B[RM Retriever Model]\n    B --> C[weaviate_rm.WeaviateRM]\n    B --> D[databricks_rm.DatabricksRM]\n    B --> E[colbertv2.ColBERTv2]\n    F[Retrieve模块] --> B\n    G[Embedder] --> H[嵌入服务]\n    B --> G\n```\n\n## Retrieve 模块\n\n`Retrieve`是DSPy中用于执行检索的核心模块，继承自`Module`基类。它作为检索系统的统一入口点，将用户的查询转换为检索请求并返回相关文档。\n\n### 基本用法\n\n```python\nimport dspy\n\n# 配置语言模型和检索模型\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\ndspy.configure(rm=WeaviateRM(\"my_collection\", weaviate_client=client))\n\n# 创建Retrieve模块\nretrieve = dspy.Retrieve(k=5)\nresults = retrieve(\"什么是机器学习\")\n```\n\n### API 参数说明\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| k | int | 3 | 返回的最相关文档数量 |\n| force_by_id | bool | False | 是否强制按ID检索 |\n\n### 工作流程\n\n```mermaid\nsequenceDiagram\n    用户 ->> Retrieve: 调用retrieve(query)\n    Retrieve ->> RM: query(query_str, k)\n    RM ->> 向量数据库: 相似度搜索\n    向量数据库 ->> RM: 返回Top-K文档\n    RM ->> Retrieve: 格式化检索结果\n    Retrieve ->> 用户: 返回Passages对象\n```\n\n## 检索模型（Retriever Model）\n\n检索模型是实际执行向量搜索的后端实现。DSPy支持多种检索后端，每种实现都遵循统一的接口规范。\n\n### Retriever 基类接口\n\n所有检索模型都需要实现以下核心方法：\n\n| 方法 | 返回类型 | 说明 |\n|------|----------|------|\n| `forward(query)` | list[str] | 根据查询返回相关文档列表 |\n| `query(query_str, k)` | list | 执行检索并返回k个结果 |\n| `__call__(*args, **kwargs)` | list[str] | 模块调用接口 |\n\n### WeaviateRM 实现\n\n`WeaviateRM`是与Weaviate向量数据库集成的检索模型实现。\n\n**构造函数参数：**\n\n| 参数 | 类型 | 必填 | 说明 |\n|------|------|------|------|\n| weaviate_collection_name | str | 是 | Weaviate集合名称 |\n| weaviate_client | WeaviateClient | 是 | Weaviate客户端实例 |\n| weaviate_collection_text_key | str | 否 | 集合中存储文本的字段名，默认\"content\" |\n| k | int | 否 | 检索结果数量，默认3 |\n| tenant_id | str | 否 | 多租户支持 |\n\n**配置示例：**\n\n```python\nimport dspy\nimport weaviate\n\nllm = dspy.Cohere(model=\"command-r-plus\", api_key=api_key)\nweaviate_client = weaviate.connect_to_local(\"your-path-here\")\nretriever_model = WeaviateRM(\"my_collection_name\", weaviate_client=weaviate_client)\ndspy.configure(lm=llm, rm=retriever_model)\n\nretrieve = dspy.Retrieve(k=1)\ntopK_passages = retrieve(\"what are the stages in planning\").passages\n```\n\n**内部机制：**\n\n该实现通过`weaviate_client.collections.get()`获取集合对象，然后使用集合的查询接口执行向量相似度搜索。文本内容通过`weaviate_collection_text_key`字段提取。\n\n### DatabricksRM 实现\n\n`DatabricksRM`是专门为Databricks平台设计的检索模型，利用Databricks向量搜索服务进行语义检索。\n\n### ColBERTv2 实现\n\n`ColBERTv2`是基于ColBERT算法的延迟交互式检索实现，适用于需要细粒度语义匹配的场景。\n\n```python\nfrom dspy.dsp.colbertv2 import ColBERTv2\n\nretriever = ColBERTv2()\nresults = retriever(\"query text\", k=5)\n```\n\n### DPR 实现\n\nDSPy还提供了基于Dense Passage Retrieval（DPR）的工具函数，位于`dspy/dsp/utils/dpr.py`中，用于处理双塔模型的检索逻辑。\n\n## 嵌入模块\n\n### Embedder 类\n\n`Embedder`是封装嵌入模型的统一接口，支持自定义嵌入函数和批量处理。\n\n**构造函数参数：**\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| model | str \\| Callable | 必填 | 嵌入模型名称或自定义函数 |\n| batch_size | int | 200 | 批处理大小 |\n| caching | bool | True | 是否启用结果缓存 |\n| kwargs | dict | {} | 传递给嵌入服务的额外参数 |\n\n**使用示例：**\n\n```python\nimport dspy\nimport numpy as np\n\n# 使用自定义嵌入函数\ndef my_embedder(texts):\n    return np.random.rand(len(texts), 10)\n\nembedder = dspy.Embedder(my_embedder)\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\n### 预处理与后处理\n\nEmbedder类包含两个关键内部方法：\n\n- `_preprocess()`：处理输入数据，支持单个字符串或字符串列表，自动进行批量分割\n- `_postprocess()`：处理嵌入结果，支持返回原始格式或批量格式\n\n## 数据结构\n\n### Passages 数据结构\n\n检索结果以`Passages`对象形式返回，包含以下属性：\n\n| 属性 | 类型 | 说明 |\n|------|------|------|\n| passages | list[str] | 检索到的文档段落列表 |\n\n```python\nresult = retrieve(\"查询内容\")\nprint(result.passages)  # ['文档1内容', '文档2内容', ...]\n```\n\n### 示例数据结构\n\n`Example`类用于组织训练数据和评估数据，支持与检索系统配合使用：\n\n```python\nexample = dspy.Example(\n    question=\"什么是检索增强生成?\",\n    answer=\"检索增强生成是一种结合检索系统和语言模型的技术。\"\n).with_inputs(\"question\")\n\n# 检索相关文档\ncontext = example.inputs().toDict()\n```\n\n## 配置管理\n\n### 全局配置\n\n通过`dspy.configure()`进行全局配置：\n\n```python\nimport dspy\n\ndspy.configure(\n    lm=dspy.LM(\"openai/gpt-4o-mini\"),  # 语言模型\n    rm=WeaviateRM(...)                   # 检索模型\n)\n```\n\n### 模块级配置\n\n也可以在模块级别设置语言模型：\n\n```python\nclass MyRAG(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.qa = dspy.Predict(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.qa(context=context, question=question)\n```\n\n## 最佳实践\n\n### 检索参数调优\n\n| 场景 | 建议配置 |\n|------|----------|\n| 快速原型开发 | k=3, 使用轻量级嵌入模型 |\n| 生产环境 | k=5-10, 启用缓存, 使用高精度嵌入 |\n| 长文档检索 | 设置合适的chunk_size, 使用rerank |\n\n### 性能优化建议\n\n1. **启用缓存**：对于重复查询较多的场景，设置`caching=True`\n2. **批量处理**：合理设置`batch_size`参数，平衡内存和吞吐量\n3. **连接池复用**：在生产环境中复用向量数据库连接\n\n## 相关模块\n\n| 模块 | 文件路径 | 用途 |\n|------|----------|------|\n| Module基类 | `dspy/primitives/module.py` | 所有DSPy模块的基类，包含`set_lm()`和`get_lm()`方法 |\n| Predict | `dspy/predict/predict.py` | 预测模块，可与Retrieve组合使用 |\n| Example | `dspy/primitives/example.py` | 数据示例类，用于组织训练和评估数据 |\n| History | `dspy/adapters/types/history.py` | 对话历史类型，支持多轮检索场景 |\n\n## 扩展开发\n\n### 自定义检索模型\n\n要实现自定义检索模型，需要继承相关基类并实现核心接口：\n\n```python\nclass MyRetriever(dspy.Module):\n    def __init__(self, collection_name, k=3):\n        self.collection_name = collection_name\n        self.k = k\n    \n    def forward(self, query):\n        # 实现检索逻辑\n        results = self._search_vector_db(query, self.k)\n        return results\n    \n    def _search_vector_db(self, query, k):\n        # 向量搜索实现\n        pass\n```\n\n### 集成新向量数据库\n\n在`dspy/retrievers/`目录下创建新的RM实现文件，参考`weaviate_rm.py`的结构，确保实现统一的`__call__`接口和检索参数规范。\n\n---\n\n<a id='page-evaluation'></a>\n\n## 评估与指标\n\n### 相关页面\n\n相关主题：[内置模块参考](#page-modules), [优化器详解](#page-optimizers), [原语与数据结构](#page-primitives)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/evaluate/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/__init__.py)\n- [dspy/evaluate/evaluate.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/evaluate.py)\n- [dspy/evaluate/metrics.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/metrics.py)\n- [dspy/evaluate/auto_evaluation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/auto_evaluation.py)\n- [dspy/datasets/__init__.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/__init__.py)\n- [dspy/datasets/dataloader.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/dataloader.py)\n- [dspy/datasets/dataset.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/dataset.py)\n</details>\n\n# 评估与指标\n\n## 概述\n\nDSPy 框架的评估与指标系统是验证和优化语言模型程序的核心组件。该系统提供了标准化的评估接口、灵活的指标定义机制，以及与 DSPy 优化器（Teleprompter）深度集成的评估流程。评估系统的设计遵循模块化原则，允许开发者自定义评估逻辑，同时保持与框架其他部分的一致性。\n\n在 DSPy 中，评估主要通过 `dspy.Evaluate` 类驱动，而指标（Metrics）则是用于衡量预测质量的回调函数。两者结合构成了完整的程序性能评估体系，支持从简单的精确匹配到复杂的语义相似度等多种评估场景。\n\n## 核心架构\n\n### 评估系统组件关系\n\n```mermaid\ngraph TD\n    A[用户程序 dspy.Module] --> B[dspy.Evaluate 评估器]\n    B --> C[评估指标 Metric 函数]\n    C --> D[Example 测试集]\n    B --> E[Prediction 预测结果]\n    E --> C\n    C --> F[评估分数 Score]\n    B --> G[Teleprompter 优化器]\n    G --> H[BootstrapFewShot / MIPROv2 等]\n```\n\n### 关键类结构\n\n| 类名 | 文件位置 | 职责 |\n|------|----------|------|\n| `Evaluate` | `dspy/evaluate/evaluate.py` | 评估引擎，协调评估流程 |\n| `Metric` | `dspy/evaluate/metrics.py` | 指标基类与预置指标 |\n| `AutoEvaluation` | `dspy/evaluate/auto_evaluation.py` | 自动评估支持 |\n| `Example` | `dspy/primitives/example.py` | 测试样本数据结构 |\n| `Prediction` | `dspy/primitives/prediction.py` | 预测结果数据结构 |\n\n## Example 数据结构\n\n`Example` 是 DSPy 中用于表示测试样本的基础数据结构，它将输入字段和标签字段分离，为评估提供标准化的数据格式。 资料来源：[dspy/primitives/example.py:1-50]()\n\n### 创建与使用 Example\n\n```python\nimport dspy\n\n# 创建带标签的示例\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# 提取输入字段\ninputs = example.inputs()\n# Example({'question': 'What is the capital of France?'}) (input_keys={'question'})\n\n# 提取标签字段\nlabels = example.labels()\n# Example({'answer': 'Paris'}) (input_keys={'question'})\n```\n\n### Example 核心方法\n\n| 方法 | 说明 | 返回值 |\n|------|------|--------|\n| `with_inputs(*keys)` | 标记输入字段 | 新的 Example 实例 |\n| `inputs()` | 获取输入部分 | 仅包含输入字段的 Example |\n| `labels()` | 获取标签部分 | 仅包含标签字段的 Example |\n| `toDict()` | 转换为字典 | 递归可序列化的字典 |\n| `copy(**kwargs)` | 复制并覆盖字段 | 新的 Example 实例 |\n| `without(*keys)` | 移除指定字段 | 新的 Example 实例 |\n\n`toDict()` 方法支持递归序列化嵌套的 `Example` 对象、Pydantic 模型、列表和字典，确保评估结果可以JSON化输出。 资料来源：[dspy/primitives/example.py:80-120]()\n\n## 评估器（Evaluate）\n\n### Evaluate 类概述\n\n`dspy.Evaluate` 是评估系统的核心类，负责执行整个评估流程。它接受待评估的程序、测试集和指标函数，并返回聚合的评估分数。\n\n### 基本用法\n\n```python\nimport dspy\n\n# 定义评估指标\ndef exact_match_metric(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 准备测试集\ntestset = [\n    dspy.Example(question=\"What is 1+1?\", answer=\"2\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\"),\n]\n\n# 创建评估器\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=exact_match_metric,\n    num_threads=1,\n)\n\n# 执行评估\nscore = evaluate(your_program)\n```\n\n### Evaluate 参数配置\n\n| 参数 | 类型 | 默认值 | 说明 |\n|------|------|--------|------|\n| `dev` | list[Example] | 必需 | 开发/测试集 |\n| `metric` | Callable | 必需 | 评估指标函数 |\n| `num_threads` | int | 1 | 并行评估线程数 |\n| `max_errors` | int | -1 | 最大允许错误数 |\n| `return_outputs` | bool | False | 是否返回详细输出 |\n| `display` | bool | True | 是否显示进度 |\n\n### 评估流程\n\n```mermaid\nsequenceDiagram\n    participant User as 用户\n    participant Eval as Evaluate\n    participant Module as dspy.Module\n    participant Metric as Metric函数\n    participant Example as Example数据\n    \n    User->>Eval: evaluate(program)\n    Loop 遍历测试集\n        Eval->>Module: forward(example.inputs())\n        Module-->>Eval: Prediction\n        Eval->>Metric: metric(example, pred, trace)\n        Metric-->>Eval: score (bool/float)\n    End\n    Eval->>Eval: 聚合分数\n    Eval-->>User: 平均分数\n```\n\n## 指标函数（Metrics）\n\n### 指标函数签名\n\n指标函数是评估的核心，它们接受三个参数并返回布尔值或浮点数：\n\n```python\ndef metric(\n    example: Example,  # 测试样本，包含输入和标签\n    pred: Prediction,  # 模型预测结果\n    trace: Trace | None  # 可选的执行轨迹（用于优化器）\n) -> bool | float\n```\n\n### 预置指标\n\nDSPy 在 `dspy.evaluate.metrics` 模块中提供了一些常用的预置指标。开发者也可以根据需求自定义指标函数。 资料来源：[dspy/evaluate/metrics.py:1-50]()\n\n### 自定义指标示例\n\n#### 精确匹配指标\n\n```python\ndef exact_match_metric(example, pred, trace=None):\n    \"\"\"检查预测答案是否与标签完全匹配（忽略大小写）\"\"\"\n    return example.answer.lower() == pred.answer.lower()\n\n# 使用示例\ngold = dspy.Example(question=\"What is 1+1?\", answer=\"2\").with_inputs(\"question\")\npred = dspy.Prediction(answer=\"2\")\nexact_match_metric(gold, pred)  # True\n```\n\n#### 包含检查指标\n\n```python\ndef answer_contains_metric(example, pred, trace=None):\n    \"\"\"检查标签是否被预测答案包含\"\"\"\n    return example.answer.lower() in pred.answer.lower()\n```\n\n#### 带权重的复合指标\n\n```python\ndef composite_metric(example, pred, trace=None):\n    \"\"\"组合多个子指标\"\"\"\n    exact_match = example.answer.lower() == pred.answer.lower()\n    length_penalty = len(pred.answer) > 0\n    return float(exact_match) * 0.8 + float(length_penalty) * 0.2\n```\n\n## 自动评估（Auto Evaluation）\n\nDSPy 提供了自动评估功能，支持在没有人工标注标签的情况下进行程序评估。这对于迭代优化过程中的快速反馈特别有用。 资料来源：[dspy/evaluate/auto_evaluation.py:1-30]()\n\n### 自动评估工作流\n\n```mermaid\ngraph LR\n    A[程序输出] --> B[Auto Evaluator]\n    B --> C{是否有参考标签}\n    C -->|是| D[使用参考指标]\n    C -->|否| E[使用LLM评判]\n    D --> F[评估分数]\n    E --> F\n```\n\n### LLM 作为评估器\n\n当没有预定义标签时，可以使用大语言模型本身来评估输出质量：\n\n```python\nimport dspy\n\n# 使用LLM进行自动评估\ndef llm_judge_metric(example, pred, trace=None):\n    lm = dspy.LM(\"openai/gpt-4\")\n    prompt = f\"\"\"评估以下回答的质量：\n    \n    问题: {example.question}\n    回答: {pred.answer}\n    \n    回答是否准确、完整且相关？只需回答 '是' 或 '否'。\"\"\"\n    \n    response = lm(prompt)\n    return \"是\" in response.lower()\n\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=llm_judge_metric,\n)\n```\n\n## 数据集（datasets）\n\nDSPy 的数据集模块提供了加载和管理评估数据的功能。`Dataset` 类是数据管理的基础抽象，支持多种数据格式和加载方式。 资料来源：[dspy/datasets/__init__.py:1-30]()\n\n### 加载内置数据集\n\n```python\nimport dspy\nfrom dspy.datasets import GSM8K, HotPotQA\n\n# 加载 GSM8K 数学数据集\ngsm8k = GSM8K()\ntrainset = gsm8k.train\ndevset = gsm8k.dev\n\n# 加载 HotPotQA 问答数据集\nhotpot = HotPotQA()\ntestset = hotpot.dev\n```\n\n### DataLoader API\n\n`DataLoader` 提供了标准化的数据加载接口，支持训练集、验证集和测试集的划分： 资料来源：[dspy/datasets/dataloader.py:1-50]()\n\n| 方法 | 说明 |\n|------|------|\n| `from Hub` | 从模型Hub加载数据集 |\n| `from_jsonl` | 从JSONL文件加载 |\n| `from_dicts` | 从字典列表加载 |\n| `train_test_split` | 划分训练集和测试集 |\n\n### 自定义数据集\n\n```python\nfrom dspy.datasets import Dataset\n\nclass MyDataset(Dataset):\n    def __init__(self, path):\n        super().__init__()\n        self._data = self._load_from_file(path)\n    \n    def _load_from_file(self, path):\n        # 自定义加载逻辑\n        pass\n\n# 使用自定义数据集\ndataset = MyDataset(\"path/to/data.jsonl\")\ntrainset = dataset.train\ndevset = dataset.dev\n```\n\n## 与优化器的集成\n\n评估系统与 DSPy 的 Teleprompter 优化器紧密集成。优化器使用评估指标来引导搜索最优的程序配置（提示词、示例选择等）。\n\n```mermaid\ngraph LR\n    A[BootstrapFewShot] --> B[评估指标]\n    C[MIPROv2] --> B\n    D[GEPA] --> B\n    B --> E[优化搜索]\n    E --> F[最优配置]\n```\n\n### 完整优化流程\n\n```python\nimport dspy\n\n# 1. 定义程序\nprogram = dspy.ChainOfThought(\"question -> answer\")\n\n# 2. 准备数据集\ntrainset = [\n    dspy.Example(question=q, answer=a).with_inputs(\"question\")\n    for q, a in question_answer_pairs\n]\n\n# 3. 定义指标\ndef exact_match(example, pred, trace=None):\n    return example.answer.lower() == pred.answer.lower()\n\n# 4. 使用优化器（内部使用评估）\noptimizer = dspy.MIPROv2(metric=exact_match)\ncompiled_program = optimizer.compile(\n    program,\n    trainset=trainset,\n    max_bootstrapped_demos=4,\n)\n```\n\n## 最佳实践\n\n### 指标设计原则\n\n1. **确定性**：相同输入应产生相同分数，避免随机性\n2. **高效性**：指标函数会被频繁调用，应尽量轻量\n3. **可解释性**：分数应能清晰反映输出质量\n4. **可组合性**：支持复合指标以评估多个维度\n\n### 评估执行建议\n\n| 场景 | 建议 |\n|------|------|\n| 快速原型开发 | 使用 `num_threads=-1` 启用所有CPU核心 |\n| 调试 | 设置 `return_outputs=True` 获取详细输出 |\n| 生产环境 | 设置合理的 `max_errors` 避免无限等待 |\n| 大规模评估 | 分批评估并保存中间结果 |\n\n### 常见问题处理\n\n**处理评估超时**：\n```python\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=my_metric,\n    max_errors=10,  # 跳过有问题的样本\n    num_threads=4,\n)\n```\n\n**获取详细评估日志**：\n```python\nevaluate = dspy.Evaluate(\n    dev=testset,\n    metric=my_metric,\n    return_outputs=True,\n    display=True,\n)\nresults = evaluate(program)\nfor i, (example, pred, score) in enumerate(results.outputs):\n    print(f\"[{i}] Score: {score}\")\n```\n\n## 相关模块\n\n- [预测模块 (Predict)](./predict.md) - 生成预测的模块\n- [优化器 (Teleprompter)](./teleprompt.md) - 优化程序配置的优化器\n- [示例模块 (Example)](./primitives.md) - 数据结构基础\n\n## 参考链接\n\n- DSPy 官方文档：https://dspy.ai\n- 评估指标文档：[dspy.evaluate.metrics](https://github.com/stanfordnlp/dspy/blob/main/dspy/evaluate/metrics.py)\n- 数据集模块：[dspy.datasets](https://github.com/stanfordnlp/dspy/blob/main/dspy/datasets/__init__.py)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：stanfordnlp/dspy\n\n摘要：发现 19 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read。\n\n## 1. 安全/权限坑 · 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_43291e191b234ac883662982bf693e18 | https://github.com/stanfordnlp/dspy/issues/9749 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：3.0.4b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.0.4b1\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_76f47f2d6cbc4f299fe2a852b20617ef | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：3.1.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.2\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3733e2d7817440638629959030da2ddb | https://github.com/stanfordnlp/dspy/releases/tag/3.1.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：3.1.3\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.3\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b7f0c4a046840b4b453167ce581b80a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：3.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.2.0\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_976a3edffce44ac3984c9da4a10a2575 | https://github.com/stanfordnlp/dspy/releases/tag/3.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：Use Tool functions that require external libaries in CodeAct\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Use Tool functions that require external libaries in CodeAct\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c605227d53e42b69651c46c3e76c162 | https://github.com/stanfordnlp/dspy/issues/8839 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:587050620 | https://github.com/stanfordnlp/dspy | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：3.0.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d192b20b863c476ca31d4ba476cec875 | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：3.0.4b2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4b2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_392f60c647b74a6592f1692bcdc0070f | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 13. 安全/权限坑 · 来源证据：3.1.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364bbccd7d4241c9b6841303fefb5a85 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：3.1.0b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0b1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4599cbf0d1fd41b4b3c47e5c1aae247a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. 安全/权限坑 · 来源证据：3.1.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5656ac7c80214b9fb410d129ccec33d2 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：3.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.2.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2250d3118a04c5e8d213eb2fce4e68d | https://github.com/stanfordnlp/dspy/releases/tag/3.2.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安全/权限坑 · 来源证据：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bb4eb14c9ce944f0a7654217c34b1d1d | https://github.com/stanfordnlp/dspy/issues/9501 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 18. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | issue_or_pr_quality=unknown\n\n## 19. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | release_recency=unknown\n\n<!-- canonical_name: stanfordnlp/dspy; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：stanfordnlp/dspy\n\n摘要：发现 19 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read。\n\n## 1. 安全/权限坑 · 来源证据：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PythonInterpreter: paths containing commas are silently misparsed by Deno's --allow-read\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_43291e191b234ac883662982bf693e18 | https://github.com/stanfordnlp/dspy/issues/9749 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：3.0.4b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.0.4b1\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_76f47f2d6cbc4f299fe2a852b20617ef | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：3.1.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.2\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3733e2d7817440638629959030da2ddb | https://github.com/stanfordnlp/dspy/releases/tag/3.1.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：3.1.3\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.1.3\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b7f0c4a046840b4b453167ce581b80a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：3.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：3.2.0\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_976a3edffce44ac3984c9da4a10a2575 | https://github.com/stanfordnlp/dspy/releases/tag/3.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：Use Tool functions that require external libaries in CodeAct\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Use Tool functions that require external libaries in CodeAct\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c605227d53e42b69651c46c3e76c162 | https://github.com/stanfordnlp/dspy/issues/8839 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:587050620 | https://github.com/stanfordnlp/dspy | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:587050620 | https://github.com/stanfordnlp/dspy | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：3.0.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d192b20b863c476ca31d4ba476cec875 | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：3.0.4b2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.0.4b2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_392f60c647b74a6592f1692bcdc0070f | https://github.com/stanfordnlp/dspy/releases/tag/3.0.4b2 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 13. 安全/权限坑 · 来源证据：3.1.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_364bbccd7d4241c9b6841303fefb5a85 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：3.1.0b1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.0b1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4599cbf0d1fd41b4b3c47e5c1aae247a | https://github.com/stanfordnlp/dspy/releases/tag/3.1.0b1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. 安全/权限坑 · 来源证据：3.1.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.1.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5656ac7c80214b9fb410d129ccec33d2 | https://github.com/stanfordnlp/dspy/releases/tag/3.1.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：3.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：3.2.1\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2250d3118a04c5e8d213eb2fce4e68d | https://github.com/stanfordnlp/dspy/releases/tag/3.2.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安全/权限坑 · 来源证据：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug] PythonInterpreter fails with default setup due to missing Deno read permissions for Pyodide\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bb4eb14c9ce944f0a7654217c34b1d1d | https://github.com/stanfordnlp/dspy/issues/9501 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 18. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | issue_or_pr_quality=unknown\n\n## 19. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:587050620 | https://github.com/stanfordnlp/dspy | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# dspy - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 dspy 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的软件开发与交付任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 示例引导, 判断线索。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 安装前能力预览: DSPy: The framework for programming—not prompting—language models 输入：用户任务, 当前 AI 对话上下文；输出：示例引导, 判断线索。\n\n【必须安装后才可验证的能力】\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. page-overview：DSPy概述。围绕“DSPy概述”模拟一次用户任务，不展示安装或运行结果。\n2. page-installation：安装与快速开始。围绕“安装与快速开始”模拟一次用户任务，不展示安装或运行结果。\n3. page-signatures：签名（Signatures）。围绕“签名（Signatures）”模拟一次用户任务，不展示安装或运行结果。\n4. page-modules：内置模块参考。围绕“内置模块参考”模拟一次用户任务，不展示安装或运行结果。\n5. page-primitives：原语与数据结构。围绕“原语与数据结构”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. page-overview\n输入：用户提供的“DSPy概述”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. page-installation\n输入：用户提供的“安装与快速开始”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. page-signatures\n输入：用户提供的“签名（Signatures）”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. page-modules\n输入：用户提供的“内置模块参考”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. page-primitives\n输入：用户提供的“原语与数据结构”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / page-overview：Step 1 必须围绕“DSPy概述”形成一个小中间产物，并等待用户确认。\n- Step 2 / page-installation：Step 2 必须围绕“安装与快速开始”形成一个小中间产物，并等待用户确认。\n- Step 3 / page-signatures：Step 3 必须围绕“签名（Signatures）”形成一个小中间产物，并等待用户确认。\n- Step 4 / page-modules：Step 4 必须围绕“内置模块参考”形成一个小中间产物，并等待用户确认。\n- Step 5 / page-primitives：Step 5 必须围绕“原语与数据结构”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/stanfordnlp/dspy\n- https://github.com/stanfordnlp/dspy#readme\n- dspy/__init__.py\n- dspy/__metadata__.py\n- README.md\n- dspy/primitives/module.py\n- dspy/primitives/base_module.py\n- pyproject.toml\n- dspy/utils/__init__.py\n- dspy/signatures/__init__.py\n- dspy/signatures/signature.py\n- dspy/signatures/field.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 dspy 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：stanfordnlp/dspy\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install dspy\n```\n\n来源：https://github.com/stanfordnlp/dspy#readme\n\n## 来源\n\n- repo: https://github.com/stanfordnlp/dspy\n- docs: https://github.com/stanfordnlp/dspy#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_61d8d0f5194148c490bf2613b11dd059"
}
