agent-framework-azure-ai-py - SKILL

发布时间:2026/10/21 11:21:39
agent-framework-azure-ai-py - SKILL name: agent-framework-azure-ai-pydescription: “Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.”risk: criticalsource: communitydate_added: “2026-02-27”Azure 托管代理的 Agent Framework使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上构建持久化代理。架构用户查询 → AzureAIAgentsProvider → Azure AI 代理服务持久化 ↓ Agent.run() / Agent.run_stream() ↓ 工具函数 | 托管代码/搜索/Web| MCP ↓ AgentThread对话持久化安装# 完整框架推荐pipinstallagent-framework--pre# 或仅 Azure 特定包pipinstallagent-framework-azure-ai--pre环境变量exportAZURE_AI_PROJECT_ENDPOINThttps://project.services.ai.azure.com/api/projects/project-idexportAZURE_AI_MODEL_DEPLOYMENT_NAMEgpt-4o-miniexportBING_CONNECTION_IDyour-bing-connection-id# 用于网络搜索身份验证fromazure.identity.aioimportAzureCliCredential,DefaultAzureCredential# 开发环境credentialAzureCliCredential()# 生产环境credentialDefaultAzureCredential()核心工作流基本代理importasynciofromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialasyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameMyAgent,instructionsYou are a helpful assistant.,)resultawaitagent.run(Hello!)print(result.text)asyncio.run(main())带函数工具的代理fromtypingimportAnnotatedfrompydanticimportFieldfromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialdefget_weather(location:Annotated[str,Field(descriptionCity name to get weather for)],)-str:Get the current weather for a location.returnfWeather in{location}: 72°F, sunnydefget_current_time()-str:Get the current UTC time.fromdatetimeimportdatetime,timezonereturndatetime.now(timezone.utc).strftime(%Y-%m-%d %H:%M:%S UTC)asyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameWeatherAgent,instructionsYou help with weather and time queries.,tools[get_weather,get_current_time],# Pass functions directly)resultawaitagent.run(Whats the weather in Seattle?)print(result.text)带托管工具的代理fromagent_frameworkimport(HostedCodeInterpreterTool,HostedFileSearchTool,HostedWebSearchTool,)fromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialasyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameMultiToolAgent,instructionsYou can execute code, search files, and search the web.,tools[HostedCodeInterpreterTool(),HostedWebSearchTool(nameBing),],)resultawaitagent.run(Calculate the factorial of 20 in Python)print(result.text)流式响应asyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameStreamingAgent,instructionsYou are a helpful assistant.,)print(Agent: ,end,flushTrue)asyncforchunkinagent.run_stream(Tell me a short story):ifchunk.text:print(chunk.text,end,flushTrue)print()对话线程fromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialasyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameChatAgent,instructionsYou are a helpful assistant.,tools[get_weather],)# 创建线程以保持对话持久化threadagent.get_new_thread()# 第一轮result1awaitagent.run(Whats the weather in Seattle?,threadthread)print(fAgent:{result1.text})# 第二轮 - 上下文保持result2awaitagent.run(What about Portland?,threadthread)print(fAgent:{result2.text})# 保存线程 ID 以便后续恢复print(fConversation ID:{thread.conversation_id})结构化输出frompydanticimportBaseModel,ConfigDictfromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialclassWeatherResponse(BaseModel):model_configConfigDict(extraforbid)location:strtemperature:floatunit:strconditions:strasyncdefmain():asyncwith(AzureCliCredential()ascredential,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameStructuredAgent,instructionsProvide weather information in structured format.,response_formatWeatherResponse,)resultawaitagent.run(Weather in Seattle?)weatherWeatherResponse.model_validate_json(result.text)print(f{weather.location}:{weather.temperature}°{weather.unit})提供者方法方法描述create_agent()在 Azure AI 服务上创建新代理get_agent(agent_id)按 ID 检索现有代理as_agent(sdk_agent)包装 SDK 代理对象无 HTTP 调用托管工具快速参考工具导入用途HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterTool执行 Python 代码HostedFileSearchToolfrom agent_framework import HostedFileSearchTool搜索向量存储HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBing 网络搜索HostedMCPToolfrom agent_framework import HostedMCPTool服务管理的 MCPMCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPTool客户端管理的 MCP完整示例importasynciofromtypingimportAnnotatedfrompydanticimportBaseModel,Fieldfromagent_frameworkimport(HostedCodeInterpreterTool,HostedWebSearchTool,MCPStreamableHTTPTool,)fromagent_framework.azureimportAzureAIAgentsProviderfromazure.identity.aioimportAzureCliCredentialdefget_weather(location:Annotated[str,Field(descriptionCity name)],)-str:Get weather for a location.returnfWeather in{location}: 72°F, sunnyclassAnalysisResult(BaseModel):summary:strkey_findings:list[str]confidence:floatasyncdefmain():asyncwith(AzureCliCredential()ascredential,MCPStreamableHTTPTool(nameDocs MCP,urlhttps://learn.microsoft.com/api/mcp,)asmcp_tool,AzureAIAgentsProvider(credentialcredential)asprovider,):agentawaitprovider.create_agent(nameResearchAssistant,instructionsYou are a research assistant with multiple capabilities.,tools[get_weather,HostedCodeInterpreterTool(),HostedWebSearchTool(nameBing),mcp_tool,],)threadagent.get_new_thread()# 非流式resultawaitagent.run(Search for Python best practices and summarize,threadthread,)print(fResponse:{result.text})# 流式print(\nStreaming: ,end)asyncforchunkinagent.run_stream(Continue with examples,threadthread):ifchunk.text:print(chunk.text,end,flushTrue)print()# 结构化输出resultawaitagent.run(Analyze findings,threadthread,response_formatAnalysisResult,)analysisAnalysisResult.model_validate_json(result.text)print(f\nConfidence:{analysis.confidence})if__name____main__:asyncio.run(main())约定始终使用异步上下文管理器async with provider:将函数直接传递给tools参数自动转换为 AIFunction对函数参数使用Annotated[type, Field(description...)]对多轮对话使用get_new_thread()对服务管理的 MCP 优先使用HostedMCPTool对客户端管理的 MCP 使用MCPStreamableHTTPTool参考文件references/tools.md详细托管工具模式references/mcp.mdMCP 集成托管 本地references/threads.md线程和对话管理references/advanced.mdOpenAPI、引用、结构化输出何时使用本技能适用于执行概述中描述的工作流或操作。限制仅当任务明确匹配上述范围时使用本技能。不要将输出视为特定环境验证、测试或专家审查的替代品。如果缺少必需的输入、权限、安全边界或成功标准请停下来要求澄清。

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询