呱呱扣可 發表於 2025-11-7 15:27:00

完整教程:双剑合璧:Microsoft Agent Framework——Python与.NET的AI智能体协奏曲

<style>pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", monospace !important; font-size: 14px !important; line-height: 1.6 !important; padding: 16px !important; margin: 16px 0 !important; background-color: rgba(248, 248, 248, 1) !important; border: 1px solid rgba(225, 228, 232, 1) !important; border-radius: 6px !important; tab-size: 4 !important; -moz-tab-size: 4 !important; max-width: 100% !important; box-sizing: border-box !important }
code { font-family: "Consolas", "Monaco", "Courier New", monospace !important; font-size: 14px !important; white-space: pre !important; word-wrap: normal !important; word-break: normal !important; overflow-wrap: normal !important; display: inline !important; background: rgba(0, 0, 0, 0) !important; border: none !important; padding: 0 !important; margin: 0 !important; line-height: inherit !important }
pre code { background: rgba(0, 0, 0, 0) !important; border: 0 !important; border-radius: 0 !important; display: block !important; line-height: 1.6 !important; margin: 0 !important; max-width: none !important; overflow: visible !important; padding: 0 !important; white-space: pre !important; word-wrap: normal !important; word-break: normal !important; color: inherit !important }
.token.comment, .token.prolog, .token.doctype, .token.cdata { color: rgba(112, 128, 144, 1) !important; font-style: italic !important }
.token.punctuation { color: rgba(153, 153, 153, 1) !important }
.token.atrule, .token.attr-value, .token.keyword { color: rgba(0, 119, 170, 1) !important; font-weight: bold !important }
.token.function, .token.class-name { color: rgba(221, 74, 104, 1) !important; font-weight: bold !important }
.token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color: rgba(102, 153, 0, 1) !important }
.token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: rgba(153, 0, 85, 1) !important }
.cnblogs-markdown pre, .cnblogs-post-body pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; background-color: rgba(248, 248, 248, 1) !important; border: 1px solid rgba(225, 228, 232, 1) !important; border-radius: 6px !important; padding: 16px !important; margin: 16px 0 !important }
pre, pre, pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important }</style>
      <div class="htmledit_views atom-one-dark" id="content_views"><blockquote><p>当Python的灵动遇见.NET的稳健,AI智能体开发进入了一个全新纪元。</p></blockquote><h3>引子:为什么我们需要又一个Agent框架?</h3><p><img alt="" height="1122" src="https://i-blog.csdnimg.cn/direct/986baea4b74741b68b0c774b6504477c.png" width="1152"></p><p>在AI Agent框架如雨后春笋般涌现的2025年,AutoGen、LangChain、LangGraph等已经占据了大量市场份额。此时微软推出Agent Framework,是又一次"重复造轮子"吗?</p><p>答案是否定的。<strong>Agent Framework最大的创新在于:它是首个真正实现Python和.NET双语言原生支持,且API设计高度一致的AI智能体框架。</strong>这不是简单的"翻译",而是深度理解两种语言生态后的精心设计。</p><p>让我们用一组对比数据来感受这种设计哲学:</p><table><tbody><tr><th>特性</th><th>AutoGen</th><th>LangGraph</th><th>Agent Framework</th></tr><tr><td>语言支持</td><td>Python</td><td>Python</td><td>Python + .NET (原生)</td></tr><tr><td>API一致性</td><td>N/A</td><td>N/A</td><td>98%+ 跨语言一致</td></tr><tr><td>工作流引擎</td><td>隐式</td><td>显式图</td><td>Pregel模型超步执行</td></tr><tr><td>检查点恢复</td><td>有限</td><td>支持</td><td>跨进程持久化</td></tr><tr><td>企业集成</td><td>中等</td><td>中等</td><td>深度Azure生态</td></tr></tbody></table><h3>第一章:架构哲学——同一个灵魂,两副躯壳</h3><h4>1.1 核心抽象:Agent的统一语义</h4><p>在Agent Framework中,**Agent不是一个具体的类,而是一种协议(Protocol)**。这是理解整个框架的关键。</p><p><strong>Python实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;AgentProtocol,&nbsp;ChatAgent,&nbsp;AgentRunResponse
