{
  "canonical_name": "stanfordnlp/dspy",
  "compilation_id": "pack_e6707a0f88d84002b889dd2664528a6f",
  "created_at": "2026-05-17T07:04:41.332694+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 Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Automated Workflow",
        "label_zh": "自动化工作流",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-automated-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "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> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for stanfordnlp/dspy.\n\nProject:\n- Name: dspy\n- Repository: https://github.com/stanfordnlp/dspy\n- Summary: DSPy: The framework for programming—not prompting—language models\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: DSPy: The framework for programming—not prompting—language models\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: DSPy: The framework for programming—not prompting—language models\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to DSPy. Produce one small intermediate artifact and wait for confirmation.\n2. core-architecture: Core Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. signatures: Signatures System. Produce one small intermediate artifact and wait for confirmation.\n4. modules: Module System. Produce one small intermediate artifact and wait for confirmation.\n5. adapters: Adapters. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/stanfordnlp/dspy\n- https://github.com/stanfordnlp/dspy#readme\n- README.md\n- dspy/__init__.py\n- dspy/__metadata__.py\n- dspy/primitives/__init__.py\n- dspy/primitives/base_module.py\n- dspy/primitives/module.py\n- dspy/primitives/prediction.py\n- dspy/primitives/example.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\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-17 06:56:43 UTC\n\n## 目录\n\n- [Introduction to DSPy](#introduction)\n- [Installation and Setup](#installation)\n- [Core Architecture](#core-architecture)\n- [Signatures System](#signatures)\n- [Module System](#modules)\n- [Adapters](#adapters)\n- [Language Model Clients](#lm-clients)\n- [Prediction Modules](#predict-modules)\n- [Agent Modules](#agent-modules)\n- [Optimizers (Teleprompt)](#optimizers)\n\n<a id='introduction'></a>\n\n## Introduction to DSPy\n\n### 相关页面\n\n相关主题：[Installation and Setup](#installation), [Core Architecture](#core-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.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/adapters/types/document.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/document.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n</details>\n\n# Introduction to DSPy\n\nDSPy (Declarative Self-Improving Language Model Programs) is a framework for building and optimizing LLM-based pipelines. It provides a systematic approach to compiling declarative module calls into self-improving pipelines that can automatically optimize prompts and weights.\n\n资料来源：[README.md:1]()\n\n## Core Philosophy\n\nDSPy abstracts away the complexity of prompt engineering by allowing developers to define programs as modules with signatures rather than manually crafting prompts. The framework then automatically optimizes how these modules interact to achieve better performance.\n\n```mermaid\ngraph TD\n    A[User Defined Program] --> B[DSPy Signatures]\n    B --> C[DSPy Modules]\n    C --> D[Optimizer Compilation]\n    D --> E[Optimized Pipeline]\n    E --> F[Better Results]\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Key Concepts\n\n### Signatures\n\nSignatures define the input-output schema for modules. They specify which fields are inputs and which are outputs using `InputField` and `OutputField` decorators.\n\n```python\nclass MySignature(dspy.Signature):\n    input_text: str = dspy.InputField(desc=\"Input sentence\")\n    output_text: str = dspy.OutputField(desc=\"Translated sentence\")\n```\n\n资料来源：[dspy/signatures/signature.py:1-30]()\n\n### Modules\n\nAll DSPy programs inherit from `dspy.Module`, which provides methods for managing predictors and configuring language models.\n\n| Method | Description |\n|--------|-------------|\n| `forward()` | Define the program's logic |\n| `named_predictors()` | Get all Predict modules with names |\n| `predictors()` | Get all Predict modules |\n| `set_lm(lm)` | Set language model for all predictors |\n| `get_lm()` | Retrieve the configured language model |\n\n资料来源：[dspy/primitives/module.py:50-100]()\n\n### Examples\n\nThe `Example` class represents data records used for training and evaluation. It supports input/label separation and dictionary-like access.\n\n```python\nexample = dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\")\n```\n\n| Method | Purpose |\n|--------|---------|\n| `with_inputs(*keys)` | Mark fields as inputs |\n| `inputs()` | Get only input fields |\n| `labels()` | Get only label fields |\n| `toDict()` | Convert to JSON-friendly dict |\n| `get(key, default)` | Dictionary-style access |\n\n资料来源：[dspy/primitives/example.py:1-100]()\n\n### Predict\n\n`Predict` is the core module that generates completions based on a signature. It can be configured with or without chain-of-thought reasoning.\n\n```python\npredictor = dspy.Predict(\"question -> answer\")\npredictor = dspy.ChainOfThought(\"question -> answer\")\n```\n\n资料来源：[dspy/primitives/module.py:80-120]()\n\n## Installation\n\n### Standard Installation\n\n```bash\npip install dspy\n```\n\n### Development Installation\n\nFor the latest features from the main branch:\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:5-12]()\n\n### Development Environment Setup\n\nPython 3.10 or later is required. The recommended setup uses `uv`:\n\n```shell\nuv venv --python 3.10\nuv sync --extra dev\n```\n\nRun tests with:\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:40-80]()\n\n## Basic Usage Pattern\n\n```mermaid\ngraph LR\n    A[Define Signature] --> B[Create Module]\n    B --> C[Configure LM]\n    C --> D[Compile with Optimizer]\n    D --> E[Run Program]\n```\n\n### Step 1: Define a Signature\n\n```python\nclass QA(dspy.Signature):\n    \"\"\"Answer questions based on the context.\"\"\"\n    context: str = dspy.InputField(desc=\"Context for answering\")\n    question: str = dspy.InputField(desc=\"Question to answer\")\n    answer: str = dspy.OutputField(desc=\"Answer to the question\")\n```\n\n### Step 2: Build a Module\n\n```python\nclass RAG(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.qa = dspy.Predict(QA)\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.qa(context=context, question=question)\n```\n\n### Step 3: Configure Language Model\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\ndspy.configure(lm=lm)\n```\n\n### Step 4: Compile and Run\n\n```python\ncompiled_rag = dspy.compile(RAG(), trainset=trainset, metric=metric)\nresult = compiled_rag(question=\"What is DSPy?\")\n```\n\n## Supported Data Types\n\nDSPy provides specialized types for common LLM use cases:\n\n| Type | Purpose |\n|------|---------|\n| `Document` | Text content with title and citations support |\n| `History` | Conversation history for multi-turn interactions |\n| `Image` | Image inputs with URL/base64 encoding |\n| `Citations` | Citation metadata from models |\n\n### Document\n\n```python\ndoc = Document(\n    data=\"The Earth orbits the Sun.\",\n    title=\"Basic Astronomy Facts\"\n)\n```\n\n资料来源：[dspy/adapters/types/document.py:1-50]()\n\n### History\n\n```python\nhistory = History(messages=[\n    {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n])\n```\n\n资料来源：[dspy/adapters/types/history.py:1-50]()\n\n## Embedding Support\n\nThe `Embedder` class provides a unified interface for embedding models:\n\n```python\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\")\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\nConfiguration options:\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `model` | Required | Embedding model name or callable |\n| `batch_size` | 200 | Number of texts per batch |\n| `caching` | True | Enable result caching |\n\n资料来源：[dspy/clients/embedding.py:1-60]()\n\n## Teleprompters and Optimization\n\nDSPy includes teleprompters that automatically optimize prompts and weights:\n\n```python\noptimizer = BootstrapFewShotWithRandomSearch(metric=metric)\ncompiled_program = optimizer.compile(student=student_program, trainset=trainset)\n```\n\nAvailable optimizers include:\n- `BootstrapFewShotWithRandomSearch` - Bootstrap demonstrations with random search\n- `BootstrapFinetune` - Fine-tune weights on bootstrapped data\n- `GEPA` - Reflective prompt evolution\n- `BetterTogether` - Combined prompt + weight optimization\n\n资料来源：[dspy/teleprompt/bettertogether.py:1-50]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"User Layer\"\n        A[User Program]\n        B[Signatures]\n        C[Examples]\n    end\n    \n    subgraph \"Core Layer\"\n        D[Module]\n        E[Predict]\n        F[ChainOfThought]\n        G[Retrieve]\n    end\n    \n    subgraph \"Optimization Layer\"\n        H[Teleprompters]\n        I[Proposers]\n        J[Metrics]\n    end\n    \n    subgraph \"Adapter Layer\"\n        K[Document]\n        L[History]\n        M[Image]\n        N[Citations]\n    end\n    \n    subgraph \"Client Layer\"\n        O[LM Client]\n        P[Embedding Client]\n        Q[Retriever Clients]\n    end\n    \n    A --> D\n    B --> D\n    C --> H\n    D --> E\n    E --> H\n    H --> I\n    K --> O\n    L --> O\n    M --> O\n    N --> O\n    O --> P\n    O --> Q\n```\n\n## Citation\n\nIf you use DSPy in your research, please cite:\n\n> **[Oct'23] [DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines](https://arxiv.org/abs/2310.03714)**\n\n资料来源：[README.md:20-30]()\n\n## Documentation and Resources\n\nFor comprehensive documentation, visit the [DSPy Docs at dspy.ai](https://dspy.ai).\n\n### Research Papers\n\n| Paper | Date | Description |\n|-------|------|-------------|\n| GEPA: Reflective Prompt Evolution | Jul'25 | Alternative to RL |\n| Optimizing Instructions and Demonstrations | Jun'24 | Multi-stage optimization |\n| DSPy: Compiling Declarative LM Calls | Oct'23 | Core framework paper |\n| Fine-Tuning and Prompt Optimization | Jul'24 | Joint optimization |\n| Prompts as Auto-Optimized Training Hyperparameters | Jun'24 | Hyperparameter analogy |\n\n资料来源：[README.md:15-35]()\n\n---\n\n<a id='installation'></a>\n\n## Installation and Setup\n\n### 相关页面\n\n相关主题：[Introduction to DSPy](#introduction), [Language Model Clients](#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- [pyproject.toml](https://github.com/stanfordnlp/dspy/blob/main/pyproject.toml)\n</details>\n\n# Installation and Setup\n\nThis page covers how to install DSPy and configure your development environment for working with the framework.\n\n## Overview\n\nDSPy (Declarative Self-Improving Language Model Programs) is a Python framework that compiles declarative language model calls into self-improving pipelines. The installation process supports both end-user usage via pip and contributor workflows with advanced development tools. 资料来源：[README.md]()\n\n## Prerequisites\n\n### System Requirements\n\n| Requirement | Minimum | Recommended |\n|-------------|---------|-------------|\n| Python Version | 3.10 | 3.11 or later |\n| Operating System | Linux, macOS, Windows | Linux/macOS |\n| Package Manager | pip | uv (Rust-based) |\n\n资料来源：[CONTRIBUTING.md]()\n\n## Basic Installation\n\n### Installing from PyPI\n\nThe simplest way to install DSPy is using pip:\n\n```bash\npip install dspy\n```\n\n资料来源：[README.md]()\n\n### Installing from Source\n\nTo install the latest development version from the main branch:\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\nThis approach installs the most up-to-date code that may include features not yet released to PyPI.\n\n资料来源：[README.md]()\n\n## Development Environment Setup\n\nFor contributors who want to modify DSPy or run tests, a development environment setup is required.\n\n### Fork and Clone\n\nFirst, fork the repository on GitHub, then clone your fork locally:\n\n```shell\ngit clone {url-to-your-fork}\ncd dspy\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Using uv (Recommended)\n\n[uv](https://github.com/astral-sh/uv) is a Rust-based Python package and project manager that provides fast dependency resolution and virtual environment management.\n\n#### Installation of uv\n\nFollow the [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/) to install uv on your system.\n\n#### Environment Creation\n\nCreate a virtual environment using Python 3.10:\n\n```shell\nuv venv --python 3.10\n```\n\nThis creates a `.venv` directory in your project root.\n\n#### Dependency Synchronization\n\nSync the environment with development dependencies:\n\n```shell\nuv sync --extra dev\n```\n\n#### Verification\n\nRun unit tests to verify the setup:\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Using conda + pip\n\nAn alternative approach using conda and pip is available for users who prefer this workflow.\n\n#### Environment Creation\n\n```shell\nconda create -n dspy-dev python=3.10\nconda activate dspy-dev\n```\n\n#### Package Installation\n\n```shell\npip install -e \".[dev]\"\n```\n\nThe `-e` flag installs the package in editable mode, allowing code changes to take effect without reinstallation.\n\n#### Verification\n\n```shell\npytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Environment Management Patterns\n\n### Using uv run\n\nThe `uv run` prefix must be used for every Python command when using the uv-managed environment:\n\n| Action | Command |\n|--------|---------|\n| Run tests | `uv run pytest tests/predict` |\n| Execute script | `uv run python script.py` |\n| Install package | `uv run pip install package-name` |\n\n资料来源：[CONTRIBUTING.md]()\n\n### Development Workflow\n\n```mermaid\ngraph TD\n    A[Fork Repository] --> B[Clone Your Fork]\n    B --> C[Install uv]\n    C --> D[Create venv with Python 3.10]\n    D --> E[Sync dependencies with dev extras]\n    E --> F[Run tests to verify]\n    F --> G[Start development]\n    G --> H[Make changes]\n    H --> I[Commit changes]\n    I --> J[Push to fork]\n    J --> K[Create Pull Request]\n```\n\n## Project Configuration\n\n### pyproject.toml Structure\n\nThe project uses `pyproject.toml` for dependency management and package configuration. Key sections include:\n\n- **build-system**: Build backend configuration\n- **project**: Core dependencies and project metadata\n- **project.optional-dependencies**: Extra dependencies for different features (dev, etc.)\n\n资料来源：[pyproject.toml]()\n\n## Pre-commit Hooks\n\nDSPy uses pre-commit hooks to maintain code quality. After installing dependencies, hooks are automatically installed but need to be staged and committed along with your changes.\n\n### Running Hooks Manually\n\n| Command | Purpose |\n|---------|---------|\n| `pre-commit run` | Check all staged files |\n| `pre-commit run --files path/to/file.py` | Check specific files |\n\nAll pre-commit checks must pass before creating a pull request. You can commit changes and let hooks fix formatting issues automatically.\n\n资料来源：[CONTRIBUTING.md]()\n\n## Verification Checklist\n\nAfter completing installation, verify your setup by checking:\n\n1. Python version: `python --version` (should be 3.10+)\n2. DSPy import: `python -c \"import dspy; print(dspy.__version__)\"`\n3. Running basic tests: `uv run pytest tests/predict -v`\n\n## Next Steps\n\nAfter successful installation and setup:\n\n- Review the [DSPy documentation](https://dspy.ai) for framework concepts\n- Explore the signature system for defining module inputs/outputs\n- Set up your language model configuration\n- Try the teleprompters for prompt optimization\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Python version too old | Upgrade to Python 3.10 or later |\n| uv command not found | Install uv following the official guide |\n| Tests fail after install | Ensure dependencies are fully synced with `uv sync --extra dev` |\n| Pre-commit hooks not running | Run `pre-commit install` to enable hooks |\n\n## Related Documentation\n\n- [DSPy Official Docs](https://dspy.ai)\n- [GitHub Repository](https://github.com/stanfordnlp/dspy)\n- [Research Papers](https://github.com/stanfordnlp/dspy#-citation-reading-more)\n\n---\n\n<a id='core-architecture'></a>\n\n## Core Architecture\n\n### 相关页面\n\n相关主题：[Signatures System](#signatures), [Module System](#modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\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/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# Core Architecture\n\nThe DSPy framework's core architecture provides the foundational building blocks for composing, executing, and optimizing language model programs. At its heart, DSPy separates the concerns of **program structure**, **data representation**, and **model interaction** into distinct but interconnected components.\n\n## Architecture Overview\n\nDSPy's core architecture follows a layered design where higher-level abstractions build upon primitive components. The primitives module (`dspy/primitives/`) contains the essential classes that define how programs are structured, how data flows through them, and how outputs are represented.\n\n```mermaid\ngraph TD\n    subgraph \"Core Primitives\"\n        Example[Example<br/>Data Container]\n        Module[Module<br/>Program Base]\n        Prediction[Prediction<br/>Output Container]\n    end\n    \n    subgraph \"Language Model Layer\"\n        LM[Language Model<br/>Client]\n        Embedder[Embedder<br/>Embedding Client]\n    end\n    \n    subgraph \"Program Layer\"\n        Predict[Predict Module]\n        CoT[ChainOfThought]\n        RLM[RLM Module]\n    end\n    \n    Example -->|Defines I/O| Module\n    Module -->|Executes via| LM\n    LM -->|Produces| Prediction\n    Predict -->|Uses| Module\n    RLM -->|Extends| Module\n```\n\n## Data Model Layer\n\n### The `Example` Class\n\nThe `Example` class serves as DSPy's primary data structure for representing training examples, test cases, and evaluation samples. It wraps a dictionary-based storage (`_store`) and maintains metadata about which fields are inputs versus labels.\n\n**Key Characteristics:**\n\n| Attribute | Type | Purpose |\n|-----------|------|---------|\n| `_store` | `dict` | Internal storage for field names and values |\n| `_input_keys` | `set[str] \\| None` | Tracks which fields are inputs |\n\n**Core Methods:**\n\n| Method | Purpose |\n|--------|---------|\n| `with_inputs(*keys)` | Marks specified fields as input fields |\n| `inputs()` | Returns a new Example containing only input fields |\n| `labels()` | Returns a new Example containing only non-input (label) fields |\n| `toDict()` | Recursively serializes the Example to a JSON-friendly dict |\n| `copy()` | Creates a shallow copy with optional field overrides |\n| `get(key, default)` | Retrieves a field value with optional default |\n| `keys()`, `values()`, `items()` | Dictionary-like access methods |\n\n资料来源：[dspy/primitives/example.py:1-50]()\n\n**Usage Pattern:**\n\n```python\n# Create an example with question-answer pairs\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# Access inputs and labels separately\nexample.inputs()    # Example({'question': '...'}) \nexample.labels()    # Example({'answer': '...'})\n\n# Convert to dictionary for serialization\nexample.toDict()    # {'question': '...', 'answer': '...'}\n```\n\nThe `toDict()` method handles nested objects by recursively converting `Example` objects, Pydantic models, lists, and dicts to JSON-friendly structures.\n\n资料来源：[dspy/primitives/example.py:1-30]()\n\n### The `Prediction` Class\n\nThe `Prediction` class represents the output of a DSPy program execution. It encapsulates the results produced by language model calls, typically containing fields that correspond to the output fields defined in a signature.\n\n## Program Structure Layer\n\n### The `Module` Class\n\nThe `Module` class is the fundamental base class from which all DSPy programs inherit. It provides the runtime infrastructure for composing language model calls, managing parameters, and executing programs.\n\n**Key Methods:**\n\n| Method | Returns | Description |\n|--------|---------|-------------|\n| `named_predictors()` | `list[tuple[str, Predict]]` | Returns all Predict modules with their attribute names |\n| `predictors()` | `list[Predict]` | Returns only the Predict module instances |\n| `set_lm(lm)` | `None` | Recursively sets the language model for all contained Predict modules |\n| `get_lm()` | `LM` | Returns the language model if all predictors share the same LM |\n\n资料来源：[dspy/primitives/module.py:1-60]()\n\n**Predictor Discovery:**\n\nThe `named_predictors()` method uses introspection to find all `Predict` instances within a 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\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(name)  # 'qa', 'summarize'\n```\n\n资料来源：[dspy/primitives/module.py:1-45]()\n\n### Language Model Integration\n\nThe `set_lm()` method traverses the module's parameter tree to attach a language model to every `Predict` instance:\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram.set_lm(lm)\n```\n\nThis recursive propagation ensures that nested modules and chained predictors all share the same language model configuration.\n\n资料来源：[dspy/primitives/module.py:45-55]()\n\n## Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Module\n    participant Predict\n    participant LM\n    participant Prediction\n    \n    User->>Module: forward(**inputs)\n    Module->>Predict: forward(**inputs)\n    Predict->>LM: generate(input_fields, signature)\n    LM-->>Predict: raw_output\n    Predict->>Prediction: format(raw_output, signature)\n    Prediction-->>Module: Prediction object\n    Module-->>User: Program output\n    \n    Note over Predict: Validates and transforms<br/>LM output according<br/>to Signature fields\n```\n\n## Signature-Based Input/Output Contract\n\nDSPy programs use **Signatures** to define the contract between modules and language models. A signature specifies input fields and output fields, along with optional descriptions that guide the LM's behavior.\n\nThe `Signature.with_updated_fields()` method allows runtime modification of field metadata:\n\n```python\nNewSig = MySig.with_updated_fields(\n    \"output_text\", \n    desc=\"The translated French text\"\n)\n```\n\n资料来源：[dspy/signatures/signature.py:1-40]()\n\n## Extended Modules\n\n### RLM (Recursive Language Model)\n\nThe `RLM` class extends the base `Module` to provide sandboxed REPL-based code execution capabilities, enabling LLMs to programmatically explore large contexts through Python code:\n\n```python\nrlm = RLM(\n    sandbox=\"python\",  # or \"bash\"\n    timeout=30\n)\n```\n\n资料来源：[dspy/predict/rlm.py:1-30]()\n\n### Embedder\n\nThe `Embedder` class provides a consistent interface for embedding generation with built-in batching and caching:\n\n```python\nembedder = dspy.Embedder(\n    model=\"openai/text-embedding-3-small\",\n    batch_size=200,\n    caching=True\n)\n```\n\n资料来源：[dspy/clients/embedding.py:1-50]()\n\n## Callback System\n\nDSPy's callback system (`dspy/utils/callback.py`) enables observability and instrumentation of program execution:\n\n```mermaid\ngraph LR\n    A[Module Forward] -->|on_module_start| B[Callback Handler]\n    B --> C[Execute]\n    C -->|on_module_end| B\n```\n\nThe `CallbackHandler` base class defines hooks for:\n\n| Hook | Trigger |\n|------|---------|\n| `on_module_start()` | Before a module's `forward()` executes |\n| `on_module_end()` | After a module's `forward()` completes |\n| `on_lm_start()` | Before an LM call |\n| `on_lm_end()` | After an LM call |\n\nCallbacks can be attached either globally or per-component:\n\n```python\n# Global callback\ndspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n\n# Local callback on specific component\nlm(question=\"What is 2+2?\", callbacks=[LoggingCallback()])\n```\n\n资料来源：[dspy/utils/callback.py:1-40]()\n\n## Component Hierarchy\n\n```mermaid\ngraph TD\n    BaseModule[BaseModule<br/>dspy.primitives]\n    Module[Module<br/>extends BaseModule]\n    Program[User Program<br/>extends Module]\n    \n    Predict[Predict<br/>Signature-driven predictor]\n    ChainOfThought[ChainOfThought<br/>extends Predict]\n    RLM[RLM<br/>extends Module]\n    \n    Example[Example<br/>Data primitive]\n    Prediction[Prediction<br/>Output primitive]\n    \n    BaseModule --> Module\n    Module --> Program\n    Module --> Predict\n    Predict --> ChainOfThought\n    Module --> RLM\n    \n    Example --> Program\n    Program --> Prediction\n```\n\n## Key Design Principles\n\n1. **Separation of Concerns**: Data (`Example`, `Prediction`), structure (`Module`), and execution (`LM`) are cleanly separated\n2. **Introspection**: The module system supports dynamic discovery of contained predictors\n3. **Recursive Configuration**: Language model and other settings propagate through nested modules\n4. **Serialization**: All data primitives support conversion to JSON-compatible formats\n5. **Extensibility**: Custom modules can inherit from `Module` and use the same infrastructure\n\n## Summary\n\nDSPy's core architecture provides a composable framework where `Example` objects define inputs and labels, `Module` subclasses implement programs, `Predict` modules handle signature-driven LM interactions, and `Prediction` objects capture outputs. This architecture enables systematic optimization and evaluation of language model programs through a consistent, introspectable API.\n\n---\n\n<a id='signatures'></a>\n\n## Signatures System\n\n### 相关页面\n\n相关主题：[Core Architecture](#core-architecture), [Prediction Modules](#predict-modules)\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 System\n\n## Overview\n\nThe Signatures System is a core abstraction in DSPy that defines the structure of inputs and outputs for language model calls. A Signature describes what fields a module expects as input and what fields it will produce as output, effectively serving as a declarative contract between DSPy programs and language models.\n\nSignatures enable DSPy to:\n- Compile declarative LM calls into self-improving pipelines\n- Separate input fields from output fields for proper data routing\n- Provide rich metadata (descriptions) for each field that guides the LM's behavior\n- Support dynamic field manipulation and signature transformation\n\n资料来源：[dspy/signatures/signature.py:1-50]()\n\n## Core Concepts\n\n### InputField vs OutputField\n\nEvery field in a Signature is classified as either an `InputField` or an `OutputField`. This distinction is fundamental to DSPy's execution model:\n\n| Field Type | Purpose | Behavior |\n|------------|---------|----------|\n| `InputField` | Data provided to the LM before generation | Passed in the prompt; LM reads but does not produce |\n| `OutputField` | Data the LM should generate | Expected output; DSPy parses and validates the response |\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField(desc=\"Input question\")\n    answer: str = dspy.OutputField(desc=\"Generated answer\")\n```\n\n资料来源：[dspy/signatures/field.py:1-30]()\n\n### Field Descriptions\n\nThe `desc` parameter in InputField/OutputField provides natural language descriptions that are injected into prompts. Well-crafted descriptions significantly improve LM accuracy.\n\n```python\nclass TranslationSignature(dspy.Signature):\n    english_text: str = dspy.InputField(desc=\"The text to translate, written in English\")\n    french_text: str = dspy.OutputField(desc=\"The translated text in French\")\n```\n\n## Signature Class\n\n### Creating Signatures\n\nSignatures can be created in multiple ways:\n\n**Class-based definition:**\n```python\nclass QASignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n```\n\n**String-based definition:**\n```python\nqa_sig = make_signature(\"question -> answer\")\n```\n\n**Dictionary-based definition:**\n```python\nsig = make_signature({\n    \"question\": (str, dspy.InputField()),\n    \"answer\": (str, dspy.OutputField())\n})\n```\n\n资料来源：[dspy/signatures/signature.py:200-280]()\n\n### Signature Methods\n\nThe Signature class provides several class methods for creating modified copies:\n\n| Method | Purpose |\n|--------|---------|\n| `with_instructions(instructions)` | Create a new Signature with updated instruction text |\n| `with_updated_fields(name, type_=None, **kwargs)` | Update a field's metadata |\n| `prepend(name, field, type_=None)` | Insert a field at the beginning |\n| `append(name, field, type_=None)` | Insert a field at the end |\n| `delete(name)` | Remove a field from the signature |\n\n```python\n# Update instructions\nNewSig = MySig.with_instructions(\"Translate to French.\")\n\n# Add a new field\nEnhancedSig = MySig.append(\"confidence\", dspy.OutputField(desc=\"Translation confidence\"))\n\n# Remove a field\nSimplifiedSig = MySig.delete(\"source_language\")\n```\n\n资料来源：[dspy/signatures/signature.py:30-120]()\n\n## Signature Structure and Fields\n\n### Fields Dictionary\n\nInternally, a Signature maintains a `fields` dictionary that maps field names to their corresponding `FieldInfo` objects:\n\n```python\nclass Signature:\n    fields: dict[str, FieldInfo]\n    instructions: str\n```\n\nThe fields are automatically categorized into inputs and outputs based on whether each field uses `InputField` or `OutputField`.\n\n### Type Handling\n\nSignatures support flexible type annotations:\n\n```python\nclass CustomSig(dspy.Signature):\n    # Basic string type\n    text: str = dspy.InputField()\n    \n    # With custom type\n    history: dspy.History = dspy.InputField()\n    \n    # List of custom types\n    images: list[dspy.Image] = dspy.InputField()\n```\n\nWhen types are not explicitly provided, they default to `str` to maintain backward compatibility with existing programs.\n\n资料来源：[dspy/signatures/utils.py:1-50]()\n\n## Using Signatures with Examples\n\nThe `Example` class works in conjunction with Signatures to manage training data and evaluation:\n\n### Marking Input Fields\n\n```python\n# Mark which fields are inputs vs labels\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# Access inputs and labels separately\ninputs = example.inputs()      # Example({'question': '...'}) (input_keys={'question'})\nlabels = example.labels()     # Example({'answer': '...'}) (input_keys={'question'})\n```\n\n### Converting Examples\n\n```python\n# Convert to dictionary for serialization\ndata = example.toDict()\n\n# Copy with overrides\nnew_example = example.copy(answer=\"Lyon\")\n```\n\n资料来源：[dspy/primitives/example.py:50-150]()\n\n## Custom Types System\n\nDSPy's Type system extends Signatures with custom data types. The base `Type` class requires implementations of the `format()` method.\n\n### Built-in Custom Types\n\n| Type | Purpose |\n|------|---------|\n| `dspy.Image` | Image inputs with URL or base64 encoding |\n| `dspy.History` | Conversation history for multi-turn interactions |\n\n### Image Type\n\n```python\nclass Image(Type):\n    url: str\n    \n    def format(self) -> list[dict[str, Any]]:\n        return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n```\n\n```python\n# Usage with signatures\nclass VQASignature(dspy.Signature):\n    image: dspy.Image = dspy.InputField(desc=\"Image to analyze\")\n    question: str = dspy.InputField(desc=\"Question about the image\")\n    answer: str = dspy.OutputField(desc=\"Answer to the question\")\n```\n\n资料来源：[dspy/adapters/types/base_type.py:1-50]()\n\n### History Type\n\n```python\nclass History(Type):\n    messages: list[dict[str, Any]]\n    \n    def format(self) -> list[dict[str, Any]]:\n        # Formats conversation history as a list of message dictionaries\n        pass\n```\n\n```python\n# Usage for multi-turn conversations\nclass ChatSignature(dspy.Signature):\n    question: str = dspy.InputField()\n    history: dspy.History = dspy.InputField()\n    answer: str = dspy.OutputField()\n```\n\n资料来源：[dspy/adapters/types/history.py:1-60]()\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[Signature Definition] --> B[Field Resolution]\n    B --> C{Field Type}\n    C -->|InputField| D[Input Fields Dict]\n    C -->|OutputField| E[Output Fields Dict]\n    \n    F[make_signature] -->|String format| G[_parse_signature]\n    F -->|Dict format| H[Direct field assignment]\n    \n    I[Example with Signature] --> J[with_inputs]\n    J --> K[Inputs]\n    J --> L[Labels]\n    \n    M[Custom Types] --> N[Type.format]\n    N --> O[Image.format]\n    N --> P[History.format]\n    \n    D --> Q[Predict Module]\n    E --> Q\n    Q --> R[LM Call]\n```\n\n## Field Modification Workflow\n\n```mermaid\ngraph LR\n    A[Original Signature] --> B[with_updated_fields]\n    A --> C[prepend/append]\n    A --> D[delete]\n    \n    B --> E[Updated field metadata]\n    C --> F[New field added]\n    D --> G[Field removed]\n    \n    E --> H[Fresh Signature Instance]\n    F --> H\n    G --> H\n```\n\n## Advanced Usage\n\n### Composing Multiple Signatures\n\nSignatures can be dynamically combined using the insertion methods:\n\n```python\nclass BaseSignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\n# Add context field\nExtendedSig = BaseSignature.prepend(\n    \"context\", \n    dspy.InputField(desc=\"Additional context\")\n)\n\n# Add metadata output\nFinalSig = ExtendedSig.append(\n    \"confidence\", \n    dspy.OutputField(desc=\"Confidence score\")\n)\n```\n\n### Custom Type Extraction\n\nThe Type system automatically extracts custom types from nested annotations:\n\n```python\nclass MyType(dspy.Type):\n    @classmethod\n    def extract_custom_type_from_annotation(cls, annotation):\n        # Detects custom types in list[dict[str, MyType]]\n        pass\n```\n\nThis enables DSPy to handle complex nested structures with custom types throughout the signature system.\n\n资料来源：[dspy/adapters/types/base_type.py:40-80]()\n\n## Best Practices\n\n1. **Provide Clear Descriptions**: Always use descriptive `desc` parameters for fields to improve LM performance\n2. **Explicit Input/Output Separation**: Use `.with_inputs()` to clearly mark which fields are inputs\n3. **Leverage Type Annotations**: Use custom types like `Image` and `History` for structured data\n4. **Immutability**: Remember that signature modification methods return new instances; originals are unchanged\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| `Predict` | `dspy/predict/predict.py` | Consumes Signatures to execute LM calls |\n| `Module` | `dspy/primitives/module.py` | Container for predictor modules |\n| `Example` | `dspy/primitives/example.py` | Training/evaluation data with signature alignment |\n| `Type` | `dspy/adapters/types/base_type.py` | Base class for custom types |\n\n## Summary\n\nThe Signatures System is the foundational abstraction in DSPy that defines the interface between programs and language models. By separating inputs from outputs and providing rich metadata through field descriptions, Signatures enable DSPy's compilation and optimization capabilities. The system supports flexible creation methods, dynamic modification, and integration with custom types for complex applications.\n\n---\n\n<a id='modules'></a>\n\n## Module System\n\n### 相关页面\n\n相关主题：[Core Architecture](#core-architecture), [Prediction Modules](#predict-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/base_module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/base_module.py)\n- [dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n- [dspy/predict/parameter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parameter.py)\n- [dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n</details>\n\n# Module System\n\nThe DSPy Module System provides a declarative, composable framework for building language model programs. It serves as the foundational abstraction layer that enables automatic optimization of both prompts and model weights through DSPy's teleprompter system.\n\n## Overview\n\nDSPy's module system extends Python's native class mechanism to create reusable, optimizable building blocks for LLM pipelines. Unlike traditional Python modules, DSPy modules represent computational stages that can be automatically configured, optimized, and composed into larger programs.\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[dspy.Predict]\n    A --> C[dspy.ChainOfThought]\n    A --> D[dspy.MultiChainComparison]\n    A --> E[User-defined Module]\n    B --> F[Signature]\n    B --> G[Language Model]\n    E --> H[Other DSPy Modules]\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Core Components\n\n### Module Base Class\n\nThe `dspy.Module` class serves as the foundation for all DSPy components. It extends Python's `nn.Module` to integrate seamlessly with neural network training paradigms while adding DSPy-specific functionality.\n\n| Method | Purpose | Returns |\n|--------|---------|---------|\n| `forward()` | Execute the module's computation | `Prediction` or similar |\n| `named_predictors()` | List all Predict submodules with names | `list[tuple[str, Predict]]` |\n| `predictors()` | Return all Predict instances | `list[Predict]` |\n| `set_lm(lm)` | Set language model for all predictors | `None` |\n| `get_lm()` | Retrieve the configured language model | `LM` instance |\n\n资料来源：[dspy/primitives/module.py:60-95]()\n\n### Predictor Parameters\n\nDSPy uses `Predict` and `Parameter` classes to define trainable components within modules. These parameters encapsulate the signature and configuration for LLM calls.\n\n```python\nclass Parameter(dspy.BaseModule):\n    \"\"\"Trainable parameter that wraps a Predict module.\"\"\"\n    \n    def __init__(self, signature, **kwargs):\n        self.signature = signature\n        self.kwargs = kwargs\n```\n\n资料来源：[dspy/predict/parameter.py:1-20]()\n\n## Module Hierarchy\n\n```mermaid\ngraph TD\n    A[nn.Module] --> B[dspy.BaseModule]\n    B --> C[dspy.Module]\n    C --> D[dspy.Predict]\n    C --> E[User Module]\n    D --> F[ChainOfThought]\n    D --> G[Retry]\n    E --> H[Composite Programs]\n    F --> I[MultiChainComparison]\n```\n\n### BaseModule\n\n`BaseModule` provides the essential interface that all DSPy components implement. It establishes the contract for modules that can be used within DSPy programs.\n\n### Module\n\nThe `Module` class adds advanced functionality including:\n\n- **Automatic predictor discovery**: Scans submodules to find all `Predict` instances\n- **Language model management**: Centralized LM configuration across the module tree\n- **Serialization support**: Ability to save and load compiled programs\n\n资料来源：[dspy/primitives/module.py:40-80]()\n\n## Predictor System\n\n### Predict Class\n\n`Predict` is the primary building block for LLM interactions. It binds a `Signature` to a language model call.\n\n```python\nclass Predict(Module):\n    def __init__(self, signature, **config):\n        self.signature = dspy.Signature(signature)\n        self.config = config\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `signature` | `str` or `Signature` | Input/output field definitions |\n| `lm` | `LM` | Language model to use (optional) |\n| `temperature` | `float` | Sampling temperature (default: varies by LM) |\n| `max_tokens` | `int` | Maximum tokens in response |\n\n资料来源：[dspy/predict/predict.py:1-60]()\n\n### Predictor Discovery\n\nModules can automatically discover their predictor submodules:\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\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(f\"{name}: {predictor.signature}\")\n# Output:\n# qa: question -> answer\n# summarize: text -> summary\n```\n\n资料来源：[dspy/primitives/module.py:50-65]()\n\n## Language Model Integration\n\n### Setting Language Models\n\nLanguage models can be set at different levels of granularity:\n\n```python\n# Set LM for entire module tree\nprogram.set_lm(dspy.LM(\"openai/gpt-4o-mini\"))\n\n# Set LM for specific predictor\nprogram.qa.lm = dspy.LM(\"anthropic/claude-3\")\n\n# Retrieve configured LM\nlm = program.get_lm()\n```\n\n资料来源：[dspy/primitives/module.py:80-95]()\n\n## Signature System\n\nSignatures define the schema for module inputs and outputs. They are central to the module system's type safety and documentation.\n\n```python\nclass Signature:\n    @classmethod\n    def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n        \"\"\"Create new Signature with custom instructions.\"\"\"\n        return Signature(cls.fields, instructions)\n    \n    @classmethod\n    def with_updated_fields(cls, name: str, **kwargs) -> type[\"Signature\"]:\n        \"\"\"Update field metadata (descriptions, types).\"\"\"\n        fields_copy = deepcopy(cls.fields)\n        fields_copy[name].json_schema_extra.update(kwargs)\n        return Signature(fields_copy, cls.instructions)\n```\n\n资料来源：[dspy/signatures/signature.py:1-50]()\n\n| Method | Purpose |\n|--------|---------|\n| `prepend()` | Add input field at the beginning |\n| `append()` | Add output field at the end |\n| `delete()` | Remove a field |\n| `with_instructions()` | Create copy with new instructions |\n| `with_updated_fields()` | Update field metadata |\n\n## Creating Custom Modules\n\nCustom modules extend `dspy.Module` and compose existing predictors:\n\n```python\nimport dspy\n\nclass RAG(dspy.Module):\n    def __init__(self, num_passages=5):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=num_passages)\n        self.generate_answer = dspy.ChainOfThought(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(query=question).passages\n        return self.generate_answer(context=context, question=question)\n```\n\n## Workflow Diagram\n\n```mermaid\ngraph LR\n    A[Define Module] --> B[Compose Predictors]\n    B --> C[Set Language Model]\n    C --> D[Compile with Teleprompter]\n    D --> E[Optimized Program]\n    E --> F[Execute on new inputs]\n```\n\n## Module Configuration Options\n\n| Option | Predictor Parameter | Default | Effect |\n|--------|---------------------|---------|--------|\n| `temperature` | Per-call | LM default | Controls randomness |\n| `max_tokens` | Per-call | LM default | Limits response length |\n| `top_p` | Per-call | 1.0 | Nucleus sampling threshold |\n| `cache` | Global | True | Enable response caching |\n\n## Compilation and Optimization\n\nModules interface with DSPy's teleprompter system for automatic optimization:\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\noptimizer = BootstrapFewShot(metric=my_metric)\ncompiled_program = optimizer.compile(\n    student=MyProgram(),\n    trainset=training_examples\n)\n```\n\nThe module system provides hooks for:\n- **Prompt optimization**: Automatically improving instructions\n- **Weight optimization**: Fine-tuning model weights via `BootstrapFinetune`\n- **Demonstration selection**: Choosing optimal few-shot examples\n\n资料来源：[dspy/primitives/module.py:1-30]()\n\n## See Also\n\n- [Signature System](../signatures/signature.md) - Input/output schema definitions\n- [Predict Module](../predict/predict.md) - Core LLM interaction component\n- [Teleprompters](../teleprompt/overview.md) - Optimization strategies\n- [Evaluator](../evaluation/evaluator.md) - Metrics and evaluation\n\n---\n\n<a id='adapters'></a>\n\n## Adapters\n\n### 相关页面\n\n相关主题：[Language Model Clients](#lm-clients)\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/base_type.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/base_type.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n- [dspy/adapters/types/image.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/image.py)\n</details>\n\n# Adapters\n\nAdapters in DSPy are core components responsible for formatting and structuring messages sent to Language Models (LMs). They act as an intermediary layer between DSPy's internal data structures and the API formats expected by various LLM providers.\n\n## Overview\n\nWhen a DSPy module executes a signature (such as `dspy.Predict` or `dspy.ChainOfThought`), the adapter transforms the structured input/output fields into a format the LM can understand, and then parses the LM's response back into structured data.\n\n```mermaid\ngraph LR\n    A[Signature Fields] --> B[Adapter]\n    B --> C[LM API Format]\n    C --> D[LM Response]\n    D --> B\n    B --> E[Structured Output]\n```\n\n**Key Responsibilities:**\n\n| Responsibility | Description |\n|----------------|-------------|\n| Input Formatting | Convert DSPy input fields into prompt content |\n| Output Parsing | Parse LM responses into structured output fields |\n| Format Selection | Support various output formats (JSON, XML, Chat, etc.) |\n| Type Handling | Process custom types like `Image`, `History`, etc. |\n\n资料来源：[dspy/adapters/__init__.py:1-50]()\n\n## Architecture\n\n### Base Adapter\n\nAll adapters inherit from `dspy.adapters.base.BaseAdapter`, which defines the common interface:\n\n```mermaid\nclassDiagram\n    class BaseAdapter {\n        +format(signature, demos, inputs) List[Message]\n        +parse(signature, completion) dict\n        +format_extractors(signature) str\n    }\n    \n    class ChatAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    class JSONAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    class XMLAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    BaseAdapter <|-- ChatAdapter\n    BaseAdapter <|-- JSONAdapter\n    BaseAdapter <|-- XMLAdapter\n```\n\n**BaseAdapter Methods:**\n\n| Method | Purpose |\n|--------|---------|\n| `format(signature, demos, inputs)` | Format inputs and demonstrations into messages for the LM |\n| `parse(signature, completion)` | Parse LM completion text into structured output dictionary |\n| `format_extractors(signature)` | Generate extractor prompt text for output fields |\n\n资料来源：[dspy/adapters/base.py:1-100]()\n\n### Adapter Selection\n\nAdapters can be selected at different levels:\n\n1. **Global Configuration**: Set via `dspy.configure(adapter=...)`\n2. **Per-Module**: Pass `adapter` parameter to module constructors\n3. **Default**: `ChatAdapter` is used when no adapter is specified\n\n```python\n# Global configuration\ndspy.configure(adapter=dspy.JSONAdapter())\n\n# Per-module configuration\npredict = dspy.Predict(\"question -> answer\", adapter=dspy.XMLAdapter())\n```\n\n## Built-in Adapters\n\n### ChatAdapter\n\nThe default adapter that formats messages in OpenAI's chat format. It uses special delimiters to separate input fields, demonstrations, and output fields.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | Chat messages array |\n| Delimiter | `<<SYS>>` / `<<CONTEXT>>` / `<<RESPONSE>>` |\n| Best For | General purpose, GPT-4, Claude models |\n\n**Message Structure:**\n\n```mermaid\ngraph TD\n    A[System Message] --> B[Instructions]\n    B --> C[Input Fields]\n    C --> D[Demos Section]\n    D --> E[Output Fields Request]\n    E --> F[User Message]\n```\n\n资料来源：[dspy/adapters/chat_adapter.py:1-150]()\n\n### JSONAdapter\n\nFormats outputs as JSON, instructing the LM to respond with valid JSON that can be directly parsed.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | JSON in response |\n| Extraction | JSON parsing |\n| Best For | Structured data extraction, function calling |\n\n**Parsing Logic:**\n\n```python\n# The adapter looks for JSON blocks in the completion\njson_match = re.search(r\"```json\\s*(.*?)\\s*```\", completion, re.DOTALL)\nif json_match:\n    return json.loads(json_match.group(1))\n```\n\n资料来源：[dspy/adapters/json_adapter.py:1-100]()\n\n### XMLAdapter\n\nUses XML-style tags to delimit fields, providing a structured format similar to HTML/XML.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | XML-tagged response |\n| Delimiter | `<question>`, `<answer>`, etc. |\n| Best For | Hierarchical or nested outputs |\n\n**Example Output Format:**\n\n```xml\n<answer>\n  The capital of France is Paris.\n</answer>\n```\n\n资料来源：[dspy/adapters/xml_adapter.py:1-100]()\n\n### TwoStepAdapter\n\nA specialized adapter that breaks the response into two steps:\n\n1. **Thought Step**: The LM first provides reasoning or analysis\n2. **Response Step**: The LM provides the final structured output\n\nThis adapter is particularly useful with `dspy.ChainOfThought` modules.\n\n资料来源：[dspy/adapters/two_step_adapter.py:1-100]()\n\n### BamlAdapter\n\nAdapter specifically designed for BAML (Business Application Markup Language) output formatting, used with BAML-compiled signatures.\n\n资料来源：[dspy/adapters/baml_adapter.py:1-50]()\n\n## Custom Types\n\nDSPy adapters support custom types that can be used in signatures:\n\n### Image Type\n\nThe `Image` type allows passing images to multimodal models:\n\n```python\nimport dspy\nfrom dspy.adapters.types import Image\n\nclass VisionSignature(dspy.Signature):\n    image: Image = dspy.InputField()\n    description: str = dspy.OutputField()\n\npredict = dspy.Predict(VisionSignature)\nresult = predict(image=Image(url=\"https://example.com/image.jpg\"))\n```\n\n**Image Formats Supported:**\n\n| Format | Support |\n|--------|---------|\n| URL string | ✅ Direct URL |\n| Base64 | ✅ Embedded data URI |\n| File path | ✅ Local file path |\n| PIL Image | ✅ In-memory image |\n| Bytes | ✅ Raw bytes |\n\n资料来源：[dspy/adapters/types/image.py:1-80]()\n\n### History Type\n\nThe `History` type allows passing conversation history:\n\n```python\nimport dspy\nfrom dspy.adapters.types import History\n\nclass ConversationSignature(dspy.Signature):\n    history: History = dspy.InputField()\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nhistory = History(messages=[\n    {\"question\": \"What is 2+2?\", \"answer\": \"4\"},\n    {\"question\": \"What is 3+3?\", \"answer\": \"6\"},\n])\n\npredict = dspy.Predict(ConversationSignature)\nresult = predict(history=history, question=\"What is 5+5?\")\n```\n\n资料来源：[dspy/adapters/types/history.py:1-100]()\n\n### Custom Type Identifiers\n\nWhen custom types are used, adapters use special identifiers:\n\n| Identifier | Purpose |\n|------------|---------|\n| `<<CUSTOM-TYPE-START-IDENTIFIER>>` | Marks start of custom type content |\n| `<<CUSTOM-TYPE-END-IDENTIFIER>>` | Marks end of custom type content |\n\nThese identifiers help adapters extract and process custom type content from LM responses.\n\n资料来源：[dspy/adapters/types/base_type.py:1-50]()\n\n## Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Module\n    participant Adapter\n    participant LM\n    participant Parser\n\n    User->>Module: Forward pass with inputs\n    Module->>Adapter: format(signature, demos, inputs)\n    Adapter->>Adapter: Structure messages\n    Adapter->>LM: Send formatted messages\n    LM-->>Adapter: Return completion\n    Adapter->>Parser: parse(signature, completion)\n    Parser->>Parser: Extract structured fields\n    Parser-->>Module: Return dict output\n    Module-->>User: Return structured output\n```\n\n## Configuration Options\n\n### Adapter Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `caching` | bool | True | Enable response caching |\n| `batch_size` | int | 200 | Batch size for embedding operations |\n| `default_kwargs` | dict | {} | Default arguments passed to LM |\n\n### Setting Adapters\n\n```python\nimport dspy\n\n# Method 1: Global configuration\ndspy.configure(adapter=dspy.JSONAdapter())\n\n# Method 2: Per-module\npredict = dspy.Predict(\n    \"question -> answer\",\n    adapter=dspy.XMLAdapter()\n)\n\n# Method 3: At initialization\ndspy.settings.adapter = dspy.ChatAdapter()\n```\n\n## Best Practices\n\n1. **Use JSONAdapter** when you need strict structured output parsing\n2. **Use ChatAdapter** for general-purpose applications (default)\n3. **Use XMLAdapter** for nested or hierarchical data structures\n4. **Use TwoStepAdapter** with `ChainOfThought` for reasoning-intensive tasks\n5. **Use custom types** (`Image`, `History`) for multimodal or conversational applications\n\n## Extending Adapters\n\nTo create a custom adapter, inherit from `BaseAdapter`:\n\n```python\nfrom dspy.adapters import BaseAdapter\n\nclass MyCustomAdapter(BaseAdapter):\n    def format(self, signature, demos, inputs):\n        # Custom formatting logic\n        messages = []\n        # ... format messages ...\n        return messages\n    \n    def parse(self, signature, completion):\n        # Custom parsing logic\n        return {\"output_field\": parsed_value}\n```\n\n## Summary\n\nAdapters are a fundamental part of DSPy's architecture, providing a flexible abstraction layer between DSPy's declarative signatures and the various API formats expected by different LMs. By supporting multiple built-in adapters and allowing custom extensions, DSPy can work seamlessly with any language model while maintaining a consistent programming interface.\n\n| Adapter | Use Case |\n|---------|----------|\n| `ChatAdapter` | Default, general purpose |\n| `JSONAdapter` | Structured JSON output |\n| `XMLAdapter` | XML-tagged output |\n| `TwoStepAdapter` | Reasoning + response |\n| `BamlAdapter` | BAML format |\n\n---\n\n<a id='lm-clients'></a>\n\n## Language Model Clients\n\n### 相关页面\n\n相关主题：[Adapters](#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/cache.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/cache.py)\n</details>\n\n# Language Model Clients\n\n## Overview\n\nThe Language Model (LM) client system in DSPy provides a unified interface for interacting with various LLM providers. This abstraction layer enables developers to swap between different LLM backends (OpenAI, Anthropic, Azure, local models, etc.) without modifying application code.\n\n## Architecture\n\nThe LM client architecture follows a layered design pattern with a base class defining the common interface and provider-specific implementations extending it.\n\n```mermaid\ngraph TD\n    A[Application Code] --> B[dspy.LM Interface]\n    B --> C[OpenAI Client]\n    B --> D[LiteLLM Client]\n    B --> E[Databricks Client]\n    B --> F[Local LM Client]\n    C --> G[OpenAI API]\n    D --> H[40+ LLM Providers]\n    E --> I[Databricks Endpoint]\n    F --> J[Ollama / vLLM]\n```\n\n## Core Components\n\n### BaseLM Abstract Class\n\nThe `BaseLM` class defines the abstract interface that all LM clients must implement. This ensures consistency across different providers.\n\n| Method | Purpose | Return Type |\n|--------|---------|-------------|\n| `__call__` | Execute a completion request | `dict` |\n| `get_reference` | Retrieve cached responses | `dict \\| None` |\n| `inspect_history` | View conversation history | `list[dict]` |\n| `drop_cache` | Clear the response cache | `None` |\n\n资料来源：[dspy/clients/base_lm.py]()\n\n### LM Factory Class\n\nThe main `LM` class serves as a factory that instantiates the appropriate client based on the model identifier format.\n\nSupported model formats include:\n- `provider/model-name` (e.g., `openai/gpt-4`, `anthropic/claude-3`)\n- `provider/model-name@timestamp` (e.g., `openai/gpt-4o-mini-2024-07-18`)\n- `provider/model-name:variant` (e.g., `openai/gpt-4-turbo:n-1106`)\n\n```python\n# Example instantiation patterns\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nlm = dspy.LM(\"anthropic/claude-3-opus-20240229\")\nlm = dspy.LM(\"azure/gpt-4o\", api_base=\"https://...\", api_key=\"...\")\n```\n\n资料来源：[dspy/clients/lm.py:1-100]()\n\n## LM Client Implementations\n\n### OpenAI Client\n\nThe OpenAI client provides direct integration with OpenAI's API endpoints.\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `model` | `str` | Required | Model name (e.g., `gpt-4o-mini`) |\n| `api_key` | `str` | Environment | API key from `OPENAI_API_KEY` |\n| `api_base` | `str` | Official API | Custom endpoint URL |\n| `temperature` | `float` | `0.0` | Sampling temperature |\n| `max_tokens` | `int` | `1024` | Maximum completion tokens |\n| `timeout` | `int \\| float` | `120` | Request timeout in seconds |\n\n资料来源：[dspy/clients/openai.py]()\n\n### LiteLLM Client\n\nThe LiteLLM client wraps the `litellm` library, providing access to over 40 LLM providers through a unified interface.\n\n```python\n# Using LiteLLM-backed LM\nlm = dspy.LM(\"anthropic/claude-3-sonnet-20240229\", \n             api_key=os.getenv(\"ANTHROPIC_API_KEY\"))\n```\n\nSupported providers include:\n- Anthropic\n- Azure OpenAI\n- AWS Bedrock\n- Google Vertex AI\n- Cohere\n- Mistral\n- Together AI\n\n资料来源：[dspy/clients/_litellm.py]()\n\n### Databricks Client\n\nThe Databricks client integrates with Databricks Model Serving endpoints for enterprise deployments.\n\n```python\nfrom dspy.clients.databricks import Databricks\n\nlm = Databricks(\n    model=\"databricks-meta-llama-3-70b-instruct\",\n    Databricks_host=\"https://your-workspace.cloud.databricks.com\",\n    Databricks_token=\"your-token\",\n)\n```\n\n| Parameter | Description |\n|-----------|-------------|\n| `model` | Databricks model endpoint name |\n| `Databricks_host` | Workspace URL |\n| `Databricks_token` | Authentication token |\n\n资料来源：[dspy/clients/databricks.py]()\n\n### Local LM Client\n\nThe Local LM client supports self-hosted models through Ollama or vLLM.\n\n```python\nfrom dspy.clients.lm_local import LocalLM\n\n# Using Ollama\nlm = LocalLM(model=\"llama3\", base_url=\"http://localhost:11434\")\n\n# Using vLLM\nlm = LocalLM(model=\"mistralai/Mistral-7B-Instruct-v0.2\", base_url=\"http://localhost:8000\")\n```\n\n资料来源：[dspy/clients/lm_local.py]()\n\n## Caching System\n\nDSPy implements a response caching mechanism to reduce API costs and improve latency for repeated requests.\n\n```mermaid\ngraph LR\n    A[Request] --> B{Cache Hit?}\n    B -->|Yes| C[Return Cached Response]\n    B -->|No| D[Execute LM Call]\n    D --> E[Store in Cache]\n    E --> F[Return Response]\n```\n\n### Cache Configuration\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `cache` | `Cache` | `None` | Cache instance |\n| `cache_turns` | `bool` | `False` | Include conversation turns in cache key |\n\nThe cache uses a hash-based key generation strategy:\n1. Serialize the input prompt\n2. Serialize adapter inputs and configuration\n3. Combine and hash to create cache key\n\n资料来源：[dspy/clients/cache.py]()\n\n## Callback System\n\nCallbacks enable monitoring and logging of LM interactions throughout the application.\n\n```mermaid\ngraph TD\n    A[LM Call] --> B[Callback Manager]\n    B --> C[on_module_start]\n    B --> D[on_module_end]\n    B --> E[on_lm_start]\n    B --> F[on_lm_end]\n```\n\n### Built-in Callbacks\n\n| Callback | Trigger | Purpose |\n|----------|---------|---------|\n| `LoggingCallback` | Every LM call | Log inputs/outputs to console |\n| Custom `Handler` | Per event type | User-defined monitoring logic |\n\n```python\nclass LoggingCallback(Handler):\n    def on_lm_start(self, call_id, instance, inputs):\n        print(f\"LM is called with inputs: {inputs}\")\n    \n    def on_lm_end(self, call_id, instance, outputs):\n        print(f\"LM is finished with outputs: {outputs}\")\n```\n\n资料来源：[dspy/utils/callback.py]()\n\n## Configuration Options\n\n### Global Configuration\n\nConfigure LM settings globally using `dspy.configure()`:\n\n```python\nimport dspy\n\ndspy.configure(\n    lm=dspy.LM(\"openai/gpt-4o-mini\"),\n    rm=dspy.Retrieve(k=3),\n    max_tokens=512,\n    temperature=0.1,\n)\n```\n\n### Per-Instance Configuration\n\nOverride settings at the component level:\n\n```python\ncot = dspy.ChainOfThought(\n    \"question -> answer\",\n    temperature=0.5,\n    max_tokens=256\n)\n```\n\n### Configuration Precedence\n\n| Level | Override Priority | Example |\n|-------|-------------------|---------|\n| Component | Highest | `dspy.Predict(..., temperature=0.8)` |\n| Global | Middle | `dspy.configure(temperature=0.5)` |\n| Default | Lowest | `dspy.LM(\"...\")` default value |\n\n## Usage Patterns\n\n### Basic Usage\n\n```python\nimport dspy\n\n# Initialize LM\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# Direct call\nresult = lm(\"What is the capital of France?\")\nprint(result)\n```\n\n### With Modules\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# Set LM for a module\nprogram = dspy.Predict(\"question -> answer\")\nprogram.set_lm(lm)\n\n# Execute\nresult = program(question=\"What is 2+2?\")\n```\n\n### Batch Processing\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\", max_tokens=100)\n\n# Multiple calls tracked in history\nfor q in questions:\n    lm(q)\n\n# Inspect all calls\nfor item in lm.inspect_history():\n    print(item)\n```\n\n## Error Handling\n\nThe LM client system handles various error conditions:\n\n| Error Type | Cause | Handling Strategy |\n|------------|-------|-------------------|\n| `AuthenticationError` | Invalid API key | Check environment variables |\n| `RateLimitError` | API quota exceeded | Implement backoff/retry |\n| `APIResponseValidationError` | Malformed response | Automatic retry with backoff |\n| `ContextWindowExceededError` | Input too long | Reduce prompt size |\n\n## Best Practices\n\n1. **Use environment variables** for API keys to avoid hardcoding credentials\n2. **Enable caching** for development and testing to reduce API costs\n3. **Set appropriate `max_tokens`** to prevent overly long responses\n4. **Use callbacks** for production monitoring and debugging\n5. **Configure timeouts** appropriately for your use case (default: 120s)\n\n## See Also\n\n- [Signature System](../signatures/signature.md) - How DSPy defines input/output schemas\n- [Modules](../primitives/module.md) - Using LMs within DSPy modules\n- [Teleprompters](../teleprompt/teleprompt.md) - Optimizing prompts with LMs\n- [Retrievers](../retrievers/retriever.md) - Combining LMs with retrieval systems\n\n---\n\n<a id='predict-modules'></a>\n\n## Prediction Modules\n\n### 相关页面\n\n相关主题：[Module System](#modules), [Agent Modules](#agent-modules)\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/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n- [dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.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/aggregation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/aggregation.py)\n- [dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n- [dspy/predict/knn.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/knn.py)\n</details>\n\n# Prediction Modules\n\n## Overview\n\nPrediction Modules are the core building blocks in DSPy for executing language model calls. They encapsulate the logic for invoking language models, handling inputs/outputs defined by Signatures, and providing various reasoning and optimization strategies. All predictors inherit from the base `Predict` class and can be composed within `dspy.Module` objects to build complex AI pipelines.\n\n**Key responsibilities:**\n- Execute language model calls with specified inputs\n- Parse and validate model outputs according to Signature definitions\n- Support multiple reasoning strategies (chain-of-thought, multi-chain comparison, etc.)\n- Integrate with DSPy's teleprompters for automatic prompt optimization\n- Track execution history for debugging and introspection\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n---\n\n## Base Predict Class\n\nThe `Predict` class serves as the foundation for all prediction modules. It wraps a Signature that defines input and output fields.\n\n### Basic Usage\n\n```python\nimport dspy\n\n# Simple question answering\nqa = dspy.Predict(\"question -> answer\")\nqa(question=\"What is the capital of France?\", lm=dspy.LM(\"openai/gpt-4o-mini\"))\n```\n\n### Signature Definition\n\nSignatures define the schema for inputs and outputs:\n\n```python\nclassify = dspy.Predict(\n    \"sentence -> sentiment: str, confidence: float\"\n)\n```\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n---\n\n## Specialized Predictor Types\n\n### Chain of Thought (CoT)\n\n`ChainOfThought` generates reasoning steps before producing the final answer. This technique improves accuracy on complex reasoning tasks.\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"If I have 5 apples and eat 2, how many do I have left?\")\n# Includes reasoning trace in addition to answer\n```\n\n资料来源：[dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n\n### Multi Chain Comparison (MCC)\n\n`MultiChainComparison` generates multiple reasoning chains and compares them to produce a more robust answer.\n\n```python\nmcc = dspy.MultiChainComparison(\"question -> answer\", n=3)\nresult = mcc(question=\"Explain why the sky is blue\")\n```\n\n资料来源：[dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n\n### Parallel Predictor\n\n`Parallel` executes multiple predictors simultaneously and returns all results.\n\n```python\nparallel = dspy.Parallel(\n    dspy.Predict(\"question -> short_answer\"),\n    dspy.Predict(\"question -> detailed_answer\")\n)\nresults = parallel(question=\"What is Python?\")\n```\n\n资料来源：[dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n\n### Best of N\n\n`BestOfN` generates N candidates and selects the best one based on a provided metric.\n\n```python\nbest_of = dspy.BestOfN(\"question -> answer\", n=5, metric=my_metric)\nresult = best_of(question=\"What is 2+2?\")\n```\n\n资料来源：[dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n\n### Retry\n\n`Retry` automatically retries failed or low-quality predictions with modified prompts.\n\n```python\nretry = dspy.Retry(\"question -> answer\", max_retries=3)\nresult = retry(question=\"Explain quantum entanglement\")\n```\n\n资料来源：[dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n\n### Refine\n\n`Refine` iteratively improves predictions through successive refinement steps.\n\n```python\nrefine = dspy.Refine(\"question -> answer\", max_iters=5)\nresult = refine(question=\"Write a haiku about coding\")\n```\n\n资料来源：[dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n\n### Aggregation\n\n`Aggregation` combines outputs from multiple predictors using various strategies (voting, majority, etc.).\n\n```python\nagg = dspy.Aggregation(\"observation -> conclusion\", strategy=\"majority_vote\")\nresult = agg(observation=\"Multiple sensors detected movement\")\n```\n\n资料来源：[dspy/predict/aggregation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/aggregation.py)\n\n### KNN Predictor\n\n`KNN` uses k-nearest neighbors approach for predictions based on similar training examples.\n\n```python\nknn = dspy.KNN(\"input -> output\", k=5)\nknn.load_examples(trainset)\nresult = knn(input=\"similar text to training data\")\n```\n\n资料来源：[dspy/predict/knn.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/knn.py)\n\n---\n\n## Integration with Modules\n\nPredictors are typically used within `dspy.Module` subclasses for building complete programs.\n\n### Declaring Predictors in Modules\n\n```python\nimport dspy\n\nclass RAGProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Predict(\"query -> context\")\n        self.answer = dspy.ChainOfThought(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(query=question)\n        return self.answer(context=context.context, question=question)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n### Managing Predictors\n\n```python\nprogram = RAGProgram()\n\n# List all predictors\nfor name, predictor in program.named_predictors():\n    print(f\"{name}: {predictor}\")\n\n# Get all predictor instances\nall_predictors = program.predictors()\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Language Model Configuration\n\n### Setting LM for All Predictors\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = RAGProgram()\nprogram.set_lm(lm)\n```\n\n### Getting LM from Module\n\n```python\nlm = program.get_lm()  # Returns LM if all predictors use the same one\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Batch Processing\n\nPredictors support batch execution with configurable parallelism and error handling:\n\n```python\nexamples = [\n    dspy.Example(question=\"What is 1+1?\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 2+2?\").with_inputs(\"question\"),\n]\n\nresults = program.batch(\n    examples=examples,\n    num_threads=4,\n    max_errors=2,\n    return_failed_examples=True,\n)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## History Inspection\n\nView past executions for debugging:\n\n```python\n# Inspect last prediction\nprogram.inspect_history(n=1)\n\n# Inspect last 5 predictions with output to file\nprogram.inspect_history(n=5, file=open(\"history.txt\", \"w\"))\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Transformative Operations\n\nApply transformations to all predictors in a module:\n\n```python\n# Wrap all predictors with Retry\nprogram.map_named_predictors(lambda p: dspy.Retry(p))\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[Predict]\n    A --> C[ChainOfThought]\n    A --> D[MultiChainComparison]\n    A --> E[Parallel]\n    A --> F[Retry]\n    A --> G[Refine]\n    A --> H[BestOfN]\n    A --> I[Aggregation]\n    A --> J[KNN]\n    \n    B --> K[Signature Definition]\n    B --> L[LM Invocation]\n    B --> M[Output Parsing]\n    \n    N[Example Data] --> O[Batch Processing]\n    O --> B\n    O --> C\n    O --> D\n    \n    P[Teleprompters] -.-> Q[Optimize Predictors]\n    Q --> B\n    Q --> C\n```\n\n---\n\n## Complete Example\n\n```python\nimport dspy\n\n# Configure language model\nlm = dspy.LM(\"openai/gpt-4o-mini\")\ndspy.configure(lm=lm)\n\n# Define a multi-step program\nclass MedicalQAProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.classify = dspy.Predict(\"question -> category: str\")\n        self.answer = dspy.ChainOfThought(\"category, question -> answer\")\n        self.refine = dspy.Retry(\"category, question, answer -> refined_answer\")\n    \n    def forward(self, question):\n        category = self.classify(question=question)\n        answer = self.answer(category=category.category, question=question)\n        refined = self.refine(\n            category=category.category,\n            question=question,\n            answer=answer.answer\n        )\n        return refined\n\n# Create and use program\nprogram = MedicalQAProgram()\nresult = program(question=\"What are the symptoms of diabetes?\")\nprint(result.refined_answer)\n```\n\n---\n\n## Summary Table\n\n| Predictor Type | Purpose | Key Parameter |\n|----------------|---------|----------------|\n| `Predict` | Base predictor for simple LM calls | `signature` |\n| `ChainOfThought` | Generate reasoning traces | `signature`, `_reasoning` |\n| `MultiChainComparison` | Compare multiple reasoning chains | `signature`, `n` |\n| `Parallel` | Execute multiple predictors simultaneously | `*predictors` |\n| `Retry` | Retry failed predictions | `max_retries`, `threshold` |\n| `Refine` | Iteratively improve predictions | `max_iters` |\n| `BestOfN` | Select best from N candidates | `n`, `metric` |\n| `Aggregation` | Combine outputs via voting | `strategy` |\n| `KNN` | K-nearest neighbors prediction | `k`, examples |\n\n---\n\n## See Also\n\n- [Signature System](../core/signatures.md) - Input/output field definitions\n- [Teleprompters](../teleprompt/overview.md) - Automatic prompt optimization\n- [Module System](../primitives/module.md) - Composing predictors into programs\n\n---\n\n<a id='agent-modules'></a>\n\n## Agent Modules\n\n### 相关页面\n\n相关主题：[Prediction Modules](#predict-modules)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n- [dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/primitives/code_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/code_interpreter.py)\n- [dspy/primitives/python_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/python_interpreter.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/propose/grounded_proposer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/propose/grounded_proposer.py)\n</details>\n\n# Agent Modules\n\n## Overview\n\nAgent Modules in DSPy are specialized modules that enable language models to interact with external tools, execute code, and perform multi-step reasoning tasks. Unlike standard Predict modules that generate direct outputs, Agent Modules implement agentic behaviors where the LM can plan, take actions (such as calling tools or executing code), observe results, and iteratively refine their approach until reaching a final answer.\n\nDSPy provides several agent implementations that share a common architectural pattern: they use a signature to define input/output fields, maintain a trajectory of their reasoning and actions, and leverage code interpreters or tool execution systems to perform computations that the language model cannot do directly.\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Architecture\n\n### Core Components\n\nAgent Modules in DSPy are built on a layered architecture:\n\n```mermaid\ngraph TD\n    A[Agent Module<br/>e.g., ReAct, Program of Thought] --> B[Signature<br/>Input/Output Field Definitions]\n    A --> C[Tool Registry<br/>Available Actions]\n    A --> D[History/Trajectory<br/>Reasoning & Actions]\n    B --> E[Code Interpreter<br/>Execution Backend]\n    C --> F[Tool Execution<br/>Function Calls]\n    D --> G[Observation Processing<br/>Feedback Loop]\n    E --> H[Python Interpreter<br/>Sandboxed Execution]\n```\n\n### Agent Base Pattern\n\nAll DSPy agent implementations follow a similar control flow:\n\n1. **Initialization**: Set up signature, tools, and configuration parameters\n2. **Loop Execution**: Iterate until max iterations or final output received\n3. **Thought Generation**: LM produces reasoning and next action\n4. **Action Execution**: Tools or code interpreters execute the proposed action\n5. **Observation Processing**: Results are appended to trajectory\n6. **Termination**: Return final prediction with full trajectory\n\n资料来源：[dspy/predict/react.py:1-80]()\n\n## ReAct Agent\n\nThe ReAct agent implements the Reasoning + Acting pattern, combining deliberate reasoning with tool usage. It allows language models to use external tools to gather information and complete tasks.\n\n### Signature Configuration\n\n```python\nclass ReAct(dspy.Module):\n    def __init__(\n        self,\n        signature,\n        max_iters: int = 10,\n        tools: list[Tool | Callable] = None,\n    ):\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `signature` | `str \\| Signature` | Required | Defines input/output fields for the task |\n| `max_iters` | `int` | `10` | Maximum number of reasoning iterations |\n| `tools` | `list[Tool \\| Callable]` | `None` | List of tools available to the agent |\n\n资料来源：[dspy/predict/react.py:50-90]()\n\n### Tool Integration\n\nThe ReAct agent automatically generates instructions that inform the LM about available tools:\n\n```python\ninputs = \", \".join([f\"`{k}`\" for k in signature.input_fields.keys()])\noutputs = \", \".join([f\"`{k}`\" for k in signature.output_fields.keys()])\ninstr = [\n    f\"You are an Agent. In each episode, you will be given the fields {inputs} as input.\",\n    f\"Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\",\n]\n```\n\nTools are converted to a `Tool` registry and made available by name for the agent to call.\n\n资料来源：[dspy/predict/react.py:70-85]()\n\n### Usage Example\n\n```python\ndef get_weather(city: str) -> str:\n    return f\"The weather in {city} is sunny.\"\n\nreact = dspy.ReAct(signature=\"question -> answer\", tools=[get_weather])\npred = react(question=\"What is the weather in Tokyo?\")\n```\n\n## Code Interpreter Agents\n\nDSPy provides agents that can execute Python code to perform computations. These agents use a sandboxed Python interpreter to run code safely.\n\n### Python Interpreter\n\nThe `PythonInterpreter` class provides the execution backend for code-based agents:\n\n| Feature | Description |\n|---------|-------------|\n| **Sandboxed Execution** | Runs code in an isolated environment |\n| **Variable Extraction** | Extracts variables from execution context |\n| **Error Handling** | Catches and reports execution errors |\n| **REPL Support** | Interactive read-eval-print loop style execution |\n\nThe interpreter extracts variables after each execution, making them available for subsequent code blocks or tool calls.\n\n资料来源：[dspy/primitives/python_interpreter.py:1-60]()\n\n### Code Interpreter Primitive\n\nThe `CodeInterpreter` class wraps the Python interpreter with additional utilities:\n\n```python\nclass CodeInterpreter:\n    def __init__(self, max_output_chars: int = 2000):\n        self.max_output_chars = max_output_chars\n    \n    def execute(self, code: str, variables: dict) -> Any:\n        # Execute code and return result\n```\n\n| Method | Description |\n|--------|-------------|\n| `execute(code, variables)` | Execute code string with provided variable context |\n| `extract_variables(result)` | Extract Python objects from execution result |\n\n资料来源：[dspy/primitives/code_interpreter.py:1-50]()\n\n## Reflexion Language Model (RLM) Agent\n\nThe RLM agent implements a Reflexion-style approach where the agent maintains a history of reasoning, code execution, and observations to iteratively improve its output.\n\n### Execution Flow\n\n```mermaid\ngraph TD\n    A[Start with Input] --> B[Generate Reasoning]\n    B --> C[Generate Code]\n    C --> D[Execute Code in Interpreter]\n    D --> E{Error?}\n    E -->|Yes| F[Record Error in History]\n    F --> G[Generate Fix Reasoning]\n    G --> C\n    E -->|No| H{Is Final Output?}\n    H -->|No| B\n    H -->|Yes| I[Return Prediction with Trajectory]\n```\n\n### Trajectory Tracking\n\nThe RLM agent maintains a `REPLHistory` that tracks all iterations:\n\n```python\nreturn Prediction(\n    **parsed_outputs,\n    trajectory=[e.model_dump() for e in final_history],\n    final_reasoning=pred.reasoning,\n)\n```\n\nEach history entry contains:\n- `reasoning`: The agent's thought process\n- `code`: The code that was executed\n- `output`: The result or error message\n\n资料来源：[dspy/predict/rlm.py:100-130]()\n\n### Result Processing\n\nThe agent processes final outputs by parsing structured results:\n\n```python\ndef _process_final_output(self, result: FinalOutput, output_field_names: list[str]):\n    parsed_outputs, error = self._process_final_output(result, output_field_names)\n    \n    if error:\n        return history.append(reasoning=pred.reasoning, code=code, output=error)\n```\n\n## Program of Thought\n\nThe Program of Thought agent combines natural language reasoning with programmatic code execution, allowing the agent to offload complex calculations to executed code while maintaining reasoning chains.\n\n### Architecture\n\n```mermaid\ngraph LR\n    A[Input Question] --> B[Reasoning Module]\n    B --> C[Code Generation]\n    C --> D[Python Interpreter]\n    D --> E[Output Extraction]\n    E --> F{More Steps Needed?}\n    F -->|Yes| B\n    F -->|No| G[Final Answer]\n```\n\n## Tool Definition\n\nDSPy uses a `Tool` class to wrap functions and make them available to agents:\n\n```python\ntool = Tool(\n    name=\"function_name\",\n    func=my_function,\n    desc=\"Description for LLM\"\n)\n```\n\nTools can be:\n- Plain Python functions\n- Decorated with the `@Tool` decorator\n- Already instantiated `Tool` objects\n\n## Configuration Parameters\n\n### Common Agent Parameters\n\n| Parameter | Type | Default | Agent Types |\n|-----------|------|---------|-------------|\n| `max_iters` | `int` | `10` | ReAct, RLM |\n| `max_output_chars` | `int` | `2000` | RLM, Code-based |\n| `temperature` | `float` | `0.0` | All agents |\n| `verbose` | `bool` | `False` | All agents |\n\n### History and Trajectory\n\nAgents maintain execution history which can be inspected:\n\n```python\nagent = dspy.ReAct(signature=\"question -> answer\", tools=[my_tool])\nresult = agent(question=\"What is 2+2?\")\n\n# Access trajectory\nfor step in result.trajectory:\n    print(f\"Thought: {step['reasoning']}\")\n    print(f\"Action: {step['code']}\")\n    print(f\"Observation: {step['output']}\")\n```\n\n## Integration with DSPy Module System\n\nAll agent modules inherit from `dspy.Module`, giving them access to:\n\n- `named_predictors()`: List all Predict instances\n- `set_lm(lm)`: Set language model for all predictors\n- `get_lm()`: Retrieve the configured language model\n- `inspect_history(n)`: Display recent LM call history\n\n```python\nclass MyAgent(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predictor = dspy.ReAct(\"question -> answer\", tools=[...])\n    \n    def forward(self, question):\n        return self.predictor(question=question)\n```\n\n资料来源：[dspy/primitives/module.py:50-120]()\n\n## Best Practices\n\n### Tool Design\n\n1. **Clear Function Names**: Use descriptive names that indicate the tool's purpose\n2. **Type Annotations**: Add type hints for better LLM understanding\n3. **Docstrings**: Provide clear descriptions of what the tool does\n4. **Return Values**: Return string or serializable types for consistency\n\n### Agent Configuration\n\n1. **Set Appropriate `max_iters`**: Too few iterations may prevent task completion; too many wastes resources\n2. **Use Temperature Control**: Lower temperatures (0.0-0.3) for deterministic tasks\n3. **Inspect Trajectories**: Use `inspect_history()` for debugging agent behavior\n\n### Error Handling\n\nAgents should be configured with error handling for:\n- Code execution failures\n- Tool invocation errors\n- Maximum iteration limits reached\n- Invalid output parsing\n\n---\n\n<a id='optimizers'></a>\n\n## Optimizers (Teleprompt)\n\n### 相关页面\n\n相关主题：[Signatures System](#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/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n- [dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n- [dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n- [dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n- [dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n- [dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n- [dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n- [dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n- [dspy/teleprompt/bootstrap_trace.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_trace.py)\n</details>\n\n# Optimizers (Teleprompt)\n\n## Overview\n\nIn DSPy, **Optimizers** (also referred to as **Teleprompters**) are compilation strategies that automatically optimize the prompts and/or weights of your LM programs. They take a raw program with a signature and training data, then search for improved instructions and/or demonstrations to include in the program's prompts.\n\nThe teleprompter system enables declarative, data-driven optimization of LLM pipelines without manual prompt engineering. Instead of crafting prompts by hand, you define:\n\n1. Your program structure (modules, signatures)\n2. A metric function to evaluate quality\n3. A training set of examples\n\nThe optimizer then compiles your program by finding optimal combinations of instructions, demonstrations, and (optionally) fine-tuned weights.\n\n## Architecture\n\nThe optimizer system follows a hierarchical architecture with a base `Teleprompter` abstract class and specialized subclasses for different optimization strategies:\n\n```mermaid\ngraph TD\n    A[Teleprompter Base] --> B[Prompt Optimizers]\n    A --> C[Weight Optimizers]\n    A --> D[Meta-Optimizers]\n    \n    B --> B1[BootstrapFewShot]\n    B --> B2[MIPROv2]\n    B --> B3[COPRO]\n    B --> B4[GEPA]\n    B --> B5[GRPO]\n    B --> B6[BootstrapFewShotWithRandomSearch]\n    \n    C --> C1[BootstrapFinetune]\n    \n    D --> D1[BetterTogether]\n    \n    A --> E[Ensemble]\n    E --> E1[Ensemble]\n```\n\n## Base Class: Teleprompter\n\nAll optimizers inherit from the abstract `Teleprompter` class defined in `dspy/teleprompt/teleprompt.py`. The base interface requires implementing a `compile()` method.\n\n### Compile Interface\n\n```python\ndef compile(self, student: Module, *, trainset: list[Example], ...) -> Module:\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `student` | `Module` | The program to optimize |\n| `trainset` | `list[Example]` | Training examples for optimization |\n| `valset` | `list[Example]` | Optional validation set for selecting best program |\n| `teacher` | `Module \\| list[Module]` | Optional teacher program for bootstrapping |\n| `strategy` | `str` | Execution strategy for meta-optimizers |\n\n## Prompt Optimizers\n\nPrompt optimizers focus on improving the instructions and demonstrations in your program's prompts without modifying model weights.\n\n### BootstrapFewShot\n\n`BootstrapFewShot` is the foundational prompt optimizer that composes demonstrations (examples) into a predictor's prompt. These demos come from two sources:\n\n1. **Labeled examples** from the training set\n2. **Bootstrapped demos** generated by running the program with the LM\n\n**Key Features:**\n\n- Each bootstrap round copies the LM with a new `rollout_id` at `temperature=1.0` to bypass caches and gather diverse traces\n- Supports multi-round bootstrapping for complex multi-step programs\n\n资料来源：[dspy/teleprompt/bootstrap.py:20-45]()\n\n```python\nteleprompter = BootstrapFewShot(\n    metric=your_metric,\n    metric_threshold=0.5,        # Minimum score to accept bootstrapped demos\n    max_bootstrapped_demos=4,      # Maximum bootstrap examples per predictor\n    max_labeled_demos=16,          # Maximum labeled examples from trainset\n    max_rounds=1,                  # Number of bootstrap rounds\n    max_errors=4,                 # Max consecutive errors before stopping\n)\ncompiled = teleprompter.compile(student, trainset=trainset)\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `metric` | `Callable` | Required | Function comparing expected and predicted values |\n| `metric_threshold` | `float` | `None` | Minimum metric score for accepting bootstrapped demos |\n| `teacher_settings` | `dict` | `None` | Settings for the teacher model |\n| `max_bootstrapped_demos` | `int` | `4` | Maximum bootstrap demonstrations to include |\n| `max_labeled_demos` | `int` | `16` | Maximum labeled examples from training set |\n| `max_rounds` | `int` | `1` | Number of bootstrap rounds |\n| `max_errors` | `int` | `None` | Maximum consecutive errors before stopping |\n\n### BootstrapFewShotWithRandomSearch\n\nThis optimizer extends `BootstrapFewShot` by adding random search over different demonstration configurations. It explores multiple bootstrap configurations and selects the best performing one.\n\n资料来源：[dspy/teleprompt/random_search.py]()\n\n### MIPROv2 (Multi-Instruction Prompt Optimization)\n\nMIPROv2 optimizes both instructions and demonstrations using Bayesian optimization. It treats the instruction template and demonstration selection as hyperparameters to optimize.\n\n**Key Characteristics:**\n\n- Uses Bayesian optimization to efficiently search the space of prompts\n- Supports fine-grained control over instruction generation\n- Can use a separate prompt model for generating candidate instructions\n\n资料来源：[dspy/teleprompt/mipro_optimizer_v2.py]()\n\n```python\nfrom dspy.teleprompt import MIPROv2\n\noptimizer = MIPROv2(\n    metric=metric,\n    num_trials=100,           # Number of optimization trials\n    max_bootstrapped_demos=4,\n    minibend_size=50,\n    auto=\"medium\",           # Automatic complexity control\n)\ncompiled = optimizer.compile(student, trainset=trainset, valset=valset)\n```\n\n### COPRO (Coordinate Prompt Optimization)\n\nCOPRO generates new prompt instructions iteratively, using a prompt model to propose variations based on the history of previous prompts.\n\n**Algorithm Parameters:**\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `breadth` | `10` | Number of new prompts to generate at each iteration |\n| `depth` | `3` | Number of iterations to generate new prompts |\n| `init_temperature` | `1.4` | Temperature for generation (higher = more creative) |\n| `track_stats` | `False` | Whether to track optimization statistics |\n\n资料来源：[dspy/teleprompt/copro_optimizer.py:20-35]()\n\n```python\nfrom dspy.teleprompt import COPRO\n\nteleprompter = COPRO(\n    prompt_model=prompt_model,\n    metric=metric,\n    breadth=10,\n    depth=3,\n    init_temperature=1.4,\n)\ncompiled = teleprompter.compile(program, trainset=trainset)\n```\n\n### GEPA (Generalized Evolutionary Prompt Algorithm)\n\nGEPA implements reflective prompt evolution using evolutionary strategies. It can outperform reinforcement learning approaches for prompt optimization.\n\n资料来源：[dspy/teleprompt/gepa/gepa.py]()\n\n```python\nfrom dspy.teleprompt import GEPA\n\noptimizer = GEPA(\n    metric=metric,\n    auto=\"medium\",            # Automatic complexity control\n    num_trials=50,\n)\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n### GRPO (Group Relative Policy Optimization)\n\nGRPO applies group relative policy optimization for instruction tuning. It uses a collection of candidate prompts and selects based on relative performance rankings.\n\n资料来源：[dspy/teleprompt/grpo.py]()\n\n## Weight Optimizers\n\nWeight optimizers fine-tune the weights of the language model itself (or adapter weights) to improve program performance.\n\n### BootstrapFinetune\n\n`BootstrapFinetune` uses bootstrapped demonstrations to fine-tune the language model weights. Unlike prompt-only optimization, this method modifies the actual model parameters.\n\n**Requirements:**\n\n- Student programs must have LMs explicitly set via `set_lm()` (not relying on global `dspy.settings.lm`)\n- Requires a training set with high-quality demonstrations\n\n资料来源：[dspy/teleprompt/bootstrap_finetune.py]()\n\n```python\nfrom dspy.teleprompt import BootstrapFinetune\n\noptimizer = BootstrapFinetune(metric=metric)\nstudent.set_lm(lm)  # Required: explicit LM setting\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n## Meta-Optimizers\n\nMeta-optimizers combine multiple optimization strategies into a unified compilation pipeline.\n\n### BetterTogether\n\n`BetterTogether` is a meta-optimizer that orchestrates multiple optimizers in sequence. It separates optimization into distinct phases:\n\n- **Prompt Optimization Phase (p)**: Optimizes instructions and demonstrations\n- **Weight Optimization Phase (w)**: Fine-tunes model weights\n\n**Execution Strategy:**\n\nThe optimizer uses a strategy string to define execution order:\n\n```mermaid\ngraph LR\n    A[Input Program] --> B[\"Strategy: 'p -> w'\"]\n    B --> C[Prompt Optimizer<br/>e.g., GEPA/MIPROv2]\n    C --> D[Weight Optimizer<br/>BootstrapFinetune]\n    D --> E[Compiled Program]\n```\n\n资料来源：[dspy/teleprompt/bettertogether.py:1-50]()\n\n```python\nfrom dspy.teleprompt import BetterTogether, GEPA, BootstrapFinetune\n\n# Combine GEPA for prompt optimization with BootstrapFinetune for weights\noptimizer = BetterTogether(\n    metric=metric,\n    p=GEPA(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric),\n)\n\nstudent.set_lm(lm)  # Required for weight optimization\ncompiled = optimizer.compile(\n    student,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\",  # Execute prompt optimization, then weight optimization\n)\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `metric` | `Callable` | Evaluation metric (required) |\n| `optimizers` | `dict[str, Teleprompter]` | Mapping of optimizer names to optimizer instances |\n| `strategy` | `str` | Execution strategy (e.g., \"p -> w\", \"p -> w -> p\") |\n\n**Optimizer-Specific Arguments:**\n\nYou can pass custom arguments to individual optimizers via `optimizer_compile_args`:\n\n```python\ncompiled = optimizer.compile(\n    student,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\",\n    optimizer_compile_args={\n        \"p\": {\"num_trials\": 10, \"max_bootstrapped_demos\": 8},\n    }\n)\n```\n\n## Ensemble\n\nThe Ensemble teleprompter combines predictions from multiple compiled programs using voting or other aggregation strategies.\n\n资料来源：[dspy/teleprompt/ensemble.py]()\n\n```python\nfrom dspy.teleprompt import Ensemble\n\n# Combine multiple compiled programs\nensemble = Ensemble(metric=metric)\ncombined = ensemble.compile(\n    [program1, program2, program3],\n    trainset=trainset,\n)\n```\n\n## Bootstrap Tracing\n\n`BootstrapFewShot` and related optimizers rely on `bootstrap_trace.py` to collect demonstrations by executing programs and recording successful traces.\n\n资料来源：[dspy/teleprompt/bootstrap_trace.py]()\n\n**Trace Collection Process:**\n\n1. Execute the student program on each training example\n2. Record input/output pairs for each predictor\n3. Accept traces that exceed the metric threshold\n4. Store demonstrations for inclusion in compiled prompts\n\n## Optimization Workflow\n\nThe typical workflow for using optimizers in DSPy:\n\n```mermaid\ngraph TD\n    A[Define Program<br/>dspy.Module] --> B[Prepare Training Set<br/>list of Examples]\n    B --> C[Define Metric<br/>evaluation function]\n    C --> D[Select Optimizer<br/>BootstrapFewShot/MIPROv2/etc.]\n    D --> E[Compile Program<br/>optimizer.compile]\n    E --> F[Evaluate on Test Set<br/>dspy.Evaluate]\n    \n    subgraph \"During Compilation\"\n        G[Generate Candidates<br/>instructions/demos/weights]\n        H[Evaluate Candidates<br/>using metric]\n        I[Select Best<br/>update program]\n        G --> H --> I\n    end\n    \n    F --> J{H满意?}\n    J -->|Yes| K[Deploy Program]\n    J -->|No| L[Adjust Parameters<br/>retry with different config]\n    L --> D\n```\n\n## Choosing an Optimizer\n\n| Use Case | Recommended Optimizer |\n|----------|----------------------|\n| Quick baseline with few examples | `BootstrapFewShot` |\n| Large training sets, efficient search | `MIPROv2` |\n| Evolutionary prompt improvement | `GEPA` |\n| Weight fine-tuning alongside prompts | `BetterTogether` with `BootstrapFinetune` |\n| Combining multiple compiled programs | `Ensemble` |\n| Batch evaluation with random sampling | `BootstrapFewShotWithRandomSearch` |\n\n## Best Practices\n\n1. **Start with BootstrapFewShot**: It's the simplest and often effective baseline for getting started.\n\n2. **Use validation sets**: When available, provide a `valset` parameter to allow the optimizer to select the best program among iterations.\n\n3. **Set LMs explicitly for weight optimization**: Call `student.set_lm(lm)` before compiling with optimizers like `BootstrapFinetune`.\n\n4. **Monitor metric threshold**: Adjust `metric_threshold` to control the quality of bootstrapped demonstrations.\n\n5. **Consider multi-phase optimization**: For best results, use `BetterTogether` to combine prompt and weight optimization.\n\n## Module Exports\n\nAll optimizers are exported from `dspy.teleprompt`:\n\n```python\nfrom dspy.teleprompt import (\n    # Base and utilities\n    Teleprompter,\n    BootstrapFewShot,\n    BootstrapFewShotWithRandomSearch,\n    \n    # Prompt optimizers\n    MIPROv2,\n    COPRO,\n    GEPA,\n    GRPO,\n    \n    # Weight optimizers\n    BootstrapFinetune,\n    \n    # Meta-optimizers\n    BetterTogether,\n    \n    # Ensemble\n    Ensemble,\n)\n```\n\n## See Also\n\n- [Signatures](signatures.md) - How to define input/output schemas for modules\n- [Modules](modules.md) - Building programs with Predict, ChainOfThought, and other modules\n- [Evaluation](evaluation.md) - Evaluating compiled programs\n- [Examples](examples.md) - Working with Example objects\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 项目说明书",
        "目录",
        "Introduction to DSPy",
        "Core Philosophy",
        "Key Concepts",
        "Installation",
        "Basic Usage Pattern",
        "Supported Data Types",
        "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": "99427f8e2525f16168cfea02cb9938671bbcae9d",
    "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- **Introduction to DSPy**：importance `high`\n  - source_paths: README.md, dspy/__init__.py, dspy/__metadata__.py\n- **Installation and Setup**：importance `high`\n  - source_paths: pyproject.toml\n- **Core Architecture**：importance `high`\n  - source_paths: dspy/primitives/__init__.py, dspy/primitives/base_module.py, dspy/primitives/module.py, dspy/primitives/prediction.py, dspy/primitives/example.py\n- **Signatures System**：importance `high`\n  - source_paths: dspy/signatures/__init__.py, dspy/signatures/signature.py, dspy/signatures/field.py, dspy/signatures/utils.py\n- **Module System**：importance `high`\n  - source_paths: dspy/primitives/module.py, dspy/primitives/base_module.py, dspy/predict/__init__.py, dspy/predict/parameter.py\n- **Adapters**：importance `high`\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- **Language Model Clients**：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- **Prediction Modules**：importance `high`\n  - source_paths: dspy/predict/__init__.py, dspy/predict/predict.py, dspy/predict/chain_of_thought.py, dspy/predict/multi_chain_comparison.py, dspy/predict/best_of_n.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `99427f8e2525f16168cfea02cb9938671bbcae9d`\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-17 06:56:43 UTC\n\n## 目录\n\n- [Introduction to DSPy](#introduction)\n- [Installation and Setup](#installation)\n- [Core Architecture](#core-architecture)\n- [Signatures System](#signatures)\n- [Module System](#modules)\n- [Adapters](#adapters)\n- [Language Model Clients](#lm-clients)\n- [Prediction Modules](#predict-modules)\n- [Agent Modules](#agent-modules)\n- [Optimizers (Teleprompt)](#optimizers)\n\n<a id='introduction'></a>\n\n## Introduction to DSPy\n\n### 相关页面\n\n相关主题：[Installation and Setup](#installation), [Core Architecture](#core-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/stanfordnlp/dspy/blob/main/README.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/adapters/types/document.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/document.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n</details>\n\n# Introduction to DSPy\n\nDSPy (Declarative Self-Improving Language Model Programs) is a framework for building and optimizing LLM-based pipelines. It provides a systematic approach to compiling declarative module calls into self-improving pipelines that can automatically optimize prompts and weights.\n\n资料来源：[README.md:1]()\n\n## Core Philosophy\n\nDSPy abstracts away the complexity of prompt engineering by allowing developers to define programs as modules with signatures rather than manually crafting prompts. The framework then automatically optimizes how these modules interact to achieve better performance.\n\n```mermaid\ngraph TD\n    A[User Defined Program] --> B[DSPy Signatures]\n    B --> C[DSPy Modules]\n    C --> D[Optimizer Compilation]\n    D --> E[Optimized Pipeline]\n    E --> F[Better Results]\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Key Concepts\n\n### Signatures\n\nSignatures define the input-output schema for modules. They specify which fields are inputs and which are outputs using `InputField` and `OutputField` decorators.\n\n```python\nclass MySignature(dspy.Signature):\n    input_text: str = dspy.InputField(desc=\"Input sentence\")\n    output_text: str = dspy.OutputField(desc=\"Translated sentence\")\n```\n\n资料来源：[dspy/signatures/signature.py:1-30]()\n\n### Modules\n\nAll DSPy programs inherit from `dspy.Module`, which provides methods for managing predictors and configuring language models.\n\n| Method | Description |\n|--------|-------------|\n| `forward()` | Define the program's logic |\n| `named_predictors()` | Get all Predict modules with names |\n| `predictors()` | Get all Predict modules |\n| `set_lm(lm)` | Set language model for all predictors |\n| `get_lm()` | Retrieve the configured language model |\n\n资料来源：[dspy/primitives/module.py:50-100]()\n\n### Examples\n\nThe `Example` class represents data records used for training and evaluation. It supports input/label separation and dictionary-like access.\n\n```python\nexample = dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\")\n```\n\n| Method | Purpose |\n|--------|---------|\n| `with_inputs(*keys)` | Mark fields as inputs |\n| `inputs()` | Get only input fields |\n| `labels()` | Get only label fields |\n| `toDict()` | Convert to JSON-friendly dict |\n| `get(key, default)` | Dictionary-style access |\n\n资料来源：[dspy/primitives/example.py:1-100]()\n\n### Predict\n\n`Predict` is the core module that generates completions based on a signature. It can be configured with or without chain-of-thought reasoning.\n\n```python\npredictor = dspy.Predict(\"question -> answer\")\npredictor = dspy.ChainOfThought(\"question -> answer\")\n```\n\n资料来源：[dspy/primitives/module.py:80-120]()\n\n## Installation\n\n### Standard Installation\n\n```bash\npip install dspy\n```\n\n### Development Installation\n\nFor the latest features from the main branch:\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\n资料来源：[README.md:5-12]()\n\n### Development Environment Setup\n\nPython 3.10 or later is required. The recommended setup uses `uv`:\n\n```shell\nuv venv --python 3.10\nuv sync --extra dev\n```\n\nRun tests with:\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md:40-80]()\n\n## Basic Usage Pattern\n\n```mermaid\ngraph LR\n    A[Define Signature] --> B[Create Module]\n    B --> C[Configure LM]\n    C --> D[Compile with Optimizer]\n    D --> E[Run Program]\n```\n\n### Step 1: Define a Signature\n\n```python\nclass QA(dspy.Signature):\n    \"\"\"Answer questions based on the context.\"\"\"\n    context: str = dspy.InputField(desc=\"Context for answering\")\n    question: str = dspy.InputField(desc=\"Question to answer\")\n    answer: str = dspy.OutputField(desc=\"Answer to the question\")\n```\n\n### Step 2: Build a Module\n\n```python\nclass RAG(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.qa = dspy.Predict(QA)\n    \n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.qa(context=context, question=question)\n```\n\n### Step 3: Configure Language Model\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\ndspy.configure(lm=lm)\n```\n\n### Step 4: Compile and Run\n\n```python\ncompiled_rag = dspy.compile(RAG(), trainset=trainset, metric=metric)\nresult = compiled_rag(question=\"What is DSPy?\")\n```\n\n## Supported Data Types\n\nDSPy provides specialized types for common LLM use cases:\n\n| Type | Purpose |\n|------|---------|\n| `Document` | Text content with title and citations support |\n| `History` | Conversation history for multi-turn interactions |\n| `Image` | Image inputs with URL/base64 encoding |\n| `Citations` | Citation metadata from models |\n\n### Document\n\n```python\ndoc = Document(\n    data=\"The Earth orbits the Sun.\",\n    title=\"Basic Astronomy Facts\"\n)\n```\n\n资料来源：[dspy/adapters/types/document.py:1-50]()\n\n### History\n\n```python\nhistory = History(messages=[\n    {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n])\n```\n\n资料来源：[dspy/adapters/types/history.py:1-50]()\n\n## Embedding Support\n\nThe `Embedder` class provides a unified interface for embedding models:\n\n```python\nembedder = dspy.Embedder(\"openai/text-embedding-3-small\")\nembeddings = embedder([\"hello\", \"world\"], batch_size=1)\n```\n\nConfiguration options:\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `model` | Required | Embedding model name or callable |\n| `batch_size` | 200 | Number of texts per batch |\n| `caching` | True | Enable result caching |\n\n资料来源：[dspy/clients/embedding.py:1-60]()\n\n## Teleprompters and Optimization\n\nDSPy includes teleprompters that automatically optimize prompts and weights:\n\n```python\noptimizer = BootstrapFewShotWithRandomSearch(metric=metric)\ncompiled_program = optimizer.compile(student=student_program, trainset=trainset)\n```\n\nAvailable optimizers include:\n- `BootstrapFewShotWithRandomSearch` - Bootstrap demonstrations with random search\n- `BootstrapFinetune` - Fine-tune weights on bootstrapped data\n- `GEPA` - Reflective prompt evolution\n- `BetterTogether` - Combined prompt + weight optimization\n\n资料来源：[dspy/teleprompt/bettertogether.py:1-50]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"User Layer\"\n        A[User Program]\n        B[Signatures]\n        C[Examples]\n    end\n    \n    subgraph \"Core Layer\"\n        D[Module]\n        E[Predict]\n        F[ChainOfThought]\n        G[Retrieve]\n    end\n    \n    subgraph \"Optimization Layer\"\n        H[Teleprompters]\n        I[Proposers]\n        J[Metrics]\n    end\n    \n    subgraph \"Adapter Layer\"\n        K[Document]\n        L[History]\n        M[Image]\n        N[Citations]\n    end\n    \n    subgraph \"Client Layer\"\n        O[LM Client]\n        P[Embedding Client]\n        Q[Retriever Clients]\n    end\n    \n    A --> D\n    B --> D\n    C --> H\n    D --> E\n    E --> H\n    H --> I\n    K --> O\n    L --> O\n    M --> O\n    N --> O\n    O --> P\n    O --> Q\n```\n\n## Citation\n\nIf you use DSPy in your research, please cite:\n\n> **[Oct'23] [DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines](https://arxiv.org/abs/2310.03714)**\n\n资料来源：[README.md:20-30]()\n\n## Documentation and Resources\n\nFor comprehensive documentation, visit the [DSPy Docs at dspy.ai](https://dspy.ai).\n\n### Research Papers\n\n| Paper | Date | Description |\n|-------|------|-------------|\n| GEPA: Reflective Prompt Evolution | Jul'25 | Alternative to RL |\n| Optimizing Instructions and Demonstrations | Jun'24 | Multi-stage optimization |\n| DSPy: Compiling Declarative LM Calls | Oct'23 | Core framework paper |\n| Fine-Tuning and Prompt Optimization | Jul'24 | Joint optimization |\n| Prompts as Auto-Optimized Training Hyperparameters | Jun'24 | Hyperparameter analogy |\n\n资料来源：[README.md:15-35]()\n\n---\n\n<a id='installation'></a>\n\n## Installation and Setup\n\n### 相关页面\n\n相关主题：[Introduction to DSPy](#introduction), [Language Model Clients](#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- [pyproject.toml](https://github.com/stanfordnlp/dspy/blob/main/pyproject.toml)\n</details>\n\n# Installation and Setup\n\nThis page covers how to install DSPy and configure your development environment for working with the framework.\n\n## Overview\n\nDSPy (Declarative Self-Improving Language Model Programs) is a Python framework that compiles declarative language model calls into self-improving pipelines. The installation process supports both end-user usage via pip and contributor workflows with advanced development tools. 资料来源：[README.md]()\n\n## Prerequisites\n\n### System Requirements\n\n| Requirement | Minimum | Recommended |\n|-------------|---------|-------------|\n| Python Version | 3.10 | 3.11 or later |\n| Operating System | Linux, macOS, Windows | Linux/macOS |\n| Package Manager | pip | uv (Rust-based) |\n\n资料来源：[CONTRIBUTING.md]()\n\n## Basic Installation\n\n### Installing from PyPI\n\nThe simplest way to install DSPy is using pip:\n\n```bash\npip install dspy\n```\n\n资料来源：[README.md]()\n\n### Installing from Source\n\nTo install the latest development version from the main branch:\n\n```bash\npip install git+https://github.com/stanfordnlp/dspy.git\n```\n\nThis approach installs the most up-to-date code that may include features not yet released to PyPI.\n\n资料来源：[README.md]()\n\n## Development Environment Setup\n\nFor contributors who want to modify DSPy or run tests, a development environment setup is required.\n\n### Fork and Clone\n\nFirst, fork the repository on GitHub, then clone your fork locally:\n\n```shell\ngit clone {url-to-your-fork}\ncd dspy\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Using uv (Recommended)\n\n[uv](https://github.com/astral-sh/uv) is a Rust-based Python package and project manager that provides fast dependency resolution and virtual environment management.\n\n#### Installation of uv\n\nFollow the [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/) to install uv on your system.\n\n#### Environment Creation\n\nCreate a virtual environment using Python 3.10:\n\n```shell\nuv venv --python 3.10\n```\n\nThis creates a `.venv` directory in your project root.\n\n#### Dependency Synchronization\n\nSync the environment with development dependencies:\n\n```shell\nuv sync --extra dev\n```\n\n#### Verification\n\nRun unit tests to verify the setup:\n\n```shell\nuv run pytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Using conda + pip\n\nAn alternative approach using conda and pip is available for users who prefer this workflow.\n\n#### Environment Creation\n\n```shell\nconda create -n dspy-dev python=3.10\nconda activate dspy-dev\n```\n\n#### Package Installation\n\n```shell\npip install -e \".[dev]\"\n```\n\nThe `-e` flag installs the package in editable mode, allowing code changes to take effect without reinstallation.\n\n#### Verification\n\n```shell\npytest tests/predict\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Environment Management Patterns\n\n### Using uv run\n\nThe `uv run` prefix must be used for every Python command when using the uv-managed environment:\n\n| Action | Command |\n|--------|---------|\n| Run tests | `uv run pytest tests/predict` |\n| Execute script | `uv run python script.py` |\n| Install package | `uv run pip install package-name` |\n\n资料来源：[CONTRIBUTING.md]()\n\n### Development Workflow\n\n```mermaid\ngraph TD\n    A[Fork Repository] --> B[Clone Your Fork]\n    B --> C[Install uv]\n    C --> D[Create venv with Python 3.10]\n    D --> E[Sync dependencies with dev extras]\n    E --> F[Run tests to verify]\n    F --> G[Start development]\n    G --> H[Make changes]\n    H --> I[Commit changes]\n    I --> J[Push to fork]\n    J --> K[Create Pull Request]\n```\n\n## Project Configuration\n\n### pyproject.toml Structure\n\nThe project uses `pyproject.toml` for dependency management and package configuration. Key sections include:\n\n- **build-system**: Build backend configuration\n- **project**: Core dependencies and project metadata\n- **project.optional-dependencies**: Extra dependencies for different features (dev, etc.)\n\n资料来源：[pyproject.toml]()\n\n## Pre-commit Hooks\n\nDSPy uses pre-commit hooks to maintain code quality. After installing dependencies, hooks are automatically installed but need to be staged and committed along with your changes.\n\n### Running Hooks Manually\n\n| Command | Purpose |\n|---------|---------|\n| `pre-commit run` | Check all staged files |\n| `pre-commit run --files path/to/file.py` | Check specific files |\n\nAll pre-commit checks must pass before creating a pull request. You can commit changes and let hooks fix formatting issues automatically.\n\n资料来源：[CONTRIBUTING.md]()\n\n## Verification Checklist\n\nAfter completing installation, verify your setup by checking:\n\n1. Python version: `python --version` (should be 3.10+)\n2. DSPy import: `python -c \"import dspy; print(dspy.__version__)\"`\n3. Running basic tests: `uv run pytest tests/predict -v`\n\n## Next Steps\n\nAfter successful installation and setup:\n\n- Review the [DSPy documentation](https://dspy.ai) for framework concepts\n- Explore the signature system for defining module inputs/outputs\n- Set up your language model configuration\n- Try the teleprompters for prompt optimization\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Python version too old | Upgrade to Python 3.10 or later |\n| uv command not found | Install uv following the official guide |\n| Tests fail after install | Ensure dependencies are fully synced with `uv sync --extra dev` |\n| Pre-commit hooks not running | Run `pre-commit install` to enable hooks |\n\n## Related Documentation\n\n- [DSPy Official Docs](https://dspy.ai)\n- [GitHub Repository](https://github.com/stanfordnlp/dspy)\n- [Research Papers](https://github.com/stanfordnlp/dspy#-citation-reading-more)\n\n---\n\n<a id='core-architecture'></a>\n\n## Core Architecture\n\n### 相关页面\n\n相关主题：[Signatures System](#signatures), [Module System](#modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\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/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/utils/callback.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/utils/callback.py)\n</details>\n\n# Core Architecture\n\nThe DSPy framework's core architecture provides the foundational building blocks for composing, executing, and optimizing language model programs. At its heart, DSPy separates the concerns of **program structure**, **data representation**, and **model interaction** into distinct but interconnected components.\n\n## Architecture Overview\n\nDSPy's core architecture follows a layered design where higher-level abstractions build upon primitive components. The primitives module (`dspy/primitives/`) contains the essential classes that define how programs are structured, how data flows through them, and how outputs are represented.\n\n```mermaid\ngraph TD\n    subgraph \"Core Primitives\"\n        Example[Example<br/>Data Container]\n        Module[Module<br/>Program Base]\n        Prediction[Prediction<br/>Output Container]\n    end\n    \n    subgraph \"Language Model Layer\"\n        LM[Language Model<br/>Client]\n        Embedder[Embedder<br/>Embedding Client]\n    end\n    \n    subgraph \"Program Layer\"\n        Predict[Predict Module]\n        CoT[ChainOfThought]\n        RLM[RLM Module]\n    end\n    \n    Example -->|Defines I/O| Module\n    Module -->|Executes via| LM\n    LM -->|Produces| Prediction\n    Predict -->|Uses| Module\n    RLM -->|Extends| Module\n```\n\n## Data Model Layer\n\n### The `Example` Class\n\nThe `Example` class serves as DSPy's primary data structure for representing training examples, test cases, and evaluation samples. It wraps a dictionary-based storage (`_store`) and maintains metadata about which fields are inputs versus labels.\n\n**Key Characteristics:**\n\n| Attribute | Type | Purpose |\n|-----------|------|---------|\n| `_store` | `dict` | Internal storage for field names and values |\n| `_input_keys` | `set[str] \\| None` | Tracks which fields are inputs |\n\n**Core Methods:**\n\n| Method | Purpose |\n|--------|---------|\n| `with_inputs(*keys)` | Marks specified fields as input fields |\n| `inputs()` | Returns a new Example containing only input fields |\n| `labels()` | Returns a new Example containing only non-input (label) fields |\n| `toDict()` | Recursively serializes the Example to a JSON-friendly dict |\n| `copy()` | Creates a shallow copy with optional field overrides |\n| `get(key, default)` | Retrieves a field value with optional default |\n| `keys()`, `values()`, `items()` | Dictionary-like access methods |\n\n资料来源：[dspy/primitives/example.py:1-50]()\n\n**Usage Pattern:**\n\n```python\n# Create an example with question-answer pairs\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# Access inputs and labels separately\nexample.inputs()    # Example({'question': '...'}) \nexample.labels()    # Example({'answer': '...'})\n\n# Convert to dictionary for serialization\nexample.toDict()    # {'question': '...', 'answer': '...'}\n```\n\nThe `toDict()` method handles nested objects by recursively converting `Example` objects, Pydantic models, lists, and dicts to JSON-friendly structures.\n\n资料来源：[dspy/primitives/example.py:1-30]()\n\n### The `Prediction` Class\n\nThe `Prediction` class represents the output of a DSPy program execution. It encapsulates the results produced by language model calls, typically containing fields that correspond to the output fields defined in a signature.\n\n## Program Structure Layer\n\n### The `Module` Class\n\nThe `Module` class is the fundamental base class from which all DSPy programs inherit. It provides the runtime infrastructure for composing language model calls, managing parameters, and executing programs.\n\n**Key Methods:**\n\n| Method | Returns | Description |\n|--------|---------|-------------|\n| `named_predictors()` | `list[tuple[str, Predict]]` | Returns all Predict modules with their attribute names |\n| `predictors()` | `list[Predict]` | Returns only the Predict module instances |\n| `set_lm(lm)` | `None` | Recursively sets the language model for all contained Predict modules |\n| `get_lm()` | `LM` | Returns the language model if all predictors share the same LM |\n\n资料来源：[dspy/primitives/module.py:1-60]()\n\n**Predictor Discovery:**\n\nThe `named_predictors()` method uses introspection to find all `Predict` instances within a 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\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(name)  # 'qa', 'summarize'\n```\n\n资料来源：[dspy/primitives/module.py:1-45]()\n\n### Language Model Integration\n\nThe `set_lm()` method traverses the module's parameter tree to attach a language model to every `Predict` instance:\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram.set_lm(lm)\n```\n\nThis recursive propagation ensures that nested modules and chained predictors all share the same language model configuration.\n\n资料来源：[dspy/primitives/module.py:45-55]()\n\n## Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Module\n    participant Predict\n    participant LM\n    participant Prediction\n    \n    User->>Module: forward(**inputs)\n    Module->>Predict: forward(**inputs)\n    Predict->>LM: generate(input_fields, signature)\n    LM-->>Predict: raw_output\n    Predict->>Prediction: format(raw_output, signature)\n    Prediction-->>Module: Prediction object\n    Module-->>User: Program output\n    \n    Note over Predict: Validates and transforms<br/>LM output according<br/>to Signature fields\n```\n\n## Signature-Based Input/Output Contract\n\nDSPy programs use **Signatures** to define the contract between modules and language models. A signature specifies input fields and output fields, along with optional descriptions that guide the LM's behavior.\n\nThe `Signature.with_updated_fields()` method allows runtime modification of field metadata:\n\n```python\nNewSig = MySig.with_updated_fields(\n    \"output_text\", \n    desc=\"The translated French text\"\n)\n```\n\n资料来源：[dspy/signatures/signature.py:1-40]()\n\n## Extended Modules\n\n### RLM (Recursive Language Model)\n\nThe `RLM` class extends the base `Module` to provide sandboxed REPL-based code execution capabilities, enabling LLMs to programmatically explore large contexts through Python code:\n\n```python\nrlm = RLM(\n    sandbox=\"python\",  # or \"bash\"\n    timeout=30\n)\n```\n\n资料来源：[dspy/predict/rlm.py:1-30]()\n\n### Embedder\n\nThe `Embedder` class provides a consistent interface for embedding generation with built-in batching and caching:\n\n```python\nembedder = dspy.Embedder(\n    model=\"openai/text-embedding-3-small\",\n    batch_size=200,\n    caching=True\n)\n```\n\n资料来源：[dspy/clients/embedding.py:1-50]()\n\n## Callback System\n\nDSPy's callback system (`dspy/utils/callback.py`) enables observability and instrumentation of program execution:\n\n```mermaid\ngraph LR\n    A[Module Forward] -->|on_module_start| B[Callback Handler]\n    B --> C[Execute]\n    C -->|on_module_end| B\n```\n\nThe `CallbackHandler` base class defines hooks for:\n\n| Hook | Trigger |\n|------|---------|\n| `on_module_start()` | Before a module's `forward()` executes |\n| `on_module_end()` | After a module's `forward()` completes |\n| `on_lm_start()` | Before an LM call |\n| `on_lm_end()` | After an LM call |\n\nCallbacks can be attached either globally or per-component:\n\n```python\n# Global callback\ndspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\n\n# Local callback on specific component\nlm(question=\"What is 2+2?\", callbacks=[LoggingCallback()])\n```\n\n资料来源：[dspy/utils/callback.py:1-40]()\n\n## Component Hierarchy\n\n```mermaid\ngraph TD\n    BaseModule[BaseModule<br/>dspy.primitives]\n    Module[Module<br/>extends BaseModule]\n    Program[User Program<br/>extends Module]\n    \n    Predict[Predict<br/>Signature-driven predictor]\n    ChainOfThought[ChainOfThought<br/>extends Predict]\n    RLM[RLM<br/>extends Module]\n    \n    Example[Example<br/>Data primitive]\n    Prediction[Prediction<br/>Output primitive]\n    \n    BaseModule --> Module\n    Module --> Program\n    Module --> Predict\n    Predict --> ChainOfThought\n    Module --> RLM\n    \n    Example --> Program\n    Program --> Prediction\n```\n\n## Key Design Principles\n\n1. **Separation of Concerns**: Data (`Example`, `Prediction`), structure (`Module`), and execution (`LM`) are cleanly separated\n2. **Introspection**: The module system supports dynamic discovery of contained predictors\n3. **Recursive Configuration**: Language model and other settings propagate through nested modules\n4. **Serialization**: All data primitives support conversion to JSON-compatible formats\n5. **Extensibility**: Custom modules can inherit from `Module` and use the same infrastructure\n\n## Summary\n\nDSPy's core architecture provides a composable framework where `Example` objects define inputs and labels, `Module` subclasses implement programs, `Predict` modules handle signature-driven LM interactions, and `Prediction` objects capture outputs. This architecture enables systematic optimization and evaluation of language model programs through a consistent, introspectable API.\n\n---\n\n<a id='signatures'></a>\n\n## Signatures System\n\n### 相关页面\n\n相关主题：[Core Architecture](#core-architecture), [Prediction Modules](#predict-modules)\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 System\n\n## Overview\n\nThe Signatures System is a core abstraction in DSPy that defines the structure of inputs and outputs for language model calls. A Signature describes what fields a module expects as input and what fields it will produce as output, effectively serving as a declarative contract between DSPy programs and language models.\n\nSignatures enable DSPy to:\n- Compile declarative LM calls into self-improving pipelines\n- Separate input fields from output fields for proper data routing\n- Provide rich metadata (descriptions) for each field that guides the LM's behavior\n- Support dynamic field manipulation and signature transformation\n\n资料来源：[dspy/signatures/signature.py:1-50]()\n\n## Core Concepts\n\n### InputField vs OutputField\n\nEvery field in a Signature is classified as either an `InputField` or an `OutputField`. This distinction is fundamental to DSPy's execution model:\n\n| Field Type | Purpose | Behavior |\n|------------|---------|----------|\n| `InputField` | Data provided to the LM before generation | Passed in the prompt; LM reads but does not produce |\n| `OutputField` | Data the LM should generate | Expected output; DSPy parses and validates the response |\n\n```python\nclass MySignature(dspy.Signature):\n    question: str = dspy.InputField(desc=\"Input question\")\n    answer: str = dspy.OutputField(desc=\"Generated answer\")\n```\n\n资料来源：[dspy/signatures/field.py:1-30]()\n\n### Field Descriptions\n\nThe `desc` parameter in InputField/OutputField provides natural language descriptions that are injected into prompts. Well-crafted descriptions significantly improve LM accuracy.\n\n```python\nclass TranslationSignature(dspy.Signature):\n    english_text: str = dspy.InputField(desc=\"The text to translate, written in English\")\n    french_text: str = dspy.OutputField(desc=\"The translated text in French\")\n```\n\n## Signature Class\n\n### Creating Signatures\n\nSignatures can be created in multiple ways:\n\n**Class-based definition:**\n```python\nclass QASignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n```\n\n**String-based definition:**\n```python\nqa_sig = make_signature(\"question -> answer\")\n```\n\n**Dictionary-based definition:**\n```python\nsig = make_signature({\n    \"question\": (str, dspy.InputField()),\n    \"answer\": (str, dspy.OutputField())\n})\n```\n\n资料来源：[dspy/signatures/signature.py:200-280]()\n\n### Signature Methods\n\nThe Signature class provides several class methods for creating modified copies:\n\n| Method | Purpose |\n|--------|---------|\n| `with_instructions(instructions)` | Create a new Signature with updated instruction text |\n| `with_updated_fields(name, type_=None, **kwargs)` | Update a field's metadata |\n| `prepend(name, field, type_=None)` | Insert a field at the beginning |\n| `append(name, field, type_=None)` | Insert a field at the end |\n| `delete(name)` | Remove a field from the signature |\n\n```python\n# Update instructions\nNewSig = MySig.with_instructions(\"Translate to French.\")\n\n# Add a new field\nEnhancedSig = MySig.append(\"confidence\", dspy.OutputField(desc=\"Translation confidence\"))\n\n# Remove a field\nSimplifiedSig = MySig.delete(\"source_language\")\n```\n\n资料来源：[dspy/signatures/signature.py:30-120]()\n\n## Signature Structure and Fields\n\n### Fields Dictionary\n\nInternally, a Signature maintains a `fields` dictionary that maps field names to their corresponding `FieldInfo` objects:\n\n```python\nclass Signature:\n    fields: dict[str, FieldInfo]\n    instructions: str\n```\n\nThe fields are automatically categorized into inputs and outputs based on whether each field uses `InputField` or `OutputField`.\n\n### Type Handling\n\nSignatures support flexible type annotations:\n\n```python\nclass CustomSig(dspy.Signature):\n    # Basic string type\n    text: str = dspy.InputField()\n    \n    # With custom type\n    history: dspy.History = dspy.InputField()\n    \n    # List of custom types\n    images: list[dspy.Image] = dspy.InputField()\n```\n\nWhen types are not explicitly provided, they default to `str` to maintain backward compatibility with existing programs.\n\n资料来源：[dspy/signatures/utils.py:1-50]()\n\n## Using Signatures with Examples\n\nThe `Example` class works in conjunction with Signatures to manage training data and evaluation:\n\n### Marking Input Fields\n\n```python\n# Mark which fields are inputs vs labels\nexample = dspy.Example(\n    question=\"What is the capital of France?\",\n    answer=\"Paris\"\n).with_inputs(\"question\")\n\n# Access inputs and labels separately\ninputs = example.inputs()      # Example({'question': '...'}) (input_keys={'question'})\nlabels = example.labels()     # Example({'answer': '...'}) (input_keys={'question'})\n```\n\n### Converting Examples\n\n```python\n# Convert to dictionary for serialization\ndata = example.toDict()\n\n# Copy with overrides\nnew_example = example.copy(answer=\"Lyon\")\n```\n\n资料来源：[dspy/primitives/example.py:50-150]()\n\n## Custom Types System\n\nDSPy's Type system extends Signatures with custom data types. The base `Type` class requires implementations of the `format()` method.\n\n### Built-in Custom Types\n\n| Type | Purpose |\n|------|---------|\n| `dspy.Image` | Image inputs with URL or base64 encoding |\n| `dspy.History` | Conversation history for multi-turn interactions |\n\n### Image Type\n\n```python\nclass Image(Type):\n    url: str\n    \n    def format(self) -> list[dict[str, Any]]:\n        return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n```\n\n```python\n# Usage with signatures\nclass VQASignature(dspy.Signature):\n    image: dspy.Image = dspy.InputField(desc=\"Image to analyze\")\n    question: str = dspy.InputField(desc=\"Question about the image\")\n    answer: str = dspy.OutputField(desc=\"Answer to the question\")\n```\n\n资料来源：[dspy/adapters/types/base_type.py:1-50]()\n\n### History Type\n\n```python\nclass History(Type):\n    messages: list[dict[str, Any]]\n    \n    def format(self) -> list[dict[str, Any]]:\n        # Formats conversation history as a list of message dictionaries\n        pass\n```\n\n```python\n# Usage for multi-turn conversations\nclass ChatSignature(dspy.Signature):\n    question: str = dspy.InputField()\n    history: dspy.History = dspy.InputField()\n    answer: str = dspy.OutputField()\n```\n\n资料来源：[dspy/adapters/types/history.py:1-60]()\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[Signature Definition] --> B[Field Resolution]\n    B --> C{Field Type}\n    C -->|InputField| D[Input Fields Dict]\n    C -->|OutputField| E[Output Fields Dict]\n    \n    F[make_signature] -->|String format| G[_parse_signature]\n    F -->|Dict format| H[Direct field assignment]\n    \n    I[Example with Signature] --> J[with_inputs]\n    J --> K[Inputs]\n    J --> L[Labels]\n    \n    M[Custom Types] --> N[Type.format]\n    N --> O[Image.format]\n    N --> P[History.format]\n    \n    D --> Q[Predict Module]\n    E --> Q\n    Q --> R[LM Call]\n```\n\n## Field Modification Workflow\n\n```mermaid\ngraph LR\n    A[Original Signature] --> B[with_updated_fields]\n    A --> C[prepend/append]\n    A --> D[delete]\n    \n    B --> E[Updated field metadata]\n    C --> F[New field added]\n    D --> G[Field removed]\n    \n    E --> H[Fresh Signature Instance]\n    F --> H\n    G --> H\n```\n\n## Advanced Usage\n\n### Composing Multiple Signatures\n\nSignatures can be dynamically combined using the insertion methods:\n\n```python\nclass BaseSignature(dspy.Signature):\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\n# Add context field\nExtendedSig = BaseSignature.prepend(\n    \"context\", \n    dspy.InputField(desc=\"Additional context\")\n)\n\n# Add metadata output\nFinalSig = ExtendedSig.append(\n    \"confidence\", \n    dspy.OutputField(desc=\"Confidence score\")\n)\n```\n\n### Custom Type Extraction\n\nThe Type system automatically extracts custom types from nested annotations:\n\n```python\nclass MyType(dspy.Type):\n    @classmethod\n    def extract_custom_type_from_annotation(cls, annotation):\n        # Detects custom types in list[dict[str, MyType]]\n        pass\n```\n\nThis enables DSPy to handle complex nested structures with custom types throughout the signature system.\n\n资料来源：[dspy/adapters/types/base_type.py:40-80]()\n\n## Best Practices\n\n1. **Provide Clear Descriptions**: Always use descriptive `desc` parameters for fields to improve LM performance\n2. **Explicit Input/Output Separation**: Use `.with_inputs()` to clearly mark which fields are inputs\n3. **Leverage Type Annotations**: Use custom types like `Image` and `History` for structured data\n4. **Immutability**: Remember that signature modification methods return new instances; originals are unchanged\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| `Predict` | `dspy/predict/predict.py` | Consumes Signatures to execute LM calls |\n| `Module` | `dspy/primitives/module.py` | Container for predictor modules |\n| `Example` | `dspy/primitives/example.py` | Training/evaluation data with signature alignment |\n| `Type` | `dspy/adapters/types/base_type.py` | Base class for custom types |\n\n## Summary\n\nThe Signatures System is the foundational abstraction in DSPy that defines the interface between programs and language models. By separating inputs from outputs and providing rich metadata through field descriptions, Signatures enable DSPy's compilation and optimization capabilities. The system supports flexible creation methods, dynamic modification, and integration with custom types for complex applications.\n\n---\n\n<a id='modules'></a>\n\n## Module System\n\n### 相关页面\n\n相关主题：[Core Architecture](#core-architecture), [Prediction Modules](#predict-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/primitives/base_module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/base_module.py)\n- [dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n- [dspy/predict/parameter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parameter.py)\n- [dspy/signatures/signature.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/signatures/signature.py)\n</details>\n\n# Module System\n\nThe DSPy Module System provides a declarative, composable framework for building language model programs. It serves as the foundational abstraction layer that enables automatic optimization of both prompts and model weights through DSPy's teleprompter system.\n\n## Overview\n\nDSPy's module system extends Python's native class mechanism to create reusable, optimizable building blocks for LLM pipelines. Unlike traditional Python modules, DSPy modules represent computational stages that can be automatically configured, optimized, and composed into larger programs.\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[dspy.Predict]\n    A --> C[dspy.ChainOfThought]\n    A --> D[dspy.MultiChainComparison]\n    A --> E[User-defined Module]\n    B --> F[Signature]\n    B --> G[Language Model]\n    E --> H[Other DSPy Modules]\n```\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Core Components\n\n### Module Base Class\n\nThe `dspy.Module` class serves as the foundation for all DSPy components. It extends Python's `nn.Module` to integrate seamlessly with neural network training paradigms while adding DSPy-specific functionality.\n\n| Method | Purpose | Returns |\n|--------|---------|---------|\n| `forward()` | Execute the module's computation | `Prediction` or similar |\n| `named_predictors()` | List all Predict submodules with names | `list[tuple[str, Predict]]` |\n| `predictors()` | Return all Predict instances | `list[Predict]` |\n| `set_lm(lm)` | Set language model for all predictors | `None` |\n| `get_lm()` | Retrieve the configured language model | `LM` instance |\n\n资料来源：[dspy/primitives/module.py:60-95]()\n\n### Predictor Parameters\n\nDSPy uses `Predict` and `Parameter` classes to define trainable components within modules. These parameters encapsulate the signature and configuration for LLM calls.\n\n```python\nclass Parameter(dspy.BaseModule):\n    \"\"\"Trainable parameter that wraps a Predict module.\"\"\"\n    \n    def __init__(self, signature, **kwargs):\n        self.signature = signature\n        self.kwargs = kwargs\n```\n\n资料来源：[dspy/predict/parameter.py:1-20]()\n\n## Module Hierarchy\n\n```mermaid\ngraph TD\n    A[nn.Module] --> B[dspy.BaseModule]\n    B --> C[dspy.Module]\n    C --> D[dspy.Predict]\n    C --> E[User Module]\n    D --> F[ChainOfThought]\n    D --> G[Retry]\n    E --> H[Composite Programs]\n    F --> I[MultiChainComparison]\n```\n\n### BaseModule\n\n`BaseModule` provides the essential interface that all DSPy components implement. It establishes the contract for modules that can be used within DSPy programs.\n\n### Module\n\nThe `Module` class adds advanced functionality including:\n\n- **Automatic predictor discovery**: Scans submodules to find all `Predict` instances\n- **Language model management**: Centralized LM configuration across the module tree\n- **Serialization support**: Ability to save and load compiled programs\n\n资料来源：[dspy/primitives/module.py:40-80]()\n\n## Predictor System\n\n### Predict Class\n\n`Predict` is the primary building block for LLM interactions. It binds a `Signature` to a language model call.\n\n```python\nclass Predict(Module):\n    def __init__(self, signature, **config):\n        self.signature = dspy.Signature(signature)\n        self.config = config\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `signature` | `str` or `Signature` | Input/output field definitions |\n| `lm` | `LM` | Language model to use (optional) |\n| `temperature` | `float` | Sampling temperature (default: varies by LM) |\n| `max_tokens` | `int` | Maximum tokens in response |\n\n资料来源：[dspy/predict/predict.py:1-60]()\n\n### Predictor Discovery\n\nModules can automatically discover their predictor submodules:\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\nprogram = MyProgram()\nfor name, predictor in program.named_predictors():\n    print(f\"{name}: {predictor.signature}\")\n# Output:\n# qa: question -> answer\n# summarize: text -> summary\n```\n\n资料来源：[dspy/primitives/module.py:50-65]()\n\n## Language Model Integration\n\n### Setting Language Models\n\nLanguage models can be set at different levels of granularity:\n\n```python\n# Set LM for entire module tree\nprogram.set_lm(dspy.LM(\"openai/gpt-4o-mini\"))\n\n# Set LM for specific predictor\nprogram.qa.lm = dspy.LM(\"anthropic/claude-3\")\n\n# Retrieve configured LM\nlm = program.get_lm()\n```\n\n资料来源：[dspy/primitives/module.py:80-95]()\n\n## Signature System\n\nSignatures define the schema for module inputs and outputs. They are central to the module system's type safety and documentation.\n\n```python\nclass Signature:\n    @classmethod\n    def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n        \"\"\"Create new Signature with custom instructions.\"\"\"\n        return Signature(cls.fields, instructions)\n    \n    @classmethod\n    def with_updated_fields(cls, name: str, **kwargs) -> type[\"Signature\"]:\n        \"\"\"Update field metadata (descriptions, types).\"\"\"\n        fields_copy = deepcopy(cls.fields)\n        fields_copy[name].json_schema_extra.update(kwargs)\n        return Signature(fields_copy, cls.instructions)\n```\n\n资料来源：[dspy/signatures/signature.py:1-50]()\n\n| Method | Purpose |\n|--------|---------|\n| `prepend()` | Add input field at the beginning |\n| `append()` | Add output field at the end |\n| `delete()` | Remove a field |\n| `with_instructions()` | Create copy with new instructions |\n| `with_updated_fields()` | Update field metadata |\n\n## Creating Custom Modules\n\nCustom modules extend `dspy.Module` and compose existing predictors:\n\n```python\nimport dspy\n\nclass RAG(dspy.Module):\n    def __init__(self, num_passages=5):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=num_passages)\n        self.generate_answer = dspy.ChainOfThought(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(query=question).passages\n        return self.generate_answer(context=context, question=question)\n```\n\n## Workflow Diagram\n\n```mermaid\ngraph LR\n    A[Define Module] --> B[Compose Predictors]\n    B --> C[Set Language Model]\n    C --> D[Compile with Teleprompter]\n    D --> E[Optimized Program]\n    E --> F[Execute on new inputs]\n```\n\n## Module Configuration Options\n\n| Option | Predictor Parameter | Default | Effect |\n|--------|---------------------|---------|--------|\n| `temperature` | Per-call | LM default | Controls randomness |\n| `max_tokens` | Per-call | LM default | Limits response length |\n| `top_p` | Per-call | 1.0 | Nucleus sampling threshold |\n| `cache` | Global | True | Enable response caching |\n\n## Compilation and Optimization\n\nModules interface with DSPy's teleprompter system for automatic optimization:\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\noptimizer = BootstrapFewShot(metric=my_metric)\ncompiled_program = optimizer.compile(\n    student=MyProgram(),\n    trainset=training_examples\n)\n```\n\nThe module system provides hooks for:\n- **Prompt optimization**: Automatically improving instructions\n- **Weight optimization**: Fine-tuning model weights via `BootstrapFinetune`\n- **Demonstration selection**: Choosing optimal few-shot examples\n\n资料来源：[dspy/primitives/module.py:1-30]()\n\n## See Also\n\n- [Signature System](../signatures/signature.md) - Input/output schema definitions\n- [Predict Module](../predict/predict.md) - Core LLM interaction component\n- [Teleprompters](../teleprompt/overview.md) - Optimization strategies\n- [Evaluator](../evaluation/evaluator.md) - Metrics and evaluation\n\n---\n\n<a id='adapters'></a>\n\n## Adapters\n\n### 相关页面\n\n相关主题：[Language Model Clients](#lm-clients)\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/base_type.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/base_type.py)\n- [dspy/adapters/types/history.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/history.py)\n- [dspy/adapters/types/image.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/adapters/types/image.py)\n</details>\n\n# Adapters\n\nAdapters in DSPy are core components responsible for formatting and structuring messages sent to Language Models (LMs). They act as an intermediary layer between DSPy's internal data structures and the API formats expected by various LLM providers.\n\n## Overview\n\nWhen a DSPy module executes a signature (such as `dspy.Predict` or `dspy.ChainOfThought`), the adapter transforms the structured input/output fields into a format the LM can understand, and then parses the LM's response back into structured data.\n\n```mermaid\ngraph LR\n    A[Signature Fields] --> B[Adapter]\n    B --> C[LM API Format]\n    C --> D[LM Response]\n    D --> B\n    B --> E[Structured Output]\n```\n\n**Key Responsibilities:**\n\n| Responsibility | Description |\n|----------------|-------------|\n| Input Formatting | Convert DSPy input fields into prompt content |\n| Output Parsing | Parse LM responses into structured output fields |\n| Format Selection | Support various output formats (JSON, XML, Chat, etc.) |\n| Type Handling | Process custom types like `Image`, `History`, etc. |\n\n资料来源：[dspy/adapters/__init__.py:1-50]()\n\n## Architecture\n\n### Base Adapter\n\nAll adapters inherit from `dspy.adapters.base.BaseAdapter`, which defines the common interface:\n\n```mermaid\nclassDiagram\n    class BaseAdapter {\n        +format(signature, demos, inputs) List[Message]\n        +parse(signature, completion) dict\n        +format_extractors(signature) str\n    }\n    \n    class ChatAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    class JSONAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    class XMLAdapter {\n        +format(signature, demos, inputs)\n        +parse(signature, completion)\n    }\n    \n    BaseAdapter <|-- ChatAdapter\n    BaseAdapter <|-- JSONAdapter\n    BaseAdapter <|-- XMLAdapter\n```\n\n**BaseAdapter Methods:**\n\n| Method | Purpose |\n|--------|---------|\n| `format(signature, demos, inputs)` | Format inputs and demonstrations into messages for the LM |\n| `parse(signature, completion)` | Parse LM completion text into structured output dictionary |\n| `format_extractors(signature)` | Generate extractor prompt text for output fields |\n\n资料来源：[dspy/adapters/base.py:1-100]()\n\n### Adapter Selection\n\nAdapters can be selected at different levels:\n\n1. **Global Configuration**: Set via `dspy.configure(adapter=...)`\n2. **Per-Module**: Pass `adapter` parameter to module constructors\n3. **Default**: `ChatAdapter` is used when no adapter is specified\n\n```python\n# Global configuration\ndspy.configure(adapter=dspy.JSONAdapter())\n\n# Per-module configuration\npredict = dspy.Predict(\"question -> answer\", adapter=dspy.XMLAdapter())\n```\n\n## Built-in Adapters\n\n### ChatAdapter\n\nThe default adapter that formats messages in OpenAI's chat format. It uses special delimiters to separate input fields, demonstrations, and output fields.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | Chat messages array |\n| Delimiter | `<<SYS>>` / `<<CONTEXT>>` / `<<RESPONSE>>` |\n| Best For | General purpose, GPT-4, Claude models |\n\n**Message Structure:**\n\n```mermaid\ngraph TD\n    A[System Message] --> B[Instructions]\n    B --> C[Input Fields]\n    C --> D[Demos Section]\n    D --> E[Output Fields Request]\n    E --> F[User Message]\n```\n\n资料来源：[dspy/adapters/chat_adapter.py:1-150]()\n\n### JSONAdapter\n\nFormats outputs as JSON, instructing the LM to respond with valid JSON that can be directly parsed.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | JSON in response |\n| Extraction | JSON parsing |\n| Best For | Structured data extraction, function calling |\n\n**Parsing Logic:**\n\n```python\n# The adapter looks for JSON blocks in the completion\njson_match = re.search(r\"```json\\s*(.*?)\\s*```\", completion, re.DOTALL)\nif json_match:\n    return json.loads(json_match.group(1))\n```\n\n资料来源：[dspy/adapters/json_adapter.py:1-100]()\n\n### XMLAdapter\n\nUses XML-style tags to delimit fields, providing a structured format similar to HTML/XML.\n\n**Characteristics:**\n\n| Feature | Value |\n|---------|-------|\n| Format | XML-tagged response |\n| Delimiter | `<question>`, `<answer>`, etc. |\n| Best For | Hierarchical or nested outputs |\n\n**Example Output Format:**\n\n```xml\n<answer>\n  The capital of France is Paris.\n</answer>\n```\n\n资料来源：[dspy/adapters/xml_adapter.py:1-100]()\n\n### TwoStepAdapter\n\nA specialized adapter that breaks the response into two steps:\n\n1. **Thought Step**: The LM first provides reasoning or analysis\n2. **Response Step**: The LM provides the final structured output\n\nThis adapter is particularly useful with `dspy.ChainOfThought` modules.\n\n资料来源：[dspy/adapters/two_step_adapter.py:1-100]()\n\n### BamlAdapter\n\nAdapter specifically designed for BAML (Business Application Markup Language) output formatting, used with BAML-compiled signatures.\n\n资料来源：[dspy/adapters/baml_adapter.py:1-50]()\n\n## Custom Types\n\nDSPy adapters support custom types that can be used in signatures:\n\n### Image Type\n\nThe `Image` type allows passing images to multimodal models:\n\n```python\nimport dspy\nfrom dspy.adapters.types import Image\n\nclass VisionSignature(dspy.Signature):\n    image: Image = dspy.InputField()\n    description: str = dspy.OutputField()\n\npredict = dspy.Predict(VisionSignature)\nresult = predict(image=Image(url=\"https://example.com/image.jpg\"))\n```\n\n**Image Formats Supported:**\n\n| Format | Support |\n|--------|---------|\n| URL string | ✅ Direct URL |\n| Base64 | ✅ Embedded data URI |\n| File path | ✅ Local file path |\n| PIL Image | ✅ In-memory image |\n| Bytes | ✅ Raw bytes |\n\n资料来源：[dspy/adapters/types/image.py:1-80]()\n\n### History Type\n\nThe `History` type allows passing conversation history:\n\n```python\nimport dspy\nfrom dspy.adapters.types import History\n\nclass ConversationSignature(dspy.Signature):\n    history: History = dspy.InputField()\n    question: str = dspy.InputField()\n    answer: str = dspy.OutputField()\n\nhistory = History(messages=[\n    {\"question\": \"What is 2+2?\", \"answer\": \"4\"},\n    {\"question\": \"What is 3+3?\", \"answer\": \"6\"},\n])\n\npredict = dspy.Predict(ConversationSignature)\nresult = predict(history=history, question=\"What is 5+5?\")\n```\n\n资料来源：[dspy/adapters/types/history.py:1-100]()\n\n### Custom Type Identifiers\n\nWhen custom types are used, adapters use special identifiers:\n\n| Identifier | Purpose |\n|------------|---------|\n| `<<CUSTOM-TYPE-START-IDENTIFIER>>` | Marks start of custom type content |\n| `<<CUSTOM-TYPE-END-IDENTIFIER>>` | Marks end of custom type content |\n\nThese identifiers help adapters extract and process custom type content from LM responses.\n\n资料来源：[dspy/adapters/types/base_type.py:1-50]()\n\n## Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Module\n    participant Adapter\n    participant LM\n    participant Parser\n\n    User->>Module: Forward pass with inputs\n    Module->>Adapter: format(signature, demos, inputs)\n    Adapter->>Adapter: Structure messages\n    Adapter->>LM: Send formatted messages\n    LM-->>Adapter: Return completion\n    Adapter->>Parser: parse(signature, completion)\n    Parser->>Parser: Extract structured fields\n    Parser-->>Module: Return dict output\n    Module-->>User: Return structured output\n```\n\n## Configuration Options\n\n### Adapter Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `caching` | bool | True | Enable response caching |\n| `batch_size` | int | 200 | Batch size for embedding operations |\n| `default_kwargs` | dict | {} | Default arguments passed to LM |\n\n### Setting Adapters\n\n```python\nimport dspy\n\n# Method 1: Global configuration\ndspy.configure(adapter=dspy.JSONAdapter())\n\n# Method 2: Per-module\npredict = dspy.Predict(\n    \"question -> answer\",\n    adapter=dspy.XMLAdapter()\n)\n\n# Method 3: At initialization\ndspy.settings.adapter = dspy.ChatAdapter()\n```\n\n## Best Practices\n\n1. **Use JSONAdapter** when you need strict structured output parsing\n2. **Use ChatAdapter** for general-purpose applications (default)\n3. **Use XMLAdapter** for nested or hierarchical data structures\n4. **Use TwoStepAdapter** with `ChainOfThought` for reasoning-intensive tasks\n5. **Use custom types** (`Image`, `History`) for multimodal or conversational applications\n\n## Extending Adapters\n\nTo create a custom adapter, inherit from `BaseAdapter`:\n\n```python\nfrom dspy.adapters import BaseAdapter\n\nclass MyCustomAdapter(BaseAdapter):\n    def format(self, signature, demos, inputs):\n        # Custom formatting logic\n        messages = []\n        # ... format messages ...\n        return messages\n    \n    def parse(self, signature, completion):\n        # Custom parsing logic\n        return {\"output_field\": parsed_value}\n```\n\n## Summary\n\nAdapters are a fundamental part of DSPy's architecture, providing a flexible abstraction layer between DSPy's declarative signatures and the various API formats expected by different LMs. By supporting multiple built-in adapters and allowing custom extensions, DSPy can work seamlessly with any language model while maintaining a consistent programming interface.\n\n| Adapter | Use Case |\n|---------|----------|\n| `ChatAdapter` | Default, general purpose |\n| `JSONAdapter` | Structured JSON output |\n| `XMLAdapter` | XML-tagged output |\n| `TwoStepAdapter` | Reasoning + response |\n| `BamlAdapter` | BAML format |\n\n---\n\n<a id='lm-clients'></a>\n\n## Language Model Clients\n\n### 相关页面\n\n相关主题：[Adapters](#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/cache.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/cache.py)\n</details>\n\n# Language Model Clients\n\n## Overview\n\nThe Language Model (LM) client system in DSPy provides a unified interface for interacting with various LLM providers. This abstraction layer enables developers to swap between different LLM backends (OpenAI, Anthropic, Azure, local models, etc.) without modifying application code.\n\n## Architecture\n\nThe LM client architecture follows a layered design pattern with a base class defining the common interface and provider-specific implementations extending it.\n\n```mermaid\ngraph TD\n    A[Application Code] --> B[dspy.LM Interface]\n    B --> C[OpenAI Client]\n    B --> D[LiteLLM Client]\n    B --> E[Databricks Client]\n    B --> F[Local LM Client]\n    C --> G[OpenAI API]\n    D --> H[40+ LLM Providers]\n    E --> I[Databricks Endpoint]\n    F --> J[Ollama / vLLM]\n```\n\n## Core Components\n\n### BaseLM Abstract Class\n\nThe `BaseLM` class defines the abstract interface that all LM clients must implement. This ensures consistency across different providers.\n\n| Method | Purpose | Return Type |\n|--------|---------|-------------|\n| `__call__` | Execute a completion request | `dict` |\n| `get_reference` | Retrieve cached responses | `dict \\| None` |\n| `inspect_history` | View conversation history | `list[dict]` |\n| `drop_cache` | Clear the response cache | `None` |\n\n资料来源：[dspy/clients/base_lm.py]()\n\n### LM Factory Class\n\nThe main `LM` class serves as a factory that instantiates the appropriate client based on the model identifier format.\n\nSupported model formats include:\n- `provider/model-name` (e.g., `openai/gpt-4`, `anthropic/claude-3`)\n- `provider/model-name@timestamp` (e.g., `openai/gpt-4o-mini-2024-07-18`)\n- `provider/model-name:variant` (e.g., `openai/gpt-4-turbo:n-1106`)\n\n```python\n# Example instantiation patterns\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nlm = dspy.LM(\"anthropic/claude-3-opus-20240229\")\nlm = dspy.LM(\"azure/gpt-4o\", api_base=\"https://...\", api_key=\"...\")\n```\n\n资料来源：[dspy/clients/lm.py:1-100]()\n\n## LM Client Implementations\n\n### OpenAI Client\n\nThe OpenAI client provides direct integration with OpenAI's API endpoints.\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `model` | `str` | Required | Model name (e.g., `gpt-4o-mini`) |\n| `api_key` | `str` | Environment | API key from `OPENAI_API_KEY` |\n| `api_base` | `str` | Official API | Custom endpoint URL |\n| `temperature` | `float` | `0.0` | Sampling temperature |\n| `max_tokens` | `int` | `1024` | Maximum completion tokens |\n| `timeout` | `int \\| float` | `120` | Request timeout in seconds |\n\n资料来源：[dspy/clients/openai.py]()\n\n### LiteLLM Client\n\nThe LiteLLM client wraps the `litellm` library, providing access to over 40 LLM providers through a unified interface.\n\n```python\n# Using LiteLLM-backed LM\nlm = dspy.LM(\"anthropic/claude-3-sonnet-20240229\", \n             api_key=os.getenv(\"ANTHROPIC_API_KEY\"))\n```\n\nSupported providers include:\n- Anthropic\n- Azure OpenAI\n- AWS Bedrock\n- Google Vertex AI\n- Cohere\n- Mistral\n- Together AI\n\n资料来源：[dspy/clients/_litellm.py]()\n\n### Databricks Client\n\nThe Databricks client integrates with Databricks Model Serving endpoints for enterprise deployments.\n\n```python\nfrom dspy.clients.databricks import Databricks\n\nlm = Databricks(\n    model=\"databricks-meta-llama-3-70b-instruct\",\n    Databricks_host=\"https://your-workspace.cloud.databricks.com\",\n    Databricks_token=\"your-token\",\n)\n```\n\n| Parameter | Description |\n|-----------|-------------|\n| `model` | Databricks model endpoint name |\n| `Databricks_host` | Workspace URL |\n| `Databricks_token` | Authentication token |\n\n资料来源：[dspy/clients/databricks.py]()\n\n### Local LM Client\n\nThe Local LM client supports self-hosted models through Ollama or vLLM.\n\n```python\nfrom dspy.clients.lm_local import LocalLM\n\n# Using Ollama\nlm = LocalLM(model=\"llama3\", base_url=\"http://localhost:11434\")\n\n# Using vLLM\nlm = LocalLM(model=\"mistralai/Mistral-7B-Instruct-v0.2\", base_url=\"http://localhost:8000\")\n```\n\n资料来源：[dspy/clients/lm_local.py]()\n\n## Caching System\n\nDSPy implements a response caching mechanism to reduce API costs and improve latency for repeated requests.\n\n```mermaid\ngraph LR\n    A[Request] --> B{Cache Hit?}\n    B -->|Yes| C[Return Cached Response]\n    B -->|No| D[Execute LM Call]\n    D --> E[Store in Cache]\n    E --> F[Return Response]\n```\n\n### Cache Configuration\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `cache` | `Cache` | `None` | Cache instance |\n| `cache_turns` | `bool` | `False` | Include conversation turns in cache key |\n\nThe cache uses a hash-based key generation strategy:\n1. Serialize the input prompt\n2. Serialize adapter inputs and configuration\n3. Combine and hash to create cache key\n\n资料来源：[dspy/clients/cache.py]()\n\n## Callback System\n\nCallbacks enable monitoring and logging of LM interactions throughout the application.\n\n```mermaid\ngraph TD\n    A[LM Call] --> B[Callback Manager]\n    B --> C[on_module_start]\n    B --> D[on_module_end]\n    B --> E[on_lm_start]\n    B --> F[on_lm_end]\n```\n\n### Built-in Callbacks\n\n| Callback | Trigger | Purpose |\n|----------|---------|---------|\n| `LoggingCallback` | Every LM call | Log inputs/outputs to console |\n| Custom `Handler` | Per event type | User-defined monitoring logic |\n\n```python\nclass LoggingCallback(Handler):\n    def on_lm_start(self, call_id, instance, inputs):\n        print(f\"LM is called with inputs: {inputs}\")\n    \n    def on_lm_end(self, call_id, instance, outputs):\n        print(f\"LM is finished with outputs: {outputs}\")\n```\n\n资料来源：[dspy/utils/callback.py]()\n\n## Configuration Options\n\n### Global Configuration\n\nConfigure LM settings globally using `dspy.configure()`:\n\n```python\nimport dspy\n\ndspy.configure(\n    lm=dspy.LM(\"openai/gpt-4o-mini\"),\n    rm=dspy.Retrieve(k=3),\n    max_tokens=512,\n    temperature=0.1,\n)\n```\n\n### Per-Instance Configuration\n\nOverride settings at the component level:\n\n```python\ncot = dspy.ChainOfThought(\n    \"question -> answer\",\n    temperature=0.5,\n    max_tokens=256\n)\n```\n\n### Configuration Precedence\n\n| Level | Override Priority | Example |\n|-------|-------------------|---------|\n| Component | Highest | `dspy.Predict(..., temperature=0.8)` |\n| Global | Middle | `dspy.configure(temperature=0.5)` |\n| Default | Lowest | `dspy.LM(\"...\")` default value |\n\n## Usage Patterns\n\n### Basic Usage\n\n```python\nimport dspy\n\n# Initialize LM\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# Direct call\nresult = lm(\"What is the capital of France?\")\nprint(result)\n```\n\n### With Modules\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\")\n\n# Set LM for a module\nprogram = dspy.Predict(\"question -> answer\")\nprogram.set_lm(lm)\n\n# Execute\nresult = program(question=\"What is 2+2?\")\n```\n\n### Batch Processing\n\n```python\nimport dspy\n\nlm = dspy.LM(\"openai/gpt-4o-mini\", max_tokens=100)\n\n# Multiple calls tracked in history\nfor q in questions:\n    lm(q)\n\n# Inspect all calls\nfor item in lm.inspect_history():\n    print(item)\n```\n\n## Error Handling\n\nThe LM client system handles various error conditions:\n\n| Error Type | Cause | Handling Strategy |\n|------------|-------|-------------------|\n| `AuthenticationError` | Invalid API key | Check environment variables |\n| `RateLimitError` | API quota exceeded | Implement backoff/retry |\n| `APIResponseValidationError` | Malformed response | Automatic retry with backoff |\n| `ContextWindowExceededError` | Input too long | Reduce prompt size |\n\n## Best Practices\n\n1. **Use environment variables** for API keys to avoid hardcoding credentials\n2. **Enable caching** for development and testing to reduce API costs\n3. **Set appropriate `max_tokens`** to prevent overly long responses\n4. **Use callbacks** for production monitoring and debugging\n5. **Configure timeouts** appropriately for your use case (default: 120s)\n\n## See Also\n\n- [Signature System](../signatures/signature.md) - How DSPy defines input/output schemas\n- [Modules](../primitives/module.md) - Using LMs within DSPy modules\n- [Teleprompters](../teleprompt/teleprompt.md) - Optimizing prompts with LMs\n- [Retrievers](../retrievers/retriever.md) - Combining LMs with retrieval systems\n\n---\n\n<a id='predict-modules'></a>\n\n## Prediction Modules\n\n### 相关页面\n\n相关主题：[Module System](#modules), [Agent Modules](#agent-modules)\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/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n- [dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.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/aggregation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/aggregation.py)\n- [dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n- [dspy/predict/knn.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/knn.py)\n</details>\n\n# Prediction Modules\n\n## Overview\n\nPrediction Modules are the core building blocks in DSPy for executing language model calls. They encapsulate the logic for invoking language models, handling inputs/outputs defined by Signatures, and providing various reasoning and optimization strategies. All predictors inherit from the base `Predict` class and can be composed within `dspy.Module` objects to build complex AI pipelines.\n\n**Key responsibilities:**\n- Execute language model calls with specified inputs\n- Parse and validate model outputs according to Signature definitions\n- Support multiple reasoning strategies (chain-of-thought, multi-chain comparison, etc.)\n- Integrate with DSPy's teleprompters for automatic prompt optimization\n- Track execution history for debugging and introspection\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n---\n\n## Base Predict Class\n\nThe `Predict` class serves as the foundation for all prediction modules. It wraps a Signature that defines input and output fields.\n\n### Basic Usage\n\n```python\nimport dspy\n\n# Simple question answering\nqa = dspy.Predict(\"question -> answer\")\nqa(question=\"What is the capital of France?\", lm=dspy.LM(\"openai/gpt-4o-mini\"))\n```\n\n### Signature Definition\n\nSignatures define the schema for inputs and outputs:\n\n```python\nclassify = dspy.Predict(\n    \"sentence -> sentiment: str, confidence: float\"\n)\n```\n\n资料来源：[dspy/predict/predict.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/predict.py)\n\n---\n\n## Specialized Predictor Types\n\n### Chain of Thought (CoT)\n\n`ChainOfThought` generates reasoning steps before producing the final answer. This technique improves accuracy on complex reasoning tasks.\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"If I have 5 apples and eat 2, how many do I have left?\")\n# Includes reasoning trace in addition to answer\n```\n\n资料来源：[dspy/predict/chain_of_thought.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/chain_of_thought.py)\n\n### Multi Chain Comparison (MCC)\n\n`MultiChainComparison` generates multiple reasoning chains and compares them to produce a more robust answer.\n\n```python\nmcc = dspy.MultiChainComparison(\"question -> answer\", n=3)\nresult = mcc(question=\"Explain why the sky is blue\")\n```\n\n资料来源：[dspy/predict/multi_chain_comparison.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/multi_chain_comparison.py)\n\n### Parallel Predictor\n\n`Parallel` executes multiple predictors simultaneously and returns all results.\n\n```python\nparallel = dspy.Parallel(\n    dspy.Predict(\"question -> short_answer\"),\n    dspy.Predict(\"question -> detailed_answer\")\n)\nresults = parallel(question=\"What is Python?\")\n```\n\n资料来源：[dspy/predict/parallel.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/parallel.py)\n\n### Best of N\n\n`BestOfN` generates N candidates and selects the best one based on a provided metric.\n\n```python\nbest_of = dspy.BestOfN(\"question -> answer\", n=5, metric=my_metric)\nresult = best_of(question=\"What is 2+2?\")\n```\n\n资料来源：[dspy/predict/best_of_n.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/best_of_n.py)\n\n### Retry\n\n`Retry` automatically retries failed or low-quality predictions with modified prompts.\n\n```python\nretry = dspy.Retry(\"question -> answer\", max_retries=3)\nresult = retry(question=\"Explain quantum entanglement\")\n```\n\n资料来源：[dspy/predict/retry.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/retry.py)\n\n### Refine\n\n`Refine` iteratively improves predictions through successive refinement steps.\n\n```python\nrefine = dspy.Refine(\"question -> answer\", max_iters=5)\nresult = refine(question=\"Write a haiku about coding\")\n```\n\n资料来源：[dspy/predict/refine.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/refine.py)\n\n### Aggregation\n\n`Aggregation` combines outputs from multiple predictors using various strategies (voting, majority, etc.).\n\n```python\nagg = dspy.Aggregation(\"observation -> conclusion\", strategy=\"majority_vote\")\nresult = agg(observation=\"Multiple sensors detected movement\")\n```\n\n资料来源：[dspy/predict/aggregation.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/aggregation.py)\n\n### KNN Predictor\n\n`KNN` uses k-nearest neighbors approach for predictions based on similar training examples.\n\n```python\nknn = dspy.KNN(\"input -> output\", k=5)\nknn.load_examples(trainset)\nresult = knn(input=\"similar text to training data\")\n```\n\n资料来源：[dspy/predict/knn.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/knn.py)\n\n---\n\n## Integration with Modules\n\nPredictors are typically used within `dspy.Module` subclasses for building complete programs.\n\n### Declaring Predictors in Modules\n\n```python\nimport dspy\n\nclass RAGProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Predict(\"query -> context\")\n        self.answer = dspy.ChainOfThought(\"context, question -> answer\")\n    \n    def forward(self, question):\n        context = self.retrieve(query=question)\n        return self.answer(context=context.context, question=question)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n### Managing Predictors\n\n```python\nprogram = RAGProgram()\n\n# List all predictors\nfor name, predictor in program.named_predictors():\n    print(f\"{name}: {predictor}\")\n\n# Get all predictor instances\nall_predictors = program.predictors()\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Language Model Configuration\n\n### Setting LM for All Predictors\n\n```python\nlm = dspy.LM(\"openai/gpt-4o-mini\")\nprogram = RAGProgram()\nprogram.set_lm(lm)\n```\n\n### Getting LM from Module\n\n```python\nlm = program.get_lm()  # Returns LM if all predictors use the same one\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Batch Processing\n\nPredictors support batch execution with configurable parallelism and error handling:\n\n```python\nexamples = [\n    dspy.Example(question=\"What is 1+1?\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 2+2?\").with_inputs(\"question\"),\n]\n\nresults = program.batch(\n    examples=examples,\n    num_threads=4,\n    max_errors=2,\n    return_failed_examples=True,\n)\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## History Inspection\n\nView past executions for debugging:\n\n```python\n# Inspect last prediction\nprogram.inspect_history(n=1)\n\n# Inspect last 5 predictions with output to file\nprogram.inspect_history(n=5, file=open(\"history.txt\", \"w\"))\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Transformative Operations\n\nApply transformations to all predictors in a module:\n\n```python\n# Wrap all predictors with Retry\nprogram.map_named_predictors(lambda p: dspy.Retry(p))\n```\n\n资料来源：[dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n\n---\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[dspy.Module] --> B[Predict]\n    A --> C[ChainOfThought]\n    A --> D[MultiChainComparison]\n    A --> E[Parallel]\n    A --> F[Retry]\n    A --> G[Refine]\n    A --> H[BestOfN]\n    A --> I[Aggregation]\n    A --> J[KNN]\n    \n    B --> K[Signature Definition]\n    B --> L[LM Invocation]\n    B --> M[Output Parsing]\n    \n    N[Example Data] --> O[Batch Processing]\n    O --> B\n    O --> C\n    O --> D\n    \n    P[Teleprompters] -.-> Q[Optimize Predictors]\n    Q --> B\n    Q --> C\n```\n\n---\n\n## Complete Example\n\n```python\nimport dspy\n\n# Configure language model\nlm = dspy.LM(\"openai/gpt-4o-mini\")\ndspy.configure(lm=lm)\n\n# Define a multi-step program\nclass MedicalQAProgram(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.classify = dspy.Predict(\"question -> category: str\")\n        self.answer = dspy.ChainOfThought(\"category, question -> answer\")\n        self.refine = dspy.Retry(\"category, question, answer -> refined_answer\")\n    \n    def forward(self, question):\n        category = self.classify(question=question)\n        answer = self.answer(category=category.category, question=question)\n        refined = self.refine(\n            category=category.category,\n            question=question,\n            answer=answer.answer\n        )\n        return refined\n\n# Create and use program\nprogram = MedicalQAProgram()\nresult = program(question=\"What are the symptoms of diabetes?\")\nprint(result.refined_answer)\n```\n\n---\n\n## Summary Table\n\n| Predictor Type | Purpose | Key Parameter |\n|----------------|---------|----------------|\n| `Predict` | Base predictor for simple LM calls | `signature` |\n| `ChainOfThought` | Generate reasoning traces | `signature`, `_reasoning` |\n| `MultiChainComparison` | Compare multiple reasoning chains | `signature`, `n` |\n| `Parallel` | Execute multiple predictors simultaneously | `*predictors` |\n| `Retry` | Retry failed predictions | `max_retries`, `threshold` |\n| `Refine` | Iteratively improve predictions | `max_iters` |\n| `BestOfN` | Select best from N candidates | `n`, `metric` |\n| `Aggregation` | Combine outputs via voting | `strategy` |\n| `KNN` | K-nearest neighbors prediction | `k`, examples |\n\n---\n\n## See Also\n\n- [Signature System](../core/signatures.md) - Input/output field definitions\n- [Teleprompters](../teleprompt/overview.md) - Automatic prompt optimization\n- [Module System](../primitives/module.md) - Composing predictors into programs\n\n---\n\n<a id='agent-modules'></a>\n\n## Agent Modules\n\n### 相关页面\n\n相关主题：[Prediction Modules](#predict-modules)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [dspy/predict/react.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/react.py)\n- [dspy/predict/rlm.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/predict/rlm.py)\n- [dspy/primitives/code_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/code_interpreter.py)\n- [dspy/primitives/python_interpreter.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/python_interpreter.py)\n- [dspy/primitives/module.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/primitives/module.py)\n- [dspy/propose/grounded_proposer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/propose/grounded_proposer.py)\n</details>\n\n# Agent Modules\n\n## Overview\n\nAgent Modules in DSPy are specialized modules that enable language models to interact with external tools, execute code, and perform multi-step reasoning tasks. Unlike standard Predict modules that generate direct outputs, Agent Modules implement agentic behaviors where the LM can plan, take actions (such as calling tools or executing code), observe results, and iteratively refine their approach until reaching a final answer.\n\nDSPy provides several agent implementations that share a common architectural pattern: they use a signature to define input/output fields, maintain a trajectory of their reasoning and actions, and leverage code interpreters or tool execution systems to perform computations that the language model cannot do directly.\n\n资料来源：[dspy/primitives/module.py:1-50]()\n\n## Architecture\n\n### Core Components\n\nAgent Modules in DSPy are built on a layered architecture:\n\n```mermaid\ngraph TD\n    A[Agent Module<br/>e.g., ReAct, Program of Thought] --> B[Signature<br/>Input/Output Field Definitions]\n    A --> C[Tool Registry<br/>Available Actions]\n    A --> D[History/Trajectory<br/>Reasoning & Actions]\n    B --> E[Code Interpreter<br/>Execution Backend]\n    C --> F[Tool Execution<br/>Function Calls]\n    D --> G[Observation Processing<br/>Feedback Loop]\n    E --> H[Python Interpreter<br/>Sandboxed Execution]\n```\n\n### Agent Base Pattern\n\nAll DSPy agent implementations follow a similar control flow:\n\n1. **Initialization**: Set up signature, tools, and configuration parameters\n2. **Loop Execution**: Iterate until max iterations or final output received\n3. **Thought Generation**: LM produces reasoning and next action\n4. **Action Execution**: Tools or code interpreters execute the proposed action\n5. **Observation Processing**: Results are appended to trajectory\n6. **Termination**: Return final prediction with full trajectory\n\n资料来源：[dspy/predict/react.py:1-80]()\n\n## ReAct Agent\n\nThe ReAct agent implements the Reasoning + Acting pattern, combining deliberate reasoning with tool usage. It allows language models to use external tools to gather information and complete tasks.\n\n### Signature Configuration\n\n```python\nclass ReAct(dspy.Module):\n    def __init__(\n        self,\n        signature,\n        max_iters: int = 10,\n        tools: list[Tool | Callable] = None,\n    ):\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `signature` | `str \\| Signature` | Required | Defines input/output fields for the task |\n| `max_iters` | `int` | `10` | Maximum number of reasoning iterations |\n| `tools` | `list[Tool \\| Callable]` | `None` | List of tools available to the agent |\n\n资料来源：[dspy/predict/react.py:50-90]()\n\n### Tool Integration\n\nThe ReAct agent automatically generates instructions that inform the LM about available tools:\n\n```python\ninputs = \", \".join([f\"`{k}`\" for k in signature.input_fields.keys()])\noutputs = \", \".join([f\"`{k}`\" for k in signature.output_fields.keys()])\ninstr = [\n    f\"You are an Agent. In each episode, you will be given the fields {inputs} as input.\",\n    f\"Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\",\n]\n```\n\nTools are converted to a `Tool` registry and made available by name for the agent to call.\n\n资料来源：[dspy/predict/react.py:70-85]()\n\n### Usage Example\n\n```python\ndef get_weather(city: str) -> str:\n    return f\"The weather in {city} is sunny.\"\n\nreact = dspy.ReAct(signature=\"question -> answer\", tools=[get_weather])\npred = react(question=\"What is the weather in Tokyo?\")\n```\n\n## Code Interpreter Agents\n\nDSPy provides agents that can execute Python code to perform computations. These agents use a sandboxed Python interpreter to run code safely.\n\n### Python Interpreter\n\nThe `PythonInterpreter` class provides the execution backend for code-based agents:\n\n| Feature | Description |\n|---------|-------------|\n| **Sandboxed Execution** | Runs code in an isolated environment |\n| **Variable Extraction** | Extracts variables from execution context |\n| **Error Handling** | Catches and reports execution errors |\n| **REPL Support** | Interactive read-eval-print loop style execution |\n\nThe interpreter extracts variables after each execution, making them available for subsequent code blocks or tool calls.\n\n资料来源：[dspy/primitives/python_interpreter.py:1-60]()\n\n### Code Interpreter Primitive\n\nThe `CodeInterpreter` class wraps the Python interpreter with additional utilities:\n\n```python\nclass CodeInterpreter:\n    def __init__(self, max_output_chars: int = 2000):\n        self.max_output_chars = max_output_chars\n    \n    def execute(self, code: str, variables: dict) -> Any:\n        # Execute code and return result\n```\n\n| Method | Description |\n|--------|-------------|\n| `execute(code, variables)` | Execute code string with provided variable context |\n| `extract_variables(result)` | Extract Python objects from execution result |\n\n资料来源：[dspy/primitives/code_interpreter.py:1-50]()\n\n## Reflexion Language Model (RLM) Agent\n\nThe RLM agent implements a Reflexion-style approach where the agent maintains a history of reasoning, code execution, and observations to iteratively improve its output.\n\n### Execution Flow\n\n```mermaid\ngraph TD\n    A[Start with Input] --> B[Generate Reasoning]\n    B --> C[Generate Code]\n    C --> D[Execute Code in Interpreter]\n    D --> E{Error?}\n    E -->|Yes| F[Record Error in History]\n    F --> G[Generate Fix Reasoning]\n    G --> C\n    E -->|No| H{Is Final Output?}\n    H -->|No| B\n    H -->|Yes| I[Return Prediction with Trajectory]\n```\n\n### Trajectory Tracking\n\nThe RLM agent maintains a `REPLHistory` that tracks all iterations:\n\n```python\nreturn Prediction(\n    **parsed_outputs,\n    trajectory=[e.model_dump() for e in final_history],\n    final_reasoning=pred.reasoning,\n)\n```\n\nEach history entry contains:\n- `reasoning`: The agent's thought process\n- `code`: The code that was executed\n- `output`: The result or error message\n\n资料来源：[dspy/predict/rlm.py:100-130]()\n\n### Result Processing\n\nThe agent processes final outputs by parsing structured results:\n\n```python\ndef _process_final_output(self, result: FinalOutput, output_field_names: list[str]):\n    parsed_outputs, error = self._process_final_output(result, output_field_names)\n    \n    if error:\n        return history.append(reasoning=pred.reasoning, code=code, output=error)\n```\n\n## Program of Thought\n\nThe Program of Thought agent combines natural language reasoning with programmatic code execution, allowing the agent to offload complex calculations to executed code while maintaining reasoning chains.\n\n### Architecture\n\n```mermaid\ngraph LR\n    A[Input Question] --> B[Reasoning Module]\n    B --> C[Code Generation]\n    C --> D[Python Interpreter]\n    D --> E[Output Extraction]\n    E --> F{More Steps Needed?}\n    F -->|Yes| B\n    F -->|No| G[Final Answer]\n```\n\n## Tool Definition\n\nDSPy uses a `Tool` class to wrap functions and make them available to agents:\n\n```python\ntool = Tool(\n    name=\"function_name\",\n    func=my_function,\n    desc=\"Description for LLM\"\n)\n```\n\nTools can be:\n- Plain Python functions\n- Decorated with the `@Tool` decorator\n- Already instantiated `Tool` objects\n\n## Configuration Parameters\n\n### Common Agent Parameters\n\n| Parameter | Type | Default | Agent Types |\n|-----------|------|---------|-------------|\n| `max_iters` | `int` | `10` | ReAct, RLM |\n| `max_output_chars` | `int` | `2000` | RLM, Code-based |\n| `temperature` | `float` | `0.0` | All agents |\n| `verbose` | `bool` | `False` | All agents |\n\n### History and Trajectory\n\nAgents maintain execution history which can be inspected:\n\n```python\nagent = dspy.ReAct(signature=\"question -> answer\", tools=[my_tool])\nresult = agent(question=\"What is 2+2?\")\n\n# Access trajectory\nfor step in result.trajectory:\n    print(f\"Thought: {step['reasoning']}\")\n    print(f\"Action: {step['code']}\")\n    print(f\"Observation: {step['output']}\")\n```\n\n## Integration with DSPy Module System\n\nAll agent modules inherit from `dspy.Module`, giving them access to:\n\n- `named_predictors()`: List all Predict instances\n- `set_lm(lm)`: Set language model for all predictors\n- `get_lm()`: Retrieve the configured language model\n- `inspect_history(n)`: Display recent LM call history\n\n```python\nclass MyAgent(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.predictor = dspy.ReAct(\"question -> answer\", tools=[...])\n    \n    def forward(self, question):\n        return self.predictor(question=question)\n```\n\n资料来源：[dspy/primitives/module.py:50-120]()\n\n## Best Practices\n\n### Tool Design\n\n1. **Clear Function Names**: Use descriptive names that indicate the tool's purpose\n2. **Type Annotations**: Add type hints for better LLM understanding\n3. **Docstrings**: Provide clear descriptions of what the tool does\n4. **Return Values**: Return string or serializable types for consistency\n\n### Agent Configuration\n\n1. **Set Appropriate `max_iters`**: Too few iterations may prevent task completion; too many wastes resources\n2. **Use Temperature Control**: Lower temperatures (0.0-0.3) for deterministic tasks\n3. **Inspect Trajectories**: Use `inspect_history()` for debugging agent behavior\n\n### Error Handling\n\nAgents should be configured with error handling for:\n- Code execution failures\n- Tool invocation errors\n- Maximum iteration limits reached\n- Invalid output parsing\n\n---\n\n<a id='optimizers'></a>\n\n## Optimizers (Teleprompt)\n\n### 相关页面\n\n相关主题：[Signatures System](#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/mipro_optimizer_v2.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/mipro_optimizer_v2.py)\n- [dspy/teleprompt/copro_optimizer.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/copro_optimizer.py)\n- [dspy/teleprompt/bettertogether.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bettertogether.py)\n- [dspy/teleprompt/ensemble.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/ensemble.py)\n- [dspy/teleprompt/random_search.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/random_search.py)\n- [dspy/teleprompt/grpo.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/grpo.py)\n- [dspy/teleprompt/gepa/gepa.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/gepa/gepa.py)\n- [dspy/teleprompt/bootstrap_finetune.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_finetune.py)\n- [dspy/teleprompt/bootstrap_trace.py](https://github.com/stanfordnlp/dspy/blob/main/dspy/teleprompt/bootstrap_trace.py)\n</details>\n\n# Optimizers (Teleprompt)\n\n## Overview\n\nIn DSPy, **Optimizers** (also referred to as **Teleprompters**) are compilation strategies that automatically optimize the prompts and/or weights of your LM programs. They take a raw program with a signature and training data, then search for improved instructions and/or demonstrations to include in the program's prompts.\n\nThe teleprompter system enables declarative, data-driven optimization of LLM pipelines without manual prompt engineering. Instead of crafting prompts by hand, you define:\n\n1. Your program structure (modules, signatures)\n2. A metric function to evaluate quality\n3. A training set of examples\n\nThe optimizer then compiles your program by finding optimal combinations of instructions, demonstrations, and (optionally) fine-tuned weights.\n\n## Architecture\n\nThe optimizer system follows a hierarchical architecture with a base `Teleprompter` abstract class and specialized subclasses for different optimization strategies:\n\n```mermaid\ngraph TD\n    A[Teleprompter Base] --> B[Prompt Optimizers]\n    A --> C[Weight Optimizers]\n    A --> D[Meta-Optimizers]\n    \n    B --> B1[BootstrapFewShot]\n    B --> B2[MIPROv2]\n    B --> B3[COPRO]\n    B --> B4[GEPA]\n    B --> B5[GRPO]\n    B --> B6[BootstrapFewShotWithRandomSearch]\n    \n    C --> C1[BootstrapFinetune]\n    \n    D --> D1[BetterTogether]\n    \n    A --> E[Ensemble]\n    E --> E1[Ensemble]\n```\n\n## Base Class: Teleprompter\n\nAll optimizers inherit from the abstract `Teleprompter` class defined in `dspy/teleprompt/teleprompt.py`. The base interface requires implementing a `compile()` method.\n\n### Compile Interface\n\n```python\ndef compile(self, student: Module, *, trainset: list[Example], ...) -> Module:\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `student` | `Module` | The program to optimize |\n| `trainset` | `list[Example]` | Training examples for optimization |\n| `valset` | `list[Example]` | Optional validation set for selecting best program |\n| `teacher` | `Module \\| list[Module]` | Optional teacher program for bootstrapping |\n| `strategy` | `str` | Execution strategy for meta-optimizers |\n\n## Prompt Optimizers\n\nPrompt optimizers focus on improving the instructions and demonstrations in your program's prompts without modifying model weights.\n\n### BootstrapFewShot\n\n`BootstrapFewShot` is the foundational prompt optimizer that composes demonstrations (examples) into a predictor's prompt. These demos come from two sources:\n\n1. **Labeled examples** from the training set\n2. **Bootstrapped demos** generated by running the program with the LM\n\n**Key Features:**\n\n- Each bootstrap round copies the LM with a new `rollout_id` at `temperature=1.0` to bypass caches and gather diverse traces\n- Supports multi-round bootstrapping for complex multi-step programs\n\n资料来源：[dspy/teleprompt/bootstrap.py:20-45]()\n\n```python\nteleprompter = BootstrapFewShot(\n    metric=your_metric,\n    metric_threshold=0.5,        # Minimum score to accept bootstrapped demos\n    max_bootstrapped_demos=4,      # Maximum bootstrap examples per predictor\n    max_labeled_demos=16,          # Maximum labeled examples from trainset\n    max_rounds=1,                  # Number of bootstrap rounds\n    max_errors=4,                 # Max consecutive errors before stopping\n)\ncompiled = teleprompter.compile(student, trainset=trainset)\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `metric` | `Callable` | Required | Function comparing expected and predicted values |\n| `metric_threshold` | `float` | `None` | Minimum metric score for accepting bootstrapped demos |\n| `teacher_settings` | `dict` | `None` | Settings for the teacher model |\n| `max_bootstrapped_demos` | `int` | `4` | Maximum bootstrap demonstrations to include |\n| `max_labeled_demos` | `int` | `16` | Maximum labeled examples from training set |\n| `max_rounds` | `int` | `1` | Number of bootstrap rounds |\n| `max_errors` | `int` | `None` | Maximum consecutive errors before stopping |\n\n### BootstrapFewShotWithRandomSearch\n\nThis optimizer extends `BootstrapFewShot` by adding random search over different demonstration configurations. It explores multiple bootstrap configurations and selects the best performing one.\n\n资料来源：[dspy/teleprompt/random_search.py]()\n\n### MIPROv2 (Multi-Instruction Prompt Optimization)\n\nMIPROv2 optimizes both instructions and demonstrations using Bayesian optimization. It treats the instruction template and demonstration selection as hyperparameters to optimize.\n\n**Key Characteristics:**\n\n- Uses Bayesian optimization to efficiently search the space of prompts\n- Supports fine-grained control over instruction generation\n- Can use a separate prompt model for generating candidate instructions\n\n资料来源：[dspy/teleprompt/mipro_optimizer_v2.py]()\n\n```python\nfrom dspy.teleprompt import MIPROv2\n\noptimizer = MIPROv2(\n    metric=metric,\n    num_trials=100,           # Number of optimization trials\n    max_bootstrapped_demos=4,\n    minibend_size=50,\n    auto=\"medium\",           # Automatic complexity control\n)\ncompiled = optimizer.compile(student, trainset=trainset, valset=valset)\n```\n\n### COPRO (Coordinate Prompt Optimization)\n\nCOPRO generates new prompt instructions iteratively, using a prompt model to propose variations based on the history of previous prompts.\n\n**Algorithm Parameters:**\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `breadth` | `10` | Number of new prompts to generate at each iteration |\n| `depth` | `3` | Number of iterations to generate new prompts |\n| `init_temperature` | `1.4` | Temperature for generation (higher = more creative) |\n| `track_stats` | `False` | Whether to track optimization statistics |\n\n资料来源：[dspy/teleprompt/copro_optimizer.py:20-35]()\n\n```python\nfrom dspy.teleprompt import COPRO\n\nteleprompter = COPRO(\n    prompt_model=prompt_model,\n    metric=metric,\n    breadth=10,\n    depth=3,\n    init_temperature=1.4,\n)\ncompiled = teleprompter.compile(program, trainset=trainset)\n```\n\n### GEPA (Generalized Evolutionary Prompt Algorithm)\n\nGEPA implements reflective prompt evolution using evolutionary strategies. It can outperform reinforcement learning approaches for prompt optimization.\n\n资料来源：[dspy/teleprompt/gepa/gepa.py]()\n\n```python\nfrom dspy.teleprompt import GEPA\n\noptimizer = GEPA(\n    metric=metric,\n    auto=\"medium\",            # Automatic complexity control\n    num_trials=50,\n)\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n### GRPO (Group Relative Policy Optimization)\n\nGRPO applies group relative policy optimization for instruction tuning. It uses a collection of candidate prompts and selects based on relative performance rankings.\n\n资料来源：[dspy/teleprompt/grpo.py]()\n\n## Weight Optimizers\n\nWeight optimizers fine-tune the weights of the language model itself (or adapter weights) to improve program performance.\n\n### BootstrapFinetune\n\n`BootstrapFinetune` uses bootstrapped demonstrations to fine-tune the language model weights. Unlike prompt-only optimization, this method modifies the actual model parameters.\n\n**Requirements:**\n\n- Student programs must have LMs explicitly set via `set_lm()` (not relying on global `dspy.settings.lm`)\n- Requires a training set with high-quality demonstrations\n\n资料来源：[dspy/teleprompt/bootstrap_finetune.py]()\n\n```python\nfrom dspy.teleprompt import BootstrapFinetune\n\noptimizer = BootstrapFinetune(metric=metric)\nstudent.set_lm(lm)  # Required: explicit LM setting\ncompiled = optimizer.compile(student, trainset=trainset)\n```\n\n## Meta-Optimizers\n\nMeta-optimizers combine multiple optimization strategies into a unified compilation pipeline.\n\n### BetterTogether\n\n`BetterTogether` is a meta-optimizer that orchestrates multiple optimizers in sequence. It separates optimization into distinct phases:\n\n- **Prompt Optimization Phase (p)**: Optimizes instructions and demonstrations\n- **Weight Optimization Phase (w)**: Fine-tunes model weights\n\n**Execution Strategy:**\n\nThe optimizer uses a strategy string to define execution order:\n\n```mermaid\ngraph LR\n    A[Input Program] --> B[\"Strategy: 'p -> w'\"]\n    B --> C[Prompt Optimizer<br/>e.g., GEPA/MIPROv2]\n    C --> D[Weight Optimizer<br/>BootstrapFinetune]\n    D --> E[Compiled Program]\n```\n\n资料来源：[dspy/teleprompt/bettertogether.py:1-50]()\n\n```python\nfrom dspy.teleprompt import BetterTogether, GEPA, BootstrapFinetune\n\n# Combine GEPA for prompt optimization with BootstrapFinetune for weights\noptimizer = BetterTogether(\n    metric=metric,\n    p=GEPA(metric=metric, auto=\"medium\"),\n    w=BootstrapFinetune(metric=metric),\n)\n\nstudent.set_lm(lm)  # Required for weight optimization\ncompiled = optimizer.compile(\n    student,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\",  # Execute prompt optimization, then weight optimization\n)\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `metric` | `Callable` | Evaluation metric (required) |\n| `optimizers` | `dict[str, Teleprompter]` | Mapping of optimizer names to optimizer instances |\n| `strategy` | `str` | Execution strategy (e.g., \"p -> w\", \"p -> w -> p\") |\n\n**Optimizer-Specific Arguments:**\n\nYou can pass custom arguments to individual optimizers via `optimizer_compile_args`:\n\n```python\ncompiled = optimizer.compile(\n    student,\n    trainset=trainset,\n    valset=valset,\n    strategy=\"p -> w\",\n    optimizer_compile_args={\n        \"p\": {\"num_trials\": 10, \"max_bootstrapped_demos\": 8},\n    }\n)\n```\n\n## Ensemble\n\nThe Ensemble teleprompter combines predictions from multiple compiled programs using voting or other aggregation strategies.\n\n资料来源：[dspy/teleprompt/ensemble.py]()\n\n```python\nfrom dspy.teleprompt import Ensemble\n\n# Combine multiple compiled programs\nensemble = Ensemble(metric=metric)\ncombined = ensemble.compile(\n    [program1, program2, program3],\n    trainset=trainset,\n)\n```\n\n## Bootstrap Tracing\n\n`BootstrapFewShot` and related optimizers rely on `bootstrap_trace.py` to collect demonstrations by executing programs and recording successful traces.\n\n资料来源：[dspy/teleprompt/bootstrap_trace.py]()\n\n**Trace Collection Process:**\n\n1. Execute the student program on each training example\n2. Record input/output pairs for each predictor\n3. Accept traces that exceed the metric threshold\n4. Store demonstrations for inclusion in compiled prompts\n\n## Optimization Workflow\n\nThe typical workflow for using optimizers in DSPy:\n\n```mermaid\ngraph TD\n    A[Define Program<br/>dspy.Module] --> B[Prepare Training Set<br/>list of Examples]\n    B --> C[Define Metric<br/>evaluation function]\n    C --> D[Select Optimizer<br/>BootstrapFewShot/MIPROv2/etc.]\n    D --> E[Compile Program<br/>optimizer.compile]\n    E --> F[Evaluate on Test Set<br/>dspy.Evaluate]\n    \n    subgraph \"During Compilation\"\n        G[Generate Candidates<br/>instructions/demos/weights]\n        H[Evaluate Candidates<br/>using metric]\n        I[Select Best<br/>update program]\n        G --> H --> I\n    end\n    \n    F --> J{H满意?}\n    J -->|Yes| K[Deploy Program]\n    J -->|No| L[Adjust Parameters<br/>retry with different config]\n    L --> D\n```\n\n## Choosing an Optimizer\n\n| Use Case | Recommended Optimizer |\n|----------|----------------------|\n| Quick baseline with few examples | `BootstrapFewShot` |\n| Large training sets, efficient search | `MIPROv2` |\n| Evolutionary prompt improvement | `GEPA` |\n| Weight fine-tuning alongside prompts | `BetterTogether` with `BootstrapFinetune` |\n| Combining multiple compiled programs | `Ensemble` |\n| Batch evaluation with random sampling | `BootstrapFewShotWithRandomSearch` |\n\n## Best Practices\n\n1. **Start with BootstrapFewShot**: It's the simplest and often effective baseline for getting started.\n\n2. **Use validation sets**: When available, provide a `valset` parameter to allow the optimizer to select the best program among iterations.\n\n3. **Set LMs explicitly for weight optimization**: Call `student.set_lm(lm)` before compiling with optimizers like `BootstrapFinetune`.\n\n4. **Monitor metric threshold**: Adjust `metric_threshold` to control the quality of bootstrapped demonstrations.\n\n5. **Consider multi-phase optimization**: For best results, use `BetterTogether` to combine prompt and weight optimization.\n\n## Module Exports\n\nAll optimizers are exported from `dspy.teleprompt`:\n\n```python\nfrom dspy.teleprompt import (\n    # Base and utilities\n    Teleprompter,\n    BootstrapFewShot,\n    BootstrapFewShotWithRandomSearch,\n    \n    # Prompt optimizers\n    MIPROv2,\n    COPRO,\n    GEPA,\n    GRPO,\n    \n    # Weight optimizers\n    BootstrapFinetune,\n    \n    # Meta-optimizers\n    BetterTogether,\n    \n    # Ensemble\n    Ensemble,\n)\n```\n\n## See Also\n\n- [Signatures](signatures.md) - How to define input/output schemas for modules\n- [Modules](modules.md) - Building programs with Predict, ChainOfThought, and other modules\n- [Evaluation](evaluation.md) - Evaluating compiled programs\n- [Examples](examples.md) - Working with Example objects\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> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for stanfordnlp/dspy.\n\nProject:\n- Name: dspy\n- Repository: https://github.com/stanfordnlp/dspy\n- Summary: DSPy: The framework for programming—not prompting—language models\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: DSPy: The framework for programming—not prompting—language models\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: DSPy: The framework for programming—not prompting—language models\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to DSPy. Produce one small intermediate artifact and wait for confirmation.\n2. core-architecture: Core Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. signatures: Signatures System. Produce one small intermediate artifact and wait for confirmation.\n4. modules: Module System. Produce one small intermediate artifact and wait for confirmation.\n5. adapters: Adapters. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/stanfordnlp/dspy\n- https://github.com/stanfordnlp/dspy#readme\n- README.md\n- dspy/__init__.py\n- dspy/__metadata__.py\n- dspy/primitives/__init__.py\n- dspy/primitives/base_module.py\n- dspy/primitives/module.py\n- dspy/primitives/prediction.py\n- dspy/primitives/example.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\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"
}
