{
  "canonical_name": "microsoft/agent-framework",
  "compilation_id": "pack_88c9bac5007b4d2c9cb7725ddcd71caa",
  "created_at": "2026-05-15T12:58:07.629207+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, 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 agent-framework` 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 agent-framework",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_7c4f8e2533bc4785884a1d62cd26fc00"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_b607c9afe26f9d1b2c98bd578d5d3eb4",
    "canonical_name": "microsoft/agent-framework",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/microsoft/agent-framework",
    "slug": "agent-framework",
    "source_packet_id": "phit_0f2c356de845420c93118ec85b53fd7c",
    "source_validation_id": "dval_899444b38f6f433c876c520e7bed344e"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 local_cli的用户",
    "github_forks": 1697,
    "github_stars": 10385,
    "one_liner_en": "A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.",
    "one_liner_zh": "A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "high",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:deploy, git, cli"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "agent-framework",
    "title_zh": "agent-framework 能力包",
    "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": "Multi-agent Collaboration",
        "label_zh": "多 Agent 协作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-multi-agent-collaboration",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_0f2c356de845420c93118ec85b53fd7c",
  "page_model": {
    "artifacts": {
      "artifact_slug": "agent-framework",
      "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 agent-framework",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/microsoft/agent-framework#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "多 Agent 协作",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET."
        },
        {
          "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": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT events",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_d329260309954749a2b3b2a9e7135d56 | https://github.com/microsoft/agent-framework/issues/4923 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_8f9f05dcb7564f34bdd5902dcea6be27 | https://github.com/microsoft/agent-framework/issues/5785 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_49875a7dd60f480a99718cfa30b12723 | https://github.com/microsoft/agent-framework/issues/5708 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_58594f7966b84d81924da21ad789effd | https://github.com/microsoft/agent-framework/issues/5707 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_644a3ed07d2d4bfd8188392b4af687c2 | https://github.com/microsoft/agent-framework/issues/5794 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Anthropic function limit fallback can return empty final response",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_b61b91ca16094a448f8c0eab5e2daaa1 | https://github.com/microsoft/agent-framework/issues/5769 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Anthropic function limit fallback can return empty final response",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: Add tutorial for building a custom chat client / LLM provider",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_959e1eeb912a469c89f68f7f12275690 | https://github.com/microsoft/agent-framework/issues/5505 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Python: Add tutorial for building a custom chat client / LLM provider",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：python-1.2.1",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_f22ed66ae1f44b28b893aa5cbe439c92 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：python-1.2.1",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows with typed outputs",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_52da26ae3ace4acb9913ac780bfb6cd0 | https://github.com/microsoft/agent-framework/issues/5745 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows…",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_48aaa2f1026c4afd9e1a1da3a1a862a6 | https://github.com/microsoft/agent-framework/issues/5793 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：dotnet-1.5.0",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_2b3d3127c36f41798428b164b5444cbb | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：dotnet-1.5.0",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：python-1.2.2",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_fb88b6cd86e04e199a03cfcf8a97dde6 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：python-1.2.2",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:974445592 | https://github.com/microsoft/agent-framework | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：dotnet-1.4.0",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_e25f39a7081848689e086b1f98f92675 | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.4.0 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：dotnet-1.4.0",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | 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:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 23 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 130,
        "forks": 1697,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 10385
      },
      "source_url": "https://github.com/microsoft/agent-framework",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.",
      "title": "agent-framework 能力包",
      "trial_prompt": "# agent-framework - 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 microsoft/agent-framework.\n\nProject:\n- Name: agent-framework\n- Repository: https://github.com/microsoft/agent-framework\n- Summary: A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.\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: Use the source-backed project context to guide one small, checkable workflow step.\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. getting-started: Getting Started with Microsoft Agent Framework. Produce one small intermediate artifact and wait for confirmation.\n2. architecture-overview: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. agents: Agent System. Produce one small intermediate artifact and wait for confirmation.\n4. tools-and-skills: Tools and Skills. Produce one small intermediate artifact and wait for confirmation.\n5. workflows: Workflows and Orchestration. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/microsoft/agent-framework\n- https://github.com/microsoft/agent-framework#readme\n- dotnet/.github/skills/build-and-test/SKILL.md\n- dotnet/.github/skills/project-structure/SKILL.md\n- dotnet/.github/skills/verify-dotnet-samples/SKILL.md\n- dotnet/.github/skills/verify-samples-tool/SKILL.md\n- dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/skills/unit-converter/SKILL.md\n- dotnet/samples/02-agents/AgentSkills/Agent_Step04_MixedSkills/skills/unit-converter/SKILL.md\n- python/.github/skills/python-code-quality/SKILL.md\n- python/.github/skills/python-development/SKILL.md\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: .NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStre（https://github.com/microsoft/agent-framework/issues/4923）；github/github_issue: Python: OpenAI store=True can silently bypass external HistoryProvider p（https://github.com/microsoft/agent-framework/issues/5798）；github/github_issue: Bug: Agent responses lose structured JSON metadata in multi-agent orches（https://github.com/microsoft/agent-framework/issues/5785）；github/github_issue: .NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows Cus（https://github.com/microsoft/agent-framework/issues/5745）；github/github_issue: .NET: [Bug]: Regression - Tool Events not being emitted correctly to the（https://github.com/microsoft/agent-framework/issues/5794）；github/github_issue: Python: CosmosHistoryProvider Code interpreter tool calls are saved chun（https://github.com/microsoft/agent-framework/issues/5793）；github/github_issue: Anthropic function limit fallback can return empty final response（https://github.com/microsoft/agent-framework/issues/5769）；github/github_issue: .NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI（https://github.com/microsoft/agent-framework/issues/5707）；github/github_issue: Python: Add tutorial for building a custom chat client / LLM provider（https://github.com/microsoft/agent-framework/issues/5505）；github/github_issue: .NET: OpenAI-compatible extra body field thinking is not forwarded when （https://github.com/microsoft/agent-framework/issues/5708）；github/github_release: dotnet-1.5.0（https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0）；github/github_release: python-1.3.0（https://github.com/microsoft/agent-framework/releases/tag/python-1.3.0）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": ".NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStre",
              "url": "https://github.com/microsoft/agent-framework/issues/4923"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Python: OpenAI store=True can silently bypass external HistoryProvider p",
              "url": "https://github.com/microsoft/agent-framework/issues/5798"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Bug: Agent responses lose structured JSON metadata in multi-agent orches",
              "url": "https://github.com/microsoft/agent-framework/issues/5785"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": ".NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows Cus",
              "url": "https://github.com/microsoft/agent-framework/issues/5745"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": ".NET: [Bug]: Regression - Tool Events not being emitted correctly to the",
              "url": "https://github.com/microsoft/agent-framework/issues/5794"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Python: CosmosHistoryProvider Code interpreter tool calls are saved chun",
              "url": "https://github.com/microsoft/agent-framework/issues/5793"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Anthropic function limit fallback can return empty final response",
              "url": "https://github.com/microsoft/agent-framework/issues/5769"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": ".NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI",
              "url": "https://github.com/microsoft/agent-framework/issues/5707"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Python: Add tutorial for building a custom chat client / LLM provider",
              "url": "https://github.com/microsoft/agent-framework/issues/5505"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": ".NET: OpenAI-compatible extra body field thinking is not forwarded when ",
              "url": "https://github.com/microsoft/agent-framework/issues/5708"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "dotnet-1.5.0",
              "url": "https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "python-1.3.0",
              "url": "https://github.com/microsoft/agent-framework/releases/tag/python-1.3.0"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.",
      "effort": "安装已验证",
      "forks": 1697,
      "icon": "code",
      "name": "agent-framework 能力包",
      "risk": "可发布",
      "slug": "agent-framework",
      "stars": 10385,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "多 Agent 协作",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/microsoft/agent-framework 项目说明书\n\n生成时间：2026-05-15 12:31:29 UTC\n\n## 目录\n\n- [Getting Started with Microsoft Agent Framework](#getting-started)\n- [System Architecture](#architecture-overview)\n- [Agent System](#agents)\n- [Tools and Skills](#tools-and-skills)\n- [Workflows and Orchestration](#workflows)\n- [Middleware System](#middleware)\n- [AI Provider Integration](#provider-integration)\n- [Sessions, History, and State Management](#sessions-and-history)\n- [Hosting and Deployment Patterns](#hosting-patterns)\n- [Observability and Telemetry](#observability)\n\n<a id='getting-started'></a>\n\n## Getting Started with Microsoft Agent Framework\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Agent System](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/README.md](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n- [README.md](https://github.com/microsoft/agent-framework/blob/main/README.md)\n- [python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n- [python/samples/02-agents/skills/code_defined_skill/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n- [python/packages/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/declarative/README.md)\n- [python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n- [python/packages/github_copilot/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/github_copilot/README.md)\n- [python/packages/azure-contentunderstanding/samples/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/azure-contentunderstanding/samples/README.md)\n- [dotnet/src/Shared/Foundry/Agents/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Shared/Foundry/Agents/README.md)\n- [dotnet/src/Microsoft.Agents.AI.DurableTask/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n</details>\n\n# Getting Started with Microsoft Agent Framework\n\n## Overview\n\nMicrosoft Agent Framework is a comprehensive, multi-language framework for building intelligent agents that integrate with various AI services and providers. The framework enables developers to create agents capable of natural language understanding, tool usage, multi-turn conversations, and complex workflow orchestration.\n\nThe framework supports two primary ecosystems:\n\n| Language | Package Manager | Core Package |\n|----------|-----------------|--------------|\n| Python | pip | `agent-framework`, `agent-framework-core` |\n| .NET | NuGet | `Microsoft.Agents.AI` |\n\n资料来源：[python/README.md:1-40](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n## Supported Platforms\n\n| Component | Requirements |\n|-----------|--------------|\n| Python | 3.10+ |\n| Operating Systems | Windows, macOS, Linux |\n| .NET | .NET 8+ |\n\n资料来源：[python/README.md:36-39](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n## Installation\n\n### Python Installation\n\nThe framework offers two installation approaches depending on your use case:\n\n#### Development Mode (Full Installation)\n\nFor exploring or developing locally with all features:\n\n```bash\npip install agent-framework\n```\n\nThis installs the core package and all integration sub-packages, ensuring all features are available without additional configuration steps.\n\n资料来源：[python/README.md:10-15](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n#### Selective Installation\n\nFor lightweight environments with specific integration needs:\n\n| Package | Command | Description |\n|---------|---------|-------------|\n| Core Only | `pip install agent-framework-core` | Azure OpenAI, OpenAI support + workflows |\n| + Azure AI Foundry | `pip install agent-framework-foundry` | Azure AI Foundry integration |\n| + Copilot Studio | `pip install agent-framework-copilotstudio --pre` | Microsoft Copilot Studio (preview) |\n\nReleased packages (`agent-framework`, `agent-framework-core`, `agent-framework-foundry`) no longer require the `--pre` flag, while preview connectors like `agent-framework-copilotstudio` still do.\n\n资料来源：[python/README.md:17-34](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n### .NET Installation\n\nFor .NET projects, add the appropriate package reference to your `.csproj` file:\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\nFor Azure Functions hosting:\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.Hosting.AzureFunctions\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Microsoft.Agents.AI.csproj](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Microsoft.Agents.AI.csproj)\n\n## Quick Start\n\n### Python: Basic Agent\n\n```python\nimport asyncio\nfrom agent_framework import Agent, AzureCliCredential\nfrom agent_framework.integrations.azure_ai import FoundryChatClient\nimport os\n\nasync def main():\n    agent = Agent(\n        client=FoundryChatClient(\n            credential=AzureCliCredential(),\n        ),\n        name=\"HaikuAgent\",\n        instructions=\"You are an upbeat assistant that writes beautifully.\",\n    )\n\n    print(await agent.run(\"Write a haiku about Microsoft Agent Framework.\"))\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n资料来源：[README.md:30-50](https://github.com/microsoft/agent-framework/blob/main/README.md)\n\n### .NET: Basic Agent\n\n```csharp\nusing Azure.AI.Projects;\nusing Azure.Identity;\nusing Microsoft.Agents.AI;\n\nstring endpoint = Environment.GetEnvironmentVariable(\"AZURE_AI_PROJECT_ENDPOINT\") \n    ?? throw new InvalidOperationException(\"AZURE_AI_PROJECT_ENDPOINT is not set.\");\nstring deploymentName = Environment.GetEnvironmentVariable(\"AZURE_AI_MODEL_DEPLOYMENT_NAME\") \n    ?? \"gpt-5.4-mini\";\n\nAIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())\n    .AsAIAgent(model: deploymentName, instructions: \"You are an upbeat assistant.\", name: \"HaikuAgent\");\n\nConsole.WriteLine(await agent.RunAsync(\"Write a haiku about Microsoft Agent Framework.\"));\n```\n\n资料来源：[README.md:52-65](https://github.com/microsoft/agent-framework/blob/main/README.md)\n\n## Environment Configuration\n\nSet API keys and configuration as environment variables or in a `.env` file at your project root:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project endpoint | Yes |\n| `FOUNDRY_MODEL` | Model deployment name (defaults to `gpt-4o`) | No |\n| `AZURE_AI_PROJECT_ENDPOINT` | Alternative endpoint variable | Yes |\n| `AZURE_AI_MODEL_DEPLOYMENT_NAME` | Model deployment name | No |\n\n资料来源：[python/samples/01-get-started/README.md:9-13](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Core Concepts\n\n### Agent Architecture\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Agent]\n    B --> C[AI Client]\n    C --> D[Azure AI Foundry / OpenAI / Claude]\n    B --> E[Tools]\n    B --> F[Memory / Session]\n    E --> G[Function Calls]\n    F --> H[Context Preservation]\n    G --> I[Action Execution]\n    I --> B\n```\n\n### Key Components\n\n| Component | Python Package | .NET Namespace | Purpose |\n|-----------|---------------|----------------|---------|\n| Agent | `agent_framework` | `Microsoft.Agents.AI` | Core agent implementation |\n| Chat Client | `agent_framework.integrations.azure_ai` | `Azure.AI.Projects` | AI service connectivity |\n| Tools | `@tool` decorator | `AITool` attribute | Function definitions |\n| Sessions | `AgentSession` | `IAgentSession` | Multi-turn conversation state |\n| Context | `ContextProvider` | `IContextProvider` | Dynamic context injection |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:15-30](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n\n## Progressive Learning Samples (Python)\n\nThe framework provides a progressive set of samples in `python/samples/01-get-started/`:\n\n| Sample | File | Learning Objective |\n|--------|------|-------------------|\n| 1 | `01_hello_agent.py` | Create your first agent and run it (streaming and non-streaming) |\n| 2 | `02_add_tools.py` | Define a function tool with `@tool` and attach it to an agent |\n| 3 | `03_multi_turn.py` | Keep conversation history across turns with `AgentSession` |\n| 4 | `04_memory.py` | Add dynamic context with a custom `ContextProvider` |\n| 5 | `05_functional_workflow_with_agents.py` | Call agents inside a functional workflow |\n| 6 | `06_functional_workflow_basics.py` | Write a workflow as a plain async function |\n| 7 | `07_first_graph_workflow.py` | Chain executors into a graph workflow with edges |\n| 8 | `08_host_your_agent.py` | Host your agent in various environments |\n\n资料来源：[python/samples/01-get-started/README.md:17-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Authentication\n\nThe framework supports multiple authentication methods:\n\n| Provider | Python Credential | .NET Credential |\n|----------|-------------------|-----------------|\n| Azure AI Foundry | `AzureCliCredential()` | `DefaultAzureCredential()` |\n| Azure Content Understanding | `AzureCliCredential()` | `DefaultAzureCredential()` |\n| GitHub Copilot | API Key-based | API Key-based |\n\nFor Azure-based authentication, run `az login` in your terminal before executing samples:\n\n```bash\naz login\n```\n\n资料来源：[python/samples/02-agents/skills/code_defined_skill/README.md:15-17](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n\n## Integration Packages\n\n### Python Integrations\n\n| Package | Purpose | Install Command |\n|---------|---------|-----------------|\n| `agent-framework-core` | Core framework with Azure OpenAI and OpenAI | Default |\n| `agent-framework-foundry` | Azure AI Foundry integration | Default |\n| `agent-framework-claude` | Claude Agent SDK integration | `pip install agent-framework-claude --pre` |\n| `agent-framework-github-copilot` | GitHub Copilot integration | `pip install agent-framework-github-copilot --pre` |\n| `agent-framework-declarative` | YAML-based agent specification | `pip install agent-framework-declarative --pre` |\n| `agent-framework-copilotstudio` | Microsoft Copilot Studio | `pip install agent-framework-copilotstudio --pre` |\n\n#### Claude Agent\n\nThe Claude agent enables integration with Claude Agent SDK, allowing interaction with Claude's agentic capabilities through the Agent Framework.\n\n```bash\npip install agent-framework-claude --pre\n```\n\n资料来源：[python/packages/claude/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n#### GitHub Copilot Agent\n\nThe GitHub Copilot agent enables integration with GitHub Copilot for agentic capabilities:\n\n```bash\npip install agent-framework-github-copilot --pre\n```\n\n资料来源：[python/packages/github_copilot/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/github_copilot/README.md)\n\n#### Declarative Agents\n\nThe declarative package provides support for building agents based on YAML specifications:\n\n```bash\npip install agent-framework-declarative --pre\n```\n\n资料来源：[python/packages/declarative/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/declarative/README.md)\n\n### .NET Integrations\n\n| Package | Purpose |\n|---------|---------|\n| `Microsoft.Agents.AI` | Core AI library |\n| `Microsoft.Agents.AI.Hosting.OpenAI` | OpenAI hosting |\n| `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot agent |\n| `Microsoft.Agents.AI.AzureAI.Persistent` | Azure AI persistent agents (deprecated) |\n| `Microsoft.Agents.AI.DurableTask` | Durable Task integration for stateful workflows |\n| `Microsoft.Agents.AI.Hosting.AzureFunctions` | Azure Functions hosting |\n| `Aspire.Hosting.AgentFramework.DevUI` | Aspire-based DevUI hosting |\n\n#### Creating a GitHub Copilot Agent (.NET)\n\n```csharp\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs:15-25](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Agent Skills\n\nAgent Skills enable domain-specific capabilities with instructions, resources, and scripts. The framework follows the [Agent Skills specification](https://agentskills.io/specification).\n\n### Skill Types\n\n| Skill Type | Python | .NET |\n|------------|--------|------|\n| File-based | `AgentFileSkill` | `AgentFileSkill` |\n| Code-defined | `AgentInlineSkill` | `AgentInlineSkill` |\n| Declarative | YAML-based | N/A |\n\n### Skill Configuration Options (.NET)\n\n```csharp\npublic sealed class AgentSkillsProviderOptions\n{\n    /// <summary>\n    /// Custom system prompt template containing {skills}, {resource_instructions}, {script_instructions}\n    /// </summary>\n    public string? SkillsInstructionPrompt { get; set; }\n\n    /// <summary>\n    /// Require script execution approval (default: false)\n    /// </summary>\n    public bool ScriptApproval { get; set; }\n\n    /// <summary>\n    /// Disable caching of tools and instructions (default: false)\n    /// </summary>\n    public bool DisableCaching { get; set; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs:14-35](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs)\n\n### Skill Content Structure\n\nThe skill content is structured as XML, containing:\n\n```xml\n<name>{skill_name}</name>\n<description>{skill_description}</description>\n<instructions>\n{skill_instructions}\n</instructions>\n<resources>\n{resource_definitions}\n</resources>\n<scripts>\n{script_definitions}\n</scripts>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs:20-40](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs)\n\n## Azure Content Understanding Integration\n\nThe framework supports Azure Content Understanding for document, image, audio, and video analysis:\n\n| Sample | Description | Run Command |\n|--------|-------------|-------------|\n| Document Q&A | Upload PDF, extract info with CU | `uv run samples/01-get-started/01_document_qa.py` |\n| Multi-Turn Session | AgentSession persistence | `uv run samples/01-get-started/02_multi_turn_session.py` |\n| Multi-Modal Chat | PDF + audio + video analysis | `uv run samples/01-get-started/03_multimodal_chat.py` |\n| Invoice Processing | Structured field extraction | `uv run samples/01-get-started/04_invoice_processing.py` |\n\nRequired environment variables:\n\n```\nFOUNDRY_PROJECT_ENDPOINT=https://your-project.services.ai.azure.com\nFOUNDRY_MODEL=gpt-4.1\nAZURE_CONTENTUNDERSTANDING_ENDPOINT=https://your-cu-resource.cognitiveservices.azure.com/\n```\n\n资料来源：[python/packages/azure-contentunderstanding/samples/README.md:1-30](https://github.com/microsoft/agent-framework/blob/main/python/packages/azure-contentunderstanding/samples/README.md)\n\n## Durable Task Integration (.NET)\n\nFor stateful, long-running workflows, use the DurableTask integration:\n\n```bash\ndotnet add package Microsoft.Agents.AI.DurableTask\n```\n\nThis package enables building stateful agents that can handle complex orchestration scenarios with checkpointing and replay capabilities.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n\n## Development Tools\n\n### DevUI Sample Application\n\nDevUI is a sample application for getting started with the Agent Framework:\n\n```tsx\n// Features displayed in settings modal\ninterface ServerInfo {\n  version: string;\n  runtime: string;\n  uiMode: string;\n  capabilities?: {\n    instrumentation?: boolean;\n    // ... other capabilities\n  };\n}\n```\n\n资料来源：[python/packages/devui/frontend/src/components/layout/settings-modal.tsx:5-20](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/layout/settings-modal.tsx)\n\n### Sample Gallery\n\nThe DevUI includes a Sample Gallery for browsing and downloading curated examples:\n\n```mermaid\ngraph LR\n    A[Sample Gallery] --> B[Beginner Examples]\n    A --> C[Advanced Examples]\n    B --> D[Download & Run Locally]\n    C --> D\n```\n\n资料来源：[python/packages/devui/frontend/src/components/features/gallery/gallery-view.tsx:10-25](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/features/gallery/gallery-view.tsx)\n\n## Workflow Orchestration\n\nThe framework supports multiple workflow patterns:\n\n```mermaid\ngraph TD\n    A[Functional Workflow] --> B[Plain Async Functions]\n    A --> C[Agent Calls within Workflows]\n    D[Graph Workflow] --> E[Chained Executors]\n    D --> F[Edges between Nodes]\n    E --> G[Complex Routing]\n```\n\n### Functional Workflow Pattern\n\nWrite workflows as plain async functions:\n\n```python\nfrom agent_framework import workflow\n\n@workflow\nasync def my_workflow(agent, input_data):\n    result = await agent.process(input_data)\n    return result\n```\n\n### Graph Workflow Pattern\n\nChain executors into a graph workflow with edges:\n\n```python\nfrom agent_framework.graph import Graph, Node, Edge\n\ngraph = Graph()\ngraph.add_node(Node(\"start\", executor_a))\ngraph.add_node(Node(\"middle\", executor_b))\ngraph.add_node(Node(\"end\", executor_c))\n\ngraph.add_edge(Edge(\"start\", \"middle\"))\ngraph.add_edge(Edge(\"middle\", \"end\"))\n```\n\n资料来源：[python/samples/01-get-started/README.md:25-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Next Steps\n\n| Resource | Purpose |\n|----------|---------|\n| [Agent Skills Specification](https://agentskills.io/) | Skill definition standard |\n| [Documentation](https://github.com/microsoft/agent-framework) | Full framework docs |\n| [Azure Functions Samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/) | .NET hosting examples |\n| [File-Based Skills Sample](../file_based_skill/) | Skill implementation patterns |\n| [Mixed Skills Sample](../mixed_skills/) | Combining multiple skill types |\n\n资料来源：[python/samples/02-agents/skills/code_defined_skill/README.md:25-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n\n---\n\n<a id='architecture-overview'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Getting Started with Microsoft Agent Framework](#getting-started), [Agent System](#agents), [Workflows and Orchestration](#workflows)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docs/design/python-package-setup.md](https://github.com/microsoft/agent-framework/blob/main/docs/design/python-package-setup.md)\n- [python/packages/core/agent_framework/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n- [docs/decisions/0008-python-subpackages.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0008-python-subpackages.md)\n- [docs/decisions/0001-agent-run-response.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0001-agent-run-response.md)\n- [dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n- [python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n- [dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n</details>\n\n# System Architecture\n\n## Overview\n\nThe Microsoft Agent Framework is a cross-platform, multi-language framework designed for building AI-powered agents with tool-calling capabilities, workflow orchestration, and extensible integrations. The architecture follows a unified conceptual model implemented in both Python (3.10+) and .NET, enabling developers to create agents that interact with various AI backends while maintaining consistent APIs and patterns across platforms.\n\nThe framework's primary purpose is to abstract the complexity of AI agent development, providing a declarative approach to defining agent behavior, tools, memory, and workflows. It supports integration with Azure AI Foundry, OpenAI, GitHub Copilot, Anthropic Claude, and Microsoft Copilot Studio.\n\n资料来源：[docs/design/python-package-setup.md](https://github.com/microsoft/agent-framework/blob/main/docs/design/python-package-setup.md)\n\n## High-Level Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Client Applications\"\n        A[Python Apps]\n        B[.NET Apps]\n    end\n    \n    subgraph \"Agent Framework Core\"\n        C[Agent Abstractions]\n        D[Workflow Engine]\n        E[Skill System]\n        F[Memory/Context Providers]\n    end\n    \n    subgraph \"AI Backend Integrations\"\n        G[Azure AI Foundry]\n        H[OpenAI / Azure OpenAI]\n        I[GitHub Copilot]\n        J[Anthropic Claude]\n        K[Copilot Studio]\n    end\n    \n    A --> C\n    B --> C\n    C --> D\n    C --> E\n    C --> F\n    C --> G\n    C --> H\n    C --> I\n    C --> J\n    C --> K\n```\n\n## Core Architecture Components\n\n### Agent Abstraction Layer\n\nThe central abstraction in the framework is the `AIAgent` interface, which defines the contract for all agent implementations. This abstraction enables loose coupling between client code and specific AI backend implementations.\n\n#### Python Implementation\n\nIn Python, the `Agent` class serves as the primary agent implementation, accepting a chat client and configuration options:\n\n```python\nagent = Agent(\n    client=FoundryChatClient(\n        credential=AzureCliCredential(),\n    ),\n    name=\"MyAgent\",\n    instructions=\"You are a helpful assistant.\",\n    tools=[my_tool]\n)\n```\n\n资料来源：[python/packages/core/agent_framework/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/__init__.py)\n\n#### .NET Implementation\n\nIn .NET, the `ChatClientAgent` class provides the core agent functionality with dependency injection support:\n\n```csharp\npublic sealed class ChatClientAgent : AIAgent\n{\n    public ChatClientAgent(\n        IChatClient chatClient,\n        string? instructions = null,\n        string? name = null,\n        string? description = null,\n        IList<AITool>? tools = null,\n        ILoggerFactory? loggerFactory = null,\n        IServiceProvider? services = null);\n}\n```\n\nThe agent accepts tools that can be invoked during conversations, and all provided tools are invoked without user approval by default. Developers should require explicit approval for tools that have side effects or access sensitive data.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### Chat Client Architecture\n\nThe framework uses a chat client abstraction pattern to separate agent logic from the underlying AI service implementation.\n\n| Chat Client | Language | Description |\n|-------------|----------|-------------|\n| `FoundryChatClient` | Python/.NET | Azure AI Foundry integration |\n| `OpenAIChatClient` | Python | OpenAI and Azure OpenAI support |\n| `CopilotClient` | .NET | GitHub Copilot integration |\n| `ClaudeClient` | Python | Anthropic Claude integration |\n\n#### Client Configuration Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `credential` | `AzureCliCredential` / `DefaultAzureCredential` | Yes (Foundry) | Authentication credential |\n| `project_endpoint` | string | Yes (Foundry) | Azure AI Foundry project endpoint |\n| `model` | string | No | Model deployment name (defaults vary) |\n| `temperature` | float | No | Sampling temperature (0.0-2.0) |\n| `top_p` | float | No | Nucleus sampling parameter |\n| `response_format` | object | No | Structured output format |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n## Package Architecture\n\n### Python Package Structure\n\nThe Python implementation uses a modular package structure allowing selective installation based on required integrations:\n\n```mermaid\ngraph TD\n    A[agent-framework] --> B[agent-framework-core]\n    A --> C[agent-framework-foundry]\n    A --> D[agent-framework-copilotstudio]\n    \n    B --> E[OpenAI Support]\n    B --> F[Workflow Engine]\n    B --> G[Skill System]\n    \n    C --> B\n    D --> B\n```\n\n#### Package Descriptions\n\n| Package | Description | Install Command |\n|---------|-------------|-----------------|\n| `agent-framework` | Full framework with all sub-packages | `pip install agent-framework` |\n| `agent-framework-core` | Core agent, workflow, and OpenAI support | `pip install agent-framework-core` |\n| `agent-framework-foundry` | Azure AI Foundry integration | `pip install agent-framework-foundry` |\n| `agent-framework-copilotstudio` | Microsoft Copilot Studio (preview) | `pip install agent-framework-copilotstudio --pre` |\n| `agent-framework-claude` | Anthropic Claude integration (preview) | `pip install agent-framework-claude --pre` |\n| `agent-framework-github-copilot` | GitHub Copilot integration (preview) | `pip install agent-framework-github-copilot --pre` |\n\nThe core package includes Azure OpenAI and OpenAI support by default, along with workflows and orchestrations.\n\n资料来源：[docs/decisions/0008-python-subpackages.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0008-python-subpackages.md)\n\n### .NET Package Structure\n\nThe .NET implementation uses a shared library pattern with dependency injection:\n\n```xml\n<PropertyGroup>\n  <InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>\n</PropertyGroup>\n```\n\nCore namespaces include:\n\n| Namespace | Purpose |\n|-----------|---------|\n| `Microsoft.Agents.AI` | Core agent abstractions and implementations |\n| `Microsoft.Agents.AI.Abstractions` | Interface definitions |\n| `Microsoft.Agents.AI.AzureAI` | Azure AI Foundry integration |\n| `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot integration |\n| `Microsoft.Agents.AI.Skills` | Skill-based agent configuration |\n\n资料来源：[dotnet/src/Shared/Foundry/Agents/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Shared/Foundry/Agents/README.md)\n\n## Agent Execution Model\n\n### Agent Run Response Pattern\n\nThe framework standardizes agent responses through a consistent return type that wraps the final output along with any intermediate steps taken during execution.\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Agent\n    participant Tool\n    participant AI_Backend\n    \n    Client->>Agent: run(input)\n    Agent->>AI_Backend: send(messages)\n    AI_Backend-->>Agent: response\n    alt tool_call detected\n        Agent->>Tool: invoke(arguments)\n        Tool-->>Agent: result\n        Agent->>AI_Backend: send(result)\n        AI_Backend-->>Agent: response\n    end\n    Agent-->>Client: RunResponse(output, steps)\n```\n\n### Multi-Turn Conversation Support\n\nAgents maintain conversation history through `AgentSession`, enabling stateful multi-turn interactions:\n\n```python\nsession = AgentSession()\nasync for response in agent.run(\"Hello\", session=session):\n    print(response)\n```\n\n资料来源：[docs/decisions/0001-agent-run-response.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0001-agent-run-response.md)\n\n## Skill System Architecture\n\n### Skill Definition\n\nSkills provide a declarative way to define agent capabilities with instructions and associated tools:\n\n```csharp\npublic class AgentInlineSkill\n{\n    public AgentInlineSkill(\n        string name,\n        string description,\n        string instructions,\n        string? license = null,\n        string? compatibility = null,\n        string? allowedTools = null,\n        AdditionalPropertiesDictionary? metadata = null,\n        JsonSerializerOptions? serializerOptions = null);\n}\n```\n\n### Skill Frontmatter Schema\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `name` | string | Yes | Skill name in kebab-case |\n| `description` | string | Yes | Skill description for discovery |\n| `instructions` | string | Yes | Skill instructions text |\n| `license` | string | No | License name or reference |\n| `compatibility` | string | No | Compatibility information (max 500 chars) |\n| `allowedTools` | string | No | Space-delimited pre-approved tools |\n| `metadata` | dictionary | No | Arbitrary key-value metadata |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkill.cs)\n\n## Workflow Orchestration\n\n### Workflow Types\n\nThe framework supports multiple workflow paradigms:\n\n| Workflow Type | Description | Use Case |\n|---------------|-------------|----------|\n| Functional Workflow | Async functions calling agents | Simple sequential operations |\n| Graph Workflow | DAG-based executor chains | Complex conditional flows |\n| Durable Workflow | Long-running with state persistence | Human-in-the-loop approval |\n\n### Graph Workflow Structure\n\n```mermaid\ngraph LR\n    A[Input] --> B[Agent 1]\n    B --> C{Decision}\n    C -->|Path A| D[Agent 2]\n    C -->|Path B| E[Agent 3]\n    D --> F[Output]\n    E --> F\n```\n\nThe graph workflow uses edges to connect executors, allowing conditional routing based on agent outputs.\n\n资料来源：[python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Memory and Context Architecture\n\n### Context Providers\n\nDynamic context injection is supported through custom `ContextProvider` implementations:\n\n```python\nclass MyContextProvider(ContextProvider):\n    async def get_context(self, context_params) -> str:\n        # Retrieve and format context\n        return formatted_context\n```\n\n### Memory Scoping\n\n| Scope Parameter | Description |\n|-----------------|-------------|\n| `application_id` | Global scope across entire application |\n| `agent_id` | Agent-specific memory isolation |\n| `user_id` | User-specific memory partitioning |\n\n### Hybrid Vector Search\n\nContext providers can optionally enable vector search for semantic retrieval:\n\n| Setting | Options | Description |\n|---------|---------|-------------|\n| `vectorizer_choice` | `\"openai\"`, `\"hf\"` | Embedding model selection |\n| `vector_field_name` | string | Redis field for vectors |\n| `overwrite_redis_index` | boolean | Index recreation control |\n\n资料来源：[python/samples/02-agents/context_providers/redis/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/context_providers/redis/README.md)\n\n## Hosting and Deployment\n\n### Local Hosting with DevUI\n\nDevUI provides a local development server with OpenAI-compatible endpoints:\n\n```bash\ndevui /path/to/agents/folder\n```\n\nAPI endpoints exposed:\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/v1/responses` | POST | Agent invocation |\n| `/v1/entities` | GET | List available entities |\n\n### Agent Entity Structure\n\nAgents must export an `agent` or `workflow` in their `__init__.py`:\n\n```python\n# my_agent/__init__.py\nfrom agent_framework import Agent\n\nagent = Agent(\n    name=\"MyAgent\",\n    client=OpenAIChatClient(),\n)\n```\n\n### Foundry Deployment\n\nProduction deployment to Azure AI Foundry uses the same agent configuration with environment-based credential resolution.\n\n资料来源：[python/samples/02-agents/devui/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/devui/README.md)\n\n## Agent Mode System\n\nThe framework supports configurable agent operating modes for interactive planning and autonomous execution:\n\n```csharp\npublic sealed class AgentMode\n{\n    public string Name { get; }\n    public string Description { get; }\n}\n\npublic class AgentModeProviderOptions\n{\n    public IReadOnlyList<AgentMode>? Modes { get; set; }\n    public string? DefaultMode { get; set; }\n}\n```\n\n| Mode | Purpose |\n|------|---------|\n| `\"plan\"` | Interactive planning with human oversight |\n| `\"execute\"` | Autonomous execution without intervention |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs)\n\n## Integration Patterns\n\n### GitHub Copilot Integration\n\nAgents can wrap GitHub Copilot clients for unified interaction:\n\n```csharp\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null);\n```\n\nThis extension method creates an `AIAgent` backed by the Copilot client with optional additional tools and instructions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Data Flow Summary\n\n```mermaid\ngraph TD\n    subgraph \"Input Processing\"\n        A[User Input] --> B[Session Manager]\n        B --> C[Context Provider]\n    end\n    \n    subgraph \"Agent Processing\"\n        C --> D[Agent Executor]\n        D --> E[AI Chat Client]\n        E --> F{Tool Call?}\n    end\n    \n    subgraph \"Tool Execution\"\n        F -->|Yes| G[Tool Executor]\n        G --> H[Result Formatter]\n        H --> E\n    end\n    \n    F -->|No| I[Response Formatter]\n    \n    subgraph \"Output\"\n        I --> J[RunResponse]\n        J --> K[Client Application]\n    end\n```\n\n## Environment Configuration\n\n### Required Environment Variables\n\n| Variable | Description | Required For |\n|---------|-------------|--------------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project URL | Foundry agents |\n| `FOUNDRY_MODEL` | Model deployment name | Foundry agents |\n| `OPENAI_API_KEY` | OpenAI API key | OpenAI clients, embeddings |\n| `AZURE_AI_PROJECT_ENDPOINT` | .NET Foundry endpoint | .NET Foundry |\n| `AZURE_AI_MODEL_DEPLOYMENT_NAME` | .NET model deployment | .NET Foundry |\n\n### Authentication Methods\n\n| Method | Use Case | Command |\n|--------|----------|---------|\n| `AzureCliCredential` | Interactive login | `az login` |\n| `DefaultAzureCredential` | Automated environments | Managed identity |\n| API Key | Direct authentication | Environment variable |\n\n资料来源：[python/README.md](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n---\n\n<a id='agents'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Tools and Skills](#tools-and-skills), [Workflows and Orchestration](#workflows), [AI Provider Integration](#provider-integration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_agents.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_agents.py)\n- [python/packages/core/agent_framework/_types.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_types.py)\n- [dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs)\n- [python/samples/01-get-started/01_hello_agent.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/01_hello_agent.py)\n- [dotnet/samples/01-get-started/01_hello_agent/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/01_hello_agent/Program.cs)\n</details>\n\n# Agent System\n\nThe Agent System is the core abstraction layer in Microsoft Agent Framework that enables the creation, configuration, and execution of AI agents. Agents are autonomous or semi-autonomous software entities that can interact with users, execute tools, maintain conversation state, and perform complex multi-step tasks using Large Language Models (LLMs) as their reasoning engine.\n\n## Architecture Overview\n\nThe Agent System follows a layered architecture that separates concerns between the agent abstraction, runtime context, tool invocation, and the underlying chat client implementations.\n\n```mermaid\ngraph TD\n    subgraph \"Agent Abstraction Layer\"\n        AIAgent[AIAgent Interface]\n        ChatClientAgent[ChatClientAgent]\n        AgentRunContext[AgentRunContext]\n    end\n    \n    subgraph \"Tool Layer\"\n        AITool[AITool]\n        ToolDefinition[ToolDefinition]\n        ToolResources[ToolResources]\n    end\n    \n    subgraph \"Client Layer\"\n        IChatClient[IChatClient]\n        CopilotClient[CopilotClient]\n        ClaudeClient[ClaudeClient]\n    end\n    \n    subgraph \"Context Layer\"\n        AIContext[AIContext]\n        AgentSession[AgentSession]\n        ContextProvider[ContextProvider]\n    end\n    \n    AIAgent --> AgentRunContext\n    AIAgent --> AITool\n    AIAgent --> IChatClient\n    ChatClientAgent --> IChatClient\n    AgentRunContext --> AIContext\n    AgentSession --> AIContext\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n## Core Components\n\n### AIAgent Interface\n\nThe `AIAgent` interface serves as the foundational abstraction for all agent implementations in the .NET SDK. It defines the contract that all concrete agent types must implement.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `Id` | `string` | Unique identifier for the agent instance |\n| `Name` | `string` | Human-readable name for the agent |\n| `Description` | `string` | Description of the agent's purpose and capabilities |\n| `Instructions` | `string` | System instructions that guide agent behavior |\n| `Tools` | `IList<AITool>` | Collection of tools available to the agent |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n### ChatClientAgent\n\n`ChatClientAgent` is the primary concrete implementation of `AIAgent` that uses an `IChatClient` for LLM interactions. It provides comprehensive support for agent configuration, tool execution, and streaming responses.\n\n#### Constructor Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `chatClient` | `IChatClient` | Yes | The chat client used for LLM communication |\n| `instructions` | `string?` | No | System instructions for agent behavior |\n| `name` | `string?` | No | Agent identifier for logging |\n| `description` | `string?` | No | Human-readable agent description |\n| `tools` | `IEnumerable<AITool>?` | No | Tools the agent can invoke |\n| `loggerFactory` | `ILoggerFactory?` | No | Factory for creating loggers |\n| `services` | `IServiceProvider?` | No | Service provider for dependency resolution |\n| `cancellationToken` | `CancellationToken` | No | Cancellation token for async operations |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### AgentRunContext\n\nThe `AgentRunContext` provides runtime context for agent execution, including conversation history, tool configurations, and execution options.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `SessionId` | `string` | Unique identifier for the current session |\n| `ConversationHistory` | `IList<ChatMessage>` | Messages exchanged in the conversation |\n| `Options` | `ChatOptions` | Configuration for the current run |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs)\n\n## Agent Configuration\n\n### Creating a Basic Agent\n\nAgents can be configured with various levels of complexity depending on the use case.\n\n```python\n# Python: Basic agent creation\n# python/samples/01-get-started/01_hello_agent.py\n\nfrom agent_framework import Agent\n\n# Simple agent with instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"You are a helpful assistant.\"\n)\n```\n\n```csharp\n// C#: Basic agent creation\n// dotnet/samples/01-get-started/01_hello_agent/Program.cs\n\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Hosting.OpenAI;\n\n// Create agent with instructions\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    instructions: \"You are a helpful assistant that answers questions accurately.\"\n);\n```\n\n资料来源：[python/samples/01-get-started/01_hello_agent.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/01_hello_agent.py)\n资料来源：[dotnet/samples/01-get-started/01_hello_agent/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/01_hello_agent/Program.cs)\n\n### Agent with Tools\n\nTools extend agent capabilities by allowing them to perform actions beyond text generation.\n\n```python\n# Python: Agent with function tool\n# python/samples/01-get-started/02_add_tools.py\n\nfrom agent_framework import Agent, tool\n\n@tool\ndef get_weather(location: str) -> str:\n    \"\"\"Get the weather for a specific location.\"\"\"\n    # Tool implementation\n    return f\"The weather in {location} is sunny.\"\n\nagent = Agent(model=\"gpt-4o\")\nagent.tools.add(get_weather)\n```\n\n```csharp\n// C#: Agent with tools\n// dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs\n\n// Tools augment any tools provided via ChatOptions.Tools when the agent is run\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    instructions: \"You are a helpful assistant.\",\n    tools: new List<AITool> { customTool }\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### Tool Security Considerations\n\nBy default, all provided tools are invoked without user approval. The AI selects which functions to call and chooses the arguments — these arguments should be treated as untrusted input.\n\n> **Security Warning**: Developers should require explicit approval for tools that have side effects, access sensitive data, or perform irreversible operations.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n## Running Agents\n\n### Synchronous Execution\n\n```python\n# Python: Non-streaming execution\n# python/samples/01-get-started/01_hello_agent.py\n\nresult = agent.run(\"What is the capital of France?\")\nprint(result)\n```\n\n### Streaming Execution\n\n```python\n# Python: Streaming execution\n# python/samples/01-get-started/01_hello_agent.py\n\nasync for chunk in agent.run_streaming(\"Tell me a story\"):\n    print(chunk, end=\"\", flush=True)\n```\n\n### Multi-Turn Conversations\n\n```python\n# Python: Multi-turn with AgentSession\n# python/samples/01-get-started/03_multi_turn.py\n\nsession = AgentSession()\n\n# First turn\nresponse1 = await session.run(agent, \"Hi, my name is Alice\")\nprint(response1)\n\n# Second turn - maintains context\nresponse2 = await session.run(agent, \"What is my name?\")\nprint(response2)  # \"Your name is Alice\"\n```\n\n资料来源：[python/samples/01-get-started/03_multi_turn.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/03_multi_turn.py)\n\n## Agent Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Agent as AIAgent/ChatClientAgent\n    participant Context as AgentRunContext\n    participant Tools as Tool System\n    participant LLM as IChatClient\n    \n    User->>Agent: Run(userMessage, options)\n    Agent->>Context: Create execution context\n    Context->>LLM: Send chat request\n    \n    alt Tool Invocation Required\n        LLM-->>Context: FunctionCall(tool_name, args)\n        Context->>Tools: InvokeTool(tool_name, args)\n        Tools-->>Context: ToolResult\n        Context->>LLM: Continue with result\n    end\n    \n    LLM-->>Agent: Final response\n    Agent-->>User: Return result\n```\n\n## Context Management\n\n### ContextProvider\n\nCustom context providers allow agents to access dynamic context during execution.\n\n```python\n# Python: Custom context provider\n# python/samples/01-get-started/04_memory.py\n\nfrom agent_framework import ContextProvider\n\nclass MemoryProvider(ContextProvider):\n    def __init__(self):\n        self.memories = []\n    \n    async def get_context(self) -> str:\n        if self.memories:\n            return \"User preferences: \" + \", \".join(self.memories)\n        return \"\"\n    \n    async def update_context(self, interaction: dict):\n        if \"preference\" in interaction:\n            self.memories.append(interaction[\"preference\"])\n\nagent = Agent(model=\"gpt-4o\")\nagent.context_providers.add(MemoryProvider())\n```\n\n资料来源：[python/samples/01-get-started/04_memory.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/04_memory.py)\n\n### AgentSession\n\n`AgentSession` maintains conversation state across multiple turns, enabling persistent interactions.\n\n| Method | Description |\n|--------|-------------|\n| `run(agent, message)` | Execute a single turn with the agent |\n| `clear()` | Clear conversation history |\n| `get_history()` | Retrieve conversation history |\n\n资料来源：[python/samples/01-get-started/03_multi_turn.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/03_multi_turn.py)\n\n## Dependency Injection\n\nThe .NET implementation supports dependency injection for resolving services required by AI functions.\n\n```csharp\n// C#: Service provider integration\n// dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs\n\n// The services parameter is particularly important when using custom tools \n// that require dependency injection\nvar services = new ServiceCollection();\nservices.AddSingleton<IMyService, MyServiceImplementation>();\n\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    services: services.BuildServiceProvider()\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n## Agent Integrations\n\n### Copilot Integration\n\n```csharp\n// C#: GitHub Copilot integration\n// dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs\n\nvar agent = copilotClient.AsAIAgent(\n    name: \"CopilotAgent\",\n    description: \"GitHub Copilot powered agent\",\n    tools: new List<AITool> { customTool }\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n### Claude Integration\n\nThe Claude agent enables integration with Claude Agent SDK for accessing Claude's agentic capabilities.\n\n资料来源：[python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n### Azure AI Foundry Integration\n\n```csharp\n// C#: Azure AI Foundry Persistent Agents\n// dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs\n\n[Obsolete(\"Please use the latest Foundry Agents service via the Microsoft.Agents.AI.AzureAI package.\")]\npublic static async Task<ChatClientAgent> CreateAIAgentAsync(\n    this PersistentAgentsClient persistentAgentsClient,\n    string model,\n    string? name = null,\n    string? description = null,\n    string? instructions = null,\n    IEnumerable<ToolDefinition>? tools = null,\n    ToolResources toolResources = null,\n    double? temperature = null,\n    double? topP = null,\n    ResponseFormat? responseFormat = null,\n    IDictionary<string, string>? metadata = null,\n    IChatClientFactory? clientFactory = null,\n    IServiceProvider services = null,\n    CancellationToken cancellationToken = default)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs)\n\n## Best Practices\n\n### 1. Clear Instructions\n\nProvide specific, detailed instructions that define the agent's role, behavior, and constraints.\n\n```python\n# Good: Specific instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"\"\"\n    You are a technical documentation assistant.\n    - Always use code blocks for code examples\n    - Include practical examples\n    - Explain technical terms on first use\n    \"\"\"\n)\n\n# Avoid: Vague instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"Be helpful.\"\n)\n```\n\n### 2. Tool Security\n\nImplement approval mechanisms for sensitive tools:\n\n```csharp\n// Review tools before allowing execution\npublic class SecureToolExecutor\n{\n    public async Task<ToolResult> ExecuteAsync(AITool tool, object args)\n    {\n        // Require approval for destructive or sensitive operations\n        if (tool.HasSideEffects)\n        {\n            var approved = await RequestApprovalAsync(tool, args);\n            if (!approved) throw new OperationCanceledException();\n        }\n        return await tool.InvokeAsync(args);\n    }\n}\n```\n\n### 3. Proper Resource Cleanup\n\nAlways dispose of agents and clients properly:\n\n```python\n# Python: Async context manager usage\nasync with Agent(model=\"gpt-4o\") as agent:\n    result = await agent.run(\"Hello\")\n# Agent is automatically cleaned up\n\n# Or explicit cleanup\nagent = Agent(model=\"gpt-4o\")\ntry:\n    result = await agent.run(\"Hello\")\nfinally:\n    await agent.close()\n```\n\n## See Also\n\n- [Get Started with Python](../python/samples/01-get-started/README.md)\n- [Get Started with .NET](../dotnet/samples/01-get-started/README.md)\n- [Agent Skills System](./agent-skills.md)\n- [Functional Workflows](./workflows.md)\n- [Graph Workflows](./graph-workflows.md)\n\n---\n\n<a id='tools-and-skills'></a>\n\n## Tools and Skills\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Middleware System](#middleware)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_tools.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_tools.py)\n- [python/packages/core/agent_framework/_skills.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_skills.py)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n- [dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs)\n- [docs/decisions/0021-agent-skills-design.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0021-agent-skills-design.md)\n- [python/samples/02-agents/skills/class_based_skill/class_based_skill.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/class_based_skill/class_based_skill.py)\n- [dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs)\n</details>\n\n# Tools and Skills\n\n## Overview\n\nTools and Skills are core abstractions in the Microsoft Agent Framework that extend an agent's capabilities beyond its base instruction set. Tools enable functional operations (like calling APIs or executing code), while Skills provide domain-specific knowledge, structured instructions, resources, and scripts that guide agent behavior in specialized areas.\n\n**Tools** are function-based capabilities that agents can invoke to perform specific tasks such as calculations, data retrieval, or external API calls. 资料来源：[python/packages/core/agent_framework/_tools.py:1-50]()\n\n**Skills** are containers of domain-specific knowledge that include instructions, reference documents (resources), and executable scripts. They enable agents to handle specialized tasks by providing contextual guidance and tooling. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:1-30]()\n\n```mermaid\ngraph TD\n    subgraph AgentFramework\n        A[Agent] --> T[Tools]\n        A --> S[Skills]\n        T --> TF[Function Tools]\n        T --> TT[Tool Definitions]\n        S --> SF[File-Based Skills]\n        S --> SC[Code-Defined Skills]\n        S --> SB[Class-Based Skills]\n        SF --> Instructions\n        SF --> Resources\n        SF --> Scripts\n        SC --> Instructions\n        SC --> Resources\n        SC --> Scripts\n    end\n```\n\n## Core Concepts\n\n### Tools\n\nTools in the Agent Framework are the primary mechanism for enabling agents to perform actions. A tool is essentially a callable function that the agent can invoke during its execution. 资料来源：[python/packages/core/agent_framework/_tools.py:1-80]()\n\n| Tool Type | Description | Use Case |\n|-----------|-------------|----------|\n| Function Tool | Decorated Python function | Custom operations in Python agents |\n| Tool Definition | Declarative tool specification | Cross-platform tool definition |\n| Managed Tool | Pre-built tool from providers | Anthropic skills, Azure AI services |\n\n### Skills\n\nSkills provide specialized knowledge and capabilities to agents. Each skill contains:\n\n- **Instructions**: Domain-specific guidance for the agent\n- **Resources**: Reference documents and data files\n- **Scripts**: Executable code for automated operations 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:20-45]()\n\n```mermaid\ngraph LR\n    subgraph SkillStructure\n        I[Instructions] --> C[Content]\n        R[Resources] --> C\n        S[Scripts] --> C\n        F[Frontmatter] --> C\n    end\n    \n    C --> A[Agent Skill]\n    A --> P[Agent Skills Provider]\n```\n\n## Skill Types\n\n### File-Based Skills\n\nFile-based skills are defined through a `SKILL.md` file containing YAML frontmatter and Markdown body. The frontmatter declares skill metadata, while the body contains instructions and references to resources and scripts. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs:1-50]()\n\n**SKILL.md Structure:**\n\n```markdown\n---\nname: my-skill\ndescription: A skill for handling specific tasks\ncompatibility: agent-framework >= 1.0.0\n---\n\n# Instructions\n\nYou are an expert in...\n\n## Resources\n- [Reference Doc](./references/guide.md)\n\n## Scripts\n- script: ./scripts/helper.py\n```\n\nThe `AgentFileSkill` class loads and parses these files, extracting content for use by the agent. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs:50-120]()\n\n### Code-Defined Skills\n\nCode-defined skills are created programmatically using the SDK. This approach provides full control over skill content and behavior through code.\n\n**Python Implementation:**\n\n```python\nfrom agent_framework import skill\n\n@skill(\n    name=\"code-skill\",\n    description=\"A programmatically defined skill\"\n)\ndef my_skill():\n    \"\"\"Instructions for the agent.\"\"\"\n    return {\n        \"instructions\": \"You are an expert in...\",\n        \"resources\": [\"./data/knowledge.json\"],\n        \"scripts\": [\"./scripts/process.py\"]\n    }\n```\n\n**C# Implementation:**\n\n```csharp\nAgentInlineSkill skill = new AgentInlineSkill(\n    name: \"code-skill\",\n    description: \"A programmatically defined skill\",\n    instructions: \"You are an expert in handling...\"\n);\n```\n\n资料来源：[python/packages/core/agent_framework/_skills.py:1-100]()\n\n### Class-Based Skills (Python)\n\nClass-based skills provide an object-oriented approach to defining skills with typed properties and methods.\n\n```python\nfrom agent_framework import AgentSkill\n\nclass MySkill(AgentSkill):\n    name = \"class-skill\"\n    description = \"A class-based skill example\"\n    \n    @property\n    def instructions(self) -> str:\n        return \"You are a specialized assistant...\"\n    \n    @property\n    def resources(self) -> list[AgentSkillResource]:\n        return [AgentSkillResource(\"data.json\", \"json://...\")]\n```\n\n资料来源：[python/samples/02-agents/skills/class_based_skill/class_based_skill.py:1-60]()\n\n## Architecture\n\n### Agent Skills Provider\n\nThe `AgentSkillsProvider` is the central component that manages skill discovery, loading, and integration with the agent's context. It builds tools from skills and injects skill instructions into the agent's system prompt. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProvider.cs:1-80]()\n\n**Key Responsibilities:**\n- Discover skills from configured sources\n- Build `load_skill` and `run_skill_script` tools for skill management\n- Generate skill instructions for the agent's context\n- Handle resource and script instructions\n\n```mermaid\ngraph TD\n    S[Skills Source] --> SP[AgentSkillsProvider]\n    SP --> ST[Skill Tools]\n    SP --> SI[Skill Instructions]\n    ST --> A[Agent]\n    SI --> A\n    \n    SP --> Config[AgentSkillsProviderOptions]\n    Config --> Cache[Caching]\n    Config --> Approval[Script Approval]\n    Config --> Template[Custom Prompt Template]\n```\n\n### Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `SkillsInstructionPrompt` | string | Custom template for skill advertising |\n| `ScriptApproval` | bool | Require approval before script execution |\n| `DisableCaching` | bool | Disable tool/instruction caching |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs:1-50]()\n\n## Skill Content Generation\n\nFor code-defined and class-based skills, the framework synthesizes an XML document containing all skill components. This ensures consistent handling regardless of the skill's origin. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs:1-60]()\n\n**Generated XML Structure:**\n\n```xml\n<name>{skill_name}</name>\n<description>{skill_description}</description>\n\n<instructions>\n{skill_instructions}\n</instructions>\n\n{resources_block}\n\n{scripts_block}\n```\n\n## Tool Generation from Skills\n\nThe Agent Framework automatically generates tools from skills:\n\n| Tool | Purpose | Triggered By |\n|------|---------|--------------|\n| `load_skill` | Retrieve skill instructions | When skills exist |\n| `run_skill_script` | Execute skill scripts | When scripts exist |\n| `{custom_tools}` | Domain-specific operations | Skill-defined tools |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProvider.cs:80-150]()\n\n## Integration Examples\n\n### Adding Skills to an Agent (Python)\n\n```python\nfrom agent_framework import Agent, AgentSkillsProvider, skill\n\n# Define a skill\n@skill(name=\"data-analyst\", description=\"Analyze datasets\")\ndef analyst_skill():\n    return {\n        \"instructions\": \"You analyze data and provide insights...\",\n        \"resources\": [\"./analyst/resources/templates.json\"]\n    }\n\n# Create skills provider\nskills_provider = AgentSkillsProvider(skills=[analyst_skill])\n\n# Attach to agent\nagent = Agent(\n    instructions=\"You are a helpful assistant.\",\n    skills_provider=skills_provider\n)\n```\n\n### Adding Skills to an Agent (C#)\n\n```csharp\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Skills.File;\n\n// Load file-based skills\nAgentFileSkill[] fileSkills = AgentFileSkill.LoadFromDirectory(\"./skills\");\n\n// Create provider with file skills\nAgentSkillsProvider provider = new AgentSkillsProvider(\n    new AgentSkillsSource(fileSkills),\n    new AgentSkillsProviderOptions\n    {\n        ScriptApproval = true\n    });\n\n// Create agent with skills\nChatClientAgent agent = new ChatClientAgent(\n    model: \"gpt-4o\",\n    instructions: \"You are a helpful assistant.\",\n    skillsProvider: provider\n);\n```\n\n资料来源：[dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs:1-80]()\n\n## Design Decisions\n\nThe Tools and Skills architecture was designed with these principles:\n\n1. **Dual Expression**: Skills can be defined declaratively (file-based) or programmatically (code-defined), allowing flexibility in how developers structure their agent capabilities. 资料来源：[docs/decisions/0021-agent-skills-design.md:1-30]()\n\n2. **Resource Abstraction**: Resources provide reference data to skills without embedding everything in instructions, enabling efficient context management.\n\n3. **Script Integration**: Scripts allow skills to perform automated actions, with optional approval workflows for security-sensitive operations.\n\n4. **Tool Synthesis**: The framework automatically generates management tools (`load_skill`, `run_skill_script`) to ensure consistent skill interaction patterns.\n\n## See Also\n\n- [Agent Framework Core](../core/)\n- [Workflows and Graphs](../workflows/)\n- [Declarative Agents](../declarative/)\n- [Sample: File-Based Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/file_based_skill)\n- [Sample: Code-Defined Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/code_defined_skill)\n- [Sample: Mixed Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/mixed_skills)\n\n---\n\n<a id='workflows'></a>\n\n## Workflows and Orchestration\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Hosting and Deployment Patterns](#hosting-patterns), [Observability and Telemetry](#observability)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_workflows/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/__init__.py)\n- [python/packages/core/agent_framework/_workflows/_workflow.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/_workflow.py)\n- [python/packages/core/agent_framework/_workflows/_runner.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/_runner.py)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n- [python/samples/03-workflows/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/README.md)\n- [dotnet/samples/03-workflows/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/03-workflows/README.md)\n</details>\n\n# Workflows and Orchestration\n\n## Overview\n\nThe Agent Framework provides a comprehensive **workflow and orchestration system** that enables developers to compose multiple agents into structured execution patterns. Workflows serve as the architectural backbone for multi-agent coordination, allowing agents to be chained, parallelized, or conditionally executed based on runtime state.\n\nWorkflows in the Agent Framework are built using an **executor-based architecture** where each component (agents, functions, workflows) implements a common executor interface. This design enables flexible composition through a builder pattern, supporting both imperative (code-based) and declarative (YAML-based) workflow definitions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n## Architecture\n\n### Core Concepts\n\n```mermaid\ngraph TD\n    A[Input] --> B[Executor]\n    B --> C[Executor]\n    C --> D[Executor]\n    B --> E[Executor]\n    D --> F[Aggregator]\n    E --> F\n    F --> G[Output]\n    \n    H[Workflow] --> B\n    H --> C\n    H --> D\n    H --> E\n    H --> F\n    \n    I[Builder] -->|Builds| H\n```\n\nThe orchestration system is built on three fundamental abstractions:\n\n| Concept | Description |\n|---------|-------------|\n| **Executor** | A callable unit that processes inputs and produces outputs |\n| **Workflow** | A composed structure of executors connected by edges |\n| **Builder** | Fluent API for constructing workflows programmatically |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs)\n\n### Executor Types\n\nExecutors form the atomic units of workflow execution:\n\n| Executor Type | Purpose |\n|---------------|---------|\n| `AIAgent` | Encapsulates an AI agent that processes text and returns responses |\n| `FunctionExecutor` | Executes synchronous or asynchronous functions |\n| `WorkflowExecutor` | Wraps an entire sub-workflow for nested orchestration |\n| `OutputMessagesExecutor` | Terminal executor that captures final output |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n## Workflow Composition Patterns\n\n### Sequential Workflow\n\nAgents or functions execute in a linear chain, where each component receives the output of the previous one.\n\n```mermaid\ngraph LR\n    A[Input] --> B[Agent 1]\n    B --> C[Agent 2]\n    C --> D[Agent 3]\n    D --> E[Output]\n```\n\n**Example: Translation Chain**\n```\nInput text (English)\n    │\n    ▼\n┌─────────────┐    ┌──────────────┐    ┌──────────────┐\n│ French Agent │ →  │ Spanish Agent │ →  │ English Agent │\n│ (translate)  │    │ (translate)   │    │ (translate)   │\n└─────────────┘    └──────────────┘    └──────────────┘\n                                              │\n                                              ▼\n                                        Final output\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/README.md)\n\n### Concurrent Workflow\n\nMultiple agents operate on the same input simultaneously, with outputs aggregated into a collection.\n\n```mermaid\ngraph TD\n    A[Input] --> B[Agent 1]\n    A --> C[Agent 2]\n    A --> D[Agent 3]\n    B --> E[Aggregator]\n    C --> E\n    D --> E\n    E --> F[Output Collection]\n```\n\n### Conditional Workflow\n\nExecution branches based on runtime conditions or agent responses.\n\n```mermaid\ngraph TD\n    A[Input] --> B[Router Agent]\n    B -->|Condition A| C[Agent A]\n    B -->|Condition B| D[Agent B]\n    B -->|Default| E[Default Agent]\n    C --> F[Output]\n    D --> F\n    E --> F\n```\n\n## Declarative Workflows\n\nThe Agent Framework supports defining workflows using YAML, enabling configuration-driven orchestration without code changes.\n\n### Workflow Structure\n\n```yaml\nname: my-workflow\ndescription: A declarative workflow example\n\nactions:\n  - kind: SetValue\n    path: turn.greeting\n    value: Hello, World!\n\n  - kind: SendActivity\n    activity:\n      text: =turn.greeting\n```\n\n资料来源：[python/samples/03-workflows/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/declarative/README.md)\n\n### Action Types\n\n#### Variable Actions\n\n| Action | Purpose |\n|--------|---------|\n| `SetValue` | Set a variable in state |\n| `SetVariable` | Set a variable (.NET style naming) |\n| `AppendValue` | Append to a list |\n| `ResetVariable` | Clear a variable |\n\n#### Control Flow\n\n| Action | Purpose |\n|--------|---------|\n| `If` | Conditional branching |\n| `Switch` | Multi-way branching |\n| `Foreach` | Iterate over collections |\n| `RepeatUntil` | Loop until condition |\n| `GotoAction` | Jump to labeled action |\n\n#### Output\n\n| Action | Purpose |\n|--------|---------|\n| `SendActivity` | Send text/attachments to user |\n\n资料来源：[python/samples/03-workflows/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/declarative/README.md)\n\n## Durable Orchestration\n\nFor long-running workflows that may span hours or days, the Agent Framework provides **durable orchestration** using the Durable Task Framework.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Client] -->|Schedule| B[Orchestrator]\n    B -->|Calls| C[Activity]\n    B -->|Calls| D[Agent]\n    C -->|Result| B\n    D -->|Result| B\n    B -->|Persisted| E[State Store]\n```\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Long-running execution** | Workflows persist across process restarts |\n| **Human-in-the-loop** | Workflows can pause and await human approval |\n| **Event-driven** | Activities can send notifications and wait for responses |\n| **State management** | Built-in state persistence with checkpointing |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs)\n\n### Human-in-the-Loop Pattern\n\nDurable workflows support pausing for human approval:\n\n1. **Initial Generation**: Agent creates content based on input\n2. **Review Loop**: Up to configurable maximum attempts\n   - Activity notifies user for approval\n   - Orchestration waits for approval event OR timeout\n3. **Resolution**:\n   - **Approved**: Content published, workflow completes\n   - **Rejected**: Feedback incorporated, regeneration triggered\n   - **Timeout**: Error raised\n\n资料来源：[python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md)\n\n### Durable Workflow Context\n\nThe `DurableWorkflowContext` manages workflow state and events:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `SentMessages` | `List<TypedPayload>` | Messages sent during activity execution |\n| `OutboundEvents` | `List<WorkflowEvent>` | Events added during execution |\n| `StateUpdates` | `Dictionary<string, string?>` | State modifications |\n| `ClearedScopes` | `HashSet<string>` | Scopes cleared during execution |\n| `HaltRequested` | `bool` | Whether executor requested workflow halt |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableWorkflowContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableWorkflowContext.cs)\n\n## Workflow Builder API\n\n### .NET Implementation\n\nThe `WorkflowBuilder` class provides a fluent API for composing workflows:\n\n```csharp\n// Sequential composition\nWorkflow workflow = WorkflowBuilder.BuildSequential(\n    \"MyWorkflow\",\n    agent1, agent2, agent3);\n\n// Concurrent composition  \nWorkflow workflow = WorkflowBuilder.BuildConcurrent(\n    \"ConcurrentWorkflow\",\n    agent1, agent2, agent3);\n```\n\n**Builder Configuration Options:**\n\n| Option | Description |\n|--------|-------------|\n| `ReassignOtherAgentsAsUsers` | When `true`, other agents in scope become user participants |\n| `ForwardIncomingMessages` | When `true`, incoming messages propagate through the chain |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n### Python Implementation\n\nThe Python workflow system provides similar builder patterns:\n\n```python\nfrom agent_framework.workflows import WorkflowBuilder\n\nworkflow = WorkflowBuilder(\n    start_executor=first_agent\n).add_edge(\n    from_node=first_agent,\n    to_node=second_agent\n).build()\n```\n\n**MagenticBuilder for Multi-Agent Orchestration:**\n\n```python\nfrom agent_framework.orchestrations import MagenticBuilder\n\nworkflow = MagenticBuilder(\n    participants=[researcher, writer, reviewer],\n    manager_agent=manager_agent,\n).build()\n```\n\n资料来源：[python/packages/orchestrations/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/orchestrations/README.md)\n\n## Workflow State Management\n\n### State Persistence\n\nWorkflows maintain state throughout execution:\n\n```mermaid\ngraph LR\n    A[Checkpoint] --> B[State Dictionary]\n    B --> C[Resume]\n    D[Input] --> E[Executor]\n    E --> F[Output]\n    E -->|State Update| B\n```\n\n### State Variables\n\nCustom state variables are stored alongside system state:\n\n| Key | Purpose |\n|-----|---------|\n| `_executor_state` | Internal executor tracking (hidden from user state) |\n| `*` (custom) | User-defined state variables |\n\n资料来源：[python/packages/devui/frontend/src/components/features/workflow/checkpoint-info-modal.tsx](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/features/workflow/checkpoint-info-modal.tsx)\n\n## Configuration\n\n### Service Registration\n\n#### .NET\n\n```xml\n<PropertyGroup>\n  <InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>\n  <InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>\n</PropertyGroup>\n```\n\n#### Durable Options Configuration\n\n```csharp\nservices.ConfigureDurableWorkflows(options =>\n{\n    options.Workflows.HubName = \"MyAgentHub\";\n    options.Workflows.TaskOrchestration.Type = OrchestrationType.InProcess;\n});\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs)\n\n### Python Environment Variables\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://your-project-endpoint\"\nexport FOUNDRY_MODEL=\"gpt-4o\"   # optional, defaults to gpt-4o\n```\n\n资料来源：[python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Sample Code Reference\n\n### Basic Sequential Workflow (.NET)\n\n```csharp\n// Create agent executors\nExecutorBinding agent1 = agent1.BindAsExecutor(options);\nExecutorBinding agent2 = agent2.BindAsExecutor(options);\n\n// Build sequential chain\nWorkflowBuilder builder = new WorkflowBuilder(agent1);\nbuilder.AddEdge(agent1, agent2);\n\n// Add terminal output executor\nOutputMessagesExecutor end = new();\nbuilder = builder.AddEdge(agent2, end).WithOutputFrom(end);\n\nWorkflow workflow = builder.Build();\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n### Durable Workflow with HITL (Python)\n\n```python\n# 1. Initial generation\ncontent = yield writer_agent.generate(topic)\n\n# 2. Notify for review\nyield send_notification(content)\n\n# 3. Wait for approval/rejection\napproval_event = yield wait_for_event(\"ApprovalEvent\")\nif approval_event.approved:\n    yield publish_content(content)\nelse:\n    # Regenerate with feedback\n    content = yield writer_agent.generate(topic, feedback=approval_event.feedback)\n```\n\n资料来源：[python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md)\n\n## Monitoring and Debugging\n\n### Durable Task Dashboard\n\nView orchestration state at `http://localhost:8082`:\n\n| View | Information Available |\n|------|----------------------|\n| Orchestrations | Instance status, runtime state, input/output, execution history |\n| Agents | Conversation history, agent state |\n\n### OpenTelemetry Traces\n\nThe framework emits Otel traces for workflow operations:\n\n```bash\ndevui ./agents --instrumentation\n```\n\n资料来源：[python/packages/devui/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/README.md)\n\n## See Also\n\n- [Agent Framework Documentation](https://aka.ms/agent-framework)\n- [Declarative Workflow Samples](../03-workflows/declarative/)\n- [Durable Task Samples](../04-hosting/durabletask/)\n- [DevUI Configuration](../packages/devui/)\n\n---\n\n<a id='middleware'></a>\n\n## Middleware System\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Tools and Skills](#tools-and-skills)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_middleware.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_middleware.py)\n- [dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs)\n- [python/samples/02-agents/middleware/function_based_middleware.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/middleware/function_based_middleware.py)\n- [dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs)\n- [docs/decisions/0007-agent-filtering-middleware.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0007-agent-filtering-middleware.md)\n</details>\n\n# Middleware System\n\n## Overview\n\nThe Middleware System in the Microsoft Agent Framework provides a powerful extensibility mechanism that allows developers to intercept, modify, and control the flow of interactions between agents, tools, and AI models. Middleware components act as interceptors in the request-response pipeline, enabling cross-cutting concerns such as logging, authentication, tool approval, and request filtering.\n\nAccording to the architecture decision record, the middleware system was designed to solve the problem of filtering agent requests and responses without tightly coupling such logic to the core agent implementation. 资料来源：[docs/decisions/0007-agent-filtering-middleware.md]()\n\n## Architecture\n\n### Core Concepts\n\nThe middleware system follows a pipeline-based architecture where requests flow through a chain of middleware components before reaching the core agent logic, and responses flow back through the same chain in reverse order.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Middleware 1]\n    B --> C[Middleware 2]\n    C --> D[Middleware N]\n    D --> E[Core Agent Logic]\n    E --> F[Response from Agent]\n    F --> D\n    D --> C\n    C --> B\n    B --> G[User Response]\n    \n    H[Tool Calls] <-->|Intercepted| D\n    I[AI Model] <-->|Filtered| D\n```\n\n### Middleware Types\n\n| Type | Purpose | Python Implementation | .NET Implementation |\n|------|---------|----------------------|---------------------|\n| Function-based | Simple callable middleware | `@middleware` decorator | Delegate-based |\n| Class-based | State-aware middleware with full lifecycle control | `Middleware` abstract class | `IAgentMiddleware` interface |\n| Tool Approval | Approves or rejects tool executions | Custom handler | `ToolApprovalAgent` |\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]() | [dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n## Python Middleware Implementation\n\n### Function-Based Middleware\n\nThe simplest way to define middleware in Python is using the `@middleware` decorator. This creates a middleware that wraps an agent and intercepts all calls.\n\n```python\nfrom agent_framework import Agent, middleware\n\n@middleware\nasync def my_logging_middleware(agent, tool_call, context, call_next):\n    print(f\"Tool call: {tool_call.name}\")\n    result = await call_next(agent, tool_call, context)\n    print(f\"Result: {result}\")\n    return result\n\n# Apply middleware to agent\nagent = Agent(...)\nwrapped_agent = my_logging_middleware(agent)\n```\n\n资料来源：[python/samples/02-agents/middleware/function_based_middleware.py]()\n\n### Middleware Base Class\n\nFor more complex scenarios, you can extend the `Middleware` abstract class:\n\n```python\nfrom agent_framework import Middleware, Agent\n\nclass ToolApprovalMiddleware(Middleware):\n    def __init__(self):\n        self.pending_approvals = []\n    \n    async def on_tool_call(\n        self, \n        agent: Agent, \n        tool_call: ToolCall, \n        context: Context\n    ) -> Awaitable[Result]:\n        # Custom logic to approve or reject\n        if self._requires_approval(tool_call):\n            return Result(success=False, error=\"Approval required\")\n        return await self.next(agent, tool_call, context)\n```\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]()\n\n### Middleware Pipeline Execution\n\nThe middleware system processes requests through a pipeline where each middleware can:\n\n1. **Pre-process**: Act on the request before passing to the next middleware\n2. **Pass through**: Forward the request to the next component in the chain\n3. **Post-process**: Act on the response as it flows back up the chain\n4. **Short-circuit**: Return a response without calling subsequent middleware\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MW1 as Middleware 1\n    participant MW2 as Middleware 2\n    participant Agent as Core Agent\n    \n    Client->>MW1: request\n    MW1->>MW2: pass to next\n    MW2->>Agent: forward request\n    Agent-->>MW2: response\n    MW2-->>MW1: post-process\n    MW1-->>Client: final response\n```\n\n## .NET Middleware Implementation\n\n### ToolApprovalAgent\n\nThe .NET implementation provides a `ToolApprovalAgent` that wraps an agent and requires approval for tool executions. This is particularly useful for scenarios where human-in-the-loop approval is required for sensitive operations.\n\n```csharp\npublic class ToolApprovalAgent : Agent\n{\n    public ToolApprovalAgent(\n        Agent inner,\n        IToolApprover toolApprover,\n        Func<ToolCall, bool>? shouldApprove = null);\n    \n    public override async Task<Result> OnToolCallAsync(\n        ToolCall toolCall,\n        Context context,\n        CancellationToken cancellationToken);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n### Middleware Registration\n\nIn .NET, middleware is typically registered through dependency injection and configured on the agent:\n\n```csharp\n// Program.cs from the sample\nvar builder = Kernel.CreateBuilder();\n\n// Register middleware\nbuilder.Services.AddSingleton<IAgentMiddleware, LoggingMiddleware>();\n\nvar kernel = builder.Build();\n\n// Configure agent with middleware\nvar agent = new ChatClientAgent(chatClient)\n    .WithMiddleware<LoggingMiddleware>()\n    .WithMiddleware<ToolApprovalMiddleware>();\n```\n\n资料来源：[dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs]()\n\n### Built-in .NET Middleware\n\n| Middleware | Description |\n|------------|-------------|\n| `LoggingMiddleware` | Logs all requests, responses, and tool calls |\n| `ToolApprovalMiddleware` | Requires approval before tool execution |\n| `RateLimitMiddleware` | Enforces rate limiting on agent requests |\n| `AuthenticationMiddleware` | Validates authentication tokens |\n\n## Middleware API Reference\n\n### Python Middleware API\n\n#### `@middleware` Decorator\n\nCreates a simple function-based middleware.\n\n```python\n@middleware\nasync def middleware_func(agent, tool_call, context, call_next):\n    \"\"\"Middleware function signature.\"\"\"\n    pass\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `agent` | `Agent` | The agent instance being wrapped |\n| `tool_call` | `ToolCall` | The tool call being processed |\n| `context` | `Context` | Execution context with state |\n| `call_next` | `Callable` | Function to invoke the next middleware/agent |\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]()\n\n#### `Middleware` Base Class\n\nAbstract class for stateful middleware:\n\n```python\nclass Middleware(ABC):\n    @abstractmethod\n    async def on_tool_call(\n        self, \n        agent: Agent, \n        tool_call: ToolCall, \n        context: Context\n    ) -> Result:\n        \"\"\"Called when a tool call is intercepted.\"\"\"\n        pass\n```\n\n| Method | Description |\n|--------|-------------|\n| `on_tool_call` | Intercepts and processes tool calls |\n| `on_request` | Intercepts incoming requests |\n| `on_response` | Intercepts outgoing responses |\n| `next()` | Passes control to the next middleware |\n\n### .NET Middleware API\n\n#### `IAgentMiddleware` Interface\n\n```csharp\npublic interface IAgentMiddleware\n{\n    Task<Result> InvokeAsync(\n        AgentContext context,\n        MiddlewareDelegate next,\n        CancellationToken cancellationToken);\n}\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `context` | `AgentContext` | Contains request, response, and state |\n| `next` | `MiddlewareDelegate` | Delegate to invoke the next middleware |\n| `cancellationToken` | `CancellationToken` | Cancellation support |\n\n#### `Agent` Extension Methods\n\n```csharp\npublic static class AgentMiddlewareExtensions\n{\n    public static TAgent WithMiddleware<TMiddleware>(\n        this TAgent agent,\n        params object[] args) where TAgent : Agent;\n    \n    public static TAgent WithMiddleware(\n        this TAgent agent,\n        Type middlewareType,\n        params object[] args) where TAgent : Agent;\n}\n```\n\n## Use Cases\n\n### 1. Tool Approval Workflow\n\nA common use case is requiring human approval before executing sensitive tools:\n\n```mermaid\ngraph LR\n    A[Agent] --> B{ToolApprovalMiddleware}\n    B --> C{Is Sensitive?}\n    C -->|Yes| D[Request Human Approval]\n    D --> E{Approved?}\n    E -->|Yes| F[Execute Tool]\n    E -->|No| G[Reject & Return Error]\n    C -->|No| F\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n### 2. Request/Response Logging\n\nMiddleware can log all interactions for debugging and auditing:\n\n```python\n@middleware\nasync def audit_logging_middleware(agent, tool_call, context, call_next):\n    log_entry = {\n        \"timestamp\": datetime.utcnow(),\n        \"tool_name\": tool_call.name,\n        \"parameters\": tool_call.arguments,\n        \"user\": context.user_id\n    }\n    await audit_log(log_entry)\n    return await call_next(agent, tool_call, context)\n```\n\n### 3. Request Filtering\n\nMiddleware can filter or modify requests before they reach the agent:\n\n```csharp\npublic class ContentFilterMiddleware : IAgentMiddleware\n{\n    public async Task<Result> InvokeAsync(\n        AgentContext context,\n        MiddlewareDelegate next,\n        CancellationToken cancellationToken)\n    {\n        // Check for prohibited content\n        if (ContainsProhibitedContent(context.Request.Text))\n        {\n            return new Result { Success = false, Error = \"Content filtered\" };\n        }\n        \n        return await next(context, cancellationToken);\n    }\n}\n```\n\n## Configuration\n\n### Python Configuration\n\n```python\nagent = Agent(\n    name=\"my_agent\",\n    instructions=\"You are a helpful assistant\",\n    middleware=[\n        LoggingMiddleware(),\n        ToolApprovalMiddleware(approver=human_approver),\n        RateLimitMiddleware(max_calls_per_minute=60)\n    ]\n)\n```\n\n### .NET Configuration\n\n```csharp\n// Via dependency injection\nbuilder.Services.AddTransient<IAgentMiddleware, LoggingMiddleware>();\nbuilder.Services.AddSingleton<IToolApprover, HumanToolApprover>();\n\n// Or inline during agent creation\nvar agent = new ChatClientAgent(chatClient)\n    .WithMiddleware<LoggingMiddleware>()\n    .WithMiddleware(sp.GetRequiredService<ToolApprovalMiddleware>());\n```\n\n## Best Practices\n\n1. **Keep middleware focused**: Each middleware should handle a single concern (logging, authentication, etc.)\n\n2. **Always call `next` or return**: Ensure middleware either passes control to the next component or returns a response\n\n3. **Handle exceptions**: Wrap `next` calls in try-catch to prevent unhandled exceptions from breaking the pipeline\n\n4. **Order matters**: Register middleware in the correct order based on dependencies\n\n5. **Avoid blocking operations**: Use async/await patterns to prevent blocking the pipeline\n\n6. **Document side effects**: Clearly document any side effects middleware may have\n\n## Error Handling\n\nMiddleware should gracefully handle errors and either:\n- Recover and continue the pipeline\n- Short-circuit with an appropriate error response\n- Propagate the error with additional context\n\n```python\n@middleware\nasync def error_handling_middleware(agent, tool_call, context, call_next):\n    try:\n        return await call_next(agent, tool_call, context)\n    except ToolExecutionException as e:\n        logger.error(f\"Tool execution failed: {e}\")\n        return Result(\n            success=False,\n            error=f\"Tool execution failed: {str(e)}\",\n            context={\"original_error\": e}\n        )\n```\n\n## Related Components\n\n| Component | Relationship |\n|-----------|--------------|\n| Agent | Core component that middleware intercepts |\n| Tools | Often the target of middleware interception |\n| Context | State container passed through middleware pipeline |\n| Skills | Can be combined with middleware for complex workflows |\n\n## Summary\n\nThe Middleware System provides a flexible, extensible pipeline architecture for intercepting and modifying agent behavior. It supports both simple function-based middleware and complex class-based middleware with full lifecycle control. The system is available across both Python and .NET implementations, enabling consistent cross-platform extensibility patterns.\n\nKey takeaways:\n- Middleware enables cross-cutting concerns without modifying core agent code\n- Both Python and .NET provide decorator/attribute-based middleware creation\n- Tool approval is a common built-in middleware pattern\n- Middleware can short-circuit, pass through, or modify requests and responses\n- Proper ordering and error handling are essential for reliable middleware pipelines\n\n---\n\n<a id='provider-integration'></a>\n\n## AI Provider Integration\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Getting Started with Microsoft Agent Framework](#getting-started)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/openai/agent_framework_openai/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/openai/agent_framework_openai/__init__.py)\n- [python/packages/anthropic/agent_framework_anthropic/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/anthropic/agent_framework_anthropic/__init__.py)\n- [python/packages/foundry/agent_framework_foundry/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry/agent_framework_foundry/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs)\n- [python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n- [dotnet/samples/02-agents/AgentProviders/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentProviders/README.md)\n</details>\n\n# AI Provider Integration\n\n## Overview\n\nThe AI Provider Integration layer in Microsoft Agent Framework enables agents to communicate with various Large Language Model (LLM) backends through a unified abstraction. This architecture allows developers to switch between different AI providers—such as OpenAI, Azure AI Foundry, Anthropic, and Ollama—without modifying agent logic. The provider system acts as the bridge between the agent's execution framework and the underlying AI models.\n\nThe framework supports both Python and .NET ecosystems, with provider implementations that expose chat completion clients, responses API clients, and specialized agent integrations. Each provider package implements common interfaces while leveraging provider-specific authentication, configuration, and API semantics.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"Agent Layer\"\n        A[Agent Instance]\n        S[Skills/Tools]\n    end\n    \n    subgraph \"Provider Abstraction\"\n        P[Provider Interface]\n    end\n    \n    subgraph \"Concrete Providers\"\n        O[OpenAI]\n        F[Azure AI Foundry]\n        An[Anthropic Claude]\n        Ol[Ollama]\n        G[GitHub Copilot]\n    end\n    \n    subgraph \"External Services\"\n        OS[OpenAI API]\n        FS[Azure Foundry]\n        AS[Anthropic API]\n        LS[Local Ollama]\n        GS[GitHub Copilot]\n    end\n    \n    A --> P\n    S --> P\n    P --> O\n    P --> F\n    P --> An\n    P --> Ol\n    P --> G\n    O --> OS\n    F --> FS\n    An --> AS\n    Ol --> LS\n    G --> GS\n```\n\n## Provider Packages\n\n### Python Provider Packages\n\n| Package | Purpose | Install Command |\n|---------|---------|-----------------|\n| `agent-framework-openai` | OpenAI and Azure OpenAI integration | `pip install agent-framework-openai` |\n| `agent-framework-anthropic` | Anthropic Claude model support | `pip install agent-framework-anthropic` |\n| `agent-framework-foundry` | Azure AI Foundry integration | `pip install agent-framework-foundry` |\n| `agent-framework-claude` | Claude-specific agentic capabilities | `pip install agent-framework-claude --pre` |\n| `agent-framework-ollama` | Local Ollama model support | `pip install agent-framework-ollama --pre` |\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Provider Assemblies\n\n| Assembly | Namespace | Purpose |\n|----------|-----------|---------|\n| `Microsoft.Agents.AI.OpenAI` | `Microsoft.Agents.AI.OpenAI` | OpenAI Response API and Chat Completions |\n| `Microsoft.Agents.AI.Foundry` | `Microsoft.Agents.AI.Foundry` | Azure AI Foundry agent and client integration |\n| `Microsoft.Agents.AI.GitHub.Copilot` | `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot agent extension |\n\n## Azure AI Foundry Provider\n\nAzure AI Foundry provides the primary production-grade provider for enterprise deployments. It integrates with Azure AI Foundry projects, enabling agents to leverage Foundry's model deployments, content safety, and telemetry.\n\n### Python Implementation\n\nThe Foundry provider package exports core classes for connecting to Azure AI Foundry projects:\n\n```python\n# python/packages/foundry/agent_framework_foundry/__init__.py\n# Core exports include:\n# - FoundryChatCompletionClient\n# - FoundryAgent\n# - Configuration utilities\n```\n\nThe provider requires environment configuration:\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://<resource>.services.ai.azure.com/api/projects/<project>\"\nexport FOUNDRY_MODEL=\"<deployment-name>\"\n```\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Implementation\n\nThe .NET Foundry provider exposes two primary integration points:\n\n#### FoundryAgent\n\nThe `FoundryAgent` class serves as the agent implementation backed by Azure AI Foundry:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs\npublic class FoundryAgent\n{\n    // Provides agent creation and lifecycle management\n    // Integrates with Azure AI Foundry service\n}\n```\n\n#### AzureAIProjectChatClient\n\nThe `AzureAIProjectChatClient` wraps the Azure AI Foundry chat client with Agent Framework conventions:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs\npublic class AzureAIProjectChatClient\n{\n    // Manages project-scoped chat interactions\n    // Handles authentication and connection to Foundry\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs)\n\n### Foundry Configuration Options\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `project_endpoint` | Azure AI Foundry project URL | Required |\n| `model` | Model deployment name | `gpt-4o` |\n| `api_version` | API version for requests | Latest stable |\n| `credential` | Azure authentication credential | `DefaultAzureCredential` |\n\n## OpenAI Provider\n\nThe OpenAI provider enables agents to connect directly to OpenAI's API or Azure OpenAI Service endpoints.\n\n### Python Integration\n\n```python\nfrom agent_framework.openai import OpenAIChatClient, OpenAIChatCompletionClient\n\n# Direct OpenAI usage\nclient = OpenAIChatClient(model=\"gpt-4\")\n\n# Using Responses API\nclient = OpenAIChatCompletionClient(model=\"gpt-4\")\n```\n\n资料来源：[python/packages/openai/agent_framework_openai/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/openai/agent_framework_openai/__init__.py)\n\n### .NET Integration\n\nThe .NET OpenAI provider uses the `OpenAIResponseClientExtensions` class to create agent instances:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs\npublic static class OpenAIResponseClientExtensions\n{\n    public static ChatClientAgent AsAIAgent(\n        this ResponsesClient client,\n        string? model = null,\n        string? instructions = null,\n        string? name = null,\n        string? description = null,\n        IList<AITool>? tools = null,\n        Func<IChatClient, IChatClient>? clientFactory = null,\n        ILoggerFactory? loggerFactory = null,\n        IServiceProvider? services = null)\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs)\n\n## Anthropic Provider\n\nThe Anthropic provider integrates Claude models into the Agent Framework, supporting both direct API access and provider-specific agentic capabilities.\n\n### Python Integration\n\n```python\nfrom agent_framework_anthropic import ClaudeAgent\n\nagent = ClaudeAgent(\n    model=\"claude-sonnet-4-20250514\",\n    # Provider-specific configuration\n)\n```\n\n资料来源：[python/packages/anthropic/agent_framework_anthropic/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/anthropic/agent_framework_anthropic/__init__.py)\n\nThe `agent-framework-claude` package specifically enables Claude agentic capabilities through the Agent Framework:\n\n```bash\npip install agent-framework-claude --pre\n```\n\n资料来源：[python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n## Ollama Provider\n\nOllama enables local LLM deployments, useful for development, testing, and privacy-sensitive scenarios.\n\n### Configuration\n\n```bash\nexport OLLAMA_BASE_URL=\"http://localhost:11434\"  # Default\nexport OLLAMA_MODEL=\"llama3.2\"  # Model to use\n```\n\n### Installation\n\n```bash\npip install agent-framework-ollama --pre\n```\n\n资料来源：[python/packages/ollama/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/ollama/README.md)\n\nSamples demonstrating Ollama connector usage are available at:\n\n```\npython/samples/02-agents/providers/ollama/\n```\n\n## GitHub Copilot Provider\n\nThe .NET implementation includes a GitHub Copilot integration through the `CopilotClientExtensions`:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Provider Selection Workflow\n\n```mermaid\ngraph LR\n    A[Choose Provider] --> B{Have Azure Account?}\n    B -->|Yes| C[Azure AI Foundry]\n    B -->|No| D[Direct OpenAI]\n    C --> E[Configure Endpoint]\n    D --> F[Set API Key]\n    E --> G[Create ChatClient]\n    F --> G\n    G --> H[Initialize Agent]\n    H --> I[Attach Skills/Tools]\n    I --> J[Execute Agent]\n```\n\n## Agent ID Model\n\nProviders use a standardized `AgentId` model for identification:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs\ninternal sealed class AgentId\n{\n    [JsonPropertyName(\"type\")]\n    public AgentIdType Type { get; init; }\n    \n    [JsonPropertyName(\"name\")]\n    public string Name { get; init; }\n    \n    [JsonPropertyName(\"version\")]\n    public string Version { get; init; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs)\n\n## Sample Applications\n\n### Python Provider Samples\n\n| Sample | Provider | Description |\n|--------|----------|-------------|\n| `providers/openai/` | OpenAI | Basic OpenAI integration |\n| `providers/foundry/` | Foundry | Azure AI Foundry integration |\n| `providers/anthropic/` | Anthropic | Claude model usage |\n| `providers/ollama/` | Ollama | Local model deployment |\n\nRun samples:\n\n```bash\ncd python\nuv run samples/02-agents/providers/<provider-name>/\n```\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Provider Samples\n\n```bash\ncd dotnet/samples/02-agents/AgentProviders\ndotnet run\n```\n\n资料来源：[dotnet/samples/02-agents/AgentProviders/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentProviders/README.md)\n\n## Authentication Patterns\n\n| Provider | Authentication Method |\n|----------|----------------------|\n| Azure AI Foundry | `DefaultAzureCredential`, `AzureCliCredential` |\n| OpenAI | API Key via environment or parameter |\n| Anthropic | API Key via environment |\n| Ollama | No authentication (local) |\n| GitHub Copilot | Copilot client authentication |\n\nMost Azure-based providers support `AzureCliCredential`, requiring `az login` before execution:\n\n```bash\naz login\n```\n\n## Best Practices\n\n1. **Environment Variables**: Store provider credentials in environment variables rather than hardcoding\n2. **Provider Selection**: Use Azure AI Foundry for production, OpenAI for development, Ollama for testing\n3. **Client Reuse**: Create chat clients once and reuse across agent instances when possible\n4. **Error Handling**: Implement retry logic for transient provider failures\n5. **Model Selection**: Match model capabilities to task requirements for cost efficiency\n\n## Deprecated Integrations\n\nThe `Microsoft.Agents.AI.AzureAI.Persistent` package is marked obsolete:\n\n```csharp\n[Obsolete(\"Please use the latest Foundry Agents service via the Microsoft.Agents.AI.AzureAI package.\")]\npublic static async Task<ChatClientAgent> CreateAIAgentAsync(...)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs)\n\nMigration to the Foundry provider is recommended for persistent agent use cases.\n\n---\n\n<a id='sessions-and-history'></a>\n\n## Sessions, History, and State Management\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Workflows and Orchestration](#workflows)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_sessions.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_sessions.py)\n- [python/packages/core/agent_framework/_compaction.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_compaction.py)\n- [dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs)\n- [python/packages/redis/agent_framework_redis/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/redis/agent_framework_redis/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs)\n- [python/samples/02-agents/conversations/custom_history_provider.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/conversations/custom_history_provider.py)\n- [python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py)\n</details>\n\n# Sessions, History, and State Management\n\nAgent Framework provides a comprehensive system for managing conversation state across multi-turn interactions. This system encompasses sessions that track user conversations, history providers that store and retrieve chat messages, and state management mechanisms that preserve context throughout agent interactions.\n\n## Overview\n\nThe session and state management architecture in Agent Framework enables persistent conversations across multiple exchanges. At its core, the framework uses `AgentSession` objects to uniquely identify conversation threads, `ChatHistoryProvider` implementations to store message history, and various compaction strategies to manage context window constraints.\n\n```mermaid\ngraph TD\n    A[Agent Invocation] --> B[AgentSession]\n    B --> C[ChatHistoryProvider]\n    C --> D[State Storage]\n    B --> E[StateBag]\n    D --> F[Persistent Storage]\n    E --> G[In-Memory State]\n    C --> H[Compaction Strategy]\n    H --> I[Context Reduction]\n    \n    style A fill:#e1f5ff\n    style F fill:#fff3e0\n    style G fill:#e8f5e9\n```\n\n## Agent Session\n\nAn `AgentSession` represents a unique conversation context between a user and an agent. The session serves as the primary container for all stateful information related to a specific interaction.\n\n### Session Structure\n\nThe session object contains metadata and state information:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `session_id` | string | Unique identifier for the session |\n| `user_id` | string | Identifier for the user |\n| `agent_id` | string | Identifier for the agent |\n| `metadata` | dict | Application-specific metadata |\n| `state_bag` | dict | Custom state storage |\n| `created_at` | datetime | Session creation timestamp |\n| `last_accessed_at` | datetime | Last activity timestamp |\n\n资料来源：[python/packages/core/agent_framework/_sessions.py]()\n\n### Session Lifecycle\n\nSessions are created when a user initiates a conversation and persist until explicitly terminated. The framework supports both in-memory and persistent session storage backends.\n\n```python\n# Session creation pattern (Python)\nsession = AgentSession(\n    user_id=\"user123\",\n    agent_id=\"assistant-01\",\n    metadata={\"conversation_type\": \"support\"}\n)\n```\n\n## Chat History Management\n\nChat history providers are responsible for storing, retrieving, and managing conversation messages. The framework provides multiple built-in providers and supports custom implementations.\n\n### Built-in History Providers\n\n| Provider | Storage Backend | Use Case |\n|----------|-----------------|----------|\n| `InMemoryChatHistoryProvider` | Memory | Development, testing |\n| `CosmosChatHistoryProvider` | Azure Cosmos DB | Production, scalable |\n| `RedisChatHistoryProvider` | Redis | Production, high-performance |\n| Custom Provider | Configurable | Application-specific needs |\n\n### In-Memory Provider\n\nThe `InMemoryChatHistoryProvider` provides session-scoped message storage suitable for single-instance deployments:\n\n```csharp\npublic class InMemoryChatHistoryProvider : ChatHistoryProvider\n{\n    private readonly SessionState _sessionState;\n    \n    public List<ChatMessage> GetMessages(AgentSession? session)\n        => this._sessionState.GetOrInitializeState(session).Messages;\n    \n    public void SetMessages(AgentSession? session, List<ChatMessage> messages)\n    {\n        Throw.IfNull(messages);\n        State state = this._sessionState.GetOrInitializeState(session);\n        state.Messages = messages;\n    }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/InMemoryChatHistoryProvider.cs:1-30]()\n\n### Cosmos DB Provider\n\nFor production deployments requiring persistence and scalability, the Cosmos DB provider offers fully managed storage:\n\n```python\n# Cosmos DB history provider initialization\nfrom agent_framework import AgentFrameworkClient\n\nclient = AgentFrameworkClient(endpoint=\"your-endpoint\")\nhistory_provider = client.create_chat_history_provider(\n    provider_type=\"cosmos\",\n    connection_string=\"your-connection-string\",\n    database=\"agent_sessions\",\n    container=\"chat_history\"\n)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs]()\n\n### Redis Provider\n\nThe Redis provider provides low-latency access to chat history with automatic expiration:\n\n```python\n# Redis session management\nfrom agent_framework_redis import RedisSessionManager\n\nsession_manager = RedisSessionManager(\n    host=\"localhost\",\n    port=6379,\n    prefix=\"agent_session:\",\n    ttl=3600  # 1 hour TTL\n)\n```\n\n资料来源：[python/packages/redis/agent_framework_redis/__init__.py]()\n\n### Custom History Provider\n\nDevelopers can implement custom history providers by extending the base `ChatHistoryProvider` class:\n\n```python\nfrom agent_framework import ChatHistoryProvider, ChatMessage\nfrom typing import List, Optional\n\nclass CustomHistoryProvider(ChatHistoryProvider):\n    def __init__(self, storage_backend):\n        self._storage = storage_backend\n    \n    async def get_messages(self, session_id: str) -> List[ChatMessage]:\n        return await self._storage.retrieve(session_id)\n    \n    async def add_message(self, session_id: str, message: ChatMessage) -> None:\n        await self._storage.append(session_id, message)\n    \n    async def clear_history(self, session_id: str) -> None:\n        await self._storage.delete(session_id)\n```\n\n资料来源：[python/samples/02-agents/conversations/custom_history_provider.py]()\n\n## Compaction and Context Management\n\nAs conversations grow, managing context window limits becomes critical. The framework provides compaction strategies that automatically reduce message history while preserving important context.\n\n### Compaction Strategy Interface\n\nBoth Python and .NET implementations define the `CompactionStrategy` interface:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `max_context_window_tokens` | int | Maximum tokens in context window |\n| `max_output_tokens` | int | Reserved tokens for model output |\n| `available_input_tokens` | int | Computed available for input |\n\n```csharp\npublic abstract class CompactionStrategy\n{\n    public int MaxContextWindowTokens { get; }\n    public int MaxOutputTokens { get; }\n    public int AvailableInputTokens => MaxContextWindowTokens - MaxOutputTokens;\n    \n    public abstract Task<IEnumerable<ChatMessage>> CompactAsync(\n        IList<ChatMessage> messages,\n        CancellationToken cancellationToken = default);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs]()\n\n### Compaction Trigger Events\n\nThe compaction process can be configured to trigger at different points in the message lifecycle:\n\n| Trigger Event | Timing | Use Case |\n|---------------|--------|----------|\n| `BeforeMessagesRetrieval` | Before history fetch | Optimize retrieval |\n| `AfterMessagesRetrieval` | After history fetch | Post-processing |\n| `OnTokenThreshold` | At token limit | Aggressive reduction |\n\n```csharp\n// Configure pre-retrieval compaction\nif (this.ReducerTriggerEvent == InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.BeforeMessagesRetrieval \n    && this.ChatReducer is not null)\n{\n    await ReduceMessagesAsync(this.ChatReducer, state, cancellationToken);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/InMemoryChatHistoryProvider.cs:25-45]()\n\n### Python Compaction Implementation\n\nThe Python implementation follows a similar pattern with configurable compaction strategies:\n\n```python\nclass CompactionStrategy(ABC):\n    def __init__(\n        self,\n        max_context_window_tokens: int = 128000,\n        max_output_tokens: int = 4096\n    ):\n        self.max_context_window_tokens = max_context_window_tokens\n        self.max_output_tokens = max_output_tokens\n    \n    @property\n    def available_input_tokens(self) -> int:\n        return self.max_context_window_tokens - self.max_output_tokens\n    \n    @abstractmethod\n    async def compact(\n        self,\n        messages: List[ChatMessage],\n        cancellation_token: Optional[CancellationToken] = None\n    ) -> List[ChatMessage]:\n        pass\n```\n\n资料来源：[python/packages/core/agent_framework/_compaction.py]()\n\n## State Management\n\n### Session State Bag\n\nThe `StateBag` provides a dictionary-like interface for storing custom application state within a session:\n\n```csharp\npublic class AgentSession\n{\n    public IDictionary<string, object> StateBag { get; set; }\n}\n\n// Usage\nsession.StateBag[\"last_intent\"] = \"greeting\";\nsession.StateBag[\"user_preference\"] = new { theme = \"dark\", language = \"en\" };\n```\n\n### Context Providers\n\n`AIContextProvider` instances enable middleware-style processing of conversation context:\n\n```mermaid\ngraph LR\n    A[User Message] --> B[AIContextProvider.BeforeInvoke]\n    B --> C[Agent Invocation]\n    C --> D[AIContextProvider.Invoked]\n    D --> E[Response to User]\n    \n    F[Update State] -.-> B\n    G[Log/Audit] -.-> D\n    H[Extract Memories] -.-> D\n```\n\n```csharp\npublic ValueTask BeforeInvokeAsync(InvokingContext context, CancellationToken cancellationToken = default)\n{\n    // Use the request and response messages to:\n    // - Update state based on conversation outcomes\n    // - Extract and store memories or preferences\n    // - Log or audit conversation details\n    return default;\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIContextProvider.cs:1-25]()\n\n### Chat History Memory Provider Scope\n\nFor scoping chat history across applications, agents, or sessions:\n\n```csharp\npublic sealed class ChatHistoryMemoryProviderScope\n{\n    public string? ApplicationId { get; set; }\n    public string? AgentId { get; set; }\n    public string? SessionId { get; set; }\n    public string? UserId { get; set; }\n}\n```\n\n| Scope Property | Effect When Set |\n|----------------|-----------------|\n| `ApplicationId` | Restricts history to specific application |\n| `AgentId` | Restricts history to specific agent |\n| `SessionId` | Restricts history to specific session |\n| `UserId` | Restricts history to specific user |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Memory/ChatHistoryMemoryProviderScope.cs]()\n\n## Workflow Checkpointing\n\nFor long-running workflows, the framework supports checkpoint-based state persistence that allows recovery from failures and resumption of interrupted executions.\n\n```python\nfrom agent_framework import CheckpointStorage, CosmosCheckpointStorage\n\ncheckpoint_storage = CosmosCheckpointStorage(\n    endpoint=\"your-cosmos-endpoint\",\n    database=\"workflows\",\n    container=\"checkpoints\"\n)\n\n# Save checkpoint\nawait checkpoint_storage.save_checkpoint(\n    workflow_id=\"workflow-123\",\n    step=\"step-3\",\n    state={\"progress\": 75, \"data\": {...}},\n    metadata={\"started_at\": \"2024-01-15T10:00:00Z\"}\n)\n\n# Resume from checkpoint\ncheckpoint = await checkpoint_storage.load_checkpoint(\n    workflow_id=\"workflow-123\"\n)\n```\n\n资料来源：[python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py]()\n\n## Agent Configuration Options\n\nThe `HarnessAgentOptions` class demonstrates comprehensive configuration for session and history management:\n\n```csharp\npublic class HarnessAgentOptions\n{\n    public ChatOptions? ChatOptions { get; set; }\n    public ChatHistoryProvider? ChatHistoryProvider { get; set; }\n    public IEnumerable<AIContextProvider>? AIContextProviders { get; set; }\n}\n```\n\n| Option | Description |\n|--------|-------------|\n| `ChatOptions` | Configures instructions, tools, and model parameters |\n| `ChatHistoryProvider` | Storage backend for conversation history |\n| `AIContextProviders` | Middleware providers for context processing |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Harness/HarnessAgentOptions.cs:1-50]()\n\n## Agent Modes\n\nSessions can operate in different modes that affect behavior:\n\n```csharp\npublic sealed class AgentMode\n{\n    public string Name { get; }\n    public string Description { get; }\n}\n\npublic class AgentModeProviderOptions\n{\n    public IReadOnlyList<AgentMode>? Modes { get; set; }\n    public string? DefaultMode { get; set; }\n}\n```\n\n| Mode | Description |\n|------|-------------|\n| `plan` | Interactive planning mode |\n| `execute` | Autonomous execution mode |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs]()\n\n## Response Updates\n\nThe `AgentResponseUpdate` class represents streaming response data with full metadata:\n\n```csharp\npublic class AgentResponseUpdate\n{\n    public string? AuthorName { get; set; }\n    public ChatRole? Role { get; set; }\n    public IList<AIContent>? Contents { get; set; }\n    public FinishReason? FinishReason { get; set; }\n    public string? MessageId { get; set; }\n    public string? ResponseId { get; set; }\n    public DateTimeOffset? CreatedAt { get; set; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseUpdate.cs:1-30]()\n\n## Best Practices\n\n### Session Management\n\n1. **Session Initialization**: Always initialize sessions with appropriate user and agent identifiers\n2. **Session Cleanup**: Implement session expiration for idle conversations\n3. **State Isolation**: Use separate state bags for different concerns\n\n### History Management\n\n1. **Provider Selection**: Choose providers based on scale requirements\n2. **Compaction Tuning**: Configure compaction thresholds based on model context limits\n3. **History Pruning**: Implement retention policies for regulatory compliance\n\n### State Management\n\n1. **State Serialization**: Ensure custom state objects are serializable\n2. **Context Providers**: Use context providers for cross-cutting concerns\n3. **Checkpoint Frequency**: Balance checkpoint overhead against recovery requirements\n\n## See Also\n\n- [Hello Agent Tutorial](python/samples/01-get-started/README.md)\n- [Multi-Turn Conversations](python/samples/02-agents/conversations/)\n- [Workflow Checkpointing](python/samples/03-workflows/checkpoint/)\n- [Agent Skills System](dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n\n---\n\n<a id='hosting-patterns'></a>\n\n## Hosting and Deployment Patterns\n\n### 相关页面\n\n相关主题：[Workflows and Orchestration](#workflows), [Observability and Telemetry](#observability)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py)\n- [python/packages/durabletask/agent_framework_durabletask/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/durabletask/agent_framework_durabletask/__init__.py)\n- [python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md)\n- [dotnet/src/Microsoft.Agents.AI.DurableTask/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n- [python/samples/04-hosting/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n- [dotnet/samples/04-hosting/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n- [python/samples/04-hosting/foundry-hosted-agents/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/foundry-hosted-agents/README.md)\n</details>\n\n# Hosting and Deployment Patterns\n\nThe Microsoft Agent Framework provides multiple hosting and deployment patterns to accommodate different runtime environments and enterprise requirements. This documentation covers the available hosting options, configuration requirements, and deployment strategies for both Python and .NET implementations.\n\n## Overview\n\nThe framework supports three primary hosting paradigms:\n\n| Hosting Pattern | Language | Runtime Environment | Use Case |\n|-----------------|----------|---------------------|----------|\n| Azure Functions | Python, .NET | Serverless/Event-driven | Stateless agent invocations |\n| Durable Task | Python, .NET | Long-running workflows | Complex orchestrations with state persistence |\n| Foundry Hosting | Python, .NET | Azure AI Foundry | Managed agent deployment with platform integration |\n\n资料来源：[python/samples/04-hosting/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n资料来源：[dotnet/samples/04-hosting/README.md:1-20](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Client Request] --> B{Deployment Pattern}\n    B -->|Azure Functions| C[Function App]\n    B -->|Durable Task| D[Orchestration Engine]\n    B -->|Foundry Hosting| E[Azure AI Foundry]\n    \n    C --> F[Stateless Agent Handler]\n    D --> G[Stateful Orchestrator]\n    E --> H[Managed Agent Runtime]\n    \n    F --> I[Response]\n    G --> I\n    H --> I\n```\n\n## Azure Functions Hosting\n\nAzure Functions provides a serverless hosting model suitable for event-driven agent invocations. The framework offers native integration through dedicated packages for both Python and .NET.\n\n### Python Azure Functions Package\n\nThe Python Azure Functions hosting package is located at `python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py`.\n\n**Installation**\n\n```bash\npip install agent-framework-azurefunctions\n```\n\n资料来源：[python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py)\n\n### .NET Azure Functions Package\n\nThe .NET Azure Functions hosting is provided through the `Microsoft.Agents.AI.Hosting.AzureFunctions` NuGet package.\n\n**Installation**\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.Hosting.AzureFunctions\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\nOr via CLI:\n\n```bash\ndotnet add package Microsoft.Agents.AI.Hosting.AzureFunctions\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md)\n\n### Configuration\n\nAzure Functions samples require the following environment configuration:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `AZURE_OPENAI_ENDPOINT` | Azure OpenAI service endpoint | `https://your-resource.openai.azure.com/` |\n| `AZURE_OPENAI_DEPLOYMENT_NAME` | Model deployment name | `gpt-4o` |\n| `TASKHUB_NAME` | Durable Task hub name (for orchestration) | `default` |\n\n资料来源：[dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md:1-30](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md)\n\n### Sample Structure\n\nThe repository includes Azure Functions samples organized by complexity:\n\n```\ndotnet/samples/04-hosting/DurableAgents/AzureFunctions/\n├── 01_SingleAgent/\n├── 02_MultiAgent/\n└── README.md\n```\n\n**Running the Sample**\n\n```bash\ncd dotnet/samples/04-hosting/DurableAgents/AzureFunctions/01_SingleAgent\nfunc start\n```\n\nThe function app becomes available at `http://localhost:7071`.\n\n资料来源：[dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md:45-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md)\n\n## Durable Task Hosting\n\nDurable Task hosting enables long-running agent workflows with state persistence and checkpoint capabilities. This pattern is essential for complex multi-step orchestrations.\n\n### Python Durable Task Package\n\n**Installation**\n\n```bash\npip install agent-framework-durabletask\n```\n\nThe package is located at `python/packages/durabletask/agent_framework_durabletask/__init__.py`.\n\n资料来源：[python/packages/durabletask/agent_framework_durabletask/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/durabletask/agent_framework_durabletask/__init__.py)\n\n### .NET Durable Task Package\n\n**Installation**\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.DurableTask\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n\n### Workflow Orchestration\n\n```mermaid\ngraph LR\n    A[Start] --> B[Activity: Initialize]\n    B --> C[Activity: Process]\n    C --> D{Continue?}\n    D -->|Yes| C\n    D -->|No| E[Activity: Finalize]\n    E --> F[Complete]\n    \n    G[Orchestrator] -.-> A\n    G -.-> B\n    G -.-> C\n    G -.-> D\n    G -.-> E\n    G -.-> F\n```\n\n### Azurite Emulator Requirement\n\nWhen running Durable Task samples locally, start the Azurite emulator:\n\n```bash\naz login\nazd pipeline config\nazd up\n```\n\nOr manually:\n\n```bash\nazurite\n```\n\n资料来源：[python/samples/04-hosting/azure_functions/README.md:1-20](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/azure_functions/README.md)\n\n## Foundry Hosting\n\nFoundry Hosting provides the most comprehensive deployment option with deep integration into Azure AI Foundry. This pattern supports managed agents, model routing, and enterprise-grade security.\n\n### Python Foundry Hosting Package\n\n**Installation**\n\n```bash\npip install agent-framework-foundry-hosting\n```\n\nThe package is located at `python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py`.\n\n资料来源：[python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py)\n\n### Configuration Requirements\n\nFoundry-hosted agents require specific environment configuration:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project endpoint | Yes |\n| `FOUNDRY_MODEL` or `AZURE_AI_MODEL_DEPLOYMENT_NAME` | Model deployment name | Yes |\n| `AZURE_BEARER_TOKEN` | Authentication token (for Docker) | Docker only |\n| `AGENT_NAME` | Foundry-managed agent name | Local dev |\n\n资料来源：[python/samples/04-hosting/foundry-hosted-agents/README.md:1-40](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/foundry-hosted-agents/README.md)\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md:1-25](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md)\n\n### Environment Setup\n\n**Bash/Linux**\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://<account>.services.ai.azure.com/api/projects/<project>\"\nexport AZURE_AI_MODEL_DEPLOYMENT_NAME=\"<your-model-deployment-name>\"\n```\n\n**PowerShell**\n\n```powershell\n$env:FOUNDRY_PROJECT_ENDPOINT=\"https://<account>.services.ai.azure.com/api/projects/<project>\"\n$env:AZURE_AI_MODEL_DEPLOYMENT_NAME=\"<your-model-deployment-name>\"\n```\n\n### Foundry Hosted Agent Samples\n\nThe repository provides multiple Foundry hosting samples:\n\n| Sample | Description | Path |\n|--------|-------------|------|\n| `Hosted-TextRag` | Text-based RAG agent | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-TextRag/` |\n| `Hosted-FoundryAgent` | Direct Foundry agent hosting | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/` |\n| `Hosted-AzureSearchRag` | Azure AI Search integration | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag/` |\n| `Hosted-McpTools` | MCP tools integration | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-McpTools/` |\n| `Hosted-Files` | Bundled file handling | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/` |\n| `Hosted-Workflow-Simple` | Multi-step workflow | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/` |\n\n资料来源：[python/samples/04-hosting/README.md:1-50](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n资料来源：[dotnet/samples/04-hosting/README.md:1-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n\n## Deployment Workflows\n\n### Direct Execution (Contributors)\n\nFor local development and contribution work:\n\n```bash\ncd dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent\nAGENT_NAME=<your-agent-name> dotnet run\n```\n\nThe agent starts on `http://localhost:8088`.\n\n### Docker Deployment\n\n#### Publishing for Container Runtime\n\n```bash\ndotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out\n```\n\n#### Building the Image\n\n```bash\ndocker build -f Dockerfile.contributor -t hosted-foundry-agent .\n```\n\n#### Running the Container\n\n```bash\nexport AZURE_BEARER_TOKEN=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)\n\ndocker run --rm -p 8088:8088 \\\n  -e AGENT_NAME=hosted-foundry-agent \\\n  -e AZURE_BEARER_TOKEN=$AZURE_BEARER_TOKEN \\\n  --env-file .env \\\n  hosted-foundry-agent\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md:20-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md)\n\n## Testing Hosted Agents\n\n### Using Azure Developer CLI\n\n```bash\nazd ai agent invoke --local \"Hello!\"\n```\n\n### Using curl\n\n```bash\ncurl -X POST http://localhost:8088/responses \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"input\": \"Hello!\", \"model\": \"<your-agent-name>\"}'\n```\n\n### Testing Session Files\n\n```bash\ncd ../Using-Samples/SessionFilesClient\n$env:AGENT_ENDPOINT = \"http://localhost:8088\"\n$env:AGENT_NAME = \"hosted-files\"\ndotnet run\n\nYou> What is the total revenue in the contoso file?\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/README.md:30-50](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/README.md)\n\n## Comparison Matrix\n\n| Feature | Azure Functions | Durable Task | Foundry Hosting |\n|---------|-----------------|--------------|-----------------|\n| Stateful Execution | No | Yes | Yes |\n| Long-running Workflows | No | Yes | Yes |\n| Serverless | Yes | No | No |\n| Managed Scaling | Yes | Manual | Yes |\n| Checkpoint/Resume | No | Yes | Yes |\n| Azure AI Foundry Integration | No | No | Yes |\n| Local Development Support | Limited | Yes | Yes |\n| Docker Deployment | Yes | Yes | Yes |\n\n## Next Steps\n\n- Explore the [Azure Functions samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions) for event-driven patterns\n- Review the [Foundry hosting samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/04-hosting/FoundryHostedAgents) for enterprise deployments\n- Check the [Durable Task documentation](https://github.com/microsoft/agent-framework/tree/main/dotnet/src/Microsoft.Agents.AI.DurableTask) for orchestration patterns\n\n---\n\n<a id='observability'></a>\n\n## Observability and Telemetry\n\n### 相关页面\n\n相关主题：[Workflows and Orchestration](#workflows), [Hosting and Deployment Patterns](#hosting-patterns)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_telemetry.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_telemetry.py)\n- [dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs)\n- [docs/decisions/0003-agent-opentelemetry-instrumentation.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0003-agent-opentelemetry-instrumentation.md)\n- [python/samples/02-agents/observability/agent_observability.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/observability/agent_observability.py)\n- [dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs)\n</details>\n\n# Observability and Telemetry\n\nThe Agent Framework provides comprehensive observability capabilities through OpenTelemetry integration, enabling distributed tracing, performance metrics collection, and detailed logging across both .NET and Python implementations.\n\n## Overview\n\nObservability in the Agent Framework allows developers to:\n\n- **Trace agent invocations** across distributed systems\n- **Collect performance metrics** and timing information\n- **Log request and response payloads** (when enabled)\n- **Track errors** and capture exception details\n- **Monitor usage statistics** and token consumption\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgentBuilderExtensions.cs:1-30]()\n\nThe implementation follows the OpenTelemetry Semantic Conventions for Generative AI systems as defined in the [OpenTelemetry specification](https://opentelemetry.io/docs/specs/semconv/gen-ai/). The specification for Generative AI is still experimental and subject to change.\n\n资料来源：[docs/decisions/0003-agent-opentelemetry-instrumentation.md:1-20]()\n\n## Architecture\n\n### High-Level Component Interaction\n\n```mermaid\ngraph TD\n    A[Application] --> B[OpenTelemetry Agent Wrapper]\n    B --> C[Inner AIAgent]\n    C --> D[IChatClient]\n    D --> E[AI Provider<br/>OpenAI/Anthropic/GitHub Copilot]\n    \n    B -.-> F[OpenTelemetry Traces]\n    B -.-> G[Metrics]\n    B -.-> H[Logs]\n    \n    F --> I[OTLP Exporter]\n    G --> I\n    H --> I\n    \n    I --> J[Telemetry Backend<br/>Azure Monitor/Jaeger/...]\n```\n\n### Auto-Wiring Mechanism\n\nWhen using `OpenTelemetryAgent`, the framework automatically wraps underlying chat clients with telemetry instrumentation:\n\n```mermaid\ngraph LR\n    A[ChatClientAgent] --> B[OpenTelemetryAgent]\n    B --> C{IChatClient}\n    C -->|autoWireChatClient: true| D[Auto-wrap with<br/>OpenTelemetryChatClient]\n    C -->|Already Instrumented| E[No Additional Wrapping]\n    D --> F[Chat-Level Telemetry]\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-25]()\n\n## .NET Implementation\n\n### OpenTelemetryAgent\n\nThe `OpenTelemetryAgent` class wraps an existing `AIAgent` to add telemetry capabilities without modifying the underlying agent's behavior.\n\n**Class Declaration:**\n\n```csharp\n[Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)]\npublic sealed class OpenTelemetryAgent : AIAgent\n```\n\n**Constructor Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `innerAgent` | `AIAgent` | The underlying agent to be augmented with telemetry |\n| `sourceName` | `string?` | Optional source name for telemetry identification |\n| `autoWireChatClient` | `bool` | Auto-wrap ChatClientAgent's IChatClient with OpenTelemetryChatClient |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-40]()\n\n**Key Features:**\n\n1. **Provider Metadata Extraction**: Automatically extracts provider metadata from the inner agent via `AIAgentMetadata`.\n\n```csharp\nthis._providerName = innerAgent.GetService<AIAgentMetadata>()?.ProviderName;\n```\n\n2. **Chat Client Auto-Wiring**: When `autoWireChatClient` is `true` and the inner agent is a `ChatClientAgent`, the underlying `IChatClient` is automatically wrapped with `OpenTelemetryChatClient`.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-50]()\n\n### Builder Extension\n\nThe recommended way to add telemetry to agents is through the `AIAgentBuilder`:\n\n```csharp\npublic static AIAgentBuilder UseOpenTelemetry(\n    this AIAgentBuilder builder,\n    string? sourceName = null,\n    Action<OpenTelemetryAgent>? configure = null)\n```\n\n**Usage:**\n\n```csharp\nAIAgent agent = builder\n    .WithChatClient(chatClient)\n    .UseOpenTelemetry(sourceName: \"my-agent\")\n    .Build();\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgentBuilderExtensions.cs:1-45]()\n\n### Workflow Telemetry Options\n\nThe `WorkflowTelemetryOptions` class provides configuration for workflow-level telemetry:\n\n| Property | Type | Default | Description |\n|----------|------|---------|-------------|\n| `EnableSensitiveData` | `bool` | `false` | Include potentially sensitive information in telemetry |\n| `DisableWorkflowBuild` | `bool` | `false` | Disable `workflow.build` activities |\n| `DisableWorkflowRun` | `bool` | `false` | Disable `workflow_invoke` activities |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Observability/WorkflowTelemetryOptions.cs:1-40]()\n\n### Activity Extensions\n\nThe framework provides extension methods for creating and managing OpenTelemetry activities in workflows:\n\n```csharp\n// Creating activity spans for workflow operations\nActivitySource activitySource = new ActivitySource(\"Microsoft.Agents.AI.Workflows\");\n\n// Activity creation following semantic conventions\nvar activity = activitySource.StartActivity(\"workflow.invoke\");\n```\n\nThese extensions ensure proper tagging and attributes according to OpenTelemetry's generative AI conventions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs:1-30]()\n\n## Python Implementation\n\n### Telemetry Module\n\nThe Python SDK provides telemetry capabilities through the `_telemetry.py` module:\n\n```python\nfrom agent_framework._telemetry import configure_otel_providers\n```\n\n**Key Functions:**\n\n| Function | Description |\n|----------|-------------|\n| `configure_otel_providers()` | Configure OpenTelemetry providers with exporters |\n| `configure_otel_providers_with_env_var()` | Use standard OTEL environment variables |\n\n资料来源：[python/packages/core/agent_framework/_telemetry.py:1-50]()\n\n### Basic Configuration\n\n```python\nfrom agent_framework.observability import configure_otel_providers\n\n# Enable console exporters for development\nconfigure_otel_providers(enable_console_exporters=True)\n```\n\n资料来源：[python/samples/02-agents/observability/agent_observability.py:1-20]()\n\n### GitHub Copilot Agent Integration\n\nThe `GitHubCopilotAgent` has OpenTelemetry tracing built-in:\n\n```python\nfrom agent_framework.observability import configure_otel_providers\nfrom agent_framework.github import GitHubCopilotAgent\n\nconfigure_otel_providers(enable_console_exporters=True)\n\nasync with GitHubCopilotAgent() as agent:\n    response = await agent.run(\"Hello!\")\n```\n\n资料来源：[python/samples/02-agents/providers/github_copilot/README.md:1-30]()\n\n### Environment Variables\n\nPython observability supports standard OpenTelemetry environment variables:\n\n| Variable | Description |\n|----------|-------------|\n| `OTEL_SERVICE_NAME` | Service name for telemetry |\n| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP exporter endpoint |\n| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol (grpc, http/protobuf) |\n| `OTEL_RESOURCE_ATTRIBUTES` | Additional resource attributes |\n\n资料来源：[python/samples/02-agents/observability/README.md:1-30]()\n\n### Logging Configuration\n\nAlign Python logs with telemetry output:\n\n```python\nimport logging\n\nlogging.basicConfig(\n    format=\"[%(asctime)s - %(pathname)s:%(lineno)d - %(levelname)s] %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\n\n# Get root logger and set detailed level\nlogger = logging.getLogger()\nlogger.setLevel(logging.NOTSET)\n```\n\n资料来源：[python/samples/02-agents/observability/README.md:1-60]()\n\n## Semantic Conventions\n\nThe Agent Framework adheres to OpenTelemetry's semantic conventions for generative AI systems. Key conventions include:\n\n```mermaid\ngraph TD\n    A[AI Agent Invocation] --> B[Semantic Convention Attributes]\n    \n    B --> C[gen_ai.system]\n    B --> D[gen_ai.request.model]\n    B --> E[gen_ai.response.id]\n    B --> F[gen_ai.usage.prompt_tokens]\n    B --> G[gen_ai.usage.completion_tokens]\n    B --> H[gen_ai.response.finish_reason]\n```\n\n**Standard Attributes:**\n\n| Attribute | Description |\n|-----------|-------------|\n| `gen_ai.system` | The AI system type (e.g., \"openai\", \"anthropic\") |\n| `gen_ai.request.model` | Model identifier for the request |\n| `gen_ai.response.id` | Unique identifier for the response |\n| `gen_ai.usage.prompt_tokens` | Number of tokens in the prompt |\n| `gen_ai.usage.completion_tokens` | Number of tokens in completion |\n| `gen_ai.response.finish_reason` | Reason for completion termination |\n\n资料来源：[docs/decisions/0003-agent-opentelemetry-instrumentation.md:1-50]()\n\n## Configuration Examples\n\n### .NET: Full Agent with Telemetry\n\n```csharp\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Telemetry;\n\n// Create the builder\nIAIAgentBuilder builder = new AgentBuilder();\n\n// Configure with telemetry\nAIAgent agent = builder\n    .WithChatClient(chatClient)\n    .UseOpenTelemetry(\n        sourceName: \"my-agent\",\n        configure: agent => \n        {\n            // Additional configuration\n        })\n    .Build();\n\n// Use the agent - all invocations are automatically traced\nvar response = await agent.InvokeAsync(\"Hello, agent!\");\n```\n\n资料来源：[dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs:1-50]()\n\n### Python: Advanced Exporter Configuration\n\n```python\nfrom agent_framework.observability import configure_otel_providers\nfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\n\n# Create custom exporter\ncustom_exporter = OTLPSpanExporter(\n    endpoint=\"https://your-endpoint.azure.com\",\n    insecure=True\n)\n\n# Configure with custom exporter\nconfigure_otel_providers(\n    service_name=\"my-agent-service\",\n    span_exporter=custom_exporter,\n    enable_console_exporters=True\n)\n```\n\n资料来源：[python/samples/02-agents/observability/configure_otel_providers_with_parameters.py:1-40]()\n\n## Best Practices\n\n### 1. Consistent Source Naming\n\nUse meaningful source names to identify telemetry data:\n\n```csharp\n// Good\nbuilder.UseOpenTelemetry(sourceName: \"customer-support-agent\");\n\n// Avoid\nbuilder.UseOpenTelemetry(); // Uses default\n```\n\n### 2. Sensitive Data Handling\n\nBy default, telemetry excludes raw inputs and outputs:\n\n```csharp\nvar options = new WorkflowTelemetryOptions\n{\n    EnableSensitiveData = false // Default - excludes raw content\n};\n```\n\nOnly enable sensitive data logging when necessary and ensure proper data protection.\n\n### 3. Selective Activity Recording\n\nDisable activities that generate excessive telemetry:\n\n```csharp\nvar options = new WorkflowTelemetryOptions\n{\n    DisableWorkflowBuild = true,  // Reduce noise in build-heavy workflows\n    DisableWorkflowRun = false   // Keep run telemetry\n};\n```\n\n### 4. Provider Compatibility\n\nThe telemetry implementation adapts to the underlying AI provider:\n\n| Provider | Telemetry Support |\n|----------|-------------------|\n| OpenAI | Full |\n| Anthropic | Full |\n| Azure AI Foundry | Full |\n| GitHub Copilot | Built-in |\n\n### 5. Environment-Based Configuration\n\nUse environment variables for deployment flexibility:\n\n```bash\n# Development\nexport OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317\nexport OTEL_SERVICE_NAME=agent-dev\n\n# Production\nexport OTEL_EXPORTER_OTLP_ENDPOINT=https://telemetry.company.com\nexport OTEL_SERVICE_NAME=agent-prod\n```\n\n## Troubleshooting\n\n### Missing Telemetry Data\n\n1. Verify OpenTelemetry SDK is properly configured\n2. Check that the exporter endpoint is accessible\n3. Ensure `ActivitySource` names match between instrumentation and export\n\n### Duplicate Telemetry\n\nIf using `ChatClientAgent` with `OpenTelemetryAgent`:\n\n- Set `autoWireChatClient: false` when chat client is already instrumented\n- Avoid manually wrapping already-wrapped clients\n\n### Performance Impact\n\nTelemetry collection adds minimal overhead. For high-throughput scenarios:\n\n- Use batch exporters instead of simple exporters\n- Consider disabling verbose logging levels\n- Sample traces when full fidelity is not required\n\n## Related Documentation\n\n- [OpenTelemetry Semantic Conventions for Generative AI](https://opentelemetry.io/docs/specs/semconv/gen-ai/)\n- [Agent Framework Decision: OpenTelemetry Instrumentation](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0003-agent-opentelemetry-instrumentation.md)\n- [Python Observability Samples](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/observability/)\n- [.NET Agent OpenTelemetry Sample](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentOpenTelemetry/)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：microsoft/agent-framework\n\n摘要：发现 23 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…。\n\n## 1. 安装坑 · 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT events\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d329260309954749a2b3b2a9e7135d56 | https://github.com/microsoft/agent-framework/issues/4923 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8f9f05dcb7564f34bdd5902dcea6be27 | https://github.com/microsoft/agent-framework/issues/5785 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 3. 安全/权限坑 · 来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_49875a7dd60f480a99718cfa30b12723 | https://github.com/microsoft/agent-framework/issues/5708 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安全/权限坑 · 来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_58594f7966b84d81924da21ad789effd | https://github.com/microsoft/agent-framework/issues/5707 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_644a3ed07d2d4bfd8188392b4af687c2 | https://github.com/microsoft/agent-framework/issues/5794 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 安全/权限坑 · 来源证据：Anthropic function limit fallback can return empty final response\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Anthropic function limit fallback can return empty final response\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b61b91ca16094a448f8c0eab5e2daaa1 | https://github.com/microsoft/agent-framework/issues/5769 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 安全/权限坑 · 来源证据：Python: Add tutorial for building a custom chat client / LLM provider\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: Add tutorial for building a custom chat client / LLM provider\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_959e1eeb912a469c89f68f7f12275690 | https://github.com/microsoft/agent-framework/issues/5505 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 来源证据：python-1.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：python-1.2.1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f22ed66ae1f44b28b893aa5cbe439c92 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. 配置坑 · 来源证据：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows…\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows with typed outputs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_52da26ae3ace4acb9913ac780bfb6cd0 | https://github.com/microsoft/agent-framework/issues/5745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 10. 配置坑 · 来源证据：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_48aaa2f1026c4afd9e1a1da3a1a862a6 | https://github.com/microsoft/agent-framework/issues/5793 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 配置坑 · 来源证据：dotnet-1.5.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：dotnet-1.5.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b3d3127c36f41798428b164b5444cbb | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 配置坑 · 来源证据：python-1.2.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：python-1.2.2\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fb88b6cd86e04e199a03cfcf8a97dde6 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 能力坑 · 能力判断依赖假设\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:974445592 | https://github.com/microsoft/agent-framework | README/documentation is current enough for a first validation pass.\n\n## 14. 维护坑 · 来源证据：dotnet-1.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：dotnet-1.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e25f39a7081848689e086b1f98f92675 | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | last_activity_observed missing\n\n## 16. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 17. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:974445592 | https://github.com/microsoft/agent-framework | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 18. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 19. 安全/权限坑 · 来源证据：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_36cbde33c0a64127b95d953c65d49c54 | https://github.com/microsoft/agent-framework/issues/5798 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 20. 安全/权限坑 · 来源证据：python-1.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.2.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa3fc8cfbbad40f98ea1da9e68eeaa3f | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 21. 安全/权限坑 · 来源证据：python-1.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6df4ed99139d4fb0bc182d80b34e9d45 | https://github.com/microsoft/agent-framework/releases/tag/python-1.3.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. 维护坑 · 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:974445592 | https://github.com/microsoft/agent-framework | issue_or_pr_quality=unknown\n\n## 23. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | release_recency=unknown\n\n<!-- canonical_name: microsoft/agent-framework; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "agent-framework",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:974445592",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/microsoft/agent-framework"
        },
        {
          "evidence_id": "art_97f588e7fdde430184d67583bc8bfaf2",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/microsoft/agent-framework#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "agent-framework 说明书",
      "toc": [
        "https://github.com/microsoft/agent-framework 项目说明书",
        "目录",
        "Getting Started with Microsoft Agent Framework",
        "Overview",
        "Supported Platforms",
        "Installation",
        "Quick Start",
        "Environment Configuration",
        "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": "d81a8753d72612fd5c53e05724dc28ea7577c61c",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "README.md",
      "docs/FAQS.md",
      "docs/specs/001-foundry-sdk-alignment.md",
      "docs/specs/spec-template.md",
      "docs/design/python-package-setup.md",
      "docs/decisions/0001-agent-run-response.md",
      "docs/decisions/0006-userapproval.md",
      "docs/decisions/0026-hosted-session-identity-context.md",
      "docs/decisions/0014-feature-collections.md",
      "docs/decisions/0021-agent-skills-design.md",
      "docs/decisions/0025-foundry-toolbox-support.md",
      "docs/decisions/0008-python-subpackages.md",
      "docs/decisions/0005-python-naming-conventions.md",
      "docs/decisions/0017-agent-additional-properties.md",
      "docs/decisions/0021-provider-leading-clients.md",
      "docs/decisions/0011-create-get-agent-api.md",
      "docs/decisions/0013-python-get-response-simplification.md",
      "docs/decisions/0012-python-typeddict-options.md",
      "docs/decisions/0018-agentthread-serialization.md",
      "docs/decisions/0004-foundry-sdk-extensions.md",
      "docs/decisions/0002-agent-tools.md",
      "docs/decisions/README.md",
      "docs/decisions/adr-short-template.md",
      "docs/decisions/0024-codeact-integration.md",
      "docs/decisions/0022-chat-history-persistence-consistency.md",
      "docs/decisions/0007-agent-filtering-middleware.md",
      "docs/decisions/0003-agent-opentelemetry-instrumentation.md",
      "docs/decisions/0024-prompt-injection-defense.md",
      "docs/decisions/adr-template.md",
      "docs/decisions/0016-python-context-middleware.md",
      "docs/decisions/0010-ag-ui-support.md",
      "docs/decisions/0016-structured-output.md",
      "docs/decisions/0020-foundry-agent-type-naming.md",
      "docs/decisions/0023-foundry-evals-integration.md",
      "docs/decisions/0009-support-long-running-operations.md",
      "docs/decisions/0015-agent-run-context.md",
      "docs/decisions/0019-python-context-compaction-strategy.md",
      "docs/features/FIDES_IMPLEMENTATION_SUMMARY.md",
      "docs/features/durable-agents/AGENTS.md",
      "docs/features/durable-agents/durable-agents-ttl.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": "# frontend - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 frontend 编译的 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 的用户**：仓库包含 Skill 文档。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等 Claim：`clm_0003` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `pip install agent-framework` 证据：`README.md` Claim：`clm_0004` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：仅建议沙盒试装\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：仅建议沙盒试装\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等 Claim：`clm_0003` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0004` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\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- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`, `dotnet/.github/skills/project-structure/SKILL.md`, `dotnet/.github/skills/verify-dotnet-samples/SKILL.md`, `dotnet/.github/skills/verify-samples-tool/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：4603\n- 重要文件覆盖：40/4603\n- 证据索引条目：96\n- 角色 / Skill 条目：16\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请基于 frontend 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 frontend 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 frontend 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 16 个角色 / Skill / 项目文档条目。\n\n- **build-and-test**（skill）：How to build and test .NET projects in the Agent Framework repository. Use this when verifying or testing changes. 激活提示：当用户任务与“build-and-test”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/.github/skills/build-and-test/SKILL.md`\n- **project-structure**（skill）：Explains the project structure of the agent-framework .NET solution 激活提示：当用户任务与“project-structure”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/.github/skills/project-structure/SKILL.md`\n- **verify-dotnet-samples**（skill）：How to build, run and verify the .NET sample projects in the Agent Framework repository. Use this when a user wants to verify that the samples still function as expected. 激活提示：当用户任务与“verify-dotnet-samples”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/.github/skills/verify-dotnet-samples/SKILL.md`\n- **verify-samples-tool**（skill）：How to use the verify-samples tool to run, verify, and manage sample definitions in the Agent Framework repository. Use this when adding, updating, or running sample verification. 激活提示：当用户任务与“verify-samples-tool”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/.github/skills/verify-samples-tool/SKILL.md`\n- **unit-converter**（skill）：Convert between common units using a multiplication factor. Use when asked to convert miles, kilometers, pounds, or kilograms. 激活提示：当用户任务与“unit-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/skills/unit-converter/SKILL.md`\n- **unit-converter**（skill）：Convert between common units using a multiplication factor. Use when asked to convert miles, kilometers, pounds, or kilograms. 激活提示：当用户任务与“unit-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step04_MixedSkills/skills/unit-converter/SKILL.md`\n- **python-code-quality**（skill）： 激活提示：当用户任务与“python-code-quality”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-code-quality/SKILL.md`\n- **python-development**（skill）： 激活提示：当用户任务与“python-development”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-development/SKILL.md`\n- **python-feature-lifecycle**（skill）： 激活提示：当用户任务与“python-feature-lifecycle”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-feature-lifecycle/SKILL.md`\n- **python-package-management**（skill）： 激活提示：当用户任务与“python-package-management”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-package-management/SKILL.md`\n- **python-samples**（skill）： 激活提示：当用户任务与“python-samples”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-samples/SKILL.md`\n- **python-testing**（skill）： 激活提示：当用户任务与“python-testing”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/.github/skills/python-testing/SKILL.md`\n- **unit-converter**（skill）：Convert between common units using a multiplication factor. Use when asked to convert miles, kilometers, pounds, or kilograms. 激活提示：当用户任务与“unit-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/samples/02-agents/skills/file_based_skill/skills/unit-converter/SKILL.md`\n- **unit-converter**（skill）：Convert between common units using a multiplication factor. Use when asked to convert miles, kilometers, pounds, or kilograms. 激活提示：当用户任务与“unit-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/samples/02-agents/skills/mixed_skills/skills/unit-converter/SKILL.md`\n- **length-converter**（skill）：Convert between common length units miles, km, feet, meters using a multiplication factor. 激活提示：当用户任务与“length-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/samples/02-agents/skills/skill_filtering/skills/length-converter/SKILL.md`\n- **volume-converter**（skill）：Convert between gallons and liters using a conversion factor. 激活提示：当用户任务与“volume-converter”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`python/samples/02-agents/skills/skill_filtering/skills/volume-converter/SKILL.md`\n\n## 证据索引\n\n- 共索引 96 条证据。\n\n- **Architectural Decision Records ADRs**（documentation）：Architectural Decision Records ADRs 证据：`docs/decisions/README.md`\n- **AGENTS.md**（documentation）：Instructions for AI coding agents working on durable agents documentation. 证据：`docs/features/durable-agents/AGENTS.md`\n- **Durable agents**（documentation）：Durable agents extend the standard Microsoft Agent Framework with durable state management powered by the Durable Task framework. An ordinary Agent Framework agent runs in-process: its conversation history lives in memory and is lost when the process ends. A durable agent persists conversation history and execution state in external storage so that sessions survive process restarts, failures, and scale-out events. 证据：`docs/features/durable-agents/README.md`\n- **Vector Stores and Embeddings**（documentation）：This feature ports the vector store abstractions, embedding generator abstractions, and their implementations from Semantic Kernel into Agent Framework. The ported code follows AF's coding standards, feels native to AF, and is structured to allow data models/schemas to be reusable across both frameworks. The embedding abstraction combines the best of SK's EmbeddingGeneratorBase and MEAI's IEmbeddingGenerator . 证据：`docs/features/vector-stores-and-embeddings/README.md`\n- **Welcome to Microsoft Agent Framework!**（documentation）：! Microsoft Agent Framework docs/assets/readme-banner.png 证据：`README.md`\n- **AGENTS.md**（documentation）：Instructions for AI coding agents working in the .NET codebase. 证据：`dotnet/AGENTS.md`\n- **Get Started with Microsoft Agent Framework for C Developers**（documentation）：Get Started with Microsoft Agent Framework for C Developers 证据：`dotnet/README.md`\n- **AGENTS.md**（documentation）：Instructions for AI coding agents working in the Python codebase. 证据：`python/AGENTS.md`\n- **Get Started with Microsoft Agent Framework for Python Developers**（documentation）：Get Started with Microsoft Agent Framework for Python Developers 证据：`python/README.md`\n- **Declarative Agents**（documentation）：This folder contains sample agent definitions that can be run using the declarative agent support, for python see the declarative agent python sample folder ../../python/samples/02-agents/declarative/ . 证据：`declarative-agents/agent-samples/README.md`\n- **Declarative Workflows**（documentation）：A Declarative Workflow is defined as a single YAML file and may be executed locally no different from any regular Workflow that is defined by code. 证据：`declarative-agents/workflow-samples/README.md`\n- **A2A Agent as Function Tools**（documentation）：This sample demonstrates how to represent an A2A agent as a set of function tools, where each function tool corresponds to a skill of the A2A agent, and register these function tools with another AI agent so it can leverage the A2A agent's skills. 证据：`dotnet/samples/02-agents/A2A/A2AAgent_AsFunctionTools/README.md`\n- **Polling for A2A Agent Task Completion**（documentation）：Polling for A2A Agent Task Completion 证据：`dotnet/samples/02-agents/A2A/A2AAgent_PollingForTaskCompletion/README.md`\n- **A2A Agent Protocol Selection**（documentation）：This sample demonstrates how to select the A2A protocol binding when creating an AIAgent from an A2A agent card. 证据：`dotnet/samples/02-agents/A2A/A2AAgent_ProtocolSelection/README.md`\n- **A2A Agent Stream Reconnection**（documentation）：This sample demonstrates how to reconnect to an A2A agent's streaming response using continuation tokens, allowing recovery from stream interruptions without losing progress. 证据：`dotnet/samples/02-agents/A2A/A2AAgent_StreamReconnection/README.md`\n- **Agent-to-Agent A2A Samples**（documentation）：These samples demonstrate how to work with Agent-to-Agent A2A specific features in the Agent Framework. 证据：`dotnet/samples/02-agents/A2A/README.md`\n- **AG-UI Getting Started Samples**（documentation）：This directory contains samples that demonstrate how to build AG-UI Agent UI Protocol servers and clients using the Microsoft Agent Framework. 证据：`dotnet/samples/02-agents/AGUI/README.md`\n- **OpenTelemetry Aspire Demo with Azure OpenAI**（documentation）：OpenTelemetry Aspire Demo with Azure OpenAI 证据：`dotnet/samples/02-agents/AgentOpenTelemetry/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_A2A/README.md`\n- **Creating an AIAgent with Anthropic**（documentation）：This sample demonstrates how to create an AIAgent using Anthropic Claude models as the underlying inference service. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_Anthropic/README.md`\n- **Classic Foundry Agents**（documentation）：This sample demonstrates how to create an agent using the classic Foundry Agents experience. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_AzureAIAgentsPersistent/README.md`\n- **New Foundry Agents**（documentation）：This sample demonstrates how to create an agent using the new Foundry Agents experience. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_AzureAIProject/README.md`\n- **Overview**（documentation）：This sample shows how to use the OpenAI SDK to create and use a simple AI agent with any model hosted in Microsoft Foundry. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_AzureFoundryModel/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_AzureOpenAIChatCompletion/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_AzureOpenAIResponses/README.md`\n- **Agent with Custom Implementation**（documentation）：This sample demonstrates how to create a fully custom agent implementation without relying on external AI services. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_CustomImplementation/README.md`\n- **Prerequisites**（documentation）：⚠️ WARNING: Container Recommendation GitHub Copilot can execute tools and commands that may interact with your system. For safety, it is strongly recommended to run this sample in a containerized environment e.g., Docker, Dev Container to avoid unintended consequences to your machine. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_GitHubCopilot/README.md`\n- **Creating an AIAgent with Google Gemini**（documentation）：Creating an AIAgent with Google Gemini 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_GoogleGemini/README.md`\n- **Prerequisites**（documentation）：WARNING: ONNX doesn't support function calling, so any function tools passed to the agent will be ignored. 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_ONNX/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_Ollama/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_OpenAIChatCompletion/README.md`\n- **Prerequisites**（documentation）：Before you begin, ensure you have the following prerequisites: 证据：`dotnet/samples/02-agents/AgentProviders/Agent_With_OpenAIResponses/README.md`\n- **Creating an AIAgent instance for various providers**（documentation）：Creating an AIAgent instance for various providers 证据：`dotnet/samples/02-agents/AgentProviders/README.md`\n- **File-Based Agent Skills Sample**（documentation）：This sample demonstrates how to use file-based Agent Skills with a ChatClientAgent . 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/README.md`\n- **Code-Defined Agent Skills Sample**（documentation）：This sample demonstrates how to define Agent Skills entirely in code using AgentInlineSkill . 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step02_CodeDefinedSkills/README.md`\n- **Class-Based Agent Skills Sample**（documentation）：This sample demonstrates how to define Agent Skills as C classes using AgentClassSkill with attributes for automatic script and resource discovery. 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step03_ClassBasedSkills/README.md`\n- **Mixed Agent Skills Sample Advanced**（documentation）：This sample demonstrates an advanced scenario : combining multiple skill types in a single agent using AgentSkillsProviderBuilder . 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step04_MixedSkills/README.md`\n- **Agent Skills with Dependency Injection**（documentation）：Agent Skills with Dependency Injection 证据：`dotnet/samples/02-agents/AgentSkills/Agent_Step05_SkillsWithDI/README.md`\n- **AgentSkills Samples**（documentation）：Samples demonstrating Agent Skills capabilities. Each sample shows a different way to define and use skills. 证据：`dotnet/samples/02-agents/AgentSkills/README.md`\n- **Running a simple agent with Anthropic**（documentation）：Running a simple agent with Anthropic 证据：`dotnet/samples/02-agents/AgentWithAnthropic/Agent_Anthropic_Step01_Running/README.md`\n- **Using reasoning with Anthropic agents**（documentation）：Using reasoning with Anthropic agents 证据：`dotnet/samples/02-agents/AgentWithAnthropic/Agent_Anthropic_Step02_Reasoning/README.md`\n- **Using Function Tools with Anthropic agents**（documentation）：Using Function Tools with Anthropic agents 证据：`dotnet/samples/02-agents/AgentWithAnthropic/Agent_Anthropic_Step03_UsingFunctionTools/README.md`\n- **Using Anthropic Skills with agents**（documentation）：This sample demonstrates how to use Anthropic-managed Skills with AI agents. Skills are pre-built capabilities provided by Anthropic that can be used with the Claude API. 证据：`dotnet/samples/02-agents/AgentWithAnthropic/Agent_Anthropic_Step04_UsingSkills/README.md`\n- **Getting started with agents using Anthropic**（documentation）：Getting started with agents using Anthropic 证据：`dotnet/samples/02-agents/AgentWithAnthropic/README.md`\n- **AgentWithCodeAct Step01 Interpreter**（documentation）：AgentWithCodeAct Step01 Interpreter 证据：`dotnet/samples/02-agents/AgentWithCodeAct/AgentWithCodeAct_Step01_Interpreter/README.md`\n- **AgentWithCodeAct Step02 ToolEnabled**（documentation）：AgentWithCodeAct Step02 ToolEnabled 证据：`dotnet/samples/02-agents/AgentWithCodeAct/AgentWithCodeAct_Step02_ToolEnabled/README.md`\n- **AgentWithCodeAct Step03 ManualWiring**（documentation）：AgentWithCodeAct Step03 ManualWiring 证据：`dotnet/samples/02-agents/AgentWithCodeAct/AgentWithCodeAct_Step03_ManualWiring/README.md`\n- **Agent Framework CodeAct Hyperlight Samples**（documentation）：Agent Framework CodeAct Hyperlight Samples 证据：`dotnet/samples/02-agents/AgentWithCodeAct/README.md`\n- **Agent with Memory Using Microsoft Foundry**（documentation）：Agent with Memory Using Microsoft Foundry 证据：`dotnet/samples/02-agents/AgentWithMemory/AgentWithMemory_Step04_MemoryUsingFoundry/README.md`\n- **Bounded Chat History with Vector Store Overflow**（documentation）：Bounded Chat History with Vector Store Overflow 证据：`dotnet/samples/02-agents/AgentWithMemory/AgentWithMemory_Step05_BoundedChatHistory/README.md`\n- **Agent Framework Retrieval Augmented Generation RAG**（documentation）：Agent Framework Retrieval Augmented Generation RAG 证据：`dotnet/samples/02-agents/AgentWithMemory/README.md`\n- **Creating an Agent from a ChatClient**（documentation）：Creating an Agent from a ChatClient 证据：`dotnet/samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/README.md`\n- **Creating an Agent from an OpenAIResponseClient**（documentation）：Creating an Agent from an OpenAIResponseClient 证据：`dotnet/samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/README.md`\n- **Managing Conversation State with OpenAI**（documentation）：Managing Conversation State with OpenAI 证据：`dotnet/samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step05_Conversation/README.md`\n- **Code Interpreter File Download OpenAI**（documentation）：Code Interpreter File Download OpenAI 证据：`dotnet/samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step06_CodeInterpreterFileDownload/README.md`\n- **Agent Framework with OpenAI**（documentation）：These samples show how to use the Agent Framework with the OpenAI exchange types. 证据：`dotnet/samples/02-agents/AgentWithOpenAI/README.md`\n- **Agent Framework Retrieval Augmented Generation RAG with an external Vector Store with a custom schema**（documentation）：Agent Framework Retrieval Augmented Generation RAG with an external Vector Store with a custom schema 证据：`dotnet/samples/02-agents/AgentWithRAG/AgentWithRAG_Step02_CustomVectorStoreRAG/README.md`\n- **Agent Framework Retrieval Augmented Generation RAG with Neo4j GraphRAG**（documentation）：Agent Framework Retrieval Augmented Generation RAG with Neo4j GraphRAG 证据：`dotnet/samples/02-agents/AgentWithRAG/AgentWithRAG_Step05_Neo4jGraphRAG/README.md`\n- **Agent Framework Retrieval Augmented Generation RAG**（documentation）：Agent Framework Retrieval Augmented Generation RAG 证据：`dotnet/samples/02-agents/AgentWithRAG/README.md`\n- **Structured Output with ChatClientAgent**（documentation）：Structured Output with ChatClientAgent 证据：`dotnet/samples/02-agents/Agents/Agent_Step02_StructuredOutput/README.md`\n- 其余 36 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/decisions/README.md`, `docs/features/durable-agents/AGENTS.md`, `docs/features/durable-agents/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/decisions/README.md`, `docs/features/durable-agents/AGENTS.md`, `docs/features/durable-agents/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- **Getting Started with Microsoft Agent Framework**：importance `high`\n  - source_paths: python/README.md, dotnet/README.md, python/DEV_SETUP.md, python/pyproject.toml, dotnet/src/Microsoft.Agents.AI/Microsoft.Agents.AI.csproj\n- **System Architecture**：importance `high`\n  - source_paths: docs/design/python-package-setup.md, python/packages/core/agent_framework/__init__.py, dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs, docs/decisions/0008-python-subpackages.md, docs/decisions/0001-agent-run-response.md\n- **Agent System**：importance `high`\n  - source_paths: python/packages/core/agent_framework/_agents.py, python/packages/core/agent_framework/_types.py, dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs, dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs, dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs\n- **Tools and Skills**：importance `high`\n  - source_paths: python/packages/core/agent_framework/_tools.py, python/packages/core/agent_framework/_skills.py, dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs, dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs, docs/decisions/0021-agent-skills-design.md\n- **Workflows and Orchestration**：importance `high`\n  - source_paths: python/packages/core/agent_framework/_workflows/__init__.py, python/packages/core/agent_framework/_workflows/_workflow.py, python/packages/core/agent_framework/_workflows/_runner.py, dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs, dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs\n- **Middleware System**：importance `medium`\n  - source_paths: python/packages/core/agent_framework/_middleware.py, dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs, python/samples/02-agents/middleware/function_based_middleware.py, dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs, docs/decisions/0007-agent-filtering-middleware.md\n- **AI Provider Integration**：importance `high`\n  - source_paths: python/packages/openai/agent_framework_openai/__init__.py, python/packages/anthropic/agent_framework_anthropic/__init__.py, python/packages/foundry/agent_framework_foundry/__init__.py, dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs, dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs\n- **Sessions, History, and State Management**：importance `medium`\n  - source_paths: python/packages/core/agent_framework/_sessions.py, python/packages/core/agent_framework/_compaction.py, dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs, python/packages/redis/agent_framework_redis/__init__.py, dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `d81a8753d72612fd5c53e05724dc28ea7577c61c`\n- inspected_files: `README.md`, `docs/FAQS.md`, `docs/specs/001-foundry-sdk-alignment.md`, `docs/specs/spec-template.md`, `docs/design/python-package-setup.md`, `docs/decisions/0001-agent-run-response.md`, `docs/decisions/0006-userapproval.md`, `docs/decisions/0026-hosted-session-identity-context.md`, `docs/decisions/0014-feature-collections.md`, `docs/decisions/0021-agent-skills-design.md`, `docs/decisions/0025-foundry-toolbox-support.md`, `docs/decisions/0008-python-subpackages.md`, `docs/decisions/0005-python-naming-conventions.md`, `docs/decisions/0017-agent-additional-properties.md`, `docs/decisions/0021-provider-leading-clients.md`, `docs/decisions/0011-create-get-agent-api.md`, `docs/decisions/0013-python-get-response-simplification.md`, `docs/decisions/0012-python-typeddict-options.md`, `docs/decisions/0018-agentthread-serialization.md`, `docs/decisions/0004-foundry-sdk-extensions.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: 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT events\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_d329260309954749a2b3b2a9e7135d56 | https://github.com/microsoft/agent-framework/issues/4923 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_8f9f05dcb7564f34bdd5902dcea6be27 | https://github.com/microsoft/agent-framework/issues/5785 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_49875a7dd60f480a99718cfa30b12723 | https://github.com/microsoft/agent-framework/issues/5708 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_58594f7966b84d81924da21ad789effd | https://github.com/microsoft/agent-framework/issues/5707 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_644a3ed07d2d4bfd8188392b4af687c2 | https://github.com/microsoft/agent-framework/issues/5794 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：Anthropic function limit fallback can return empty final response\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Anthropic function limit fallback can return empty final response\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_b61b91ca16094a448f8c0eab5e2daaa1 | https://github.com/microsoft/agent-framework/issues/5769 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：Python: Add tutorial for building a custom chat client / LLM provider\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: Add tutorial for building a custom chat client / LLM provider\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_959e1eeb912a469c89f68f7f12275690 | https://github.com/microsoft/agent-framework/issues/5505 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 来源证据：python-1.2.1\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：python-1.2.1\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_f22ed66ae1f44b28b893aa5cbe439c92 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 来源证据：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows…\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows with typed outputs\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_52da26ae3ace4acb9913ac780bfb6cd0 | https://github.com/microsoft/agent-framework/issues/5745 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_48aaa2f1026c4afd9e1a1da3a1a862a6 | https://github.com/microsoft/agent-framework/issues/5793 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\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项目：microsoft/agent-framework\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- 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]（high）：可能影响升级、迁移或版本选择。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\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/microsoft/agent-framework 项目说明书\n\n生成时间：2026-05-15 12:31:29 UTC\n\n## 目录\n\n- [Getting Started with Microsoft Agent Framework](#getting-started)\n- [System Architecture](#architecture-overview)\n- [Agent System](#agents)\n- [Tools and Skills](#tools-and-skills)\n- [Workflows and Orchestration](#workflows)\n- [Middleware System](#middleware)\n- [AI Provider Integration](#provider-integration)\n- [Sessions, History, and State Management](#sessions-and-history)\n- [Hosting and Deployment Patterns](#hosting-patterns)\n- [Observability and Telemetry](#observability)\n\n<a id='getting-started'></a>\n\n## Getting Started with Microsoft Agent Framework\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Agent System](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/README.md](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n- [README.md](https://github.com/microsoft/agent-framework/blob/main/README.md)\n- [python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n- [python/samples/02-agents/skills/code_defined_skill/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n- [python/packages/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/declarative/README.md)\n- [python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n- [python/packages/github_copilot/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/github_copilot/README.md)\n- [python/packages/azure-contentunderstanding/samples/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/azure-contentunderstanding/samples/README.md)\n- [dotnet/src/Shared/Foundry/Agents/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Shared/Foundry/Agents/README.md)\n- [dotnet/src/Microsoft.Agents.AI.DurableTask/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n</details>\n\n# Getting Started with Microsoft Agent Framework\n\n## Overview\n\nMicrosoft Agent Framework is a comprehensive, multi-language framework for building intelligent agents that integrate with various AI services and providers. The framework enables developers to create agents capable of natural language understanding, tool usage, multi-turn conversations, and complex workflow orchestration.\n\nThe framework supports two primary ecosystems:\n\n| Language | Package Manager | Core Package |\n|----------|-----------------|--------------|\n| Python | pip | `agent-framework`, `agent-framework-core` |\n| .NET | NuGet | `Microsoft.Agents.AI` |\n\n资料来源：[python/README.md:1-40](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n## Supported Platforms\n\n| Component | Requirements |\n|-----------|--------------|\n| Python | 3.10+ |\n| Operating Systems | Windows, macOS, Linux |\n| .NET | .NET 8+ |\n\n资料来源：[python/README.md:36-39](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n## Installation\n\n### Python Installation\n\nThe framework offers two installation approaches depending on your use case:\n\n#### Development Mode (Full Installation)\n\nFor exploring or developing locally with all features:\n\n```bash\npip install agent-framework\n```\n\nThis installs the core package and all integration sub-packages, ensuring all features are available without additional configuration steps.\n\n资料来源：[python/README.md:10-15](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n#### Selective Installation\n\nFor lightweight environments with specific integration needs:\n\n| Package | Command | Description |\n|---------|---------|-------------|\n| Core Only | `pip install agent-framework-core` | Azure OpenAI, OpenAI support + workflows |\n| + Azure AI Foundry | `pip install agent-framework-foundry` | Azure AI Foundry integration |\n| + Copilot Studio | `pip install agent-framework-copilotstudio --pre` | Microsoft Copilot Studio (preview) |\n\nReleased packages (`agent-framework`, `agent-framework-core`, `agent-framework-foundry`) no longer require the `--pre` flag, while preview connectors like `agent-framework-copilotstudio` still do.\n\n资料来源：[python/README.md:17-34](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n### .NET Installation\n\nFor .NET projects, add the appropriate package reference to your `.csproj` file:\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\nFor Azure Functions hosting:\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.Hosting.AzureFunctions\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Microsoft.Agents.AI.csproj](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Microsoft.Agents.AI.csproj)\n\n## Quick Start\n\n### Python: Basic Agent\n\n```python\nimport asyncio\nfrom agent_framework import Agent, AzureCliCredential\nfrom agent_framework.integrations.azure_ai import FoundryChatClient\nimport os\n\nasync def main():\n    agent = Agent(\n        client=FoundryChatClient(\n            credential=AzureCliCredential(),\n        ),\n        name=\"HaikuAgent\",\n        instructions=\"You are an upbeat assistant that writes beautifully.\",\n    )\n\n    print(await agent.run(\"Write a haiku about Microsoft Agent Framework.\"))\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n资料来源：[README.md:30-50](https://github.com/microsoft/agent-framework/blob/main/README.md)\n\n### .NET: Basic Agent\n\n```csharp\nusing Azure.AI.Projects;\nusing Azure.Identity;\nusing Microsoft.Agents.AI;\n\nstring endpoint = Environment.GetEnvironmentVariable(\"AZURE_AI_PROJECT_ENDPOINT\") \n    ?? throw new InvalidOperationException(\"AZURE_AI_PROJECT_ENDPOINT is not set.\");\nstring deploymentName = Environment.GetEnvironmentVariable(\"AZURE_AI_MODEL_DEPLOYMENT_NAME\") \n    ?? \"gpt-5.4-mini\";\n\nAIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())\n    .AsAIAgent(model: deploymentName, instructions: \"You are an upbeat assistant.\", name: \"HaikuAgent\");\n\nConsole.WriteLine(await agent.RunAsync(\"Write a haiku about Microsoft Agent Framework.\"));\n```\n\n资料来源：[README.md:52-65](https://github.com/microsoft/agent-framework/blob/main/README.md)\n\n## Environment Configuration\n\nSet API keys and configuration as environment variables or in a `.env` file at your project root:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project endpoint | Yes |\n| `FOUNDRY_MODEL` | Model deployment name (defaults to `gpt-4o`) | No |\n| `AZURE_AI_PROJECT_ENDPOINT` | Alternative endpoint variable | Yes |\n| `AZURE_AI_MODEL_DEPLOYMENT_NAME` | Model deployment name | No |\n\n资料来源：[python/samples/01-get-started/README.md:9-13](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Core Concepts\n\n### Agent Architecture\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Agent]\n    B --> C[AI Client]\n    C --> D[Azure AI Foundry / OpenAI / Claude]\n    B --> E[Tools]\n    B --> F[Memory / Session]\n    E --> G[Function Calls]\n    F --> H[Context Preservation]\n    G --> I[Action Execution]\n    I --> B\n```\n\n### Key Components\n\n| Component | Python Package | .NET Namespace | Purpose |\n|-----------|---------------|----------------|---------|\n| Agent | `agent_framework` | `Microsoft.Agents.AI` | Core agent implementation |\n| Chat Client | `agent_framework.integrations.azure_ai` | `Azure.AI.Projects` | AI service connectivity |\n| Tools | `@tool` decorator | `AITool` attribute | Function definitions |\n| Sessions | `AgentSession` | `IAgentSession` | Multi-turn conversation state |\n| Context | `ContextProvider` | `IContextProvider` | Dynamic context injection |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:15-30](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n\n## Progressive Learning Samples (Python)\n\nThe framework provides a progressive set of samples in `python/samples/01-get-started/`:\n\n| Sample | File | Learning Objective |\n|--------|------|-------------------|\n| 1 | `01_hello_agent.py` | Create your first agent and run it (streaming and non-streaming) |\n| 2 | `02_add_tools.py` | Define a function tool with `@tool` and attach it to an agent |\n| 3 | `03_multi_turn.py` | Keep conversation history across turns with `AgentSession` |\n| 4 | `04_memory.py` | Add dynamic context with a custom `ContextProvider` |\n| 5 | `05_functional_workflow_with_agents.py` | Call agents inside a functional workflow |\n| 6 | `06_functional_workflow_basics.py` | Write a workflow as a plain async function |\n| 7 | `07_first_graph_workflow.py` | Chain executors into a graph workflow with edges |\n| 8 | `08_host_your_agent.py` | Host your agent in various environments |\n\n资料来源：[python/samples/01-get-started/README.md:17-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Authentication\n\nThe framework supports multiple authentication methods:\n\n| Provider | Python Credential | .NET Credential |\n|----------|-------------------|-----------------|\n| Azure AI Foundry | `AzureCliCredential()` | `DefaultAzureCredential()` |\n| Azure Content Understanding | `AzureCliCredential()` | `DefaultAzureCredential()` |\n| GitHub Copilot | API Key-based | API Key-based |\n\nFor Azure-based authentication, run `az login` in your terminal before executing samples:\n\n```bash\naz login\n```\n\n资料来源：[python/samples/02-agents/skills/code_defined_skill/README.md:15-17](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n\n## Integration Packages\n\n### Python Integrations\n\n| Package | Purpose | Install Command |\n|---------|---------|-----------------|\n| `agent-framework-core` | Core framework with Azure OpenAI and OpenAI | Default |\n| `agent-framework-foundry` | Azure AI Foundry integration | Default |\n| `agent-framework-claude` | Claude Agent SDK integration | `pip install agent-framework-claude --pre` |\n| `agent-framework-github-copilot` | GitHub Copilot integration | `pip install agent-framework-github-copilot --pre` |\n| `agent-framework-declarative` | YAML-based agent specification | `pip install agent-framework-declarative --pre` |\n| `agent-framework-copilotstudio` | Microsoft Copilot Studio | `pip install agent-framework-copilotstudio --pre` |\n\n#### Claude Agent\n\nThe Claude agent enables integration with Claude Agent SDK, allowing interaction with Claude's agentic capabilities through the Agent Framework.\n\n```bash\npip install agent-framework-claude --pre\n```\n\n资料来源：[python/packages/claude/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n#### GitHub Copilot Agent\n\nThe GitHub Copilot agent enables integration with GitHub Copilot for agentic capabilities:\n\n```bash\npip install agent-framework-github-copilot --pre\n```\n\n资料来源：[python/packages/github_copilot/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/github_copilot/README.md)\n\n#### Declarative Agents\n\nThe declarative package provides support for building agents based on YAML specifications:\n\n```bash\npip install agent-framework-declarative --pre\n```\n\n资料来源：[python/packages/declarative/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/python/packages/declarative/README.md)\n\n### .NET Integrations\n\n| Package | Purpose |\n|---------|---------|\n| `Microsoft.Agents.AI` | Core AI library |\n| `Microsoft.Agents.AI.Hosting.OpenAI` | OpenAI hosting |\n| `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot agent |\n| `Microsoft.Agents.AI.AzureAI.Persistent` | Azure AI persistent agents (deprecated) |\n| `Microsoft.Agents.AI.DurableTask` | Durable Task integration for stateful workflows |\n| `Microsoft.Agents.AI.Hosting.AzureFunctions` | Azure Functions hosting |\n| `Aspire.Hosting.AgentFramework.DevUI` | Aspire-based DevUI hosting |\n\n#### Creating a GitHub Copilot Agent (.NET)\n\n```csharp\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs:15-25](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Agent Skills\n\nAgent Skills enable domain-specific capabilities with instructions, resources, and scripts. The framework follows the [Agent Skills specification](https://agentskills.io/specification).\n\n### Skill Types\n\n| Skill Type | Python | .NET |\n|------------|--------|------|\n| File-based | `AgentFileSkill` | `AgentFileSkill` |\n| Code-defined | `AgentInlineSkill` | `AgentInlineSkill` |\n| Declarative | YAML-based | N/A |\n\n### Skill Configuration Options (.NET)\n\n```csharp\npublic sealed class AgentSkillsProviderOptions\n{\n    /// <summary>\n    /// Custom system prompt template containing {skills}, {resource_instructions}, {script_instructions}\n    /// </summary>\n    public string? SkillsInstructionPrompt { get; set; }\n\n    /// <summary>\n    /// Require script execution approval (default: false)\n    /// </summary>\n    public bool ScriptApproval { get; set; }\n\n    /// <summary>\n    /// Disable caching of tools and instructions (default: false)\n    /// </summary>\n    public bool DisableCaching { get; set; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs:14-35](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs)\n\n### Skill Content Structure\n\nThe skill content is structured as XML, containing:\n\n```xml\n<name>{skill_name}</name>\n<description>{skill_description}</description>\n<instructions>\n{skill_instructions}\n</instructions>\n<resources>\n{resource_definitions}\n</resources>\n<scripts>\n{script_definitions}\n</scripts>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs:20-40](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs)\n\n## Azure Content Understanding Integration\n\nThe framework supports Azure Content Understanding for document, image, audio, and video analysis:\n\n| Sample | Description | Run Command |\n|--------|-------------|-------------|\n| Document Q&A | Upload PDF, extract info with CU | `uv run samples/01-get-started/01_document_qa.py` |\n| Multi-Turn Session | AgentSession persistence | `uv run samples/01-get-started/02_multi_turn_session.py` |\n| Multi-Modal Chat | PDF + audio + video analysis | `uv run samples/01-get-started/03_multimodal_chat.py` |\n| Invoice Processing | Structured field extraction | `uv run samples/01-get-started/04_invoice_processing.py` |\n\nRequired environment variables:\n\n```\nFOUNDRY_PROJECT_ENDPOINT=https://your-project.services.ai.azure.com\nFOUNDRY_MODEL=gpt-4.1\nAZURE_CONTENTUNDERSTANDING_ENDPOINT=https://your-cu-resource.cognitiveservices.azure.com/\n```\n\n资料来源：[python/packages/azure-contentunderstanding/samples/README.md:1-30](https://github.com/microsoft/agent-framework/blob/main/python/packages/azure-contentunderstanding/samples/README.md)\n\n## Durable Task Integration (.NET)\n\nFor stateful, long-running workflows, use the DurableTask integration:\n\n```bash\ndotnet add package Microsoft.Agents.AI.DurableTask\n```\n\nThis package enables building stateful agents that can handle complex orchestration scenarios with checkpointing and replay capabilities.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n\n## Development Tools\n\n### DevUI Sample Application\n\nDevUI is a sample application for getting started with the Agent Framework:\n\n```tsx\n// Features displayed in settings modal\ninterface ServerInfo {\n  version: string;\n  runtime: string;\n  uiMode: string;\n  capabilities?: {\n    instrumentation?: boolean;\n    // ... other capabilities\n  };\n}\n```\n\n资料来源：[python/packages/devui/frontend/src/components/layout/settings-modal.tsx:5-20](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/layout/settings-modal.tsx)\n\n### Sample Gallery\n\nThe DevUI includes a Sample Gallery for browsing and downloading curated examples:\n\n```mermaid\ngraph LR\n    A[Sample Gallery] --> B[Beginner Examples]\n    A --> C[Advanced Examples]\n    B --> D[Download & Run Locally]\n    C --> D\n```\n\n资料来源：[python/packages/devui/frontend/src/components/features/gallery/gallery-view.tsx:10-25](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/features/gallery/gallery-view.tsx)\n\n## Workflow Orchestration\n\nThe framework supports multiple workflow patterns:\n\n```mermaid\ngraph TD\n    A[Functional Workflow] --> B[Plain Async Functions]\n    A --> C[Agent Calls within Workflows]\n    D[Graph Workflow] --> E[Chained Executors]\n    D --> F[Edges between Nodes]\n    E --> G[Complex Routing]\n```\n\n### Functional Workflow Pattern\n\nWrite workflows as plain async functions:\n\n```python\nfrom agent_framework import workflow\n\n@workflow\nasync def my_workflow(agent, input_data):\n    result = await agent.process(input_data)\n    return result\n```\n\n### Graph Workflow Pattern\n\nChain executors into a graph workflow with edges:\n\n```python\nfrom agent_framework.graph import Graph, Node, Edge\n\ngraph = Graph()\ngraph.add_node(Node(\"start\", executor_a))\ngraph.add_node(Node(\"middle\", executor_b))\ngraph.add_node(Node(\"end\", executor_c))\n\ngraph.add_edge(Edge(\"start\", \"middle\"))\ngraph.add_edge(Edge(\"middle\", \"end\"))\n```\n\n资料来源：[python/samples/01-get-started/README.md:25-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Next Steps\n\n| Resource | Purpose |\n|----------|---------|\n| [Agent Skills Specification](https://agentskills.io/) | Skill definition standard |\n| [Documentation](https://github.com/microsoft/agent-framework) | Full framework docs |\n| [Azure Functions Samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/) | .NET hosting examples |\n| [File-Based Skills Sample](../file_based_skill/) | Skill implementation patterns |\n| [Mixed Skills Sample](../mixed_skills/) | Combining multiple skill types |\n\n资料来源：[python/samples/02-agents/skills/code_defined_skill/README.md:25-30](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/code_defined_skill/README.md)\n\n---\n\n<a id='architecture-overview'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Getting Started with Microsoft Agent Framework](#getting-started), [Agent System](#agents), [Workflows and Orchestration](#workflows)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docs/design/python-package-setup.md](https://github.com/microsoft/agent-framework/blob/main/docs/design/python-package-setup.md)\n- [python/packages/core/agent_framework/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n- [docs/decisions/0008-python-subpackages.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0008-python-subpackages.md)\n- [docs/decisions/0001-agent-run-response.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0001-agent-run-response.md)\n- [dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n- [python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n- [dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n</details>\n\n# System Architecture\n\n## Overview\n\nThe Microsoft Agent Framework is a cross-platform, multi-language framework designed for building AI-powered agents with tool-calling capabilities, workflow orchestration, and extensible integrations. The architecture follows a unified conceptual model implemented in both Python (3.10+) and .NET, enabling developers to create agents that interact with various AI backends while maintaining consistent APIs and patterns across platforms.\n\nThe framework's primary purpose is to abstract the complexity of AI agent development, providing a declarative approach to defining agent behavior, tools, memory, and workflows. It supports integration with Azure AI Foundry, OpenAI, GitHub Copilot, Anthropic Claude, and Microsoft Copilot Studio.\n\n资料来源：[docs/design/python-package-setup.md](https://github.com/microsoft/agent-framework/blob/main/docs/design/python-package-setup.md)\n\n## High-Level Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Client Applications\"\n        A[Python Apps]\n        B[.NET Apps]\n    end\n    \n    subgraph \"Agent Framework Core\"\n        C[Agent Abstractions]\n        D[Workflow Engine]\n        E[Skill System]\n        F[Memory/Context Providers]\n    end\n    \n    subgraph \"AI Backend Integrations\"\n        G[Azure AI Foundry]\n        H[OpenAI / Azure OpenAI]\n        I[GitHub Copilot]\n        J[Anthropic Claude]\n        K[Copilot Studio]\n    end\n    \n    A --> C\n    B --> C\n    C --> D\n    C --> E\n    C --> F\n    C --> G\n    C --> H\n    C --> I\n    C --> J\n    C --> K\n```\n\n## Core Architecture Components\n\n### Agent Abstraction Layer\n\nThe central abstraction in the framework is the `AIAgent` interface, which defines the contract for all agent implementations. This abstraction enables loose coupling between client code and specific AI backend implementations.\n\n#### Python Implementation\n\nIn Python, the `Agent` class serves as the primary agent implementation, accepting a chat client and configuration options:\n\n```python\nagent = Agent(\n    client=FoundryChatClient(\n        credential=AzureCliCredential(),\n    ),\n    name=\"MyAgent\",\n    instructions=\"You are a helpful assistant.\",\n    tools=[my_tool]\n)\n```\n\n资料来源：[python/packages/core/agent_framework/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/__init__.py)\n\n#### .NET Implementation\n\nIn .NET, the `ChatClientAgent` class provides the core agent functionality with dependency injection support:\n\n```csharp\npublic sealed class ChatClientAgent : AIAgent\n{\n    public ChatClientAgent(\n        IChatClient chatClient,\n        string? instructions = null,\n        string? name = null,\n        string? description = null,\n        IList<AITool>? tools = null,\n        ILoggerFactory? loggerFactory = null,\n        IServiceProvider? services = null);\n}\n```\n\nThe agent accepts tools that can be invoked during conversations, and all provided tools are invoked without user approval by default. Developers should require explicit approval for tools that have side effects or access sensitive data.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### Chat Client Architecture\n\nThe framework uses a chat client abstraction pattern to separate agent logic from the underlying AI service implementation.\n\n| Chat Client | Language | Description |\n|-------------|----------|-------------|\n| `FoundryChatClient` | Python/.NET | Azure AI Foundry integration |\n| `OpenAIChatClient` | Python | OpenAI and Azure OpenAI support |\n| `CopilotClient` | .NET | GitHub Copilot integration |\n| `ClaudeClient` | Python | Anthropic Claude integration |\n\n#### Client Configuration Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `credential` | `AzureCliCredential` / `DefaultAzureCredential` | Yes (Foundry) | Authentication credential |\n| `project_endpoint` | string | Yes (Foundry) | Azure AI Foundry project endpoint |\n| `model` | string | No | Model deployment name (defaults vary) |\n| `temperature` | float | No | Sampling temperature (0.0-2.0) |\n| `top_p` | float | No | Nucleus sampling parameter |\n| `response_format` | object | No | Structured output format |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n## Package Architecture\n\n### Python Package Structure\n\nThe Python implementation uses a modular package structure allowing selective installation based on required integrations:\n\n```mermaid\ngraph TD\n    A[agent-framework] --> B[agent-framework-core]\n    A --> C[agent-framework-foundry]\n    A --> D[agent-framework-copilotstudio]\n    \n    B --> E[OpenAI Support]\n    B --> F[Workflow Engine]\n    B --> G[Skill System]\n    \n    C --> B\n    D --> B\n```\n\n#### Package Descriptions\n\n| Package | Description | Install Command |\n|---------|-------------|-----------------|\n| `agent-framework` | Full framework with all sub-packages | `pip install agent-framework` |\n| `agent-framework-core` | Core agent, workflow, and OpenAI support | `pip install agent-framework-core` |\n| `agent-framework-foundry` | Azure AI Foundry integration | `pip install agent-framework-foundry` |\n| `agent-framework-copilotstudio` | Microsoft Copilot Studio (preview) | `pip install agent-framework-copilotstudio --pre` |\n| `agent-framework-claude` | Anthropic Claude integration (preview) | `pip install agent-framework-claude --pre` |\n| `agent-framework-github-copilot` | GitHub Copilot integration (preview) | `pip install agent-framework-github-copilot --pre` |\n\nThe core package includes Azure OpenAI and OpenAI support by default, along with workflows and orchestrations.\n\n资料来源：[docs/decisions/0008-python-subpackages.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0008-python-subpackages.md)\n\n### .NET Package Structure\n\nThe .NET implementation uses a shared library pattern with dependency injection:\n\n```xml\n<PropertyGroup>\n  <InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>\n</PropertyGroup>\n```\n\nCore namespaces include:\n\n| Namespace | Purpose |\n|-----------|---------|\n| `Microsoft.Agents.AI` | Core agent abstractions and implementations |\n| `Microsoft.Agents.AI.Abstractions` | Interface definitions |\n| `Microsoft.Agents.AI.AzureAI` | Azure AI Foundry integration |\n| `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot integration |\n| `Microsoft.Agents.AI.Skills` | Skill-based agent configuration |\n\n资料来源：[dotnet/src/Shared/Foundry/Agents/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Shared/Foundry/Agents/README.md)\n\n## Agent Execution Model\n\n### Agent Run Response Pattern\n\nThe framework standardizes agent responses through a consistent return type that wraps the final output along with any intermediate steps taken during execution.\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Agent\n    participant Tool\n    participant AI_Backend\n    \n    Client->>Agent: run(input)\n    Agent->>AI_Backend: send(messages)\n    AI_Backend-->>Agent: response\n    alt tool_call detected\n        Agent->>Tool: invoke(arguments)\n        Tool-->>Agent: result\n        Agent->>AI_Backend: send(result)\n        AI_Backend-->>Agent: response\n    end\n    Agent-->>Client: RunResponse(output, steps)\n```\n\n### Multi-Turn Conversation Support\n\nAgents maintain conversation history through `AgentSession`, enabling stateful multi-turn interactions:\n\n```python\nsession = AgentSession()\nasync for response in agent.run(\"Hello\", session=session):\n    print(response)\n```\n\n资料来源：[docs/decisions/0001-agent-run-response.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0001-agent-run-response.md)\n\n## Skill System Architecture\n\n### Skill Definition\n\nSkills provide a declarative way to define agent capabilities with instructions and associated tools:\n\n```csharp\npublic class AgentInlineSkill\n{\n    public AgentInlineSkill(\n        string name,\n        string description,\n        string instructions,\n        string? license = null,\n        string? compatibility = null,\n        string? allowedTools = null,\n        AdditionalPropertiesDictionary? metadata = null,\n        JsonSerializerOptions? serializerOptions = null);\n}\n```\n\n### Skill Frontmatter Schema\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `name` | string | Yes | Skill name in kebab-case |\n| `description` | string | Yes | Skill description for discovery |\n| `instructions` | string | Yes | Skill instructions text |\n| `license` | string | No | License name or reference |\n| `compatibility` | string | No | Compatibility information (max 500 chars) |\n| `allowedTools` | string | No | Space-delimited pre-approved tools |\n| `metadata` | dictionary | No | Arbitrary key-value metadata |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkill.cs)\n\n## Workflow Orchestration\n\n### Workflow Types\n\nThe framework supports multiple workflow paradigms:\n\n| Workflow Type | Description | Use Case |\n|---------------|-------------|----------|\n| Functional Workflow | Async functions calling agents | Simple sequential operations |\n| Graph Workflow | DAG-based executor chains | Complex conditional flows |\n| Durable Workflow | Long-running with state persistence | Human-in-the-loop approval |\n\n### Graph Workflow Structure\n\n```mermaid\ngraph LR\n    A[Input] --> B[Agent 1]\n    B --> C{Decision}\n    C -->|Path A| D[Agent 2]\n    C -->|Path B| E[Agent 3]\n    D --> F[Output]\n    E --> F\n```\n\nThe graph workflow uses edges to connect executors, allowing conditional routing based on agent outputs.\n\n资料来源：[python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Memory and Context Architecture\n\n### Context Providers\n\nDynamic context injection is supported through custom `ContextProvider` implementations:\n\n```python\nclass MyContextProvider(ContextProvider):\n    async def get_context(self, context_params) -> str:\n        # Retrieve and format context\n        return formatted_context\n```\n\n### Memory Scoping\n\n| Scope Parameter | Description |\n|-----------------|-------------|\n| `application_id` | Global scope across entire application |\n| `agent_id` | Agent-specific memory isolation |\n| `user_id` | User-specific memory partitioning |\n\n### Hybrid Vector Search\n\nContext providers can optionally enable vector search for semantic retrieval:\n\n| Setting | Options | Description |\n|---------|---------|-------------|\n| `vectorizer_choice` | `\"openai\"`, `\"hf\"` | Embedding model selection |\n| `vector_field_name` | string | Redis field for vectors |\n| `overwrite_redis_index` | boolean | Index recreation control |\n\n资料来源：[python/samples/02-agents/context_providers/redis/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/context_providers/redis/README.md)\n\n## Hosting and Deployment\n\n### Local Hosting with DevUI\n\nDevUI provides a local development server with OpenAI-compatible endpoints:\n\n```bash\ndevui /path/to/agents/folder\n```\n\nAPI endpoints exposed:\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/v1/responses` | POST | Agent invocation |\n| `/v1/entities` | GET | List available entities |\n\n### Agent Entity Structure\n\nAgents must export an `agent` or `workflow` in their `__init__.py`:\n\n```python\n# my_agent/__init__.py\nfrom agent_framework import Agent\n\nagent = Agent(\n    name=\"MyAgent\",\n    client=OpenAIChatClient(),\n)\n```\n\n### Foundry Deployment\n\nProduction deployment to Azure AI Foundry uses the same agent configuration with environment-based credential resolution.\n\n资料来源：[python/samples/02-agents/devui/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/devui/README.md)\n\n## Agent Mode System\n\nThe framework supports configurable agent operating modes for interactive planning and autonomous execution:\n\n```csharp\npublic sealed class AgentMode\n{\n    public string Name { get; }\n    public string Description { get; }\n}\n\npublic class AgentModeProviderOptions\n{\n    public IReadOnlyList<AgentMode>? Modes { get; set; }\n    public string? DefaultMode { get; set; }\n}\n```\n\n| Mode | Purpose |\n|------|---------|\n| `\"plan\"` | Interactive planning with human oversight |\n| `\"execute\"` | Autonomous execution without intervention |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs)\n\n## Integration Patterns\n\n### GitHub Copilot Integration\n\nAgents can wrap GitHub Copilot clients for unified interaction:\n\n```csharp\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null);\n```\n\nThis extension method creates an `AIAgent` backed by the Copilot client with optional additional tools and instructions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Data Flow Summary\n\n```mermaid\ngraph TD\n    subgraph \"Input Processing\"\n        A[User Input] --> B[Session Manager]\n        B --> C[Context Provider]\n    end\n    \n    subgraph \"Agent Processing\"\n        C --> D[Agent Executor]\n        D --> E[AI Chat Client]\n        E --> F{Tool Call?}\n    end\n    \n    subgraph \"Tool Execution\"\n        F -->|Yes| G[Tool Executor]\n        G --> H[Result Formatter]\n        H --> E\n    end\n    \n    F -->|No| I[Response Formatter]\n    \n    subgraph \"Output\"\n        I --> J[RunResponse]\n        J --> K[Client Application]\n    end\n```\n\n## Environment Configuration\n\n### Required Environment Variables\n\n| Variable | Description | Required For |\n|---------|-------------|--------------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project URL | Foundry agents |\n| `FOUNDRY_MODEL` | Model deployment name | Foundry agents |\n| `OPENAI_API_KEY` | OpenAI API key | OpenAI clients, embeddings |\n| `AZURE_AI_PROJECT_ENDPOINT` | .NET Foundry endpoint | .NET Foundry |\n| `AZURE_AI_MODEL_DEPLOYMENT_NAME` | .NET model deployment | .NET Foundry |\n\n### Authentication Methods\n\n| Method | Use Case | Command |\n|--------|----------|---------|\n| `AzureCliCredential` | Interactive login | `az login` |\n| `DefaultAzureCredential` | Automated environments | Managed identity |\n| API Key | Direct authentication | Environment variable |\n\n资料来源：[python/README.md](https://github.com/microsoft/agent-framework/blob/main/python/README.md)\n\n---\n\n<a id='agents'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Tools and Skills](#tools-and-skills), [Workflows and Orchestration](#workflows), [AI Provider Integration](#provider-integration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_agents.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_agents.py)\n- [python/packages/core/agent_framework/_types.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_types.py)\n- [dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs)\n- [python/samples/01-get-started/01_hello_agent.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/01_hello_agent.py)\n- [dotnet/samples/01-get-started/01_hello_agent/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/01_hello_agent/Program.cs)\n</details>\n\n# Agent System\n\nThe Agent System is the core abstraction layer in Microsoft Agent Framework that enables the creation, configuration, and execution of AI agents. Agents are autonomous or semi-autonomous software entities that can interact with users, execute tools, maintain conversation state, and perform complex multi-step tasks using Large Language Models (LLMs) as their reasoning engine.\n\n## Architecture Overview\n\nThe Agent System follows a layered architecture that separates concerns between the agent abstraction, runtime context, tool invocation, and the underlying chat client implementations.\n\n```mermaid\ngraph TD\n    subgraph \"Agent Abstraction Layer\"\n        AIAgent[AIAgent Interface]\n        ChatClientAgent[ChatClientAgent]\n        AgentRunContext[AgentRunContext]\n    end\n    \n    subgraph \"Tool Layer\"\n        AITool[AITool]\n        ToolDefinition[ToolDefinition]\n        ToolResources[ToolResources]\n    end\n    \n    subgraph \"Client Layer\"\n        IChatClient[IChatClient]\n        CopilotClient[CopilotClient]\n        ClaudeClient[ClaudeClient]\n    end\n    \n    subgraph \"Context Layer\"\n        AIContext[AIContext]\n        AgentSession[AgentSession]\n        ContextProvider[ContextProvider]\n    end\n    \n    AIAgent --> AgentRunContext\n    AIAgent --> AITool\n    AIAgent --> IChatClient\n    ChatClientAgent --> IChatClient\n    AgentRunContext --> AIContext\n    AgentSession --> AIContext\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n## Core Components\n\n### AIAgent Interface\n\nThe `AIAgent` interface serves as the foundational abstraction for all agent implementations in the .NET SDK. It defines the contract that all concrete agent types must implement.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `Id` | `string` | Unique identifier for the agent instance |\n| `Name` | `string` | Human-readable name for the agent |\n| `Description` | `string` | Description of the agent's purpose and capabilities |\n| `Instructions` | `string` | System instructions that guide agent behavior |\n| `Tools` | `IList<AITool>` | Collection of tools available to the agent |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs)\n\n### ChatClientAgent\n\n`ChatClientAgent` is the primary concrete implementation of `AIAgent` that uses an `IChatClient` for LLM interactions. It provides comprehensive support for agent configuration, tool execution, and streaming responses.\n\n#### Constructor Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `chatClient` | `IChatClient` | Yes | The chat client used for LLM communication |\n| `instructions` | `string?` | No | System instructions for agent behavior |\n| `name` | `string?` | No | Agent identifier for logging |\n| `description` | `string?` | No | Human-readable agent description |\n| `tools` | `IEnumerable<AITool>?` | No | Tools the agent can invoke |\n| `loggerFactory` | `ILoggerFactory?` | No | Factory for creating loggers |\n| `services` | `IServiceProvider?` | No | Service provider for dependency resolution |\n| `cancellationToken` | `CancellationToken` | No | Cancellation token for async operations |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### AgentRunContext\n\nThe `AgentRunContext` provides runtime context for agent execution, including conversation history, tool configurations, and execution options.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `SessionId` | `string` | Unique identifier for the current session |\n| `ConversationHistory` | `IList<ChatMessage>` | Messages exchanged in the conversation |\n| `Options` | `ChatOptions` | Configuration for the current run |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunContext.cs)\n\n## Agent Configuration\n\n### Creating a Basic Agent\n\nAgents can be configured with various levels of complexity depending on the use case.\n\n```python\n# Python: Basic agent creation\n# python/samples/01-get-started/01_hello_agent.py\n\nfrom agent_framework import Agent\n\n# Simple agent with instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"You are a helpful assistant.\"\n)\n```\n\n```csharp\n// C#: Basic agent creation\n// dotnet/samples/01-get-started/01_hello_agent/Program.cs\n\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Hosting.OpenAI;\n\n// Create agent with instructions\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    instructions: \"You are a helpful assistant that answers questions accurately.\"\n);\n```\n\n资料来源：[python/samples/01-get-started/01_hello_agent.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/01_hello_agent.py)\n资料来源：[dotnet/samples/01-get-started/01_hello_agent/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/01_hello_agent/Program.cs)\n\n### Agent with Tools\n\nTools extend agent capabilities by allowing them to perform actions beyond text generation.\n\n```python\n# Python: Agent with function tool\n# python/samples/01-get-started/02_add_tools.py\n\nfrom agent_framework import Agent, tool\n\n@tool\ndef get_weather(location: str) -> str:\n    \"\"\"Get the weather for a specific location.\"\"\"\n    # Tool implementation\n    return f\"The weather in {location} is sunny.\"\n\nagent = Agent(model=\"gpt-4o\")\nagent.tools.add(get_weather)\n```\n\n```csharp\n// C#: Agent with tools\n// dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs\n\n// Tools augment any tools provided via ChatOptions.Tools when the agent is run\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    instructions: \"You are a helpful assistant.\",\n    tools: new List<AITool> { customTool }\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n### Tool Security Considerations\n\nBy default, all provided tools are invoked without user approval. The AI selects which functions to call and chooses the arguments — these arguments should be treated as untrusted input.\n\n> **Security Warning**: Developers should require explicit approval for tools that have side effects, access sensitive data, or perform irreversible operations.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n## Running Agents\n\n### Synchronous Execution\n\n```python\n# Python: Non-streaming execution\n# python/samples/01-get-started/01_hello_agent.py\n\nresult = agent.run(\"What is the capital of France?\")\nprint(result)\n```\n\n### Streaming Execution\n\n```python\n# Python: Streaming execution\n# python/samples/01-get-started/01_hello_agent.py\n\nasync for chunk in agent.run_streaming(\"Tell me a story\"):\n    print(chunk, end=\"\", flush=True)\n```\n\n### Multi-Turn Conversations\n\n```python\n# Python: Multi-turn with AgentSession\n# python/samples/01-get-started/03_multi_turn.py\n\nsession = AgentSession()\n\n# First turn\nresponse1 = await session.run(agent, \"Hi, my name is Alice\")\nprint(response1)\n\n# Second turn - maintains context\nresponse2 = await session.run(agent, \"What is my name?\")\nprint(response2)  # \"Your name is Alice\"\n```\n\n资料来源：[python/samples/01-get-started/03_multi_turn.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/03_multi_turn.py)\n\n## Agent Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Agent as AIAgent/ChatClientAgent\n    participant Context as AgentRunContext\n    participant Tools as Tool System\n    participant LLM as IChatClient\n    \n    User->>Agent: Run(userMessage, options)\n    Agent->>Context: Create execution context\n    Context->>LLM: Send chat request\n    \n    alt Tool Invocation Required\n        LLM-->>Context: FunctionCall(tool_name, args)\n        Context->>Tools: InvokeTool(tool_name, args)\n        Tools-->>Context: ToolResult\n        Context->>LLM: Continue with result\n    end\n    \n    LLM-->>Agent: Final response\n    Agent-->>User: Return result\n```\n\n## Context Management\n\n### ContextProvider\n\nCustom context providers allow agents to access dynamic context during execution.\n\n```python\n# Python: Custom context provider\n# python/samples/01-get-started/04_memory.py\n\nfrom agent_framework import ContextProvider\n\nclass MemoryProvider(ContextProvider):\n    def __init__(self):\n        self.memories = []\n    \n    async def get_context(self) -> str:\n        if self.memories:\n            return \"User preferences: \" + \", \".join(self.memories)\n        return \"\"\n    \n    async def update_context(self, interaction: dict):\n        if \"preference\" in interaction:\n            self.memories.append(interaction[\"preference\"])\n\nagent = Agent(model=\"gpt-4o\")\nagent.context_providers.add(MemoryProvider())\n```\n\n资料来源：[python/samples/01-get-started/04_memory.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/04_memory.py)\n\n### AgentSession\n\n`AgentSession` maintains conversation state across multiple turns, enabling persistent interactions.\n\n| Method | Description |\n|--------|-------------|\n| `run(agent, message)` | Execute a single turn with the agent |\n| `clear()` | Clear conversation history |\n| `get_history()` | Retrieve conversation history |\n\n资料来源：[python/samples/01-get-started/03_multi_turn.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/03_multi_turn.py)\n\n## Dependency Injection\n\nThe .NET implementation supports dependency injection for resolving services required by AI functions.\n\n```csharp\n// C#: Service provider integration\n// dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs\n\n// The services parameter is particularly important when using custom tools \n// that require dependency injection\nvar services = new ServiceCollection();\nservices.AddSingleton<IMyService, MyServiceImplementation>();\n\nvar agent = new ChatClientAgent(\n    chatClient: chatClient,\n    services: services.BuildServiceProvider()\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)\n\n## Agent Integrations\n\n### Copilot Integration\n\n```csharp\n// C#: GitHub Copilot integration\n// dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs\n\nvar agent = copilotClient.AsAIAgent(\n    name: \"CopilotAgent\",\n    description: \"GitHub Copilot powered agent\",\n    tools: new List<AITool> { customTool }\n);\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n### Claude Integration\n\nThe Claude agent enables integration with Claude Agent SDK for accessing Claude's agentic capabilities.\n\n资料来源：[python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n### Azure AI Foundry Integration\n\n```csharp\n// C#: Azure AI Foundry Persistent Agents\n// dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs\n\n[Obsolete(\"Please use the latest Foundry Agents service via the Microsoft.Agents.AI.AzureAI package.\")]\npublic static async Task<ChatClientAgent> CreateAIAgentAsync(\n    this PersistentAgentsClient persistentAgentsClient,\n    string model,\n    string? name = null,\n    string? description = null,\n    string? instructions = null,\n    IEnumerable<ToolDefinition>? tools = null,\n    ToolResources toolResources = null,\n    double? temperature = null,\n    double? topP = null,\n    ResponseFormat? responseFormat = null,\n    IDictionary<string, string>? metadata = null,\n    IChatClientFactory? clientFactory = null,\n    IServiceProvider services = null,\n    CancellationToken cancellationToken = default)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs)\n\n## Best Practices\n\n### 1. Clear Instructions\n\nProvide specific, detailed instructions that define the agent's role, behavior, and constraints.\n\n```python\n# Good: Specific instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"\"\"\n    You are a technical documentation assistant.\n    - Always use code blocks for code examples\n    - Include practical examples\n    - Explain technical terms on first use\n    \"\"\"\n)\n\n# Avoid: Vague instructions\nagent = Agent(\n    model=\"gpt-4o\",\n    instructions=\"Be helpful.\"\n)\n```\n\n### 2. Tool Security\n\nImplement approval mechanisms for sensitive tools:\n\n```csharp\n// Review tools before allowing execution\npublic class SecureToolExecutor\n{\n    public async Task<ToolResult> ExecuteAsync(AITool tool, object args)\n    {\n        // Require approval for destructive or sensitive operations\n        if (tool.HasSideEffects)\n        {\n            var approved = await RequestApprovalAsync(tool, args);\n            if (!approved) throw new OperationCanceledException();\n        }\n        return await tool.InvokeAsync(args);\n    }\n}\n```\n\n### 3. Proper Resource Cleanup\n\nAlways dispose of agents and clients properly:\n\n```python\n# Python: Async context manager usage\nasync with Agent(model=\"gpt-4o\") as agent:\n    result = await agent.run(\"Hello\")\n# Agent is automatically cleaned up\n\n# Or explicit cleanup\nagent = Agent(model=\"gpt-4o\")\ntry:\n    result = await agent.run(\"Hello\")\nfinally:\n    await agent.close()\n```\n\n## See Also\n\n- [Get Started with Python](../python/samples/01-get-started/README.md)\n- [Get Started with .NET](../dotnet/samples/01-get-started/README.md)\n- [Agent Skills System](./agent-skills.md)\n- [Functional Workflows](./workflows.md)\n- [Graph Workflows](./graph-workflows.md)\n\n---\n\n<a id='tools-and-skills'></a>\n\n## Tools and Skills\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Middleware System](#middleware)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_tools.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_tools.py)\n- [python/packages/core/agent_framework/_skills.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_skills.py)\n- [dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n- [dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs)\n- [docs/decisions/0021-agent-skills-design.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0021-agent-skills-design.md)\n- [python/samples/02-agents/skills/class_based_skill/class_based_skill.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/skills/class_based_skill/class_based_skill.py)\n- [dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs)\n</details>\n\n# Tools and Skills\n\n## Overview\n\nTools and Skills are core abstractions in the Microsoft Agent Framework that extend an agent's capabilities beyond its base instruction set. Tools enable functional operations (like calling APIs or executing code), while Skills provide domain-specific knowledge, structured instructions, resources, and scripts that guide agent behavior in specialized areas.\n\n**Tools** are function-based capabilities that agents can invoke to perform specific tasks such as calculations, data retrieval, or external API calls. 资料来源：[python/packages/core/agent_framework/_tools.py:1-50]()\n\n**Skills** are containers of domain-specific knowledge that include instructions, reference documents (resources), and executable scripts. They enable agents to handle specialized tasks by providing contextual guidance and tooling. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:1-30]()\n\n```mermaid\ngraph TD\n    subgraph AgentFramework\n        A[Agent] --> T[Tools]\n        A --> S[Skills]\n        T --> TF[Function Tools]\n        T --> TT[Tool Definitions]\n        S --> SF[File-Based Skills]\n        S --> SC[Code-Defined Skills]\n        S --> SB[Class-Based Skills]\n        SF --> Instructions\n        SF --> Resources\n        SF --> Scripts\n        SC --> Instructions\n        SC --> Resources\n        SC --> Scripts\n    end\n```\n\n## Core Concepts\n\n### Tools\n\nTools in the Agent Framework are the primary mechanism for enabling agents to perform actions. A tool is essentially a callable function that the agent can invoke during its execution. 资料来源：[python/packages/core/agent_framework/_tools.py:1-80]()\n\n| Tool Type | Description | Use Case |\n|-----------|-------------|----------|\n| Function Tool | Decorated Python function | Custom operations in Python agents |\n| Tool Definition | Declarative tool specification | Cross-platform tool definition |\n| Managed Tool | Pre-built tool from providers | Anthropic skills, Azure AI services |\n\n### Skills\n\nSkills provide specialized knowledge and capabilities to agents. Each skill contains:\n\n- **Instructions**: Domain-specific guidance for the agent\n- **Resources**: Reference documents and data files\n- **Scripts**: Executable code for automated operations 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs:20-45]()\n\n```mermaid\ngraph LR\n    subgraph SkillStructure\n        I[Instructions] --> C[Content]\n        R[Resources] --> C\n        S[Scripts] --> C\n        F[Frontmatter] --> C\n    end\n    \n    C --> A[Agent Skill]\n    A --> P[Agent Skills Provider]\n```\n\n## Skill Types\n\n### File-Based Skills\n\nFile-based skills are defined through a `SKILL.md` file containing YAML frontmatter and Markdown body. The frontmatter declares skill metadata, while the body contains instructions and references to resources and scripts. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs:1-50]()\n\n**SKILL.md Structure:**\n\n```markdown\n---\nname: my-skill\ndescription: A skill for handling specific tasks\ncompatibility: agent-framework >= 1.0.0\n---\n\n# Instructions\n\nYou are an expert in...\n\n## Resources\n- [Reference Doc](./references/guide.md)\n\n## Scripts\n- script: ./scripts/helper.py\n```\n\nThe `AgentFileSkill` class loads and parses these files, extracting content for use by the agent. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/File/AgentFileSkill.cs:50-120]()\n\n### Code-Defined Skills\n\nCode-defined skills are created programmatically using the SDK. This approach provides full control over skill content and behavior through code.\n\n**Python Implementation:**\n\n```python\nfrom agent_framework import skill\n\n@skill(\n    name=\"code-skill\",\n    description=\"A programmatically defined skill\"\n)\ndef my_skill():\n    \"\"\"Instructions for the agent.\"\"\"\n    return {\n        \"instructions\": \"You are an expert in...\",\n        \"resources\": [\"./data/knowledge.json\"],\n        \"scripts\": [\"./scripts/process.py\"]\n    }\n```\n\n**C# Implementation:**\n\n```csharp\nAgentInlineSkill skill = new AgentInlineSkill(\n    name: \"code-skill\",\n    description: \"A programmatically defined skill\",\n    instructions: \"You are an expert in handling...\"\n);\n```\n\n资料来源：[python/packages/core/agent_framework/_skills.py:1-100]()\n\n### Class-Based Skills (Python)\n\nClass-based skills provide an object-oriented approach to defining skills with typed properties and methods.\n\n```python\nfrom agent_framework import AgentSkill\n\nclass MySkill(AgentSkill):\n    name = \"class-skill\"\n    description = \"A class-based skill example\"\n    \n    @property\n    def instructions(self) -> str:\n        return \"You are a specialized assistant...\"\n    \n    @property\n    def resources(self) -> list[AgentSkillResource]:\n        return [AgentSkillResource(\"data.json\", \"json://...\")]\n```\n\n资料来源：[python/samples/02-agents/skills/class_based_skill/class_based_skill.py:1-60]()\n\n## Architecture\n\n### Agent Skills Provider\n\nThe `AgentSkillsProvider` is the central component that manages skill discovery, loading, and integration with the agent's context. It builds tools from skills and injects skill instructions into the agent's system prompt. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProvider.cs:1-80]()\n\n**Key Responsibilities:**\n- Discover skills from configured sources\n- Build `load_skill` and `run_skill_script` tools for skill management\n- Generate skill instructions for the agent's context\n- Handle resource and script instructions\n\n```mermaid\ngraph TD\n    S[Skills Source] --> SP[AgentSkillsProvider]\n    SP --> ST[Skill Tools]\n    SP --> SI[Skill Instructions]\n    ST --> A[Agent]\n    SI --> A\n    \n    SP --> Config[AgentSkillsProviderOptions]\n    Config --> Cache[Caching]\n    Config --> Approval[Script Approval]\n    Config --> Template[Custom Prompt Template]\n```\n\n### Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `SkillsInstructionPrompt` | string | Custom template for skill advertising |\n| `ScriptApproval` | bool | Require approval before script execution |\n| `DisableCaching` | bool | Disable tool/instruction caching |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProviderOptions.cs:1-50]()\n\n## Skill Content Generation\n\nFor code-defined and class-based skills, the framework synthesizes an XML document containing all skill components. This ensures consistent handling regardless of the skill's origin. 资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/Programmatic/AgentInlineSkillContentBuilder.cs:1-60]()\n\n**Generated XML Structure:**\n\n```xml\n<name>{skill_name}</name>\n<description>{skill_description}</description>\n\n<instructions>\n{skill_instructions}\n</instructions>\n\n{resources_block}\n\n{scripts_block}\n```\n\n## Tool Generation from Skills\n\nThe Agent Framework automatically generates tools from skills:\n\n| Tool | Purpose | Triggered By |\n|------|---------|--------------|\n| `load_skill` | Retrieve skill instructions | When skills exist |\n| `run_skill_script` | Execute skill scripts | When scripts exist |\n| `{custom_tools}` | Domain-specific operations | Skill-defined tools |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Skills/AgentSkillsProvider.cs:80-150]()\n\n## Integration Examples\n\n### Adding Skills to an Agent (Python)\n\n```python\nfrom agent_framework import Agent, AgentSkillsProvider, skill\n\n# Define a skill\n@skill(name=\"data-analyst\", description=\"Analyze datasets\")\ndef analyst_skill():\n    return {\n        \"instructions\": \"You analyze data and provide insights...\",\n        \"resources\": [\"./analyst/resources/templates.json\"]\n    }\n\n# Create skills provider\nskills_provider = AgentSkillsProvider(skills=[analyst_skill])\n\n# Attach to agent\nagent = Agent(\n    instructions=\"You are a helpful assistant.\",\n    skills_provider=skills_provider\n)\n```\n\n### Adding Skills to an Agent (C#)\n\n```csharp\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Skills.File;\n\n// Load file-based skills\nAgentFileSkill[] fileSkills = AgentFileSkill.LoadFromDirectory(\"./skills\");\n\n// Create provider with file skills\nAgentSkillsProvider provider = new AgentSkillsProvider(\n    new AgentSkillsSource(fileSkills),\n    new AgentSkillsProviderOptions\n    {\n        ScriptApproval = true\n    });\n\n// Create agent with skills\nChatClientAgent agent = new ChatClientAgent(\n    model: \"gpt-4o\",\n    instructions: \"You are a helpful assistant.\",\n    skillsProvider: provider\n);\n```\n\n资料来源：[dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/Program.cs:1-80]()\n\n## Design Decisions\n\nThe Tools and Skills architecture was designed with these principles:\n\n1. **Dual Expression**: Skills can be defined declaratively (file-based) or programmatically (code-defined), allowing flexibility in how developers structure their agent capabilities. 资料来源：[docs/decisions/0021-agent-skills-design.md:1-30]()\n\n2. **Resource Abstraction**: Resources provide reference data to skills without embedding everything in instructions, enabling efficient context management.\n\n3. **Script Integration**: Scripts allow skills to perform automated actions, with optional approval workflows for security-sensitive operations.\n\n4. **Tool Synthesis**: The framework automatically generates management tools (`load_skill`, `run_skill_script`) to ensure consistent skill interaction patterns.\n\n## See Also\n\n- [Agent Framework Core](../core/)\n- [Workflows and Graphs](../workflows/)\n- [Declarative Agents](../declarative/)\n- [Sample: File-Based Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/file_based_skill)\n- [Sample: Code-Defined Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/code_defined_skill)\n- [Sample: Mixed Skills](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/skills/mixed_skills)\n\n---\n\n<a id='workflows'></a>\n\n## Workflows and Orchestration\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Hosting and Deployment Patterns](#hosting-patterns), [Observability and Telemetry](#observability)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_workflows/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/__init__.py)\n- [python/packages/core/agent_framework/_workflows/_workflow.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/_workflow.py)\n- [python/packages/core/agent_framework/_workflows/_runner.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_workflows/_runner.py)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n- [python/samples/03-workflows/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/README.md)\n- [dotnet/samples/03-workflows/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/03-workflows/README.md)\n</details>\n\n# Workflows and Orchestration\n\n## Overview\n\nThe Agent Framework provides a comprehensive **workflow and orchestration system** that enables developers to compose multiple agents into structured execution patterns. Workflows serve as the architectural backbone for multi-agent coordination, allowing agents to be chained, parallelized, or conditionally executed based on runtime state.\n\nWorkflows in the Agent Framework are built using an **executor-based architecture** where each component (agents, functions, workflows) implements a common executor interface. This design enables flexible composition through a builder pattern, supporting both imperative (code-based) and declarative (YAML-based) workflow definitions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n## Architecture\n\n### Core Concepts\n\n```mermaid\ngraph TD\n    A[Input] --> B[Executor]\n    B --> C[Executor]\n    C --> D[Executor]\n    B --> E[Executor]\n    D --> F[Aggregator]\n    E --> F\n    F --> G[Output]\n    \n    H[Workflow] --> B\n    H --> C\n    H --> D\n    H --> E\n    H --> F\n    \n    I[Builder] -->|Builds| H\n```\n\nThe orchestration system is built on three fundamental abstractions:\n\n| Concept | Description |\n|---------|-------------|\n| **Executor** | A callable unit that processes inputs and produces outputs |\n| **Workflow** | A composed structure of executors connected by edges |\n| **Builder** | Fluent API for constructing workflows programmatically |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Workflow.cs)\n\n### Executor Types\n\nExecutors form the atomic units of workflow execution:\n\n| Executor Type | Purpose |\n|---------------|---------|\n| `AIAgent` | Encapsulates an AI agent that processes text and returns responses |\n| `FunctionExecutor` | Executes synchronous or asynchronous functions |\n| `WorkflowExecutor` | Wraps an entire sub-workflow for nested orchestration |\n| `OutputMessagesExecutor` | Terminal executor that captures final output |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n## Workflow Composition Patterns\n\n### Sequential Workflow\n\nAgents or functions execute in a linear chain, where each component receives the output of the previous one.\n\n```mermaid\ngraph LR\n    A[Input] --> B[Agent 1]\n    B --> C[Agent 2]\n    C --> D[Agent 3]\n    D --> E[Output]\n```\n\n**Example: Translation Chain**\n```\nInput text (English)\n    │\n    ▼\n┌─────────────┐    ┌──────────────┐    ┌──────────────┐\n│ French Agent │ →  │ Spanish Agent │ →  │ English Agent │\n│ (translate)  │    │ (translate)   │    │ (translate)   │\n└─────────────┘    └──────────────┘    └──────────────┘\n                                              │\n                                              ▼\n                                        Final output\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/README.md)\n\n### Concurrent Workflow\n\nMultiple agents operate on the same input simultaneously, with outputs aggregated into a collection.\n\n```mermaid\ngraph TD\n    A[Input] --> B[Agent 1]\n    A --> C[Agent 2]\n    A --> D[Agent 3]\n    B --> E[Aggregator]\n    C --> E\n    D --> E\n    E --> F[Output Collection]\n```\n\n### Conditional Workflow\n\nExecution branches based on runtime conditions or agent responses.\n\n```mermaid\ngraph TD\n    A[Input] --> B[Router Agent]\n    B -->|Condition A| C[Agent A]\n    B -->|Condition B| D[Agent B]\n    B -->|Default| E[Default Agent]\n    C --> F[Output]\n    D --> F\n    E --> F\n```\n\n## Declarative Workflows\n\nThe Agent Framework supports defining workflows using YAML, enabling configuration-driven orchestration without code changes.\n\n### Workflow Structure\n\n```yaml\nname: my-workflow\ndescription: A declarative workflow example\n\nactions:\n  - kind: SetValue\n    path: turn.greeting\n    value: Hello, World!\n\n  - kind: SendActivity\n    activity:\n      text: =turn.greeting\n```\n\n资料来源：[python/samples/03-workflows/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/declarative/README.md)\n\n### Action Types\n\n#### Variable Actions\n\n| Action | Purpose |\n|--------|---------|\n| `SetValue` | Set a variable in state |\n| `SetVariable` | Set a variable (.NET style naming) |\n| `AppendValue` | Append to a list |\n| `ResetVariable` | Clear a variable |\n\n#### Control Flow\n\n| Action | Purpose |\n|--------|---------|\n| `If` | Conditional branching |\n| `Switch` | Multi-way branching |\n| `Foreach` | Iterate over collections |\n| `RepeatUntil` | Loop until condition |\n| `GotoAction` | Jump to labeled action |\n\n#### Output\n\n| Action | Purpose |\n|--------|---------|\n| `SendActivity` | Send text/attachments to user |\n\n资料来源：[python/samples/03-workflows/declarative/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/declarative/README.md)\n\n## Durable Orchestration\n\nFor long-running workflows that may span hours or days, the Agent Framework provides **durable orchestration** using the Durable Task Framework.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Client] -->|Schedule| B[Orchestrator]\n    B -->|Calls| C[Activity]\n    B -->|Calls| D[Agent]\n    C -->|Result| B\n    D -->|Result| B\n    B -->|Persisted| E[State Store]\n```\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Long-running execution** | Workflows persist across process restarts |\n| **Human-in-the-loop** | Workflows can pause and await human approval |\n| **Event-driven** | Activities can send notifications and wait for responses |\n| **State management** | Built-in state persistence with checkpointing |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs)\n\n### Human-in-the-Loop Pattern\n\nDurable workflows support pausing for human approval:\n\n1. **Initial Generation**: Agent creates content based on input\n2. **Review Loop**: Up to configurable maximum attempts\n   - Activity notifies user for approval\n   - Orchestration waits for approval event OR timeout\n3. **Resolution**:\n   - **Approved**: Content published, workflow completes\n   - **Rejected**: Feedback incorporated, regeneration triggered\n   - **Timeout**: Error raised\n\n资料来源：[python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md)\n\n### Durable Workflow Context\n\nThe `DurableWorkflowContext` manages workflow state and events:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `SentMessages` | `List<TypedPayload>` | Messages sent during activity execution |\n| `OutboundEvents` | `List<WorkflowEvent>` | Events added during execution |\n| `StateUpdates` | `Dictionary<string, string?>` | State modifications |\n| `ClearedScopes` | `HashSet<string>` | Scopes cleared during execution |\n| `HaltRequested` | `bool` | Whether executor requested workflow halt |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableWorkflowContext.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableWorkflowContext.cs)\n\n## Workflow Builder API\n\n### .NET Implementation\n\nThe `WorkflowBuilder` class provides a fluent API for composing workflows:\n\n```csharp\n// Sequential composition\nWorkflow workflow = WorkflowBuilder.BuildSequential(\n    \"MyWorkflow\",\n    agent1, agent2, agent3);\n\n// Concurrent composition  \nWorkflow workflow = WorkflowBuilder.BuildConcurrent(\n    \"ConcurrentWorkflow\",\n    agent1, agent2, agent3);\n```\n\n**Builder Configuration Options:**\n\n| Option | Description |\n|--------|-------------|\n| `ReassignOtherAgentsAsUsers` | When `true`, other agents in scope become user participants |\n| `ForwardIncomingMessages` | When `true`, incoming messages propagate through the chain |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n### Python Implementation\n\nThe Python workflow system provides similar builder patterns:\n\n```python\nfrom agent_framework.workflows import WorkflowBuilder\n\nworkflow = WorkflowBuilder(\n    start_executor=first_agent\n).add_edge(\n    from_node=first_agent,\n    to_node=second_agent\n).build()\n```\n\n**MagenticBuilder for Multi-Agent Orchestration:**\n\n```python\nfrom agent_framework.orchestrations import MagenticBuilder\n\nworkflow = MagenticBuilder(\n    participants=[researcher, writer, reviewer],\n    manager_agent=manager_agent,\n).build()\n```\n\n资料来源：[python/packages/orchestrations/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/orchestrations/README.md)\n\n## Workflow State Management\n\n### State Persistence\n\nWorkflows maintain state throughout execution:\n\n```mermaid\ngraph LR\n    A[Checkpoint] --> B[State Dictionary]\n    B --> C[Resume]\n    D[Input] --> E[Executor]\n    E --> F[Output]\n    E -->|State Update| B\n```\n\n### State Variables\n\nCustom state variables are stored alongside system state:\n\n| Key | Purpose |\n|-----|---------|\n| `_executor_state` | Internal executor tracking (hidden from user state) |\n| `*` (custom) | User-defined state variables |\n\n资料来源：[python/packages/devui/frontend/src/components/features/workflow/checkpoint-info-modal.tsx](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/frontend/src/components/features/workflow/checkpoint-info-modal.tsx)\n\n## Configuration\n\n### Service Registration\n\n#### .NET\n\n```xml\n<PropertyGroup>\n  <InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>\n  <InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>\n</PropertyGroup>\n```\n\n#### Durable Options Configuration\n\n```csharp\nservices.ConfigureDurableWorkflows(options =>\n{\n    options.Workflows.HubName = \"MyAgentHub\";\n    options.Workflows.TaskOrchestration.Type = OrchestrationType.InProcess;\n});\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/ServiceCollectionExtensions.cs)\n\n### Python Environment Variables\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://your-project-endpoint\"\nexport FOUNDRY_MODEL=\"gpt-4o\"   # optional, defaults to gpt-4o\n```\n\n资料来源：[python/samples/01-get-started/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/01-get-started/README.md)\n\n## Sample Code Reference\n\n### Basic Sequential Workflow (.NET)\n\n```csharp\n// Create agent executors\nExecutorBinding agent1 = agent1.BindAsExecutor(options);\nExecutorBinding agent2 = agent2.BindAsExecutor(options);\n\n// Build sequential chain\nWorkflowBuilder builder = new WorkflowBuilder(agent1);\nbuilder.AddEdge(agent1, agent2);\n\n// Add terminal output executor\nOutputMessagesExecutor end = new();\nbuilder = builder.AddEdge(agent2, end).WithOutputFrom(end);\n\nWorkflow workflow = builder.Build();\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilder.cs)\n\n### Durable Workflow with HITL (Python)\n\n```python\n# 1. Initial generation\ncontent = yield writer_agent.generate(topic)\n\n# 2. Notify for review\nyield send_notification(content)\n\n# 3. Wait for approval/rejection\napproval_event = yield wait_for_event(\"ApprovalEvent\")\nif approval_event.approved:\n    yield publish_content(content)\nelse:\n    # Regenerate with feedback\n    content = yield writer_agent.generate(topic, feedback=approval_event.feedback)\n```\n\n资料来源：[python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/README.md)\n\n## Monitoring and Debugging\n\n### Durable Task Dashboard\n\nView orchestration state at `http://localhost:8082`:\n\n| View | Information Available |\n|------|----------------------|\n| Orchestrations | Instance status, runtime state, input/output, execution history |\n| Agents | Conversation history, agent state |\n\n### OpenTelemetry Traces\n\nThe framework emits Otel traces for workflow operations:\n\n```bash\ndevui ./agents --instrumentation\n```\n\n资料来源：[python/packages/devui/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/devui/README.md)\n\n## See Also\n\n- [Agent Framework Documentation](https://aka.ms/agent-framework)\n- [Declarative Workflow Samples](../03-workflows/declarative/)\n- [Durable Task Samples](../04-hosting/durabletask/)\n- [DevUI Configuration](../packages/devui/)\n\n---\n\n<a id='middleware'></a>\n\n## Middleware System\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Tools and Skills](#tools-and-skills)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_middleware.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_middleware.py)\n- [dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs)\n- [python/samples/02-agents/middleware/function_based_middleware.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/middleware/function_based_middleware.py)\n- [dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs)\n- [docs/decisions/0007-agent-filtering-middleware.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0007-agent-filtering-middleware.md)\n</details>\n\n# Middleware System\n\n## Overview\n\nThe Middleware System in the Microsoft Agent Framework provides a powerful extensibility mechanism that allows developers to intercept, modify, and control the flow of interactions between agents, tools, and AI models. Middleware components act as interceptors in the request-response pipeline, enabling cross-cutting concerns such as logging, authentication, tool approval, and request filtering.\n\nAccording to the architecture decision record, the middleware system was designed to solve the problem of filtering agent requests and responses without tightly coupling such logic to the core agent implementation. 资料来源：[docs/decisions/0007-agent-filtering-middleware.md]()\n\n## Architecture\n\n### Core Concepts\n\nThe middleware system follows a pipeline-based architecture where requests flow through a chain of middleware components before reaching the core agent logic, and responses flow back through the same chain in reverse order.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Middleware 1]\n    B --> C[Middleware 2]\n    C --> D[Middleware N]\n    D --> E[Core Agent Logic]\n    E --> F[Response from Agent]\n    F --> D\n    D --> C\n    C --> B\n    B --> G[User Response]\n    \n    H[Tool Calls] <-->|Intercepted| D\n    I[AI Model] <-->|Filtered| D\n```\n\n### Middleware Types\n\n| Type | Purpose | Python Implementation | .NET Implementation |\n|------|---------|----------------------|---------------------|\n| Function-based | Simple callable middleware | `@middleware` decorator | Delegate-based |\n| Class-based | State-aware middleware with full lifecycle control | `Middleware` abstract class | `IAgentMiddleware` interface |\n| Tool Approval | Approves or rejects tool executions | Custom handler | `ToolApprovalAgent` |\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]() | [dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n## Python Middleware Implementation\n\n### Function-Based Middleware\n\nThe simplest way to define middleware in Python is using the `@middleware` decorator. This creates a middleware that wraps an agent and intercepts all calls.\n\n```python\nfrom agent_framework import Agent, middleware\n\n@middleware\nasync def my_logging_middleware(agent, tool_call, context, call_next):\n    print(f\"Tool call: {tool_call.name}\")\n    result = await call_next(agent, tool_call, context)\n    print(f\"Result: {result}\")\n    return result\n\n# Apply middleware to agent\nagent = Agent(...)\nwrapped_agent = my_logging_middleware(agent)\n```\n\n资料来源：[python/samples/02-agents/middleware/function_based_middleware.py]()\n\n### Middleware Base Class\n\nFor more complex scenarios, you can extend the `Middleware` abstract class:\n\n```python\nfrom agent_framework import Middleware, Agent\n\nclass ToolApprovalMiddleware(Middleware):\n    def __init__(self):\n        self.pending_approvals = []\n    \n    async def on_tool_call(\n        self, \n        agent: Agent, \n        tool_call: ToolCall, \n        context: Context\n    ) -> Awaitable[Result]:\n        # Custom logic to approve or reject\n        if self._requires_approval(tool_call):\n            return Result(success=False, error=\"Approval required\")\n        return await self.next(agent, tool_call, context)\n```\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]()\n\n### Middleware Pipeline Execution\n\nThe middleware system processes requests through a pipeline where each middleware can:\n\n1. **Pre-process**: Act on the request before passing to the next middleware\n2. **Pass through**: Forward the request to the next component in the chain\n3. **Post-process**: Act on the response as it flows back up the chain\n4. **Short-circuit**: Return a response without calling subsequent middleware\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MW1 as Middleware 1\n    participant MW2 as Middleware 2\n    participant Agent as Core Agent\n    \n    Client->>MW1: request\n    MW1->>MW2: pass to next\n    MW2->>Agent: forward request\n    Agent-->>MW2: response\n    MW2-->>MW1: post-process\n    MW1-->>Client: final response\n```\n\n## .NET Middleware Implementation\n\n### ToolApprovalAgent\n\nThe .NET implementation provides a `ToolApprovalAgent` that wraps an agent and requires approval for tool executions. This is particularly useful for scenarios where human-in-the-loop approval is required for sensitive operations.\n\n```csharp\npublic class ToolApprovalAgent : Agent\n{\n    public ToolApprovalAgent(\n        Agent inner,\n        IToolApprover toolApprover,\n        Func<ToolCall, bool>? shouldApprove = null);\n    \n    public override async Task<Result> OnToolCallAsync(\n        ToolCall toolCall,\n        Context context,\n        CancellationToken cancellationToken);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n### Middleware Registration\n\nIn .NET, middleware is typically registered through dependency injection and configured on the agent:\n\n```csharp\n// Program.cs from the sample\nvar builder = Kernel.CreateBuilder();\n\n// Register middleware\nbuilder.Services.AddSingleton<IAgentMiddleware, LoggingMiddleware>();\n\nvar kernel = builder.Build();\n\n// Configure agent with middleware\nvar agent = new ChatClientAgent(chatClient)\n    .WithMiddleware<LoggingMiddleware>()\n    .WithMiddleware<ToolApprovalMiddleware>();\n```\n\n资料来源：[dotnet/samples/02-agents/Agents/Agent_Step11_Middleware/Program.cs]()\n\n### Built-in .NET Middleware\n\n| Middleware | Description |\n|------------|-------------|\n| `LoggingMiddleware` | Logs all requests, responses, and tool calls |\n| `ToolApprovalMiddleware` | Requires approval before tool execution |\n| `RateLimitMiddleware` | Enforces rate limiting on agent requests |\n| `AuthenticationMiddleware` | Validates authentication tokens |\n\n## Middleware API Reference\n\n### Python Middleware API\n\n#### `@middleware` Decorator\n\nCreates a simple function-based middleware.\n\n```python\n@middleware\nasync def middleware_func(agent, tool_call, context, call_next):\n    \"\"\"Middleware function signature.\"\"\"\n    pass\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `agent` | `Agent` | The agent instance being wrapped |\n| `tool_call` | `ToolCall` | The tool call being processed |\n| `context` | `Context` | Execution context with state |\n| `call_next` | `Callable` | Function to invoke the next middleware/agent |\n\n资料来源：[python/packages/core/agent_framework/_middleware.py]()\n\n#### `Middleware` Base Class\n\nAbstract class for stateful middleware:\n\n```python\nclass Middleware(ABC):\n    @abstractmethod\n    async def on_tool_call(\n        self, \n        agent: Agent, \n        tool_call: ToolCall, \n        context: Context\n    ) -> Result:\n        \"\"\"Called when a tool call is intercepted.\"\"\"\n        pass\n```\n\n| Method | Description |\n|--------|-------------|\n| `on_tool_call` | Intercepts and processes tool calls |\n| `on_request` | Intercepts incoming requests |\n| `on_response` | Intercepts outgoing responses |\n| `next()` | Passes control to the next middleware |\n\n### .NET Middleware API\n\n#### `IAgentMiddleware` Interface\n\n```csharp\npublic interface IAgentMiddleware\n{\n    Task<Result> InvokeAsync(\n        AgentContext context,\n        MiddlewareDelegate next,\n        CancellationToken cancellationToken);\n}\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `context` | `AgentContext` | Contains request, response, and state |\n| `next` | `MiddlewareDelegate` | Delegate to invoke the next middleware |\n| `cancellationToken` | `CancellationToken` | Cancellation support |\n\n#### `Agent` Extension Methods\n\n```csharp\npublic static class AgentMiddlewareExtensions\n{\n    public static TAgent WithMiddleware<TMiddleware>(\n        this TAgent agent,\n        params object[] args) where TAgent : Agent;\n    \n    public static TAgent WithMiddleware(\n        this TAgent agent,\n        Type middlewareType,\n        params object[] args) where TAgent : Agent;\n}\n```\n\n## Use Cases\n\n### 1. Tool Approval Workflow\n\nA common use case is requiring human approval before executing sensitive tools:\n\n```mermaid\ngraph LR\n    A[Agent] --> B{ToolApprovalMiddleware}\n    B --> C{Is Sensitive?}\n    C -->|Yes| D[Request Human Approval]\n    D --> E{Approved?}\n    E -->|Yes| F[Execute Tool]\n    E -->|No| G[Reject & Return Error]\n    C -->|No| F\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/ToolApproval/ToolApprovalAgent.cs]()\n\n### 2. Request/Response Logging\n\nMiddleware can log all interactions for debugging and auditing:\n\n```python\n@middleware\nasync def audit_logging_middleware(agent, tool_call, context, call_next):\n    log_entry = {\n        \"timestamp\": datetime.utcnow(),\n        \"tool_name\": tool_call.name,\n        \"parameters\": tool_call.arguments,\n        \"user\": context.user_id\n    }\n    await audit_log(log_entry)\n    return await call_next(agent, tool_call, context)\n```\n\n### 3. Request Filtering\n\nMiddleware can filter or modify requests before they reach the agent:\n\n```csharp\npublic class ContentFilterMiddleware : IAgentMiddleware\n{\n    public async Task<Result> InvokeAsync(\n        AgentContext context,\n        MiddlewareDelegate next,\n        CancellationToken cancellationToken)\n    {\n        // Check for prohibited content\n        if (ContainsProhibitedContent(context.Request.Text))\n        {\n            return new Result { Success = false, Error = \"Content filtered\" };\n        }\n        \n        return await next(context, cancellationToken);\n    }\n}\n```\n\n## Configuration\n\n### Python Configuration\n\n```python\nagent = Agent(\n    name=\"my_agent\",\n    instructions=\"You are a helpful assistant\",\n    middleware=[\n        LoggingMiddleware(),\n        ToolApprovalMiddleware(approver=human_approver),\n        RateLimitMiddleware(max_calls_per_minute=60)\n    ]\n)\n```\n\n### .NET Configuration\n\n```csharp\n// Via dependency injection\nbuilder.Services.AddTransient<IAgentMiddleware, LoggingMiddleware>();\nbuilder.Services.AddSingleton<IToolApprover, HumanToolApprover>();\n\n// Or inline during agent creation\nvar agent = new ChatClientAgent(chatClient)\n    .WithMiddleware<LoggingMiddleware>()\n    .WithMiddleware(sp.GetRequiredService<ToolApprovalMiddleware>());\n```\n\n## Best Practices\n\n1. **Keep middleware focused**: Each middleware should handle a single concern (logging, authentication, etc.)\n\n2. **Always call `next` or return**: Ensure middleware either passes control to the next component or returns a response\n\n3. **Handle exceptions**: Wrap `next` calls in try-catch to prevent unhandled exceptions from breaking the pipeline\n\n4. **Order matters**: Register middleware in the correct order based on dependencies\n\n5. **Avoid blocking operations**: Use async/await patterns to prevent blocking the pipeline\n\n6. **Document side effects**: Clearly document any side effects middleware may have\n\n## Error Handling\n\nMiddleware should gracefully handle errors and either:\n- Recover and continue the pipeline\n- Short-circuit with an appropriate error response\n- Propagate the error with additional context\n\n```python\n@middleware\nasync def error_handling_middleware(agent, tool_call, context, call_next):\n    try:\n        return await call_next(agent, tool_call, context)\n    except ToolExecutionException as e:\n        logger.error(f\"Tool execution failed: {e}\")\n        return Result(\n            success=False,\n            error=f\"Tool execution failed: {str(e)}\",\n            context={\"original_error\": e}\n        )\n```\n\n## Related Components\n\n| Component | Relationship |\n|-----------|--------------|\n| Agent | Core component that middleware intercepts |\n| Tools | Often the target of middleware interception |\n| Context | State container passed through middleware pipeline |\n| Skills | Can be combined with middleware for complex workflows |\n\n## Summary\n\nThe Middleware System provides a flexible, extensible pipeline architecture for intercepting and modifying agent behavior. It supports both simple function-based middleware and complex class-based middleware with full lifecycle control. The system is available across both Python and .NET implementations, enabling consistent cross-platform extensibility patterns.\n\nKey takeaways:\n- Middleware enables cross-cutting concerns without modifying core agent code\n- Both Python and .NET provide decorator/attribute-based middleware creation\n- Tool approval is a common built-in middleware pattern\n- Middleware can short-circuit, pass through, or modify requests and responses\n- Proper ordering and error handling are essential for reliable middleware pipelines\n\n---\n\n<a id='provider-integration'></a>\n\n## AI Provider Integration\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Getting Started with Microsoft Agent Framework](#getting-started)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/openai/agent_framework_openai/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/openai/agent_framework_openai/__init__.py)\n- [python/packages/anthropic/agent_framework_anthropic/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/anthropic/agent_framework_anthropic/__init__.py)\n- [python/packages/foundry/agent_framework_foundry/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry/agent_framework_foundry/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs)\n- [python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n- [dotnet/samples/02-agents/AgentProviders/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentProviders/README.md)\n</details>\n\n# AI Provider Integration\n\n## Overview\n\nThe AI Provider Integration layer in Microsoft Agent Framework enables agents to communicate with various Large Language Model (LLM) backends through a unified abstraction. This architecture allows developers to switch between different AI providers—such as OpenAI, Azure AI Foundry, Anthropic, and Ollama—without modifying agent logic. The provider system acts as the bridge between the agent's execution framework and the underlying AI models.\n\nThe framework supports both Python and .NET ecosystems, with provider implementations that expose chat completion clients, responses API clients, and specialized agent integrations. Each provider package implements common interfaces while leveraging provider-specific authentication, configuration, and API semantics.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"Agent Layer\"\n        A[Agent Instance]\n        S[Skills/Tools]\n    end\n    \n    subgraph \"Provider Abstraction\"\n        P[Provider Interface]\n    end\n    \n    subgraph \"Concrete Providers\"\n        O[OpenAI]\n        F[Azure AI Foundry]\n        An[Anthropic Claude]\n        Ol[Ollama]\n        G[GitHub Copilot]\n    end\n    \n    subgraph \"External Services\"\n        OS[OpenAI API]\n        FS[Azure Foundry]\n        AS[Anthropic API]\n        LS[Local Ollama]\n        GS[GitHub Copilot]\n    end\n    \n    A --> P\n    S --> P\n    P --> O\n    P --> F\n    P --> An\n    P --> Ol\n    P --> G\n    O --> OS\n    F --> FS\n    An --> AS\n    Ol --> LS\n    G --> GS\n```\n\n## Provider Packages\n\n### Python Provider Packages\n\n| Package | Purpose | Install Command |\n|---------|---------|-----------------|\n| `agent-framework-openai` | OpenAI and Azure OpenAI integration | `pip install agent-framework-openai` |\n| `agent-framework-anthropic` | Anthropic Claude model support | `pip install agent-framework-anthropic` |\n| `agent-framework-foundry` | Azure AI Foundry integration | `pip install agent-framework-foundry` |\n| `agent-framework-claude` | Claude-specific agentic capabilities | `pip install agent-framework-claude --pre` |\n| `agent-framework-ollama` | Local Ollama model support | `pip install agent-framework-ollama --pre` |\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Provider Assemblies\n\n| Assembly | Namespace | Purpose |\n|----------|-----------|---------|\n| `Microsoft.Agents.AI.OpenAI` | `Microsoft.Agents.AI.OpenAI` | OpenAI Response API and Chat Completions |\n| `Microsoft.Agents.AI.Foundry` | `Microsoft.Agents.AI.Foundry` | Azure AI Foundry agent and client integration |\n| `Microsoft.Agents.AI.GitHub.Copilot` | `Microsoft.Agents.AI.GitHub.Copilot` | GitHub Copilot agent extension |\n\n## Azure AI Foundry Provider\n\nAzure AI Foundry provides the primary production-grade provider for enterprise deployments. It integrates with Azure AI Foundry projects, enabling agents to leverage Foundry's model deployments, content safety, and telemetry.\n\n### Python Implementation\n\nThe Foundry provider package exports core classes for connecting to Azure AI Foundry projects:\n\n```python\n# python/packages/foundry/agent_framework_foundry/__init__.py\n# Core exports include:\n# - FoundryChatCompletionClient\n# - FoundryAgent\n# - Configuration utilities\n```\n\nThe provider requires environment configuration:\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://<resource>.services.ai.azure.com/api/projects/<project>\"\nexport FOUNDRY_MODEL=\"<deployment-name>\"\n```\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Implementation\n\nThe .NET Foundry provider exposes two primary integration points:\n\n#### FoundryAgent\n\nThe `FoundryAgent` class serves as the agent implementation backed by Azure AI Foundry:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs\npublic class FoundryAgent\n{\n    // Provides agent creation and lifecycle management\n    // Integrates with Azure AI Foundry service\n}\n```\n\n#### AzureAIProjectChatClient\n\nThe `AzureAIProjectChatClient` wraps the Azure AI Foundry chat client with Agent Framework conventions:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClient.cs\npublic class AzureAIProjectChatClient\n{\n    // Manages project-scoped chat interactions\n    // Handles authentication and connection to Foundry\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Foundry/FoundryAgent.cs)\n\n### Foundry Configuration Options\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `project_endpoint` | Azure AI Foundry project URL | Required |\n| `model` | Model deployment name | `gpt-4o` |\n| `api_version` | API version for requests | Latest stable |\n| `credential` | Azure authentication credential | `DefaultAzureCredential` |\n\n## OpenAI Provider\n\nThe OpenAI provider enables agents to connect directly to OpenAI's API or Azure OpenAI Service endpoints.\n\n### Python Integration\n\n```python\nfrom agent_framework.openai import OpenAIChatClient, OpenAIChatCompletionClient\n\n# Direct OpenAI usage\nclient = OpenAIChatClient(model=\"gpt-4\")\n\n# Using Responses API\nclient = OpenAIChatCompletionClient(model=\"gpt-4\")\n```\n\n资料来源：[python/packages/openai/agent_framework_openai/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/openai/agent_framework_openai/__init__.py)\n\n### .NET Integration\n\nThe .NET OpenAI provider uses the `OpenAIResponseClientExtensions` class to create agent instances:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs\npublic static class OpenAIResponseClientExtensions\n{\n    public static ChatClientAgent AsAIAgent(\n        this ResponsesClient client,\n        string? model = null,\n        string? instructions = null,\n        string? name = null,\n        string? description = null,\n        IList<AITool>? tools = null,\n        Func<IChatClient, IChatClient>? clientFactory = null,\n        ILoggerFactory? loggerFactory = null,\n        IServiceProvider? services = null)\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/OpenAIResponseClientExtensions.cs)\n\n## Anthropic Provider\n\nThe Anthropic provider integrates Claude models into the Agent Framework, supporting both direct API access and provider-specific agentic capabilities.\n\n### Python Integration\n\n```python\nfrom agent_framework_anthropic import ClaudeAgent\n\nagent = ClaudeAgent(\n    model=\"claude-sonnet-4-20250514\",\n    # Provider-specific configuration\n)\n```\n\n资料来源：[python/packages/anthropic/agent_framework_anthropic/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/anthropic/agent_framework_anthropic/__init__.py)\n\nThe `agent-framework-claude` package specifically enables Claude agentic capabilities through the Agent Framework:\n\n```bash\npip install agent-framework-claude --pre\n```\n\n资料来源：[python/packages/claude/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/claude/README.md)\n\n## Ollama Provider\n\nOllama enables local LLM deployments, useful for development, testing, and privacy-sensitive scenarios.\n\n### Configuration\n\n```bash\nexport OLLAMA_BASE_URL=\"http://localhost:11434\"  # Default\nexport OLLAMA_MODEL=\"llama3.2\"  # Model to use\n```\n\n### Installation\n\n```bash\npip install agent-framework-ollama --pre\n```\n\n资料来源：[python/packages/ollama/README.md](https://github.com/microsoft/agent-framework/blob/main/python/packages/ollama/README.md)\n\nSamples demonstrating Ollama connector usage are available at:\n\n```\npython/samples/02-agents/providers/ollama/\n```\n\n## GitHub Copilot Provider\n\nThe .NET implementation includes a GitHub Copilot integration through the `CopilotClientExtensions`:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs\npublic static AIAgent AsAIAgent(\n    this CopilotClient client,\n    bool ownsClient = false,\n    string? id = null,\n    string? name = null,\n    string? description = null,\n    IList<AITool>? tools = null,\n    string? instructions = null)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/CopilotClientExtensions.cs)\n\n## Provider Selection Workflow\n\n```mermaid\ngraph LR\n    A[Choose Provider] --> B{Have Azure Account?}\n    B -->|Yes| C[Azure AI Foundry]\n    B -->|No| D[Direct OpenAI]\n    C --> E[Configure Endpoint]\n    D --> F[Set API Key]\n    E --> G[Create ChatClient]\n    F --> G\n    G --> H[Initialize Agent]\n    H --> I[Attach Skills/Tools]\n    I --> J[Execute Agent]\n```\n\n## Agent ID Model\n\nProviders use a standardized `AgentId` model for identification:\n\n```csharp\n// dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs\ninternal sealed class AgentId\n{\n    [JsonPropertyName(\"type\")]\n    public AgentIdType Type { get; init; }\n    \n    [JsonPropertyName(\"name\")]\n    public string Name { get; init; }\n    \n    [JsonPropertyName(\"version\")]\n    public string Version { get; init; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/Models/AgentId.cs)\n\n## Sample Applications\n\n### Python Provider Samples\n\n| Sample | Provider | Description |\n|--------|----------|-------------|\n| `providers/openai/` | OpenAI | Basic OpenAI integration |\n| `providers/foundry/` | Foundry | Azure AI Foundry integration |\n| `providers/anthropic/` | Anthropic | Claude model usage |\n| `providers/ollama/` | Ollama | Local model deployment |\n\nRun samples:\n\n```bash\ncd python\nuv run samples/02-agents/providers/<provider-name>/\n```\n\n资料来源：[python/samples/02-agents/providers/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/README.md)\n\n### .NET Provider Samples\n\n```bash\ncd dotnet/samples/02-agents/AgentProviders\ndotnet run\n```\n\n资料来源：[dotnet/samples/02-agents/AgentProviders/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentProviders/README.md)\n\n## Authentication Patterns\n\n| Provider | Authentication Method |\n|----------|----------------------|\n| Azure AI Foundry | `DefaultAzureCredential`, `AzureCliCredential` |\n| OpenAI | API Key via environment or parameter |\n| Anthropic | API Key via environment |\n| Ollama | No authentication (local) |\n| GitHub Copilot | Copilot client authentication |\n\nMost Azure-based providers support `AzureCliCredential`, requiring `az login` before execution:\n\n```bash\naz login\n```\n\n## Best Practices\n\n1. **Environment Variables**: Store provider credentials in environment variables rather than hardcoding\n2. **Provider Selection**: Use Azure AI Foundry for production, OpenAI for development, Ollama for testing\n3. **Client Reuse**: Create chat clients once and reuse across agent instances when possible\n4. **Error Handling**: Implement retry logic for transient provider failures\n5. **Model Selection**: Match model capabilities to task requirements for cost efficiency\n\n## Deprecated Integrations\n\nThe `Microsoft.Agents.AI.AzureAI.Persistent` package is marked obsolete:\n\n```csharp\n[Obsolete(\"Please use the latest Foundry Agents service via the Microsoft.Agents.AI.AzureAI package.\")]\npublic static async Task<ChatClientAgent> CreateAIAgentAsync(...)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.AzureAI.Persistent/PersistentAgentsClientExtensions.cs)\n\nMigration to the Foundry provider is recommended for persistent agent use cases.\n\n---\n\n<a id='sessions-and-history'></a>\n\n## Sessions, History, and State Management\n\n### 相关页面\n\n相关主题：[Agent System](#agents), [Workflows and Orchestration](#workflows)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_sessions.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_sessions.py)\n- [python/packages/core/agent_framework/_compaction.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_compaction.py)\n- [dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs)\n- [python/packages/redis/agent_framework_redis/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/redis/agent_framework_redis/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs)\n- [python/samples/02-agents/conversations/custom_history_provider.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/conversations/custom_history_provider.py)\n- [python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py)\n</details>\n\n# Sessions, History, and State Management\n\nAgent Framework provides a comprehensive system for managing conversation state across multi-turn interactions. This system encompasses sessions that track user conversations, history providers that store and retrieve chat messages, and state management mechanisms that preserve context throughout agent interactions.\n\n## Overview\n\nThe session and state management architecture in Agent Framework enables persistent conversations across multiple exchanges. At its core, the framework uses `AgentSession` objects to uniquely identify conversation threads, `ChatHistoryProvider` implementations to store message history, and various compaction strategies to manage context window constraints.\n\n```mermaid\ngraph TD\n    A[Agent Invocation] --> B[AgentSession]\n    B --> C[ChatHistoryProvider]\n    C --> D[State Storage]\n    B --> E[StateBag]\n    D --> F[Persistent Storage]\n    E --> G[In-Memory State]\n    C --> H[Compaction Strategy]\n    H --> I[Context Reduction]\n    \n    style A fill:#e1f5ff\n    style F fill:#fff3e0\n    style G fill:#e8f5e9\n```\n\n## Agent Session\n\nAn `AgentSession` represents a unique conversation context between a user and an agent. The session serves as the primary container for all stateful information related to a specific interaction.\n\n### Session Structure\n\nThe session object contains metadata and state information:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `session_id` | string | Unique identifier for the session |\n| `user_id` | string | Identifier for the user |\n| `agent_id` | string | Identifier for the agent |\n| `metadata` | dict | Application-specific metadata |\n| `state_bag` | dict | Custom state storage |\n| `created_at` | datetime | Session creation timestamp |\n| `last_accessed_at` | datetime | Last activity timestamp |\n\n资料来源：[python/packages/core/agent_framework/_sessions.py]()\n\n### Session Lifecycle\n\nSessions are created when a user initiates a conversation and persist until explicitly terminated. The framework supports both in-memory and persistent session storage backends.\n\n```python\n# Session creation pattern (Python)\nsession = AgentSession(\n    user_id=\"user123\",\n    agent_id=\"assistant-01\",\n    metadata={\"conversation_type\": \"support\"}\n)\n```\n\n## Chat History Management\n\nChat history providers are responsible for storing, retrieving, and managing conversation messages. The framework provides multiple built-in providers and supports custom implementations.\n\n### Built-in History Providers\n\n| Provider | Storage Backend | Use Case |\n|----------|-----------------|----------|\n| `InMemoryChatHistoryProvider` | Memory | Development, testing |\n| `CosmosChatHistoryProvider` | Azure Cosmos DB | Production, scalable |\n| `RedisChatHistoryProvider` | Redis | Production, high-performance |\n| Custom Provider | Configurable | Application-specific needs |\n\n### In-Memory Provider\n\nThe `InMemoryChatHistoryProvider` provides session-scoped message storage suitable for single-instance deployments:\n\n```csharp\npublic class InMemoryChatHistoryProvider : ChatHistoryProvider\n{\n    private readonly SessionState _sessionState;\n    \n    public List<ChatMessage> GetMessages(AgentSession? session)\n        => this._sessionState.GetOrInitializeState(session).Messages;\n    \n    public void SetMessages(AgentSession? session, List<ChatMessage> messages)\n    {\n        Throw.IfNull(messages);\n        State state = this._sessionState.GetOrInitializeState(session);\n        state.Messages = messages;\n    }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/InMemoryChatHistoryProvider.cs:1-30]()\n\n### Cosmos DB Provider\n\nFor production deployments requiring persistence and scalability, the Cosmos DB provider offers fully managed storage:\n\n```python\n# Cosmos DB history provider initialization\nfrom agent_framework import AgentFrameworkClient\n\nclient = AgentFrameworkClient(endpoint=\"your-endpoint\")\nhistory_provider = client.create_chat_history_provider(\n    provider_type=\"cosmos\",\n    connection_string=\"your-connection-string\",\n    database=\"agent_sessions\",\n    container=\"chat_history\"\n)\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatHistoryProvider.cs]()\n\n### Redis Provider\n\nThe Redis provider provides low-latency access to chat history with automatic expiration:\n\n```python\n# Redis session management\nfrom agent_framework_redis import RedisSessionManager\n\nsession_manager = RedisSessionManager(\n    host=\"localhost\",\n    port=6379,\n    prefix=\"agent_session:\",\n    ttl=3600  # 1 hour TTL\n)\n```\n\n资料来源：[python/packages/redis/agent_framework_redis/__init__.py]()\n\n### Custom History Provider\n\nDevelopers can implement custom history providers by extending the base `ChatHistoryProvider` class:\n\n```python\nfrom agent_framework import ChatHistoryProvider, ChatMessage\nfrom typing import List, Optional\n\nclass CustomHistoryProvider(ChatHistoryProvider):\n    def __init__(self, storage_backend):\n        self._storage = storage_backend\n    \n    async def get_messages(self, session_id: str) -> List[ChatMessage]:\n        return await self._storage.retrieve(session_id)\n    \n    async def add_message(self, session_id: str, message: ChatMessage) -> None:\n        await self._storage.append(session_id, message)\n    \n    async def clear_history(self, session_id: str) -> None:\n        await self._storage.delete(session_id)\n```\n\n资料来源：[python/samples/02-agents/conversations/custom_history_provider.py]()\n\n## Compaction and Context Management\n\nAs conversations grow, managing context window limits becomes critical. The framework provides compaction strategies that automatically reduce message history while preserving important context.\n\n### Compaction Strategy Interface\n\nBoth Python and .NET implementations define the `CompactionStrategy` interface:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `max_context_window_tokens` | int | Maximum tokens in context window |\n| `max_output_tokens` | int | Reserved tokens for model output |\n| `available_input_tokens` | int | Computed available for input |\n\n```csharp\npublic abstract class CompactionStrategy\n{\n    public int MaxContextWindowTokens { get; }\n    public int MaxOutputTokens { get; }\n    public int AvailableInputTokens => MaxContextWindowTokens - MaxOutputTokens;\n    \n    public abstract Task<IEnumerable<ChatMessage>> CompactAsync(\n        IList<ChatMessage> messages,\n        CancellationToken cancellationToken = default);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Compaction/CompactionStrategy.cs]()\n\n### Compaction Trigger Events\n\nThe compaction process can be configured to trigger at different points in the message lifecycle:\n\n| Trigger Event | Timing | Use Case |\n|---------------|--------|----------|\n| `BeforeMessagesRetrieval` | Before history fetch | Optimize retrieval |\n| `AfterMessagesRetrieval` | After history fetch | Post-processing |\n| `OnTokenThreshold` | At token limit | Aggressive reduction |\n\n```csharp\n// Configure pre-retrieval compaction\nif (this.ReducerTriggerEvent == InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.BeforeMessagesRetrieval \n    && this.ChatReducer is not null)\n{\n    await ReduceMessagesAsync(this.ChatReducer, state, cancellationToken);\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/InMemoryChatHistoryProvider.cs:25-45]()\n\n### Python Compaction Implementation\n\nThe Python implementation follows a similar pattern with configurable compaction strategies:\n\n```python\nclass CompactionStrategy(ABC):\n    def __init__(\n        self,\n        max_context_window_tokens: int = 128000,\n        max_output_tokens: int = 4096\n    ):\n        self.max_context_window_tokens = max_context_window_tokens\n        self.max_output_tokens = max_output_tokens\n    \n    @property\n    def available_input_tokens(self) -> int:\n        return self.max_context_window_tokens - self.max_output_tokens\n    \n    @abstractmethod\n    async def compact(\n        self,\n        messages: List[ChatMessage],\n        cancellation_token: Optional[CancellationToken] = None\n    ) -> List[ChatMessage]:\n        pass\n```\n\n资料来源：[python/packages/core/agent_framework/_compaction.py]()\n\n## State Management\n\n### Session State Bag\n\nThe `StateBag` provides a dictionary-like interface for storing custom application state within a session:\n\n```csharp\npublic class AgentSession\n{\n    public IDictionary<string, object> StateBag { get; set; }\n}\n\n// Usage\nsession.StateBag[\"last_intent\"] = \"greeting\";\nsession.StateBag[\"user_preference\"] = new { theme = \"dark\", language = \"en\" };\n```\n\n### Context Providers\n\n`AIContextProvider` instances enable middleware-style processing of conversation context:\n\n```mermaid\ngraph LR\n    A[User Message] --> B[AIContextProvider.BeforeInvoke]\n    B --> C[Agent Invocation]\n    C --> D[AIContextProvider.Invoked]\n    D --> E[Response to User]\n    \n    F[Update State] -.-> B\n    G[Log/Audit] -.-> D\n    H[Extract Memories] -.-> D\n```\n\n```csharp\npublic ValueTask BeforeInvokeAsync(InvokingContext context, CancellationToken cancellationToken = default)\n{\n    // Use the request and response messages to:\n    // - Update state based on conversation outcomes\n    // - Extract and store memories or preferences\n    // - Log or audit conversation details\n    return default;\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AIContextProvider.cs:1-25]()\n\n### Chat History Memory Provider Scope\n\nFor scoping chat history across applications, agents, or sessions:\n\n```csharp\npublic sealed class ChatHistoryMemoryProviderScope\n{\n    public string? ApplicationId { get; set; }\n    public string? AgentId { get; set; }\n    public string? SessionId { get; set; }\n    public string? UserId { get; set; }\n}\n```\n\n| Scope Property | Effect When Set |\n|----------------|-----------------|\n| `ApplicationId` | Restricts history to specific application |\n| `AgentId` | Restricts history to specific agent |\n| `SessionId` | Restricts history to specific session |\n| `UserId` | Restricts history to specific user |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Memory/ChatHistoryMemoryProviderScope.cs]()\n\n## Workflow Checkpointing\n\nFor long-running workflows, the framework supports checkpoint-based state persistence that allows recovery from failures and resumption of interrupted executions.\n\n```python\nfrom agent_framework import CheckpointStorage, CosmosCheckpointStorage\n\ncheckpoint_storage = CosmosCheckpointStorage(\n    endpoint=\"your-cosmos-endpoint\",\n    database=\"workflows\",\n    container=\"checkpoints\"\n)\n\n# Save checkpoint\nawait checkpoint_storage.save_checkpoint(\n    workflow_id=\"workflow-123\",\n    step=\"step-3\",\n    state={\"progress\": 75, \"data\": {...}},\n    metadata={\"started_at\": \"2024-01-15T10:00:00Z\"}\n)\n\n# Resume from checkpoint\ncheckpoint = await checkpoint_storage.load_checkpoint(\n    workflow_id=\"workflow-123\"\n)\n```\n\n资料来源：[python/samples/03-workflows/checkpoint/cosmos_workflow_checkpointing.py]()\n\n## Agent Configuration Options\n\nThe `HarnessAgentOptions` class demonstrates comprehensive configuration for session and history management:\n\n```csharp\npublic class HarnessAgentOptions\n{\n    public ChatOptions? ChatOptions { get; set; }\n    public ChatHistoryProvider? ChatHistoryProvider { get; set; }\n    public IEnumerable<AIContextProvider>? AIContextProviders { get; set; }\n}\n```\n\n| Option | Description |\n|--------|-------------|\n| `ChatOptions` | Configures instructions, tools, and model parameters |\n| `ChatHistoryProvider` | Storage backend for conversation history |\n| `AIContextProviders` | Middleware providers for context processing |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Harness/HarnessAgentOptions.cs:1-50]()\n\n## Agent Modes\n\nSessions can operate in different modes that affect behavior:\n\n```csharp\npublic sealed class AgentMode\n{\n    public string Name { get; }\n    public string Description { get; }\n}\n\npublic class AgentModeProviderOptions\n{\n    public IReadOnlyList<AgentMode>? Modes { get; set; }\n    public string? DefaultMode { get; set; }\n}\n```\n\n| Mode | Description |\n|------|-------------|\n| `plan` | Interactive planning mode |\n| `execute` | Autonomous execution mode |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/Harness/AgentMode/AgentModeProviderOptions.cs]()\n\n## Response Updates\n\nThe `AgentResponseUpdate` class represents streaming response data with full metadata:\n\n```csharp\npublic class AgentResponseUpdate\n{\n    public string? AuthorName { get; set; }\n    public ChatRole? Role { get; set; }\n    public IList<AIContent>? Contents { get; set; }\n    public FinishReason? FinishReason { get; set; }\n    public string? MessageId { get; set; }\n    public string? ResponseId { get; set; }\n    public DateTimeOffset? CreatedAt { get; set; }\n}\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseUpdate.cs:1-30]()\n\n## Best Practices\n\n### Session Management\n\n1. **Session Initialization**: Always initialize sessions with appropriate user and agent identifiers\n2. **Session Cleanup**: Implement session expiration for idle conversations\n3. **State Isolation**: Use separate state bags for different concerns\n\n### History Management\n\n1. **Provider Selection**: Choose providers based on scale requirements\n2. **Compaction Tuning**: Configure compaction thresholds based on model context limits\n3. **History Pruning**: Implement retention policies for regulatory compliance\n\n### State Management\n\n1. **State Serialization**: Ensure custom state objects are serializable\n2. **Context Providers**: Use context providers for cross-cutting concerns\n3. **Checkpoint Frequency**: Balance checkpoint overhead against recovery requirements\n\n## See Also\n\n- [Hello Agent Tutorial](python/samples/01-get-started/README.md)\n- [Multi-Turn Conversations](python/samples/02-agents/conversations/)\n- [Workflow Checkpointing](python/samples/03-workflows/checkpoint/)\n- [Agent Skills System](dotnet/src/Microsoft.Agents.AI/Skills/AgentSkill.cs)\n\n---\n\n<a id='hosting-patterns'></a>\n\n## Hosting and Deployment Patterns\n\n### 相关页面\n\n相关主题：[Workflows and Orchestration](#workflows), [Observability and Telemetry](#observability)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py)\n- [python/packages/durabletask/agent_framework_durabletask/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/durabletask/agent_framework_durabletask/__init__.py)\n- [python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py)\n- [dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md)\n- [dotnet/src/Microsoft.Agents.AI.DurableTask/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n- [python/samples/04-hosting/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n- [dotnet/samples/04-hosting/README.md](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n- [python/samples/04-hosting/foundry-hosted-agents/README.md](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/foundry-hosted-agents/README.md)\n</details>\n\n# Hosting and Deployment Patterns\n\nThe Microsoft Agent Framework provides multiple hosting and deployment patterns to accommodate different runtime environments and enterprise requirements. This documentation covers the available hosting options, configuration requirements, and deployment strategies for both Python and .NET implementations.\n\n## Overview\n\nThe framework supports three primary hosting paradigms:\n\n| Hosting Pattern | Language | Runtime Environment | Use Case |\n|-----------------|----------|---------------------|----------|\n| Azure Functions | Python, .NET | Serverless/Event-driven | Stateless agent invocations |\n| Durable Task | Python, .NET | Long-running workflows | Complex orchestrations with state persistence |\n| Foundry Hosting | Python, .NET | Azure AI Foundry | Managed agent deployment with platform integration |\n\n资料来源：[python/samples/04-hosting/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n资料来源：[dotnet/samples/04-hosting/README.md:1-20](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Client Request] --> B{Deployment Pattern}\n    B -->|Azure Functions| C[Function App]\n    B -->|Durable Task| D[Orchestration Engine]\n    B -->|Foundry Hosting| E[Azure AI Foundry]\n    \n    C --> F[Stateless Agent Handler]\n    D --> G[Stateful Orchestrator]\n    E --> H[Managed Agent Runtime]\n    \n    F --> I[Response]\n    G --> I\n    H --> I\n```\n\n## Azure Functions Hosting\n\nAzure Functions provides a serverless hosting model suitable for event-driven agent invocations. The framework offers native integration through dedicated packages for both Python and .NET.\n\n### Python Azure Functions Package\n\nThe Python Azure Functions hosting package is located at `python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py`.\n\n**Installation**\n\n```bash\npip install agent-framework-azurefunctions\n```\n\n资料来源：[python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/azurefunctions/agent_framework_azurefunctions/__init__.py)\n\n### .NET Azure Functions Package\n\nThe .NET Azure Functions hosting is provided through the `Microsoft.Agents.AI.Hosting.AzureFunctions` NuGet package.\n\n**Installation**\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.Hosting.AzureFunctions\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\nOr via CLI:\n\n```bash\ndotnet add package Microsoft.Agents.AI.Hosting.AzureFunctions\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md:1-15](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md)\n\n### Configuration\n\nAzure Functions samples require the following environment configuration:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `AZURE_OPENAI_ENDPOINT` | Azure OpenAI service endpoint | `https://your-resource.openai.azure.com/` |\n| `AZURE_OPENAI_DEPLOYMENT_NAME` | Model deployment name | `gpt-4o` |\n| `TASKHUB_NAME` | Durable Task hub name (for orchestration) | `default` |\n\n资料来源：[dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md:1-30](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md)\n\n### Sample Structure\n\nThe repository includes Azure Functions samples organized by complexity:\n\n```\ndotnet/samples/04-hosting/DurableAgents/AzureFunctions/\n├── 01_SingleAgent/\n├── 02_MultiAgent/\n└── README.md\n```\n\n**Running the Sample**\n\n```bash\ncd dotnet/samples/04-hosting/DurableAgents/AzureFunctions/01_SingleAgent\nfunc start\n```\n\nThe function app becomes available at `http://localhost:7071`.\n\n资料来源：[dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md:45-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions/README.md)\n\n## Durable Task Hosting\n\nDurable Task hosting enables long-running agent workflows with state persistence and checkpoint capabilities. This pattern is essential for complex multi-step orchestrations.\n\n### Python Durable Task Package\n\n**Installation**\n\n```bash\npip install agent-framework-durabletask\n```\n\nThe package is located at `python/packages/durabletask/agent_framework_durabletask/__init__.py`.\n\n资料来源：[python/packages/durabletask/agent_framework_durabletask/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/durabletask/agent_framework_durabletask/__init__.py)\n\n### .NET Durable Task Package\n\n**Installation**\n\n```xml\n<ItemGroup>\n  <PackageReference Include=\"Microsoft.Agents.AI.DurableTask\" Version=\"[CURRENTVERSION]\" />\n</ItemGroup>\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.DurableTask/README.md:1-10](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.DurableTask/README.md)\n\n### Workflow Orchestration\n\n```mermaid\ngraph LR\n    A[Start] --> B[Activity: Initialize]\n    B --> C[Activity: Process]\n    C --> D{Continue?}\n    D -->|Yes| C\n    D -->|No| E[Activity: Finalize]\n    E --> F[Complete]\n    \n    G[Orchestrator] -.-> A\n    G -.-> B\n    G -.-> C\n    G -.-> D\n    G -.-> E\n    G -.-> F\n```\n\n### Azurite Emulator Requirement\n\nWhen running Durable Task samples locally, start the Azurite emulator:\n\n```bash\naz login\nazd pipeline config\nazd up\n```\n\nOr manually:\n\n```bash\nazurite\n```\n\n资料来源：[python/samples/04-hosting/azure_functions/README.md:1-20](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/azure_functions/README.md)\n\n## Foundry Hosting\n\nFoundry Hosting provides the most comprehensive deployment option with deep integration into Azure AI Foundry. This pattern supports managed agents, model routing, and enterprise-grade security.\n\n### Python Foundry Hosting Package\n\n**Installation**\n\n```bash\npip install agent-framework-foundry-hosting\n```\n\nThe package is located at `python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py`.\n\n资料来源：[python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/foundry_hosting/agent_framework_foundry_hosting/__init__.py)\n\n### Configuration Requirements\n\nFoundry-hosted agents require specific environment configuration:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `FOUNDRY_PROJECT_ENDPOINT` | Azure AI Foundry project endpoint | Yes |\n| `FOUNDRY_MODEL` or `AZURE_AI_MODEL_DEPLOYMENT_NAME` | Model deployment name | Yes |\n| `AZURE_BEARER_TOKEN` | Authentication token (for Docker) | Docker only |\n| `AGENT_NAME` | Foundry-managed agent name | Local dev |\n\n资料来源：[python/samples/04-hosting/foundry-hosted-agents/README.md:1-40](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/foundry-hosted-agents/README.md)\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md:1-25](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md)\n\n### Environment Setup\n\n**Bash/Linux**\n\n```bash\nexport FOUNDRY_PROJECT_ENDPOINT=\"https://<account>.services.ai.azure.com/api/projects/<project>\"\nexport AZURE_AI_MODEL_DEPLOYMENT_NAME=\"<your-model-deployment-name>\"\n```\n\n**PowerShell**\n\n```powershell\n$env:FOUNDRY_PROJECT_ENDPOINT=\"https://<account>.services.ai.azure.com/api/projects/<project>\"\n$env:AZURE_AI_MODEL_DEPLOYMENT_NAME=\"<your-model-deployment-name>\"\n```\n\n### Foundry Hosted Agent Samples\n\nThe repository provides multiple Foundry hosting samples:\n\n| Sample | Description | Path |\n|--------|-------------|------|\n| `Hosted-TextRag` | Text-based RAG agent | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-TextRag/` |\n| `Hosted-FoundryAgent` | Direct Foundry agent hosting | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/` |\n| `Hosted-AzureSearchRag` | Azure AI Search integration | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag/` |\n| `Hosted-McpTools` | MCP tools integration | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-McpTools/` |\n| `Hosted-Files` | Bundled file handling | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/` |\n| `Hosted-Workflow-Simple` | Multi-step workflow | `dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/` |\n\n资料来源：[python/samples/04-hosting/README.md:1-50](https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/README.md)\n资料来源：[dotnet/samples/04-hosting/README.md:1-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/README.md)\n\n## Deployment Workflows\n\n### Direct Execution (Contributors)\n\nFor local development and contribution work:\n\n```bash\ncd dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent\nAGENT_NAME=<your-agent-name> dotnet run\n```\n\nThe agent starts on `http://localhost:8088`.\n\n### Docker Deployment\n\n#### Publishing for Container Runtime\n\n```bash\ndotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out\n```\n\n#### Building the Image\n\n```bash\ndocker build -f Dockerfile.contributor -t hosted-foundry-agent .\n```\n\n#### Running the Container\n\n```bash\nexport AZURE_BEARER_TOKEN=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)\n\ndocker run --rm -p 8088:8088 \\\n  -e AGENT_NAME=hosted-foundry-agent \\\n  -e AZURE_BEARER_TOKEN=$AZURE_BEARER_TOKEN \\\n  --env-file .env \\\n  hosted-foundry-agent\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md:20-60](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/README.md)\n\n## Testing Hosted Agents\n\n### Using Azure Developer CLI\n\n```bash\nazd ai agent invoke --local \"Hello!\"\n```\n\n### Using curl\n\n```bash\ncurl -X POST http://localhost:8088/responses \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"input\": \"Hello!\", \"model\": \"<your-agent-name>\"}'\n```\n\n### Testing Session Files\n\n```bash\ncd ../Using-Samples/SessionFilesClient\n$env:AGENT_ENDPOINT = \"http://localhost:8088\"\n$env:AGENT_NAME = \"hosted-files\"\ndotnet run\n\nYou> What is the total revenue in the contoso file?\n```\n\n资料来源：[dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/README.md:30-50](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/README.md)\n\n## Comparison Matrix\n\n| Feature | Azure Functions | Durable Task | Foundry Hosting |\n|---------|-----------------|--------------|-----------------|\n| Stateful Execution | No | Yes | Yes |\n| Long-running Workflows | No | Yes | Yes |\n| Serverless | Yes | No | No |\n| Managed Scaling | Yes | Manual | Yes |\n| Checkpoint/Resume | No | Yes | Yes |\n| Azure AI Foundry Integration | No | No | Yes |\n| Local Development Support | Limited | Yes | Yes |\n| Docker Deployment | Yes | Yes | Yes |\n\n## Next Steps\n\n- Explore the [Azure Functions samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/04-hosting/DurableAgents/AzureFunctions) for event-driven patterns\n- Review the [Foundry hosting samples](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/04-hosting/FoundryHostedAgents) for enterprise deployments\n- Check the [Durable Task documentation](https://github.com/microsoft/agent-framework/tree/main/dotnet/src/Microsoft.Agents.AI.DurableTask) for orchestration patterns\n\n---\n\n<a id='observability'></a>\n\n## Observability and Telemetry\n\n### 相关页面\n\n相关主题：[Workflows and Orchestration](#workflows), [Hosting and Deployment Patterns](#hosting-patterns)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [python/packages/core/agent_framework/_telemetry.py](https://github.com/microsoft/agent-framework/blob/main/python/packages/core/agent_framework/_telemetry.py)\n- [dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs)\n- [dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs)\n- [docs/decisions/0003-agent-opentelemetry-instrumentation.md](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0003-agent-opentelemetry-instrumentation.md)\n- [python/samples/02-agents/observability/agent_observability.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/observability/agent_observability.py)\n- [dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs)\n</details>\n\n# Observability and Telemetry\n\nThe Agent Framework provides comprehensive observability capabilities through OpenTelemetry integration, enabling distributed tracing, performance metrics collection, and detailed logging across both .NET and Python implementations.\n\n## Overview\n\nObservability in the Agent Framework allows developers to:\n\n- **Trace agent invocations** across distributed systems\n- **Collect performance metrics** and timing information\n- **Log request and response payloads** (when enabled)\n- **Track errors** and capture exception details\n- **Monitor usage statistics** and token consumption\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgentBuilderExtensions.cs:1-30]()\n\nThe implementation follows the OpenTelemetry Semantic Conventions for Generative AI systems as defined in the [OpenTelemetry specification](https://opentelemetry.io/docs/specs/semconv/gen-ai/). The specification for Generative AI is still experimental and subject to change.\n\n资料来源：[docs/decisions/0003-agent-opentelemetry-instrumentation.md:1-20]()\n\n## Architecture\n\n### High-Level Component Interaction\n\n```mermaid\ngraph TD\n    A[Application] --> B[OpenTelemetry Agent Wrapper]\n    B --> C[Inner AIAgent]\n    C --> D[IChatClient]\n    D --> E[AI Provider<br/>OpenAI/Anthropic/GitHub Copilot]\n    \n    B -.-> F[OpenTelemetry Traces]\n    B -.-> G[Metrics]\n    B -.-> H[Logs]\n    \n    F --> I[OTLP Exporter]\n    G --> I\n    H --> I\n    \n    I --> J[Telemetry Backend<br/>Azure Monitor/Jaeger/...]\n```\n\n### Auto-Wiring Mechanism\n\nWhen using `OpenTelemetryAgent`, the framework automatically wraps underlying chat clients with telemetry instrumentation:\n\n```mermaid\ngraph LR\n    A[ChatClientAgent] --> B[OpenTelemetryAgent]\n    B --> C{IChatClient}\n    C -->|autoWireChatClient: true| D[Auto-wrap with<br/>OpenTelemetryChatClient]\n    C -->|Already Instrumented| E[No Additional Wrapping]\n    D --> F[Chat-Level Telemetry]\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-25]()\n\n## .NET Implementation\n\n### OpenTelemetryAgent\n\nThe `OpenTelemetryAgent` class wraps an existing `AIAgent` to add telemetry capabilities without modifying the underlying agent's behavior.\n\n**Class Declaration:**\n\n```csharp\n[Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)]\npublic sealed class OpenTelemetryAgent : AIAgent\n```\n\n**Constructor Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `innerAgent` | `AIAgent` | The underlying agent to be augmented with telemetry |\n| `sourceName` | `string?` | Optional source name for telemetry identification |\n| `autoWireChatClient` | `bool` | Auto-wrap ChatClientAgent's IChatClient with OpenTelemetryChatClient |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-40]()\n\n**Key Features:**\n\n1. **Provider Metadata Extraction**: Automatically extracts provider metadata from the inner agent via `AIAgentMetadata`.\n\n```csharp\nthis._providerName = innerAgent.GetService<AIAgentMetadata>()?.ProviderName;\n```\n\n2. **Chat Client Auto-Wiring**: When `autoWireChatClient` is `true` and the inner agent is a `ChatClientAgent`, the underlying `IChatClient` is automatically wrapped with `OpenTelemetryChatClient`.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs:1-50]()\n\n### Builder Extension\n\nThe recommended way to add telemetry to agents is through the `AIAgentBuilder`:\n\n```csharp\npublic static AIAgentBuilder UseOpenTelemetry(\n    this AIAgentBuilder builder,\n    string? sourceName = null,\n    Action<OpenTelemetryAgent>? configure = null)\n```\n\n**Usage:**\n\n```csharp\nAIAgent agent = builder\n    .WithChatClient(chatClient)\n    .UseOpenTelemetry(sourceName: \"my-agent\")\n    .Build();\n```\n\n资料来源：[dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgentBuilderExtensions.cs:1-45]()\n\n### Workflow Telemetry Options\n\nThe `WorkflowTelemetryOptions` class provides configuration for workflow-level telemetry:\n\n| Property | Type | Default | Description |\n|----------|------|---------|-------------|\n| `EnableSensitiveData` | `bool` | `false` | Include potentially sensitive information in telemetry |\n| `DisableWorkflowBuild` | `bool` | `false` | Disable `workflow.build` activities |\n| `DisableWorkflowRun` | `bool` | `false` | Disable `workflow_invoke` activities |\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Observability/WorkflowTelemetryOptions.cs:1-40]()\n\n### Activity Extensions\n\nThe framework provides extension methods for creating and managing OpenTelemetry activities in workflows:\n\n```csharp\n// Creating activity spans for workflow operations\nActivitySource activitySource = new ActivitySource(\"Microsoft.Agents.AI.Workflows\");\n\n// Activity creation following semantic conventions\nvar activity = activitySource.StartActivity(\"workflow.invoke\");\n```\n\nThese extensions ensure proper tagging and attributes according to OpenTelemetry's generative AI conventions.\n\n资料来源：[dotnet/src/Microsoft.Agents.AI.Workflows/Observability/ActivityExtensions.cs:1-30]()\n\n## Python Implementation\n\n### Telemetry Module\n\nThe Python SDK provides telemetry capabilities through the `_telemetry.py` module:\n\n```python\nfrom agent_framework._telemetry import configure_otel_providers\n```\n\n**Key Functions:**\n\n| Function | Description |\n|----------|-------------|\n| `configure_otel_providers()` | Configure OpenTelemetry providers with exporters |\n| `configure_otel_providers_with_env_var()` | Use standard OTEL environment variables |\n\n资料来源：[python/packages/core/agent_framework/_telemetry.py:1-50]()\n\n### Basic Configuration\n\n```python\nfrom agent_framework.observability import configure_otel_providers\n\n# Enable console exporters for development\nconfigure_otel_providers(enable_console_exporters=True)\n```\n\n资料来源：[python/samples/02-agents/observability/agent_observability.py:1-20]()\n\n### GitHub Copilot Agent Integration\n\nThe `GitHubCopilotAgent` has OpenTelemetry tracing built-in:\n\n```python\nfrom agent_framework.observability import configure_otel_providers\nfrom agent_framework.github import GitHubCopilotAgent\n\nconfigure_otel_providers(enable_console_exporters=True)\n\nasync with GitHubCopilotAgent() as agent:\n    response = await agent.run(\"Hello!\")\n```\n\n资料来源：[python/samples/02-agents/providers/github_copilot/README.md:1-30]()\n\n### Environment Variables\n\nPython observability supports standard OpenTelemetry environment variables:\n\n| Variable | Description |\n|----------|-------------|\n| `OTEL_SERVICE_NAME` | Service name for telemetry |\n| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP exporter endpoint |\n| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol (grpc, http/protobuf) |\n| `OTEL_RESOURCE_ATTRIBUTES` | Additional resource attributes |\n\n资料来源：[python/samples/02-agents/observability/README.md:1-30]()\n\n### Logging Configuration\n\nAlign Python logs with telemetry output:\n\n```python\nimport logging\n\nlogging.basicConfig(\n    format=\"[%(asctime)s - %(pathname)s:%(lineno)d - %(levelname)s] %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\n\n# Get root logger and set detailed level\nlogger = logging.getLogger()\nlogger.setLevel(logging.NOTSET)\n```\n\n资料来源：[python/samples/02-agents/observability/README.md:1-60]()\n\n## Semantic Conventions\n\nThe Agent Framework adheres to OpenTelemetry's semantic conventions for generative AI systems. Key conventions include:\n\n```mermaid\ngraph TD\n    A[AI Agent Invocation] --> B[Semantic Convention Attributes]\n    \n    B --> C[gen_ai.system]\n    B --> D[gen_ai.request.model]\n    B --> E[gen_ai.response.id]\n    B --> F[gen_ai.usage.prompt_tokens]\n    B --> G[gen_ai.usage.completion_tokens]\n    B --> H[gen_ai.response.finish_reason]\n```\n\n**Standard Attributes:**\n\n| Attribute | Description |\n|-----------|-------------|\n| `gen_ai.system` | The AI system type (e.g., \"openai\", \"anthropic\") |\n| `gen_ai.request.model` | Model identifier for the request |\n| `gen_ai.response.id` | Unique identifier for the response |\n| `gen_ai.usage.prompt_tokens` | Number of tokens in the prompt |\n| `gen_ai.usage.completion_tokens` | Number of tokens in completion |\n| `gen_ai.response.finish_reason` | Reason for completion termination |\n\n资料来源：[docs/decisions/0003-agent-opentelemetry-instrumentation.md:1-50]()\n\n## Configuration Examples\n\n### .NET: Full Agent with Telemetry\n\n```csharp\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Telemetry;\n\n// Create the builder\nIAIAgentBuilder builder = new AgentBuilder();\n\n// Configure with telemetry\nAIAgent agent = builder\n    .WithChatClient(chatClient)\n    .UseOpenTelemetry(\n        sourceName: \"my-agent\",\n        configure: agent => \n        {\n            // Additional configuration\n        })\n    .Build();\n\n// Use the agent - all invocations are automatically traced\nvar response = await agent.InvokeAsync(\"Hello, agent!\");\n```\n\n资料来源：[dotnet/samples/02-agents/AgentOpenTelemetry/Program.cs:1-50]()\n\n### Python: Advanced Exporter Configuration\n\n```python\nfrom agent_framework.observability import configure_otel_providers\nfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\n\n# Create custom exporter\ncustom_exporter = OTLPSpanExporter(\n    endpoint=\"https://your-endpoint.azure.com\",\n    insecure=True\n)\n\n# Configure with custom exporter\nconfigure_otel_providers(\n    service_name=\"my-agent-service\",\n    span_exporter=custom_exporter,\n    enable_console_exporters=True\n)\n```\n\n资料来源：[python/samples/02-agents/observability/configure_otel_providers_with_parameters.py:1-40]()\n\n## Best Practices\n\n### 1. Consistent Source Naming\n\nUse meaningful source names to identify telemetry data:\n\n```csharp\n// Good\nbuilder.UseOpenTelemetry(sourceName: \"customer-support-agent\");\n\n// Avoid\nbuilder.UseOpenTelemetry(); // Uses default\n```\n\n### 2. Sensitive Data Handling\n\nBy default, telemetry excludes raw inputs and outputs:\n\n```csharp\nvar options = new WorkflowTelemetryOptions\n{\n    EnableSensitiveData = false // Default - excludes raw content\n};\n```\n\nOnly enable sensitive data logging when necessary and ensure proper data protection.\n\n### 3. Selective Activity Recording\n\nDisable activities that generate excessive telemetry:\n\n```csharp\nvar options = new WorkflowTelemetryOptions\n{\n    DisableWorkflowBuild = true,  // Reduce noise in build-heavy workflows\n    DisableWorkflowRun = false   // Keep run telemetry\n};\n```\n\n### 4. Provider Compatibility\n\nThe telemetry implementation adapts to the underlying AI provider:\n\n| Provider | Telemetry Support |\n|----------|-------------------|\n| OpenAI | Full |\n| Anthropic | Full |\n| Azure AI Foundry | Full |\n| GitHub Copilot | Built-in |\n\n### 5. Environment-Based Configuration\n\nUse environment variables for deployment flexibility:\n\n```bash\n# Development\nexport OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317\nexport OTEL_SERVICE_NAME=agent-dev\n\n# Production\nexport OTEL_EXPORTER_OTLP_ENDPOINT=https://telemetry.company.com\nexport OTEL_SERVICE_NAME=agent-prod\n```\n\n## Troubleshooting\n\n### Missing Telemetry Data\n\n1. Verify OpenTelemetry SDK is properly configured\n2. Check that the exporter endpoint is accessible\n3. Ensure `ActivitySource` names match between instrumentation and export\n\n### Duplicate Telemetry\n\nIf using `ChatClientAgent` with `OpenTelemetryAgent`:\n\n- Set `autoWireChatClient: false` when chat client is already instrumented\n- Avoid manually wrapping already-wrapped clients\n\n### Performance Impact\n\nTelemetry collection adds minimal overhead. For high-throughput scenarios:\n\n- Use batch exporters instead of simple exporters\n- Consider disabling verbose logging levels\n- Sample traces when full fidelity is not required\n\n## Related Documentation\n\n- [OpenTelemetry Semantic Conventions for Generative AI](https://opentelemetry.io/docs/specs/semconv/gen-ai/)\n- [Agent Framework Decision: OpenTelemetry Instrumentation](https://github.com/microsoft/agent-framework/blob/main/docs/decisions/0003-agent-opentelemetry-instrumentation.md)\n- [Python Observability Samples](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/observability/)\n- [.NET Agent OpenTelemetry Sample](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/02-agents/AgentOpenTelemetry/)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：microsoft/agent-framework\n\n摘要：发现 23 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…。\n\n## 1. 安装坑 · 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT events\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d329260309954749a2b3b2a9e7135d56 | https://github.com/microsoft/agent-framework/issues/4923 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8f9f05dcb7564f34bdd5902dcea6be27 | https://github.com/microsoft/agent-framework/issues/5785 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 3. 安全/权限坑 · 来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_49875a7dd60f480a99718cfa30b12723 | https://github.com/microsoft/agent-framework/issues/5708 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安全/权限坑 · 来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_58594f7966b84d81924da21ad789effd | https://github.com/microsoft/agent-framework/issues/5707 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_644a3ed07d2d4bfd8188392b4af687c2 | https://github.com/microsoft/agent-framework/issues/5794 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 安全/权限坑 · 来源证据：Anthropic function limit fallback can return empty final response\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Anthropic function limit fallback can return empty final response\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b61b91ca16094a448f8c0eab5e2daaa1 | https://github.com/microsoft/agent-framework/issues/5769 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 安全/权限坑 · 来源证据：Python: Add tutorial for building a custom chat client / LLM provider\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: Add tutorial for building a custom chat client / LLM provider\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_959e1eeb912a469c89f68f7f12275690 | https://github.com/microsoft/agent-framework/issues/5505 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 来源证据：python-1.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：python-1.2.1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f22ed66ae1f44b28b893aa5cbe439c92 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. 配置坑 · 来源证据：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows…\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows with typed outputs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_52da26ae3ace4acb9913ac780bfb6cd0 | https://github.com/microsoft/agent-framework/issues/5745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 10. 配置坑 · 来源证据：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_48aaa2f1026c4afd9e1a1da3a1a862a6 | https://github.com/microsoft/agent-framework/issues/5793 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 配置坑 · 来源证据：dotnet-1.5.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：dotnet-1.5.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b3d3127c36f41798428b164b5444cbb | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 配置坑 · 来源证据：python-1.2.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：python-1.2.2\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fb88b6cd86e04e199a03cfcf8a97dde6 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 能力坑 · 能力判断依赖假设\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:974445592 | https://github.com/microsoft/agent-framework | README/documentation is current enough for a first validation pass.\n\n## 14. 维护坑 · 来源证据：dotnet-1.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：dotnet-1.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e25f39a7081848689e086b1f98f92675 | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | last_activity_observed missing\n\n## 16. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 17. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:974445592 | https://github.com/microsoft/agent-framework | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 18. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 19. 安全/权限坑 · 来源证据：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_36cbde33c0a64127b95d953c65d49c54 | https://github.com/microsoft/agent-framework/issues/5798 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 20. 安全/权限坑 · 来源证据：python-1.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.2.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa3fc8cfbbad40f98ea1da9e68eeaa3f | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 21. 安全/权限坑 · 来源证据：python-1.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6df4ed99139d4fb0bc182d80b34e9d45 | https://github.com/microsoft/agent-framework/releases/tag/python-1.3.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. 维护坑 · 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:974445592 | https://github.com/microsoft/agent-framework | issue_or_pr_quality=unknown\n\n## 23. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | release_recency=unknown\n\n<!-- canonical_name: microsoft/agent-framework; 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项目：microsoft/agent-framework\n\n摘要：发现 23 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…。\n\n## 1. 安装坑 · 来源证据：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CON…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：.NET: [Bug]: TextContent.AdditionalProperties dropped by AsAGUIEventStreamAsync for TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT events\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d329260309954749a2b3b2a9e7135d56 | https://github.com/microsoft/agent-framework/issues/4923 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Bug: Agent responses lose structured JSON metadata in multi-agent orchestration (MAF 1.x.x)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8f9f05dcb7564f34bdd5902dcea6be27 | https://github.com/microsoft/agent-framework/issues/5785 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 3. 安全/权限坑 · 来源证据：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: OpenAI-compatible extra body field thinking is not forwarded when using Microsoft.Agents.AI.OpenAI\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_49875a7dd60f480a99718cfa30b12723 | https://github.com/microsoft/agent-framework/issues/5708 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安全/权限坑 · 来源证据：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: In v. 1.5.0 Microsoft.Agents.AI.Anthropic (and Google.GenAI) do not work [Regression]\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_58594f7966b84d81924da21ad789effd | https://github.com/microsoft/agent-framework/issues/5707 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：.NET: [Bug]: Regression - Tool Events not being emitted correctly to the front end\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_644a3ed07d2d4bfd8188392b4af687c2 | https://github.com/microsoft/agent-framework/issues/5794 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 安全/权限坑 · 来源证据：Anthropic function limit fallback can return empty final response\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Anthropic function limit fallback can return empty final response\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b61b91ca16094a448f8c0eab5e2daaa1 | https://github.com/microsoft/agent-framework/issues/5769 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 安全/权限坑 · 来源证据：Python: Add tutorial for building a custom chat client / LLM provider\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: Add tutorial for building a custom chat client / LLM provider\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_959e1eeb912a469c89f68f7f12275690 | https://github.com/microsoft/agent-framework/issues/5505 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 来源证据：python-1.2.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：python-1.2.1\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f22ed66ae1f44b28b893aa5cbe439c92 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. 配置坑 · 来源证据：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows…\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：.NET: [Bug]: DurableTask: SuperstepState.AccumulatedEvents overflows CustomStatus 16 KB cap on multi-executor workflows with typed outputs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_52da26ae3ace4acb9913ac780bfb6cd0 | https://github.com/microsoft/agent-framework/issues/5745 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 10. 配置坑 · 来源证据：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Python: CosmosHistoryProvider Code interpreter tool calls are saved chunk by chunk\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_48aaa2f1026c4afd9e1a1da3a1a862a6 | https://github.com/microsoft/agent-framework/issues/5793 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 配置坑 · 来源证据：dotnet-1.5.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：dotnet-1.5.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b3d3127c36f41798428b164b5444cbb | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.5.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 配置坑 · 来源证据：python-1.2.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：python-1.2.2\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fb88b6cd86e04e199a03cfcf8a97dde6 | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 能力坑 · 能力判断依赖假设\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:974445592 | https://github.com/microsoft/agent-framework | README/documentation is current enough for a first validation pass.\n\n## 14. 维护坑 · 来源证据：dotnet-1.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：dotnet-1.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e25f39a7081848689e086b1f98f92675 | https://github.com/microsoft/agent-framework/releases/tag/dotnet-1.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | last_activity_observed missing\n\n## 16. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 17. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:974445592 | https://github.com/microsoft/agent-framework | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 18. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:974445592 | https://github.com/microsoft/agent-framework | no_demo; severity=medium\n\n## 19. 安全/权限坑 · 来源证据：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Python: OpenAI store=True can silently bypass external HistoryProvider persistence\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_36cbde33c0a64127b95d953c65d49c54 | https://github.com/microsoft/agent-framework/issues/5798 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 20. 安全/权限坑 · 来源证据：python-1.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.2.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa3fc8cfbbad40f98ea1da9e68eeaa3f | https://github.com/microsoft/agent-framework/releases/tag/python-1.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 21. 安全/权限坑 · 来源证据：python-1.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：python-1.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6df4ed99139d4fb0bc182d80b34e9d45 | https://github.com/microsoft/agent-framework/releases/tag/python-1.3.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. 维护坑 · 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:974445592 | https://github.com/microsoft/agent-framework | issue_or_pr_quality=unknown\n\n## 23. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:974445592 | https://github.com/microsoft/agent-framework | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# agent-framework - 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 microsoft/agent-framework.\n\nProject:\n- Name: agent-framework\n- Repository: https://github.com/microsoft/agent-framework\n- Summary: A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: A framework for building, orchestrating and deploying AI agents and multi-agent workflows with support for Python and .NET.\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: Use the source-backed project context to guide one small, checkable workflow step.\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. getting-started: Getting Started with Microsoft Agent Framework. Produce one small intermediate artifact and wait for confirmation.\n2. architecture-overview: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. agents: Agent System. Produce one small intermediate artifact and wait for confirmation.\n4. tools-and-skills: Tools and Skills. Produce one small intermediate artifact and wait for confirmation.\n5. workflows: Workflows and Orchestration. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/microsoft/agent-framework\n- https://github.com/microsoft/agent-framework#readme\n- dotnet/.github/skills/build-and-test/SKILL.md\n- dotnet/.github/skills/project-structure/SKILL.md\n- dotnet/.github/skills/verify-dotnet-samples/SKILL.md\n- dotnet/.github/skills/verify-samples-tool/SKILL.md\n- dotnet/samples/02-agents/AgentSkills/Agent_Step01_FileBasedSkills/skills/unit-converter/SKILL.md\n- dotnet/samples/02-agents/AgentSkills/Agent_Step04_MixedSkills/skills/unit-converter/SKILL.md\n- python/.github/skills/python-code-quality/SKILL.md\n- python/.github/skills/python-development/SKILL.md\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项目：microsoft/agent-framework\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install agent-framework\n```\n\n来源：https://github.com/microsoft/agent-framework#readme\n\n## 来源\n\n- repo: https://github.com/microsoft/agent-framework\n- docs: https://github.com/microsoft/agent-framework#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_899444b38f6f433c876c520e7bed344e"
}