#&nbsp;AgentProtocol是一个结构化协议(duck&nbsp;typing)
#&nbsp;任何实现了run()和run_stream()的类都是Agent
class&nbsp;CustomAgent:
&nbsp;&nbsp;&nbsp;&nbsp;@property
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;id(self)&nbsp;-&gt;&nbsp;str:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;"my-agent-001"
&nbsp;&nbsp;&nbsp;&nbsp;@property
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;name(self)&nbsp;-&gt;&nbsp;str:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;"Custom&nbsp;Agent"
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;run(self,&nbsp;messages=None,&nbsp;*,&nbsp;thread=None,&nbsp;**kwargs)&nbsp;-&gt;&nbsp;AgentRunResponse:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;自定义实现
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;AgentRunResponse(messages=[],&nbsp;response_id="resp-001")
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;run_stream(self,&nbsp;messages=None,&nbsp;*,&nbsp;thread=None,&nbsp;**kwargs):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;_stream():
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield&nbsp;AgentRunResponseUpdate()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;_stream()
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;get_new_thread(self,&nbsp;**kwargs):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;AgentThread()
#&nbsp;验证协议兼容性
assert&nbsp;isinstance(CustomAgent(),&nbsp;AgentProtocol)</code></pre>
<p><strong>.NET实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>//&nbsp;AIAgent是抽象基类,定义了强类型契约
public&nbsp;abstract&nbsp;class&nbsp;AIAgent
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;virtual&nbsp;string&nbsp;Id&nbsp;{&nbsp;get;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;virtual&nbsp;string?&nbsp;Name&nbsp;{&nbsp;get;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;virtual&nbsp;string&nbsp;DisplayName&nbsp;=&gt;&nbsp;Name&nbsp;??&nbsp;Id;
&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;核心方法:同步运行
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;abstract&nbsp;Task&nbsp;RunAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable<chatmessage>&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentThread?&nbsp;thread&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentRunOptions?&nbsp;options&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CancellationToken&nbsp;cancellationToken&nbsp;=&nbsp;default);
&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;流式运行
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;abstract&nbsp;IAsyncEnumerable&nbsp;RunStreamingAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable<chatmessage>&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentThread?&nbsp;thread&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentRunOptions?&nbsp;options&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CancellationToken&nbsp;cancellationToken&nbsp;=&nbsp;default);
&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;线程管理
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;abstract&nbsp;AgentThread&nbsp;GetNewThread();
}</chatmessage></agentrunresponseupdate></chatmessage></agentrunresponse></code></pre>
<p><strong>设计洞察:</strong></p><ul><li><p><strong>Python采用Protocol</strong>: 利用Python的duck typing,最大化灵活性,允许开发者完全自定义Agent实现</p></li><li><p><strong>.NET采用抽象类</strong>: 利用静态类型系统,提供编译时检查和IntelliSense支持</p></li><li><p><strong>语义等价性</strong>: 尽管实现机制不同,两者的行为契约完全一致</p></li></ul><h4>1.2 响应模型:Primary vs Secondary内容的哲学思考</h4><p>Agent执行过程中会产生大量输出:最终答案、工具调用、推理过程、状态更新等。如何组织这些信息?Agent Framework借鉴了OpenAI Agent SDK和AutoGen的设计,将输出分为:</p><ol><li><p><strong>Primary内容</strong>: 面向最终用户的响应(文本、图片、结构化数据)</p></li><li><p><strong>Secondary内容</strong>: 中间过程信息(工具调用、日志、状态变化)</p></li></ol><p><strong>Python响应结构:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>@dataclass
class&nbsp;AgentRunResponse:
&nbsp;&nbsp;&nbsp;&nbsp;messages:&nbsp;list&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Primary内容
&nbsp;&nbsp;&nbsp;&nbsp;response_id:&nbsp;str
&nbsp;&nbsp;&nbsp;&nbsp;created_at:&nbsp;datetime&nbsp;|&nbsp;None&nbsp;=&nbsp;None
&nbsp;&nbsp;&nbsp;&nbsp;usage_details:&nbsp;UsageDetails&nbsp;|&nbsp;None&nbsp;=&nbsp;None
&nbsp;&nbsp;&nbsp;&nbsp;raw_representation:&nbsp;Any&nbsp;=&nbsp;None&nbsp;&nbsp;&nbsp;#&nbsp;Secondary内容(完整响应)
&nbsp;&nbsp;&nbsp;&nbsp;@property
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;text(self)&nbsp;-&gt;&nbsp;str:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"""聚合所有TextContent,始终返回Primary内容"""
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;"".join(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;content.text
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;msg&nbsp;in&nbsp;self.messages
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;content&nbsp;in&nbsp;msg.contents
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;isinstance(content,&nbsp;TextContent)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)</code></pre>
<p><strong>.NET响应结构:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>public&nbsp;class&nbsp;AgentRunResponse
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;IList<chatmessage>&nbsp;Messages&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}&nbsp;&nbsp;//&nbsp;Primary内容
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;string&nbsp;Text&nbsp;{&nbsp;get;&nbsp;}&nbsp;&nbsp;//&nbsp;自动聚合TextContent
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;string?&nbsp;ResponseId&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;DateTimeOffset?&nbsp;CreatedAt&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;UsageDetails?&nbsp;Usage&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;object?&nbsp;RawRepresentation&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}&nbsp;&nbsp;//&nbsp;Secondary内容
}</chatmessage></code></pre>
<p><strong>关键决策:</strong> 根据ADR-0001,框架选择了"Option 1.1a"方案:</p><ul><li><p><strong>非流式调用</strong>: 返回包含Primary+Secondary的完整响应,但<code>Text</code>属性智能过滤,仅返回Primary</p></li><li><p><strong>流式调用</strong>: 返回混合流,由开发者按需过滤</p></li><li><p><strong>理由</strong>: 平衡简单性与灵活性,避免强制区分导致的API复杂度</p></li></ul><h4>1.3 工作流:从消息传递到图执行</h4><p>Agent Framework的工作流不是简单的Agent链式调用,而是基于<strong>Pregel模型的超步(Superstep)执行</strong>。这是一个鲜为人知但极其强大的设计。</p><p><strong>什么是Pregel模型?</strong></p><ul><li><p>起源于Google的图计算框架</p></li><li><p>核心思想:以<strong>顶点为中心</strong>进行批量同步并行(BSP)计算</p></li><li><p>执行模式:Think-Send-Receive的超步循环</p></li></ul><p><strong>Python工作流实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;Executor,&nbsp;WorkflowBuilder,&nbsp;WorkflowContext,&nbsp;handler
class&nbsp;UpperCase(Executor):
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;__init__(self,&nbsp;id:&nbsp;str):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super().__init__(id=id)
&nbsp;&nbsp;&nbsp;&nbsp;@handler
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;to_upper_case(self,&nbsp;text:&nbsp;str,&nbsp;ctx:&nbsp;WorkflowContext)&nbsp;-&gt;&nbsp;None:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WorkflowContext表示此节点会向下游发送str类型消息
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;text.upper()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;ctx.send_message(result)&nbsp;&nbsp;#&nbsp;发送到下游节点
@executor(id="reverse_text_executor")
async&nbsp;def&nbsp;reverse_text(text:&nbsp;str,&nbsp;ctx:&nbsp;WorkflowContext)&nbsp;-&gt;&nbsp;None:
&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;WorkflowContext表示:
&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;Never:&nbsp;不向下游发送消息
&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;str:&nbsp;产生str类型的工作流输出
&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;text[::-1]
&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;ctx.yield_output(result)&nbsp;&nbsp;#&nbsp;产生最终输出
#&nbsp;构建工作流
workflow&nbsp;=&nbsp;(WorkflowBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(UpperCase(id="upper"),&nbsp;reverse_text)
&nbsp;&nbsp;&nbsp;&nbsp;.set_start_executor(upper)
&nbsp;&nbsp;&nbsp;&nbsp;.build())
#&nbsp;执行
result&nbsp;=&nbsp;await&nbsp;workflow.run("hello&nbsp;world")
print(result.get_outputs())&nbsp;&nbsp;#&nbsp;['DLROW&nbsp;OLLEH']</code></pre>
<p><strong>.NET工作流实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>//&nbsp;定义Executor节点
public&nbsp;class&nbsp;UpperCaseExecutor&nbsp;:&nbsp;Executor<string, string>
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;override&nbsp;async&nbsp;Task&nbsp;ExecuteAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string&nbsp;input,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WorkflowContext<string>&nbsp;context)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;result&nbsp;=&nbsp;input.ToUpper();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;context.SendMessageAsync(result);
&nbsp;&nbsp;&nbsp;&nbsp;}
}
public&nbsp;class&nbsp;ReverseExecutor&nbsp;:&nbsp;Executor<string>
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;override&nbsp;async&nbsp;Task&nbsp;ExecuteAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string&nbsp;input,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WorkflowContext&nbsp;context)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;result&nbsp;=&nbsp;new&nbsp;string(input.Reverse().ToArray());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;context.YieldOutputAsync(result);
&nbsp;&nbsp;&nbsp;&nbsp;}
}
//&nbsp;构建工作流
var&nbsp;workflow&nbsp;=&nbsp;new&nbsp;WorkflowBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;.AddEdge(new&nbsp;UpperCaseExecutor(),&nbsp;new&nbsp;ReverseExecutor())
&nbsp;&nbsp;&nbsp;&nbsp;.SetStartExecutor<uppercaseexecutor>()
&nbsp;&nbsp;&nbsp;&nbsp;.Build<string>();
//&nbsp;执行
var&nbsp;result&nbsp;=&nbsp;await&nbsp;workflow.RunAsync("hello&nbsp;world");
Console.WriteLine(string.Join(",&nbsp;",&nbsp;result.GetOutputs()));&nbsp;//&nbsp;DLROW&nbsp;OLLEH</string></uppercaseexecutor></string></string></string, string></code></pre>
<p><strong>超步执行的魔力:</strong></p><ol><li><p><strong>消息隔离</strong>: 超步内的消息发送不会立即送达,而是在超步结束时批量传递</p></li><li><p><strong>状态一致性</strong>: 每个节点在超步内看到的是上一超步的稳定状态</p></li><li><p><strong>检查点友好</strong>: 每个超步结束都是一个自然的检查点边界</p></li><li><p><strong>并行执行</strong>: 同一超步内没有依赖的节点可以并行执行</p></li></ol><h3>第二章:实战对比——同一场景,两种实现</h3><h4>2.1 场景:多Agent协作的市场研究系统</h4><p><strong>需求:</strong></p><ol><li><p><strong>WebAgent</strong>: 从互联网搜索信息</p></li><li><p><strong>AnalystAgent</strong>: 分析数据并生成洞察</p></li><li><p><strong>CoderAgent</strong>: 将洞察转化为可视化代码</p></li><li><p><strong>ManagerAgent</strong>: 协调三者并汇总报告</p></li></ol><h5>Python实现</h5>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>import&nbsp;asyncio
from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent,&nbsp;WorkflowBuilder,&nbsp;Executor,&nbsp;handler
from&nbsp;agent_framework.openai&nbsp;import&nbsp;OpenAIChatClient
from&nbsp;agent_framework.workflows&nbsp;import&nbsp;WorkflowContext
#&nbsp;定义四个Agent
web_agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=OpenAIChatClient(),
&nbsp;&nbsp;&nbsp;&nbsp;name="WebAgent",
&nbsp;&nbsp;&nbsp;&nbsp;instructions="You&nbsp;search&nbsp;the&nbsp;web&nbsp;for&nbsp;market&nbsp;data&nbsp;and&nbsp;trends.",
&nbsp;&nbsp;&nbsp;&nbsp;tools=&nbsp;&nbsp;#&nbsp;假设已定义
)
analyst_agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=OpenAIChatClient(),
&nbsp;&nbsp;&nbsp;&nbsp;name="AnalystAgent",
&nbsp;&nbsp;&nbsp;&nbsp;instructions="You&nbsp;analyze&nbsp;market&nbsp;data&nbsp;and&nbsp;provide&nbsp;strategic&nbsp;insights."
)
coder_agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=OpenAIChatClient(),
&nbsp;&nbsp;&nbsp;&nbsp;name="CoderAgent",
&nbsp;&nbsp;&nbsp;&nbsp;instructions="You&nbsp;generate&nbsp;Python&nbsp;visualization&nbsp;code&nbsp;based&nbsp;on&nbsp;insights."
)
#&nbsp;定义协调器Executor
class&nbsp;ManagerExecutor(Executor):
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;__init__(self):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super().__init__(id="manager")
&nbsp;&nbsp;&nbsp;&nbsp;@handler
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;coordinate(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;results:&nbsp;list,&nbsp;&nbsp;#&nbsp;Fan-in接收多个输入
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ctx:&nbsp;WorkflowContext
&nbsp;&nbsp;&nbsp;&nbsp;)&nbsp;-&gt;&nbsp;None:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;汇总所有Agent的输出
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;final_report&nbsp;=&nbsp;f"""
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Market&nbsp;Research&nbsp;Report
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;======================
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Web&nbsp;Research:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Analysis:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Visualization:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;ctx.yield_output(final_report)
#&nbsp;构建工作流
workflow&nbsp;=&nbsp;(WorkflowBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;WebAgent&nbsp;-&gt;&nbsp;AnalystAgent&nbsp;-&gt;&nbsp;CoderAgent
&nbsp;&nbsp;&nbsp;&nbsp;.add_chain()
&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;三个Agent的输出汇聚到ManagerExecutor
&nbsp;&nbsp;&nbsp;&nbsp;.add_fan_in_edges(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ManagerExecutor()
&nbsp;&nbsp;&nbsp;&nbsp;)
&nbsp;&nbsp;&nbsp;&nbsp;.set_start_executor(web_agent)
&nbsp;&nbsp;&nbsp;&nbsp;.build()
)
#&nbsp;执行
result&nbsp;=&nbsp;await&nbsp;workflow.run("Analyze&nbsp;the&nbsp;AI&nbsp;chip&nbsp;market&nbsp;in&nbsp;2025")
print(result.get_outputs())</code></pre>
<p><strong>Python实现亮点:</strong></p><ul><li><p><strong>隐式Agent包装</strong>: WorkflowBuilder自动将<code>ChatAgent</code>包装为<code>AgentExecutor</code></p></li><li><p><strong>类型推断</strong>: <code>WorkflowContext]</code>自动处理fan-in聚合</p></li><li><p><strong>链式API</strong>: <code>add_chain()</code>一行代码定义顺序执行</p></li></ul><h5>.NET实现</h5>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>using&nbsp;Microsoft.Agents.AI;
using&nbsp;Microsoft.Agents.AI.Workflows;
//&nbsp;定义四个Agent
var&nbsp;webAgent&nbsp;=&nbsp;new&nbsp;AzureOpenAIClient(endpoint,&nbsp;credential)
&nbsp;&nbsp;&nbsp;&nbsp;.GetChatClient(deploymentName)
&nbsp;&nbsp;&nbsp;&nbsp;.CreateAIAgent("You&nbsp;search&nbsp;the&nbsp;web&nbsp;for&nbsp;market&nbsp;data.",&nbsp;"WebAgent");
var&nbsp;analystAgent&nbsp;=&nbsp;new&nbsp;AzureOpenAIClient(endpoint,&nbsp;credential)
&nbsp;&nbsp;&nbsp;&nbsp;.GetChatClient(deploymentName)
&nbsp;&nbsp;&nbsp;&nbsp;.CreateAIAgent("You&nbsp;analyze&nbsp;market&nbsp;data.",&nbsp;"AnalystAgent");
var&nbsp;coderAgent&nbsp;=&nbsp;new&nbsp;AzureOpenAIClient(endpoint,&nbsp;credential)
&nbsp;&nbsp;&nbsp;&nbsp;.GetChatClient(deploymentName)
&nbsp;&nbsp;&nbsp;&nbsp;.CreateAIAgent("You&nbsp;generate&nbsp;visualization&nbsp;code.",&nbsp;"CoderAgent");
//&nbsp;定义协调器Executor
public&nbsp;class&nbsp;ManagerExecutor&nbsp;:&nbsp;Executor<list<string>,&nbsp;string&gt;
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;override&nbsp;async&nbsp;Task&nbsp;ExecuteAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List<string>&nbsp;results,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WorkflowContext<string>&nbsp;context)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;finalReport&nbsp;=&nbsp;$@"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Market&nbsp;Research&nbsp;Report
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;======================
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Web&nbsp;Research:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Analysis:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Visualization:&nbsp;{results}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;context.YieldOutputAsync(finalReport);
&nbsp;&nbsp;&nbsp;&nbsp;}
}
//&nbsp;构建工作流
var&nbsp;workflow&nbsp;=&nbsp;new&nbsp;WorkflowBuilder<string>()
&nbsp;&nbsp;&nbsp;&nbsp;.AddChain(new[]&nbsp;{&nbsp;webAgent,&nbsp;analystAgent,&nbsp;coderAgent&nbsp;})
&nbsp;&nbsp;&nbsp;&nbsp;.AddFanInEdges(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new[]&nbsp;{&nbsp;webAgent,&nbsp;analystAgent,&nbsp;coderAgent&nbsp;},
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;ManagerExecutor()
&nbsp;&nbsp;&nbsp;&nbsp;)
&nbsp;&nbsp;&nbsp;&nbsp;.SetStartExecutor(webAgent)
&nbsp;&nbsp;&nbsp;&nbsp;.Build();
//&nbsp;执行
var&nbsp;result&nbsp;=&nbsp;await&nbsp;workflow.RunAsync("Analyze&nbsp;the&nbsp;AI&nbsp;chip&nbsp;market&nbsp;in&nbsp;2025");
Console.WriteLine(result.GetOutputs());</string></string></string></list<string></code></pre>
<p><strong>.NET实现亮点:</strong></p><ul><li><p><strong>强类型泛型</strong>: <code>Executor&lt;List&lt;string&gt;, string&gt;</code>明确输入输出类型,编译时检查</p></li><li><p><strong>扩展方法</strong>: <code>.CreateAIAgent()</code>是ChatClient的扩展方法,链式调用</p></li><li><p><strong>LINQ风格</strong>: 流畅的API设计符合.NET开发者习惯</p></li></ul><h4>2.2 高级特性:Checkpoint与Human-in-the-Loop</h4><p>这是Agent Framework相比其他框架的杀手级功能。</p><h5>Python检查点实现</h5>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.workflows&nbsp;import&nbsp;InMemoryCheckpointStorage,&nbsp;WorkflowBuilder
#&nbsp;启用检查点
checkpoint_storage&nbsp;=&nbsp;InMemoryCheckpointStorage()
workflow&nbsp;=&nbsp;(WorkflowBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(web_agent,&nbsp;analyst_agent)
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(analyst_agent,&nbsp;approval_executor)&nbsp;&nbsp;#&nbsp;人工审批节点
&nbsp;&nbsp;&nbsp;&nbsp;.with_checkpointing(checkpoint_storage)
&nbsp;&nbsp;&nbsp;&nbsp;.build()
)
#&nbsp;第一次运行:执行到需要审批的地方
result&nbsp;=&nbsp;await&nbsp;workflow.run_stream("Research&nbsp;AI&nbsp;market")
async&nbsp;for&nbsp;event&nbsp;in&nbsp;result:
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;isinstance(event,&nbsp;RequestInfoEvent):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;checkpoint_id&nbsp;=&nbsp;event.checkpoint_id
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;request_id&nbsp;=&nbsp;event.request_id
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(f"Checkpoint&nbsp;saved:&nbsp;{checkpoint_id}")
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(f"Awaiting&nbsp;approval&nbsp;for:&nbsp;{event.data}")
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break
#&nbsp;...&nbsp;应用程序可以关闭&nbsp;...
#&nbsp;稍后恢复:从检查点继续,带上人工批准
responses&nbsp;=&nbsp;{request_id:&nbsp;"Approved"}
resumed_result&nbsp;=&nbsp;await&nbsp;workflow.run_from_checkpoint(
&nbsp;&nbsp;&nbsp;&nbsp;checkpoint_id,
&nbsp;&nbsp;&nbsp;&nbsp;checkpoint_storage,
&nbsp;&nbsp;&nbsp;&nbsp;responses=responses
)
print(resumed_result.get_outputs())</code></pre>
<h5>.NET检查点实现</h5>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>using&nbsp;Microsoft.Agents.AI.Workflows.Checkpointing;
//&nbsp;启用检查点
var&nbsp;checkpointStorage&nbsp;=&nbsp;new&nbsp;InMemoryCheckpointStorage();
var&nbsp;workflow&nbsp;=&nbsp;new&nbsp;WorkflowBuilder<string>()
&nbsp;&nbsp;&nbsp;&nbsp;.AddEdge(webAgent,&nbsp;analystAgent)
&nbsp;&nbsp;&nbsp;&nbsp;.AddEdge(analystAgent,&nbsp;approvalExecutor)
&nbsp;&nbsp;&nbsp;&nbsp;.WithCheckpointing(checkpointStorage)
&nbsp;&nbsp;&nbsp;&nbsp;.Build();
//&nbsp;第一次运行
string&nbsp;checkpointId&nbsp;=&nbsp;null;
string&nbsp;requestId&nbsp;=&nbsp;null;
await&nbsp;foreach&nbsp;(var&nbsp;evt&nbsp;in&nbsp;workflow.RunStreamingAsync("Research&nbsp;AI&nbsp;market"))
{
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(evt&nbsp;is&nbsp;RequestInfoEvent&nbsp;requestEvent)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;checkpointId&nbsp;=&nbsp;requestEvent.CheckpointId;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;requestId&nbsp;=&nbsp;requestEvent.RequestId;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine($"Checkpoint&nbsp;saved:&nbsp;{checkpointId}");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine($"Awaiting&nbsp;approval&nbsp;for:&nbsp;{requestEvent.Data}");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
//&nbsp;...&nbsp;应用程序重启&nbsp;...
//&nbsp;从检查点恢复
var&nbsp;responses&nbsp;=&nbsp;new&nbsp;Dictionary<string, object>
{
&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;requestId,&nbsp;"Approved"&nbsp;}
};
var&nbsp;resumedResult&nbsp;=&nbsp;await&nbsp;workflow.RunFromCheckpointAsync(
&nbsp;&nbsp;&nbsp;&nbsp;checkpointId,
&nbsp;&nbsp;&nbsp;&nbsp;checkpointStorage,
&nbsp;&nbsp;&nbsp;&nbsp;responses
);
Console.WriteLine(string.Join(",&nbsp;",&nbsp;resumedResult.GetOutputs()));</string, object></string></code></pre>
<p><strong>检查点机制深度解析:</strong></p><p>Agent Framework的检查点不是简单的"快照",而是包含:</p><ol><li><p><strong>图拓扑签名</strong>: 防止用不兼容的工作流恢复检查点</p></li><li><p><strong>Executor状态</strong>: 每个节点的内部状态(如果实现了<code>IResettableExecutor</code>)</p></li><li><p><strong>飞行消息</strong>: 超步间传递但尚未处理的消息</p></li><li><p><strong>共享状态</strong>: <code>SharedState</code>中的全局数据</p></li></ol>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;Python:&nbsp;图签名计算
def&nbsp;_compute_graph_signature(self)&nbsp;-&gt;&nbsp;dict:
&nbsp;&nbsp;&nbsp;&nbsp;executors_signature&nbsp;=&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;executor_id:&nbsp;f"{executor.__class__.__module__}.{executor.__class__.__name__}"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;executor_id,&nbsp;executor&nbsp;in&nbsp;self.executors.items()
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;edge_groups_signature&nbsp;=&nbsp;[
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"group_type":&nbsp;group.__class__.__name__,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"sources":&nbsp;sorted(group.source_executor_ids),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"targets":&nbsp;sorted(group.target_executor_ids),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"edges":&nbsp;sorted([
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"source":&nbsp;e.source_id,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"target":&nbsp;e.target_id,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"condition":&nbsp;getattr(e,&nbsp;"condition_name",&nbsp;None)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;e&nbsp;in&nbsp;group.edges
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;])
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;group&nbsp;in&nbsp;self.edge_groups
&nbsp;&nbsp;&nbsp;&nbsp;]
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"start_executor":&nbsp;self.start_executor_id,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"executors":&nbsp;executors_signature,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"edge_groups":&nbsp;edge_groups_signature,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"max_iterations":&nbsp;self.max_iterations
&nbsp;&nbsp;&nbsp;&nbsp;}
#&nbsp;计算SHA256哈希
canonical&nbsp;=&nbsp;json.dumps(signature,&nbsp;sort_keys=True,&nbsp;separators=(",",&nbsp;":"))
return&nbsp;hashlib.sha256(canonical.encode()).hexdigest()</code></pre>
<h3>第三章:技术创新——超越现有框架的三大突破</h3><h4>3.1 Microsoft.Extensions.AI集成:统一的抽象层</h4><p>Agent Framework不是孤立的框架,而是深度集成了微软的<code>Microsoft.Extensions.AI</code>(MEAI)抽象层。</p><p><strong>MEAI是什么?</strong></p><ul><li><p>类似于Python的<code>langchain-core</code>,但更接近.NET生态</p></li><li><p>定义了<code>IChatClient</code>、<code>IEmbeddingsGenerator</code>等统一接口</p></li><li><p>所有主流LLM提供商都有MEAI实现</p></li></ul><p><strong>Python中的等价物:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;BaseChatClient,&nbsp;ChatResponse
class&nbsp;CustomLLMClient(BaseChatClient):
&nbsp;&nbsp;&nbsp;&nbsp;"""任何实现此协议的类都可用作ChatClient"""
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;get_response(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messages:&nbsp;list,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;chat_options:&nbsp;ChatOptions
&nbsp;&nbsp;&nbsp;&nbsp;)&nbsp;-&gt;&nbsp;ChatResponse:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;调用自定义LLM&nbsp;API
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;response&nbsp;=&nbsp;await&nbsp;my_llm_api(messages)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;ChatResponse(messages=[...])
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;get_streaming_response(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messages:&nbsp;list,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;chat_options:&nbsp;ChatOptions
&nbsp;&nbsp;&nbsp;&nbsp;)&nbsp;-&gt;&nbsp;AsyncIterator:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;for&nbsp;chunk&nbsp;in&nbsp;my_llm_api_stream(messages):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield&nbsp;ChatResponseUpdate(contents=)
#&nbsp;直接使用
agent&nbsp;=&nbsp;ChatAgent(chat_client=CustomLLMClient(),&nbsp;...)</code></pre>
<p><strong>.NET中的实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>//&nbsp;任何IChatClient实现都可以用于Agent
public&nbsp;class&nbsp;CustomLLMClient&nbsp;:&nbsp;IChatClient
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;async&nbsp;Task<chatresponse>&nbsp;CompleteChatAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable<chatmessage>&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ChatOptions?&nbsp;options&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CancellationToken&nbsp;cancellationToken&nbsp;=&nbsp;default)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;调用自定义LLM&nbsp;API
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;response&nbsp;=&nbsp;await&nbsp;MyLlmApi.SendAsync(messages);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;ChatResponse
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Messages&nbsp;=&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;};
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;async&nbsp;IAsyncEnumerable<chatresponseupdate>&nbsp;CompleteStreamingChatAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable<chatmessage>&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ChatOptions?&nbsp;options&nbsp;=&nbsp;null,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CancellationToken&nbsp;cancellationToken&nbsp;=&nbsp;default)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;foreach&nbsp;(var&nbsp;chunk&nbsp;in&nbsp;MyLlmApi.StreamAsync(messages))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield&nbsp;return&nbsp;new&nbsp;ChatResponseUpdate
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Contents&nbsp;=&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;};
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
}
//&nbsp;直接使用
var&nbsp;agent&nbsp;=&nbsp;customClient.CreateAIAgent(instructions,&nbsp;name);</chatmessage></chatresponseupdate></chatmessage></chatresponse></code></pre>
<p><strong>关键洞察:</strong> 这种设计让Agent Framework成为<strong>提供商中立</strong>的框架:</p><ul><li><p>支持OpenAI、Azure OpenAI、Anthropic、Google、本地Ollama等</p></li><li><p>无需修改Agent代码即可切换后端</p></li><li><p>自定义LLM集成只需实现统一接口</p></li></ul><h4>3.2 中间件架构:AOP范式进入Agent领域</h4><p>Agent Framework首创性地将**面向切面编程(AOP)**引入AI Agent开发。</p><p><strong>Python中间件实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;Middleware
class&nbsp;LoggingMiddleware(Middleware):
&nbsp;&nbsp;&nbsp;&nbsp;"""记录所有Agent调用"""
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;on_agent_run(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;next_handler,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;agent,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;thread,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;options
&nbsp;&nbsp;&nbsp;&nbsp;):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(f"&nbsp;Agent&nbsp;{agent.name}&nbsp;starting...")
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;start_time&nbsp;=&nbsp;time.time()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;await&nbsp;next_handler(agent,&nbsp;messages,&nbsp;thread,&nbsp;options)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elapsed&nbsp;=&nbsp;time.time()&nbsp;-&nbsp;start_time
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(f"&nbsp;Agent&nbsp;{agent.name}&nbsp;completed&nbsp;in&nbsp;{elapsed:.2f}s")
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;result
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;except&nbsp;Exception&nbsp;as&nbsp;e:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(f"&nbsp;Agent&nbsp;{agent.name}&nbsp;failed:&nbsp;{e}")
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;raise
class&nbsp;CostTrackingMiddleware(Middleware):
&nbsp;&nbsp;&nbsp;&nbsp;"""追踪Token使用成本"""
&nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;__init__(self):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.total_cost&nbsp;=&nbsp;0.0
&nbsp;&nbsp;&nbsp;&nbsp;async&nbsp;def&nbsp;on_agent_run(self,&nbsp;next_handler,&nbsp;agent,&nbsp;messages,&nbsp;thread,&nbsp;options):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;await&nbsp;next_handler(agent,&nbsp;messages,&nbsp;thread,&nbsp;options)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;result.usage_details:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;input_cost&nbsp;=&nbsp;result.usage_details.input_tokens&nbsp;*&nbsp;0.00001
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output_cost&nbsp;=&nbsp;result.usage_details.output_tokens&nbsp;*&nbsp;0.00002
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.total_cost&nbsp;+=&nbsp;input_cost&nbsp;+&nbsp;output_cost
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;result
#&nbsp;应用中间件
agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=client,
&nbsp;&nbsp;&nbsp;&nbsp;middleware=,
&nbsp;&nbsp;&nbsp;&nbsp;...
)</code></pre>
<p><strong>.NET中间件实现:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>public&nbsp;class&nbsp;LoggingMiddleware&nbsp;:&nbsp;IAgentMiddleware
{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;async&nbsp;Task&nbsp;OnAgentRunAsync(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&nbsp;next,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AIAgent&nbsp;agent,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable<chatmessage>&nbsp;messages,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentThread?&nbsp;thread,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AgentRunOptions?&nbsp;options)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_logger.LogInformation("Agent&nbsp;{Name}&nbsp;starting...",&nbsp;agent.Name);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;stopwatch&nbsp;=&nbsp;Stopwatch.StartNew();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;result&nbsp;=&nbsp;await&nbsp;next();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stopwatch.Stop();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_logger.LogInformation(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Agent&nbsp;{Name}&nbsp;completed&nbsp;in&nbsp;{Elapsed}ms",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;agent.Name,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stopwatch.ElapsedMilliseconds
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;result;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;catch&nbsp;(Exception&nbsp;ex)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_logger.LogError(ex,&nbsp;"Agent&nbsp;{Name}&nbsp;failed",&nbsp;agent.Name);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
}
//&nbsp;应用中间件
var&nbsp;agent&nbsp;=&nbsp;chatClient
&nbsp;&nbsp;&nbsp;&nbsp;.CreateAIAgent(instructions,&nbsp;name)
&nbsp;&nbsp;&nbsp;&nbsp;.WithMiddleware(new&nbsp;LoggingMiddleware())
&nbsp;&nbsp;&nbsp;&nbsp;.WithMiddleware(new&nbsp;CostTrackingMiddleware());</chatmessage></agentrunresponse></agentrunresponse></code></pre>
<p><strong>中间件的威力:</strong></p><ol><li><p><strong>横切关注点分离</strong>: 日志、监控、限流、缓存等逻辑与业务代码解耦</p></li><li><p><strong>组合性</strong>: 多个中间件可以形成管道,按顺序执行</p></li><li><p><strong>可测试性</strong>: 每个中间件可以独立测试</p></li><li><p><strong>企业级功能</strong>: 轻松实现审计、合规、性能监控</p></li></ol><h4>3.3 OpenTelemetry原生集成:可观测性从第一天就内建</h4><p>在生产环境中,**可观测性(Observability)**是成败的分水岭。Agent Framework在这方面远超同类框架。</p><p><strong>Python OpenTelemetry集成:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent,&nbsp;use_agent_observability
from&nbsp;opentelemetry&nbsp;import&nbsp;trace
from&nbsp;opentelemetry.sdk.trace&nbsp;import&nbsp;TracerProvider
from&nbsp;opentelemetry.sdk.trace.export&nbsp;import&nbsp;ConsoleSpanExporter,&nbsp;BatchSpanProcessor
#&nbsp;配置追踪器
provider&nbsp;=&nbsp;TracerProvider()
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
#&nbsp;Agent自动注入追踪
@use_agent_observability&nbsp;&nbsp;#&nbsp;装饰器自动启用
class&nbsp;TracedAgent(ChatAgent):
&nbsp;&nbsp;&nbsp;&nbsp;pass
agent&nbsp;=&nbsp;TracedAgent(chat_client=client,&nbsp;name="ObservableAgent")
#&nbsp;每次调用自动生成Span
result&nbsp;=&nbsp;await&nbsp;agent.run("Analyze&nbsp;market")
#&nbsp;输出Span信息:
#&nbsp;Span:&nbsp;agent.run
#&nbsp;&nbsp;&nbsp;-&nbsp;agent.id:&nbsp;observable-agent
#&nbsp;&nbsp;&nbsp;-&nbsp;agent.name:&nbsp;ObservableAgent
#&nbsp;&nbsp;&nbsp;-&nbsp;input.message_count:&nbsp;1
#&nbsp;&nbsp;&nbsp;-&nbsp;output.message_count:&nbsp;1
#&nbsp;&nbsp;&nbsp;-&nbsp;usage.input_tokens:&nbsp;25
#&nbsp;&nbsp;&nbsp;-&nbsp;usage.output_tokens:&nbsp;150</code></pre>
<p><strong>.NET OpenTelemetry集成:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>using&nbsp;OpenTelemetry;
using&nbsp;OpenTelemetry.Resources;
using&nbsp;OpenTelemetry.Trace;
//&nbsp;配置追踪
var&nbsp;tracerProvider&nbsp;=&nbsp;Sdk.CreateTracerProviderBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;.SetResourceBuilder(ResourceBuilder.CreateDefault()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.AddService("MyAgentApp"))
&nbsp;&nbsp;&nbsp;&nbsp;.AddSource("Microsoft.Agents.AI")&nbsp;&nbsp;//&nbsp;Agent&nbsp;Framework的Trace&nbsp;Source
&nbsp;&nbsp;&nbsp;&nbsp;.AddConsoleExporter()
&nbsp;&nbsp;&nbsp;&nbsp;.Build();
//&nbsp;Agent自动注入追踪
var&nbsp;agent&nbsp;=&nbsp;chatClient.CreateAIAgent(instructions,&nbsp;name);
var&nbsp;result&nbsp;=&nbsp;await&nbsp;agent.RunAsync("Analyze&nbsp;market");
//&nbsp;自动生成的Trace结构:
//&nbsp;Span:&nbsp;agent.run
//&nbsp;&nbsp;&nbsp;├─&nbsp;Span:&nbsp;chat_client.complete
//&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;├─&nbsp;Attribute:&nbsp;model.name&nbsp;=&nbsp;"gpt-4"
//&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;├─&nbsp;Attribute:&nbsp;input.tokens&nbsp;=&nbsp;25
//&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;└─&nbsp;Attribute:&nbsp;output.tokens&nbsp;=&nbsp;150
//&nbsp;&nbsp;&nbsp;├─&nbsp;Span:&nbsp;tool.invoke&nbsp;(if&nbsp;tools&nbsp;called)
//&nbsp;&nbsp;&nbsp;└─&nbsp;Event:&nbsp;agent.completed</code></pre>
<p><strong>工作流追踪更强大:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.workflows&nbsp;import&nbsp;WorkflowBuilder
workflow&nbsp;=&nbsp;(WorkflowBuilder(name="Market&nbsp;Research&nbsp;Workflow")
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(web_agent,&nbsp;analyst_agent)
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(analyst_agent,&nbsp;coder_agent)
&nbsp;&nbsp;&nbsp;&nbsp;.build()
)
#&nbsp;工作流执行自动生成嵌套Span
result&nbsp;=&nbsp;await&nbsp;workflow.run("Analyze&nbsp;AI&nbsp;chip&nbsp;market")
#&nbsp;Trace结构:
#&nbsp;Span:&nbsp;workflow.run&nbsp;
#&nbsp;&nbsp;&nbsp;├─&nbsp;Span:&nbsp;workflow.superstep&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;├─&nbsp;Span:&nbsp;executor.execute&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;└─&nbsp;Span:&nbsp;agent.run&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└─&nbsp;Span:&nbsp;tool.invoke&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;└─&nbsp;Event:&nbsp;superstep.completed&nbsp;
#&nbsp;&nbsp;&nbsp;├─&nbsp;Span:&nbsp;workflow.superstep&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;└─&nbsp;Span:&nbsp;executor.execute&nbsp;
#&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└─&nbsp;Span:&nbsp;agent.run&nbsp;
#&nbsp;&nbsp;&nbsp;└─&nbsp;Event:&nbsp;workflow.completed&nbsp;</code></pre>
<p><strong>可观测性的商业价值:</strong></p><ul><li><p><strong>故障诊断</strong>: 精确定位哪个Agent/Executor出错</p></li><li><p><strong>性能优化</strong>: 识别瓶颈节点和超时调用</p></li><li><p><strong>成本管理</strong>: 追踪每个Agent的Token消耗和API调用次数</p></li><li><p><strong>合规审计</strong>: 完整记录AI决策过程</p></li></ul><h3>第四章:生态系统——不仅是框架,更是平台</h3><h4>4.1 Azure AI Foundry深度集成</h4><p>Agent Framework与Azure AI Foundry的集成不是简单的"支持",而是<strong>原生对接</strong>。</p><p><strong>Python Azure AI Agent:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.azure_ai&nbsp;import&nbsp;AzureAIChatClient
from&nbsp;azure.identity&nbsp;import&nbsp;DefaultAzureCredential
#&nbsp;使用Azure&nbsp;AI&nbsp;Foundry托管Agent
client&nbsp;=&nbsp;AzureAIChatClient(
&nbsp;&nbsp;&nbsp;&nbsp;endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
&nbsp;&nbsp;&nbsp;&nbsp;credential=DefaultAzureCredential(),
&nbsp;&nbsp;&nbsp;&nbsp;deployment_name="my-foundry-agent"
)
agent&nbsp;=&nbsp;ChatAgent(chat_client=client,&nbsp;name="FoundryAgent")
#&nbsp;Azure&nbsp;AI特性:
#&nbsp;1.&nbsp;服务端Tool执行(Code&nbsp;Interpreter,&nbsp;File&nbsp;Search)
#&nbsp;2.&nbsp;持久化线程(跨会话)
#&nbsp;3.&nbsp;企业级安全和合规
result&nbsp;=&nbsp;await&nbsp;agent.run(
&nbsp;&nbsp;&nbsp;&nbsp;"Analyze&nbsp;sales.csv&nbsp;and&nbsp;generate&nbsp;insights",
&nbsp;&nbsp;&nbsp;&nbsp;thread=agent.get_new_thread(service_thread_id="persistent-123")
)</code></pre>
<p><strong>.NET Azure AI Agent:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>using&nbsp;Azure.AI.Projects;
using&nbsp;Azure.Identity;
var&nbsp;projectClient&nbsp;=&nbsp;new&nbsp;AIProjectClient(
&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;Uri(Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")),
&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;DefaultAzureCredential()
);
var&nbsp;agentClient&nbsp;=&nbsp;projectClient.GetAgentClient();
var&nbsp;agent&nbsp;=&nbsp;await&nbsp;agentClient.CreateAgentAsync(
&nbsp;&nbsp;&nbsp;&nbsp;deploymentName:&nbsp;"my-foundry-agent",
&nbsp;&nbsp;&nbsp;&nbsp;instructions:&nbsp;"You&nbsp;analyze&nbsp;data&nbsp;and&nbsp;provide&nbsp;insights."
);
//&nbsp;使用服务端工具
var&nbsp;thread&nbsp;=&nbsp;await&nbsp;agentClient.CreateThreadAsync();
await&nbsp;agentClient.CreateMessageAsync(
&nbsp;&nbsp;&nbsp;&nbsp;thread.Id,
&nbsp;&nbsp;&nbsp;&nbsp;MessageRole.User,
&nbsp;&nbsp;&nbsp;&nbsp;"Analyze&nbsp;sales.csv"
);
var&nbsp;run&nbsp;=&nbsp;await&nbsp;agentClient.CreateRunAsync(thread.Id,&nbsp;agent.Id);</code></pre>
<p><strong>Azure AI Foundry的独特价值:</strong></p><ul><li><p><strong>托管Agents</strong>: 无需管理基础设施,按需扩展</p></li><li><p><strong>安全沙盒</strong>: Code Interpreter在隔离容器中执行</p></li><li><p><strong>企业治理</strong>: RBAC、数据驻留、审计日志</p></li><li><p><strong>Evaluation</strong>: 内置评估工具评估Agent质量</p></li></ul><h4>4.2 Model Context Protocol (MCP) 支持</h4><p>Agent Framework是首批支持MCP的框架之一,这将改变Agent与外部系统交互的方式。</p><p><strong>Python MCP集成:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;MCPTool
#&nbsp;连接到MCP服务器(如文件系统、数据库)
mcp_server&nbsp;=&nbsp;MCPTool(
&nbsp;&nbsp;&nbsp;&nbsp;server_params=StdioServerParameters(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;command="uvx",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;args=["mcp-server-filesystem",&nbsp;"/workspace"]
&nbsp;&nbsp;&nbsp;&nbsp;)
)
#&nbsp;Agent自动获得MCP服务器的所有工具
agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=client,
&nbsp;&nbsp;&nbsp;&nbsp;tools=&nbsp;&nbsp;#&nbsp;MCP服务器的工具会自动注入
)
async&nbsp;with&nbsp;agent:&nbsp;&nbsp;#&nbsp;上下文管理器自动启动/关闭MCP连接
&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;await&nbsp;agent.run("List&nbsp;files&nbsp;in&nbsp;/workspace&nbsp;and&nbsp;read&nbsp;config.json")</code></pre>
<p><strong>.NET MCP集成:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>//&nbsp;目前.NET的MCP支持通过Azure&nbsp;AI&nbsp;Foundry&nbsp;Hosted&nbsp;MCP
var&nbsp;agent&nbsp;=&nbsp;chatClient.CreateAIAgent(
&nbsp;&nbsp;&nbsp;&nbsp;instructions:&nbsp;"You&nbsp;help&nbsp;with&nbsp;file&nbsp;operations",
&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;"FileAgent"
);
//&nbsp;在Azure&nbsp;AI&nbsp;Foundry中配置MCP服务器
//&nbsp;Agent自动获得文件系统、Git、Slack等能力</code></pre>
<p><strong>MCP的革命性意义:</strong></p><ul><li><p><strong>标准化</strong>: 不再需要为每个API写自定义工具</p></li><li><p><strong>动态发现</strong>: Agent运行时自动发现MCP服务器的能力</p></li><li><p><strong>生态系统</strong>: 社区共享MCP服务器(已有100+)</p></li></ul><h4>4.3 DevUI:Agent开发的"Chrome DevTools"</h4><p>Python独有的<code>agent-framework-devui</code>包提供了可视化开发体验。</p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>pip&nbsp;install&nbsp;agent-framework</code></pre>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent
from&nbsp;agent_framework.workflows&nbsp;import&nbsp;WorkflowBuilder
#&nbsp;1.&nbsp;标记要调试的Agent/Workflow
agent&nbsp;=&nbsp;ChatAgent(...,&nbsp;name="DebugAgent")
workflow&nbsp;=&nbsp;WorkflowBuilder(name="DebugWorkflow").build()
#&nbsp;2.&nbsp;启动DevUI服务器
#&nbsp;$&nbsp;python&nbsp;-m&nbsp;agent_framework.devui
#&nbsp;3.&nbsp;浏览器打开&nbsp;http://localhost:8000
#&nbsp;-&nbsp;实时查看Workflow图形
#&nbsp;-&nbsp;单步执行Executor
#&nbsp;-&nbsp;查看消息流
#&nbsp;-&nbsp;修改Agent参数并重新运行</code></pre>
<p><strong>DevUI功能:</strong></p><ul><li><p><strong>可视化</strong>: 工作流图形化展示,实时更新节点状态</p></li><li><p><strong>交互式调试</strong>: 在RequestInfoExecutor处暂停,手动提供输入</p></li><li><p><strong>Trace查看器</strong>: 集成OpenTelemetry,可视化Span树</p></li><li><p><strong>性能分析</strong>: 识别慢节点和热路径</p></li></ul><h3>第五章:抉择时刻——何时选择Agent Framework?</h3><h4>5.1 适用场景</h4><p><strong>高度推荐:</strong></p><ol><li><p><strong>.NET生态企业</strong>: 已有大量C#代码和.NET基础设施</p></li><li><p><strong>Azure深度用户</strong>: 使用Azure OpenAI、Azure AI等服务</p></li><li><p><strong>复杂工作流</strong>: 需要分支、循环、人工审批的多Agent系统</p></li><li><p><strong>长时间运行</strong>: 工作流需要跨天运行,需要检查点恢复</p></li><li><p><strong>企业级需求</strong>: 需要审计、合规、OpenTelemetry集成</p></li></ol><p><strong>谨慎考虑:</strong></p><ol><li><p><strong>简单脚本</strong>: 如果只是"发一个LLM请求",直接用SDK可能更简单</p></li><li><p><strong>Python纯粹主义</strong>: 如果不需要.NET互操作性,LangGraph可能更轻量</p></li><li><p><strong>特定框架绑定</strong>: 如果深度使用LangChain生态(LangSmith、LangServe),迁移成本高</p></li></ol><h4>5.2 与竞品对比</h4><table><tbody><tr><th>维度</th><th>Agent Framework</th><th>AutoGen</th><th>LangGraph</th><th>Semantic Kernel</th></tr><tr><td><strong>多语言支持</strong></td><td>⭐⭐⭐⭐⭐ Python/.NET原生</td><td>⭐⭐⭐ Python为主</td><td>⭐⭐⭐ Python+JS</td><td>⭐⭐⭐⭐ Python/.NET</td></tr><tr><td><strong>工作流复杂度</strong></td><td>⭐⭐⭐⭐⭐ Pregel+图</td><td>⭐⭐⭐ 群聊编排</td><td>⭐⭐⭐⭐⭐ StateGraph</td><td>⭐⭐⭐ 函数链</td></tr><tr><td><strong>检查点恢复</strong></td><td>⭐⭐⭐⭐⭐ 跨进程持久化</td><td>⭐⭐ 有限</td><td>⭐⭐⭐⭐ SQLite/Postgres</td><td>⭐⭐ 内存状态</td></tr><tr><td><strong>企业集成</strong></td><td>⭐⭐⭐⭐⭐ Azure全栈</td><td>⭐⭐⭐ 开源中立</td><td>⭐⭐⭐ LangSmith</td><td>⭐⭐⭐⭐ Azure</td></tr><tr><td><strong>学习曲线</strong></td><td>⭐⭐⭐ 中等</td><td>⭐⭐⭐⭐ 较陡</td><td>⭐⭐⭐ 中等</td><td>⭐⭐ 较平</td></tr><tr><td><strong>可观测性</strong></td><td>⭐⭐⭐⭐⭐ OTel原生</td><td>⭐⭐⭐ 自定义日志</td><td>⭐⭐⭐⭐ LangSmith</td><td>⭐⭐⭐ 日志</td></tr><tr><td><strong>社区生态</strong></td><td>⭐⭐⭐ 新兴(2024)</td><td>⭐⭐⭐⭐⭐ 成熟</td><td>⭐⭐⭐⭐ 活跃</td><td>⭐⭐⭐⭐ 微软支持</td></tr></tbody></table><h4>5.3 迁移建议</h4><p><strong>从Semantic Kernel迁移:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;Semantic&nbsp;Kernel&nbsp;(旧)
from&nbsp;semantic_kernel&nbsp;import&nbsp;Kernel
from&nbsp;semantic_kernel.connectors.ai.open_ai&nbsp;import&nbsp;AzureChatCompletion
kernel&nbsp;=&nbsp;Kernel()
kernel.add_service(AzureChatCompletion(...))
result&nbsp;=&nbsp;await&nbsp;kernel.invoke_prompt("Hello")
#&nbsp;Agent&nbsp;Framework&nbsp;(新)
from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent
from&nbsp;agent_framework.azure&nbsp;import&nbsp;AzureOpenAIChatClient
agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;chat_client=AzureOpenAIChatClient(...),
&nbsp;&nbsp;&nbsp;&nbsp;instructions="System&nbsp;prompt&nbsp;here"
)
result&nbsp;=&nbsp;await&nbsp;agent.run("Hello")</code></pre>
<p><strong>从AutoGen迁移:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;AutoGen&nbsp;(旧)
from&nbsp;autogen&nbsp;import&nbsp;ConversableAgent,&nbsp;GroupChat
assistant&nbsp;=&nbsp;ConversableAgent(name="Assistant",&nbsp;llm_config={...})
user_proxy&nbsp;=&nbsp;ConversableAgent(name="User",&nbsp;llm_config={...})
group_chat&nbsp;=&nbsp;GroupChat(agents=,&nbsp;messages=[])
#&nbsp;Agent&nbsp;Framework&nbsp;(新)
from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent,&nbsp;WorkflowBuilder
assistant&nbsp;=&nbsp;ChatAgent(name="Assistant",&nbsp;...)
user_proxy&nbsp;=&nbsp;ChatAgent(name="User",&nbsp;...)
workflow&nbsp;=&nbsp;WorkflowBuilder().add_edge(user_proxy,&nbsp;assistant).build()</code></pre>
<h3>第六章:未来展望——2025年的Agent Framework路线图</h3><p>根据GitHub Issues和社区讨论,Agent Framework的未来方向包括:</p><h4>6.1 声明式工作流 (Declarative Workflows)</h4><p><strong>.NET已支持,Python即将到来:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;workflow.yaml
name:&nbsp;Market&nbsp;Research&nbsp;Workflow
description:&nbsp;Multi-agent&nbsp;market&nbsp;analysis&nbsp;pipeline
agents:
&nbsp;&nbsp;-&nbsp;id:&nbsp;web_agent
&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;AzureOpenAIChatClient
&nbsp;&nbsp;&nbsp;&nbsp;config:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;deployment:&nbsp;gpt-4o
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;instructions:&nbsp;"Search&nbsp;the&nbsp;web&nbsp;for&nbsp;market&nbsp;data"
&nbsp;&nbsp;-&nbsp;id:&nbsp;analyst
&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;AzureOpenAIChatClient
&nbsp;&nbsp;&nbsp;&nbsp;config:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;deployment:&nbsp;gpt-4o
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;instructions:&nbsp;"Analyze&nbsp;data&nbsp;and&nbsp;provide&nbsp;insights"
workflow:
&nbsp;&nbsp;start:&nbsp;web_agent
&nbsp;&nbsp;edges:
&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;from:&nbsp;web_agent
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;to:&nbsp;analyst
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;condition:&nbsp;"lambda&nbsp;x:&nbsp;'data'&nbsp;in&nbsp;x"
&nbsp;&nbsp;outputs:
&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;from:&nbsp;analyst
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;structured
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;schema:&nbsp;MarketReport</code></pre>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.workflows&nbsp;import&nbsp;DeclarativeWorkflow
workflow&nbsp;=&nbsp;DeclarativeWorkflow.from_yaml("workflow.yaml")
result&nbsp;=&nbsp;await&nbsp;workflow.run("Analyze&nbsp;AI&nbsp;chip&nbsp;market")</code></pre>
<h4>6.2 多模态Agent</h4><p><strong>视觉理解、语音交互:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent,&nbsp;ImageContent,&nbsp;AudioContent
#&nbsp;多模态输入
image_message&nbsp;=&nbsp;ChatMessage(
&nbsp;&nbsp;&nbsp;&nbsp;role=Role.USER,
&nbsp;&nbsp;&nbsp;&nbsp;contents=[
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TextContent("What's&nbsp;in&nbsp;this&nbsp;image?"),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ImageContent(url="https://example.com/chart.png")
&nbsp;&nbsp;&nbsp;&nbsp;]
)
audio_message&nbsp;=&nbsp;ChatMessage(
&nbsp;&nbsp;&nbsp;&nbsp;role=Role.USER,
&nbsp;&nbsp;&nbsp;&nbsp;contents=
)
agent&nbsp;=&nbsp;ChatAgent(chat_client=client,&nbsp;...)
result&nbsp;=&nbsp;await&nbsp;agent.run()</code></pre>
<h4>6.3 分布式工作流 (Distributed Workflows)</h4><p><strong>跨机器、跨数据中心的Agent协作:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.workflows&nbsp;import&nbsp;DistributedWorkflowBuilder
#&nbsp;Executor可以运行在不同的机器上
workflow&nbsp;=&nbsp;(DistributedWorkflowBuilder()
&nbsp;&nbsp;&nbsp;&nbsp;.add_edge(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;local_agent,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;remote_agent,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;execution_location="https://worker-01.example.com"
&nbsp;&nbsp;&nbsp;&nbsp;)
&nbsp;&nbsp;&nbsp;&nbsp;.build()
)</code></pre>
<h4>6.4 AutoGen兼容模式</h4><p><strong>无缝迁移,降低切换成本:</strong></p>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>from&nbsp;agent_framework.legacy&nbsp;import&nbsp;AutoGenAdapter
#&nbsp;包装现有AutoGen&nbsp;Agent
autogen_agent&nbsp;=&nbsp;ConversableAgent(...)
af_agent&nbsp;=&nbsp;AutoGenAdapter(autogen_agent)
#&nbsp;在Agent&nbsp;Framework工作流中使用
workflow&nbsp;=&nbsp;WorkflowBuilder().add_edge(af_agent,&nbsp;native_agent).build()</code></pre>
<h3>结语:双语言时代的AI Agent开发哲学</h3><p>Agent Framework的出现标志着一个转折点:AI Agent不再是Python的专利。<strong>企业级.NET应用可以与前沿AI技术无缝融合,而Python开发者也能享受到强类型和工具支持带来的生产力提升。</strong></p><p>这不是两个框架的简单并存,而是同一个设计哲学在两种语言中的精致表达:</p><ul><li><p><strong>Protocol vs Abstract Class</strong>: 鸭子类型与静态类型的优雅平衡</p></li><li><p><strong>Decorator vs Extension Method</strong>: 元编程与流畅API的各自精彩</p></li><li><p><strong>AsyncIterator vs IAsyncEnumerable</strong>: 异步流的殊途同归</p></li></ul><p>当你的团队既有Python数据科学家又有.NET架构师,当你的系统既需要快速原型又需要企业级稳定性,当你的AI应用既要调用开源模型又要深度集成Azure——<strong>Agent Framework就是为这样的复杂现实而生。</strong></p><p>或许在不久的将来,我们会看到用Python定义Agent原型,用.NET部署生产环境;或者Python处理实时推理,.NET管理长时间运行工作流。这种混合架构不再是妥协,而是两种语言优势的化学反应。</p><p><strong>AI Agent的未来,是多语言、多模态、多云的。Agent Framework已经迈出了第一步。</strong></p><hr><h3>附录:快速开始清单</h3><h4>Python环境 (3分钟启动)</h4>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;1.&nbsp;安装
pip&nbsp;install&nbsp;agent-framework&nbsp;--pre
#&nbsp;2.&nbsp;设置环境变量
export&nbsp;AZURE_OPENAI_ENDPOINT="https://your-endpoint.openai.azure.com"
export&nbsp;AZURE_OPENAI_DEPLOYMENT_NAME="gpt-4o"
#&nbsp;3.&nbsp;运行第一个Agent
python&nbsp;-c&nbsp;"
import&nbsp;asyncio
from&nbsp;agent_framework&nbsp;import&nbsp;ChatAgent
from&nbsp;agent_framework.azure&nbsp;import&nbsp;AzureOpenAIChatClient
from&nbsp;azure.identity&nbsp;import&nbsp;DefaultAzureCredential
async&nbsp;def&nbsp;main():
&nbsp;&nbsp;&nbsp;&nbsp;agent&nbsp;=&nbsp;ChatAgent(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;chat_client=AzureOpenAIChatClient(credential=DefaultAzureCredential()),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name='FirstAgent'
&nbsp;&nbsp;&nbsp;&nbsp;)
&nbsp;&nbsp;&nbsp;&nbsp;print(await&nbsp;agent.run('Hello,&nbsp;Agent&nbsp;Framework!'))
asyncio.run(main())
"</code></pre>
<h4>.NET环境 (3分钟启动)</h4>
<pre style="white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important"><code>#&nbsp;1.&nbsp;创建项目
dotnet&nbsp;new&nbsp;console&nbsp;-n&nbsp;MyFirstAgent
cd&nbsp;MyFirstAgent
#&nbsp;2.&nbsp;安装包
dotnet&nbsp;add&nbsp;package&nbsp;Microsoft.Agents.AI.OpenAI&nbsp;--prerelease
dotnet&nbsp;add&nbsp;package&nbsp;Azure.Identity
#&nbsp;3.&nbsp;编辑Program.cs
cat&nbsp;&gt;&nbsp;Program.cs&nbsp;&lt;&lt;&nbsp;'EOF'
using&nbsp;Azure.AI.OpenAI;
using&nbsp;Azure.Identity;
using&nbsp;Microsoft.Agents.AI;
var&nbsp;endpoint&nbsp;=&nbsp;Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
var&nbsp;deployment&nbsp;=&nbsp;Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME")!;
var&nbsp;agent&nbsp;=&nbsp;new&nbsp;AzureOpenAIClient(new&nbsp;Uri(endpoint),&nbsp;new&nbsp;DefaultAzureCredential())
&nbsp;&nbsp;&nbsp;&nbsp;.GetChatClient(deployment)
&nbsp;&nbsp;&nbsp;&nbsp;.CreateAIAgent(name:&nbsp;"FirstAgent",&nbsp;instructions:&nbsp;"You&nbsp;are&nbsp;a&nbsp;helpful&nbsp;assistant");
Console.WriteLine(await&nbsp;agent.RunAsync("Hello,&nbsp;Agent&nbsp;Framework!"));
EOF
#&nbsp;4.&nbsp;运行
dotnet&nbsp;run</code></pre>
<h4>学习资源</h4><p><strong>官方文档:</strong></p><ul><li><p>MS Learn 文档</p></li><li><p>GitHub仓库</p></li><li><p>架构决策记录(ADR)</p></li></ul><p><strong>示例代码:</strong></p><ul><li><p>Python Samples</p></li><li><p>.NET Samples</p></li></ul><p><strong>社区:</strong></p><ul><li><p>Discord频道</p></li><li><p>GitHub Discussions</p></li></ul><p>更多AIGC文章</p><p>RAG技术全解:从原理到实战的简明指南</p><hr></div><br><br>
来源:https://www.cnblogs.com/yangykaifa/p/19199854
頁: [1]
查看完整版本: 完整教程:双剑合璧:Microsoft Agent Framework——Python与.NET的AI智能体协奏曲