基于 Microsoft Foundry 的智能体式 AI——使用 Foundry 构建你的第一个智能体

9 阅读25分钟

想象一下,你拥有一个 digital assistant,它不仅能回答问题,还能代表你完成任务,例如预订会议、筛选销售线索,或研究竞争对手。这就是 AI agent 的力量。传统 chatbots 会回应单个 query,并在短时间后忘记对话;而 AI agents 能够推理复杂问题、采取自主行动,并从结果中学习,以达成特定目标。

本章将帮助你从 model consumer 转变为 agent builder。你将学习 agents 与传统 LLM applications 的区别,学习使用 Microsoft Foundry Agent Service,并构建一个 production-ready 的 sales automation agent。基于前几章中的概念,本章会展示如何创建 agents,使它们能够与 external systems 交互、基于 context 做决策,并与其他 agents 协调来解决复杂问题。

现在你已经从概念上理解了 agents 是什么,本节将展示如何在实践中构建它们。我们将逐步介绍 service architecture,创建你的第一个 agent,并探索 thread 和 run lifecycle。

具体来说,本章中的 agent concepts 建立在第 2 章的 Foundry project setup、第 4 章的 Model Catalog 和 deployment modes,以及第 5 章的 prompt engineering techniques 之上。如果你还没有完成第 2 章中描述的 environment setup,请先完成后再继续。本章代码示例假设你已经拥有一个可用的 Microsoft Foundry project,并至少部署了一个 model。

本章将覆盖以下主题:

  • What is an AI Agent?
  • Microsoft Foundry Agent Service
  • Orchestrating multi-agent systems
  • Use Case:sales automation agent
  • Testing and Refining Agent behaviors

Technical requirements

本章需要一个带 Standard agent configuration 的 Microsoft Foundry resource。随着产品持续演进并引入新 features,setup process 可能发生变化。在本书写作时,Standard Agent 是具备所有 agent 构建功能的配置。

要求如下:

  • Microsoft Foundry project with Standard agent configuration
  • Python 3.10 或更高版本,并安装 azure-ai-projectsazure-identity packages
  • Visual Studio Code with Python extension,推荐使用
  • 已安装并完成认证的 Azure CLI,即 az login

要一次性安装本章使用的 Python packages,请在新的 virtual environment 中运行以下命令:

pip install azure-ai-projects azure-identity azure-ai-agents

如果你希望在 source control 中 pin versions,对应的 requirements.txt entries 为:

azure-ai-projects>=1.0.0
azure-identity>=1.17.0
azure-ai-agents>=1.0.0

请在运行 pip install 时 pin 到当时可用的最新 patch versions。

Foundry Agent Service 于 2025 年 5 月达到 General Availability(GA),API version 为 2025-05-01。标记为 Preview 的 features 可能会发生变化。请始终查看 Microsoft Learn 文档以获取最新可用性信息: learn.microsoft.com/en-us/azure…

What is an AI Agent?

AI agent 不只是带 chat interface 的 language model。它是一个 autonomous system,能够感知环境、做出决策、采取行动,并从结果中学习,以达成特定目标。在接下来的 sections 中,我们将……

Structure of an AI Agent

可以把 AI agent 想象成由四个关键 components 协同工作的系统,就像组织中一名熟练员工一样。以下 components 构成你使用 Foundry 构建 agents 时将要实现的 architecture foundation。

继续这个员工类比:Agent Core 是员工的大脑和训练;Tools 是员工桌上的软件;Memory 是员工的笔记本;Orchestration 是决定员工什么时候独立行动、什么时候升级处理,以及如何协调工作的 manager。

AI Agent 的 components 如下:

Agent Core:带有 instructions 的 LLM,这些 instructions 定义 personality 和 capabilities。

Memory:跨 interactions 持久存在的 short-term 和 long-term context。

Tools:Agent 可以调用以采取 actions 的 external functions 和 APIs。

Knowledge:Agent 可以引用的 domain-specific information。Knowledge component 正是下图中实现 retrieval-augmented generation(RAG)的部分。当 agent 收到 query 时,它首先搜索其绑定的 knowledge sources,例如 vector indexes、files 或 web grounding,并将 model response grounding 到这些 retrieved passages 中,而不是仅依赖 model training data。

该结构如下图所示:

image.png

图 6.1:Foundry Agent Service architecture — 四个核心 components:Models、Knowledge、Actions 和 Identity

上面的四个 components 描述了 agent 由什么构成,也就是 structural building blocks。接下来的五个 characteristics 描述 agent 如何表现,也就是 observable qualities。可以把 components 看作 blueprint,把 characteristics 看作 performance specification。

Core characteristics of AI Agents

AI agent 与 simple chatbot 的区别是什么?在 enterprise deployments 中,agents 通常表现出五项核心 characteristics,使它们能够自主处理复杂的 multi-step tasks。以下每个 characteristic 都会直接影响你如何设计 agent architecture、选择 tools,并在 production systems 中管理 state。

Autonomy:Agents 可以独立运行,在没有持续 human intervention 的情况下做出决策。当你要求 agent 安排一场与 client 的会议时,它不会只是建议时间,而是会检查 calendars、发送 invitations,并确认 booking。正是这种 autonomous behavior,让 agents 对真实世界任务真正有用。

Tool Use and Function Calling:Agents 可以通过 tools 与 external systems 交互。这包括查询 databases 以获取 customer data,调用 APIs 来发送 emails 或创建 calendar events,执行 file operations 来读取和处理 documents,以及进行 web searches 来收集 real-time information。能够采取 text generation 之外的 actions,正是将 LLM 转变为 agent 的关键。

Memory and State Management:不同于 stateless chatbots,agents 可以在 interactions 之间维护 context。它们会记得之前 conversations 中讨论过的内容,跟踪 ongoing tasks 的 progress,并随着时间建立理解。Microsoft Foundry 同时提供 short-term memory,用于 conversation context;以及 long-term memory,用于关于 users 和 tasks 的 persistent facts。

Reasoning and Planning:面对复杂 goal 时,agents 会将其分解为可管理的步骤。它们会创建 plans,按顺序或并行执行,并在情况不如预期时进行调整。这种 planning capability 使 agents 能处理传统 chatbots 难以承载的 multi-step workflows。

Adaptability:Agents 会从 outcomes 中学习,并调整自己的方法。如果某个 tool call 失败,它们会尝试 alternative methods。如果 user 提供 feedback,它们会将其纳入未来 responses。这种 adaptability 让 agents 在 production environments 中更稳健,因为意外情况很常见。

Understanding the Agent pattern

一种广泛使用的 agent reasoning pattern 是 reasoning and acting(ReAct)pattern。在这种 pattern 中,agent 遵循一个循环:观察当前 state,推理下一步该做什么,采取 action,然后观察结果。这个循环会持续进行,直到 goal 达成。

考虑一个简单例子:user 要求 agent 为 team lunch 找到最合适的 restaurant。传统 chatbot 可能只是列出热门 restaurants。而遵循 ReAct pattern 的 agent 会:

Reason:我需要知道 team size、dietary restrictions 和 budget。

Act:向 user 询问这些 details,或查看之前的 conversation memory。

Observe:User 说有 8 个人、两位素食者、中等预算。

Reason:我应该搜索能满足这些条件的 restaurants。

Act:使用这些 criteria 调用 restaurant search tool。

Observe:找到了 5 家符合条件的 restaurants,并带有 ratings 和 reviews。

Reason:我应该向 user 展示 top options,并提供相关 details。

Act:格式化并向 user 展示 recommendations。

这种结构化方法确保 agents 能有条理地处理问题,而不是直接跳到结论。

Agents 和 chatbots 之间的区别并不是二元的。许多 production systems 存在于一个 spectrum 上:一端是 simple Q&A bots,另一端是 fully autonomous agents。应从更简单的 agent patterns 开始,只有当 use case 确实需要时,才增加复杂性。

现在你已经理解构成 AI agent 的核心 components,接下来我们将探索 Microsoft Foundry 如何提供 infrastructure 和 services,使这些概念落地。下一节中,你将学习 Foundry Agent Service,并使用它创建你的第一个 agent。

Microsoft Foundry Agent Service

本节将带你了解 Foundry Agent Service 到底是什么、service 中 agent 由哪些 components 构成,以及它的 managed runtime 如何移除你原本需要自己承担的 operational burden。理解这个 baseline 很重要,因为本章后续所有内容,包括 portal walkthrough、SDK quickstart、multi-agent pattern、sales-automation case study 和 production hardening guidance,都建立在同一个 component model 和 managed lifecycle 之上。如果你把本节看作 conceptual map,那么本章其余部分就是 field guide。

Microsoft Foundry Agent Service 提供一个 managed platform,用于在 enterprise scale 上构建、部署和管理 AI agents。该服务于 2025 年 5 月以 API version 2025-05-01 generally available。它会处理复杂 infrastructure,包括 thread management、tool execution、memory persistence 和 security,使你可以专注于设计有效 agents。

Agent Service 解决了 LLM prototypes 与 production systems 之间的关键缺口。在 enterprise deployments 中,teams 从零构建 agents 时,常常会在 state management、tool orchestration 和 observability 上遇到困难。Agent Service 开箱即用地提供这些能力,将 production time 从数月降低到数周。

Agent service architecture

在深入 implementation 之前,先从 architecture level 理解 building blocks 会很有帮助。下面的拆解展示了哪些 concerns 由 platform 处理,哪些是你的责任。

Agent Service Architecture 由六个 integrated components 组成,它们协同驱动你的 agents:

image.png

图 6.2:Agent Service architecture

Models:从 Foundry model catalog 中选择 models,包括 GPT-4o、GPT-4、gpt-4o-mini,以及 Llama 等 open-source models。Model Router Feature 已 Generally Available(GA),可以基于 complexity 自动为每个 request 选择 optimal model,从而在 cost 和 quality 之间取得平衡。

Customizability:可以 fine-tune models、应用 domain-specific prompts,或将 larger models distill 成针对 specific use case 的更小、更快版本。

Knowledge and Tools:为 agents 配备 enterprise tools,包括用于 knowledge retrieval 的 Bing Search、SharePoint、Azure AI Search,以及用于采取 actions 的 Azure Logic Apps、Azure Functions 和 OpenAPI endpoints。

Orchestration:使用 Connected Agents(GA)协调多个 agents。它支持 agent-to-agent communication,而不需要 external orchestration frameworks。

当多个 agents 有必要存在时,下一个问题是它们如何通信。如果没有 platform-level orchestration layer,你需要自己构建 message routing 和 error propagation logic。

Connected Agents 的关键好处是 separation of concerns:每个 specialist 都可以独立开发和更新。这种 modularity 在下一节构建完整 sales automation agent 时会变得很有价值。

Observability:通过 Application Insights integration,在每一步捕获 logs、traces 和 evaluations。这种 visibility 对随时间 debug 和改进 agent behavior 至关重要。

Trust and Security:提供 enterprise-grade security,包括用于 identity 的 Microsoft Entra、用于 access control 的 RBAC、用于 safety 的 content filters,以及适合 sensitive workloads 的 network isolation options。

这六个 components 作为一条 pipeline 运行:user message 通过 Conversation Manager 到达,Conversation Manager 将 run 分派给 Agent Runtime。Runtime 会咨询 LLM Orchestrator,由它决定是否需要 tool call。在整个 flow 中,Knowledge Retrieval 会注入 grounding data,而 Trust and Security 会在每个 boundary 执行 guardrails。

Setting up your first agent

在 Microsoft Foundry 中创建 agents 有两种方式:通过 portal UI 快速 prototyping,或通过 SDK 进行 production development。本节将覆盖两种方法。

当你需要 version-controlled、reproducible deployments 时,请使用 SDK。大多数 teams 会先用 portal 验证 agent design,然后在 design 稳定后转向 SDK。

Portal setup

要通过 portal 设置 agent,请按照以下步骤操作:

  1. 进入 Microsoft Foundry portal:https://ai.azure.com
  2. 在 home page 点击 Create an agent
  3. 输入 project name,并可选地通过 Advanced options 自定义。
  4. 点击 Create,等待 provisioning 完成。
  5. 完成后,你会获得 account、project、deployed gpt-4o model 和 default agent。
  6. 进入 Agent Playground,配置 agent instructions 并开始聊天。

图 6.3 展示了你点击上述按钮后,Foundry portal 中的 Create-an-agent panel 立即呈现的样子。这是你在配置 model 和 instructions 之前应该看到的内容:

image.png

图 6.3:Creating a new agent in the Microsoft Foundry portal — Models tab,用于选择底层 LLM、设置 deployment name 和配置默认 instructions

上面的 portal screenshot 显示 Models tab 已预填 project 的 default deployment。在进入 hands-on steps 前,请确认你的 project 至少有一个 deployed model。空的 Models list 会阻止 agent creation。下面的 note 强调了首次使用时值得 double-check 的两个 settings:

Foundry portal 现在有两个版本:Microsoft Foundry(classic)和 Microsoft Foundry(new)。本章使用新的 portal experience。如果你看到不同 interface,请检查顶部导航中的 portal switcher。

SDK setup

对于 production development,我们将使用 Python SDK。请按照以下步骤操作。

设置 environment variables:

PROJECT_ENDPOINT=https://<YourFoundryResource>.services.ai.azure.com/api/projects/<ProjectName>
MODEL_DEPLOYMENT_NAME=gpt-4o

接下来,我们使用 DefaultAzureCredential 初始化 project client。它会自动使用你的 Azure CLI login 或 managed identity 处理 authentication。随后我们创建一个 agent,包含 name、定义其 behavior 的 instructions,以及一个 tool,也就是用于运行 Python code 的 CodeInterpreter。下面是初始化 client 并创建第一个 agent 的代码:

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.identity import DefaultAzureCredential
import os

# Initialize the project client
project_client = AIProjectClient(
    endpoint=os.getenv("PROJECT_ENDPOINT"),
    credential=DefaultAzureCredential()
)

# Create an agent with instructions
agent = project_client.agents.create_agent(
    model=os.getenv("MODEL_DEPLOYMENT_NAME"),
    name="customer-support-agent",
    instructions="""You are a helpful customer support agent.
    - Answer questions about our products politely
    - If you do not know the answer, say so honestly
    - Keep responses concise and actionable""",
    tools=[CodeInterpreterTool()]
)

print(f"Created agent: {agent.name} (ID: {agent.id})")

image.png

图 6.4:Creation of Agent and Agent output based on user query

Agent lifecycle:Threads and runs

理解 threads 和 runs 对构建有效 agents 至关重要。Thread 表示 user 与 agent 之间的 conversation session。Run 是 thread 内 agent 的一次 execution。

下面展示如何与你的 agent 创建一次 conversation:

# Create a thread for the conversation

下面的代码展示完整 thread lifecycle:创建 thread、添加 user message、执行 run,并检索 agent response。

thread = project_client.agents.threads.create()

# Add a user message
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",
    content="What are your business hours?"
)

# Run the agent on the thread
run = project_client.agents.runs.create_and_wait(
    thread_id=thread.id,
    agent_id=agent.id
)

# Retrieve the agent response
messages = project_client.agents.messages.list(thread_id=thread.id)

for msg in messages:
    if msg.role == "assistant":
        print(msg.content)

Thread 会持久保存在 conversation history 中,因此同一个 thread 中的后续 messages 可以访问完整 context。这正是 agents 在一个 session 内维持 memory 的方式。

Thread storage 底层使用 Azure Cosmos DB。对于 production workloads,你可以 bring your own Cosmos DB instance,以更好控制 data residency 和 backup policies。请查看 Azure 文档了解 BYO Thread Storage configuration。在刚才讲解的 thread lifecycle 代码中,每条 message 和每个 run output 都会在底层写入同一个 managed Cosmos DB instance;这使 agent 不需要在 application 中显式编写 save / load logic,也能跨多个 user turns 具备 conversation memory。Bring-your-own 选项在 threads 包含 regulated data 时尤其相关,例如 PHI、PCI、financial records,并且你的 compliance posture 要求 storage 位于你自己的 subscription 中,使用你自己的 encryption keys 和 retention policies。

在本节中,你学习了如何设置 Microsoft Foundry Agent Service 并创建第一个 agent。你了解了如何同时使用 portal UI 和 Python SDK,也理解了 conversations 中的 thread 和 run model。当一个单一 agent 成功运行后,你可能会问:如果任务太复杂,单个 agent 无法处理,会发生什么?下一节中,我们将探索如何协调多个 agents 来处理更复杂 workflows。

Orchestrating multi-agent systems

上一节中,你学习了如何创建 individual agents。Single agents 擅长 focused tasks,但复杂 workflows 往往需要多个 specialists 协同工作。可以把它想象成一个公司:receptionist 会把电话路由到正确部门;research agent 可能负责收集信息,writing agent 负责撰写 responses,review agent 则确保 quality。Microsoft Foundry 通过 Connected Agents 支持这种模式。Connected Agents 是一项 GA feature,可以在不依赖 external orchestration frameworks 的情况下支持 agent-to-agent collaboration。这正是 agentic AI 真正力量出现的地方:specialized agents 协同解决任何单一 agent 都难以有效处理的问题。本节将重点讨论如何连接多个 agents,让它们共同处理复杂任务。

When to use multi-agent systems

不是每个问题都需要多个 agents。增加 agents 会增加 complexity、latency 和 cost。基于前面讨论的 implementations,现在我们来讨论判断 multi-agent orchestration 是否有意义的若干标准。

当满足以下情况时,可以考虑 multi-agent orchestration:

  • 任务需要 distinct expertise areas,例如 research、writing 和 analysis。
  • 不同步骤需要不同 model capabilities 或 temperature settings。
  • 你希望通过并行化 independent subtasks 加快执行速度。
  • 单个 agent 的 responses 变得过于复杂或不可靠。
  • 出于 security 或 compliance 原因,需要保持 separation of concerns。

在以下情况中,坚持使用 single agent:

  • 任务定义清晰,并聚焦于一个 domain。
  • Subtasks 之间的 context switching 很少。
  • Latency 很关键,因为每个 agent 都会增加 communication overhead。
  • Workflow 是线性的,并不会从 parallel execution 中受益。

这些标准是 guidelines,而不是硬性规则。每增加一个 agent,都会增加 complexity、latency 和 monitoring overhead。应从 single agent 开始,只有当你能清楚说明每个 agent 各自拥有的责任时,才进行拆分。

Connected Agents in Microsoft Foundry

在进入 implementation 之前,先了解 Connected Agents 在更广泛 orchestration landscape 中的位置会很有帮助。大多数 production multi-agent systems 使用三种 patterns 之一:hand-rolled orchestrator,也就是一个 Python service,用于向 specialist agents fan out calls 并聚合 results;external framework,例如 LangGraph 或 AutoGen,它们提供更丰富 routing semantics,但需要额外 infrastructure 来托管和 patch;或 service-managed orchestrator。

Connected Agents 是 Foundry 对第三类模式的答案:routing、delegation 和 synthesis 发生在 Agent Service 内部,因此你可以保留 multi-agent reasoning,而不需要采用 external framework 或运营 orchestrator process。其 trade-off 也正好相反:你会放弃一些 orchestrator 如何选择 specialists 的灵活性,但移除了一个需要 monitoring 和 hardening 的完整 infrastructure tier。

Connected Agents 是 Microsoft Foundry 内置的 multi-agent orchestration feature。借助 Connected Agents,一个 orchestrator agent 可以将 tasks 委派给 specialist agents,接收它们的 responses,并合成 final answer。整个过程发生在 Foundry service 内部,不需要 AutoGen 或 LangGraph 等 external frameworks。

下图展示了一个 multi-agent workflow,其中 primary agent 会根据 complexity 将 tasks 委派给 specialized agents。每个 agent 使用 models、knowledge 或 tools 处理特定部分,它们的 outputs 会被组合成结果,并且可选地引入 human involvement 进行 review。

image.png

图 6.5:Connected Agents pattern — orchestrator agent 将任务委派给 specialist agents(lead enrichment、qualification、scheduling),并合成 responses

下面是使用 Connected Agents 创建 multi-agent system 的 sample code。你可以在任何已安装 azure-ai-projects 且已针对拥有 Foundry project 的 subscription 执行 az login 的环境中运行这段代码,例如 local notebook、Codespaces dev container 或 Azure Cloud Shell terminal。

运行后,你应该会在 stdout 中看到三个 agent IDs:一个 orchestrator 和两个 specialists。Orchestrator 的 ID 是你将在下一个代码块中传递给 threads.create()runs.create_and_wait() 的 ID;两个 specialist IDs 会由 orchestrator 的 instructions 在内部引用,通常不需要直接调用它们。

在下面的代码中,我们首先创建 individual specialist agents。每个 agent 都有面向特定任务的 focused instructions。Research agent 负责收集信息,writing agent 负责创建内容。

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import ConnectedAgentTool
from azure.identity import DefaultAzureCredential
import os

project_client = AIProjectClient(
    endpoint=os.getenv("PROJECT_ENDPOINT"),
    credential=DefaultAzureCredential()
)

# Create specialist agents first
research_agent = project_client.agents.create_agent(
    model=os.getenv("MODEL_DEPLOYMENT_NAME"),
    name="research-specialist",
    instructions="You research topics thoroughly and provide factual summaries with citations."
)

writing_agent = project_client.agents.create_agent(
    model=os.getenv("MODEL_DEPLOYMENT_NAME"),
    name="writing-specialist",
    instructions="You write clear, engaging content based on research provided to you."
)

接下来,我们创建连接这些 specialists 的 orchestrator:

# Create orchestrator that connects to specialists
orchestrator = project_client.agents.create_agent(
    model=os.getenv("MODEL_DEPLOYMENT_NAME"),
    name="content-orchestrator",
    instructions="""You coordinate content creation tasks.
    Route research requests to the research specialist.
    Route writing requests to the writing specialist.
    Combine their outputs into a cohesive final response.""",
    tools=[
        ConnectedAgentTool(agent_id=research_agent.id),
        ConnectedAgentTool(agent_id=writing_agent.id)
    ]
)

ConnectedAgentTool 会让 specialist agents 对 orchestrator 可用。当 orchestrator 判断自己需要 research 时,它会把 research agent 当作 tool 调用。Response 返回后,orchestrator 可以再带着该 research 调用 writing agent。

你刚刚构建的 pattern,即一个 orchestrator 在单个 Foundry-managed run 内路由到 specialist agents,正是大多数 production multi-agent systems 最终采用的模式。它也可以与本章后面覆盖的 connected-tools 和 tracing primitives 组合。现在你已经掌握 connected-agents pattern,下一节将从 generic patterns 转向一个具体端到端构建:一个 sales automation agent,它将 knowledge、tools 和你目前看到的 orchestration patterns 组合成一个能够交付可衡量 business value 的系统。

Running multi-agent workflows

执行 multi-agent workflow 与运行 single agent 类似。你创建 thread、添加 message,并运行 orchestrator。Orchestrator 会在内部处理所有 coordination。下面看可用于执行这一流程的代码:

# Create a thread and send a complex request
thread = project_client.agents.threads.create()

message = project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",
    content="Research the latest trends in AI agents, then write a summary article."
)

# Run the orchestrator - it will delegate to specialists as needed
run = project_client.agents.runs.create_and_wait(
    thread_id=thread.id,
    agent_id=orchestrator.id
)

# Retrieve the final synthesized response
messages = project_client.agents.messages.list(thread_id=thread.id)

for msg in messages:
    if msg.role == "assistant":
        print(msg.content)

Orchestrator 会自动与两个 specialists 协调。首先它调用 research agent 收集信息,然后调用 writing agent 撰写文章,最后将所有内容 synthesize 成 coherent response。

Token usage 会随着 involved agents 的数量增长。每次 agent-to-agent communication 都会消耗两个 agents 的 tokens。对于 two-agent call,你需要为 orchestrator tokens 加上 specialist tokens 付费。在 production 中部署 multi-agent systems 时,应仔细监控 usage。

粗略举例:一个 single-agent query 可能消耗 2,000 tokens,但通过一个 orchestrator 调用两个 specialists 时,可能消耗 6,000 tokens。以 GPT-4o pricing 粗略估算,约为每百万 input tokens 5 美元、每百万 output tokens 15 美元,single-agent 大约 0.03 美元,而 multi-agent 大约 0.09 美元。

理解 orchestration patterns 很有价值,但最好的学习方式是构建真实东西。下一节中,我们将用一个完整 sales automation agent,把这些概念落到实践中。它既展示实用 patterns,也解决一个具体 business problem。

Use case:Sales Automation Agent

考虑一个典型 sales team 场景:sales representatives 会把大量时间花在重复性任务上,例如 qualifying leads、scheduling meetings、updating CRM records,以及回答高频 routine questions。这些工作大多遵循可预测 patterns,AI agent 可以有效处理,从而让 sales representatives 专注于更依赖关系经营、且最能创造价值的工作。

在 enterprise scale 上,最清晰的公开示例来自销售之外、相邻的 customer-service 领域:Air India 的 AI.g agent。该 agent 基于 Azure OpenAI in Foundry Models 构建,目前每天处理大约 40,000 个 customer queries,覆盖 1,300 多种不同 question types,包括 booking changes、refund requests、pet-policy questions,以及旅客向航空公司提出的长尾问题。自上线以来,AI.g 已解决超过 1,300 万次 conversations,success rate 达到 97%,这意味着只有 3% 的 queries 会 escalate 到 human agent。大约一半 Air India customers 现在选择该 agent 作为 first point of contact,另一半仍偏好 human,而系统设计上允许 customers 做出这种选择。

从员工侧来看,Air India Chief Digital and Technology Officer Dr. Satya Ramaswamy 强调了其好处:contact center workers 不再整天处理重复问题,而是可以腾出时间处理需要 human judgment 的复杂 case。Microsoft 已发布完整 case study:

www.microsoft.com/en/customer…

本节中构建的 sales-automation agent 会将相同 patterns 应用于 lead qualification、meeting scheduling 和 CRM updates。我们不会引用特定 lead-response 或 conversion-lift percentage,因为提升幅度会因行业、deployment maturity 和 starting baseline 显著变化。读者应查阅当前 Microsoft customer story collection,了解 sales-specific deployments,并在自己的环境中 instrument deployment 以测量真实数字:

www.microsoft.com/en-in/custo…

Air India 示例的重点不是百分比,而是 architecture pattern:一个 single agent、多个 tools、清晰的 escalation path to humans,以及 platform-managed orchestration 来处理规模化流量。

Requirements and architecture

在编写代码前,我们先定义 sales automation agent 需要做什么。Sales automation agent 应该:

  • 基于 company size、industry 和 budget 筛选 incoming leads。
  • 使用 calendar integration 与 qualified leads 安排 meetings。
  • 将 interaction summaries 更新到 CRM。
  • 将 complex inquiries 升级给 human representatives。

在这个案例中,我们将构建一个 single agent with multiple tools,而不是 multi-agent system。这些任务彼此相关且顺序执行,因此一个带 tools 的 single agent 比协调多个 specialists 更高效。该架构如下图所示:

image.png

图 6.6:Sales automation agent in production — tracing view 显示从 inbound lead 到 enrichment、qualification 和 CRM update 的完整 execution graph

当 sales-automation agent 的 architecture 和 capabilities 确定后,接下来简短一节会介绍具体 provisioning steps:你需要哪些 Foundry resources,要连接哪些 connections,以及第一次 run-through,用于确认在把 agent 包装进 production application 前,所有内容都可以端到端访问。

Implementing the Sales Agent

我们将分阶段构建 agent,从 core agent 开始,并逐步添加 tools。这种方式与开发 production agent 的方式一致:先从简单开始,验证 behavior,然后添加 capabilities。下面看涉及的步骤。

首先,定义 agent instructions。Effective instructions 通常遵循一个 pattern:persona、capabilities、constraints 和 output format。代码如下:

SALES_AGENT_INSTRUCTIONS = """
You are a professional sales assistant for Contoso Technology Solutions.

PERSONA:
- Friendly, professional, and helpful
- Knowledgeable about enterprise software products
- Focused on understanding customer needs

CAPABILITIES:
- Qualify leads using the qualify_lead tool
- Schedule meetings using the schedule_meeting tool
- Update CRM records using the update_crm tool

CONSTRAINTS:
- Never discuss competitor products
- Escalate pricing negotiations to human representatives
- Always confirm meeting times before scheduling

OUTPUT FORMAT:
- Keep responses concise (2-3 sentences maximum)
- Use bullet points for multiple items
- End with a clear next step or question
"""

这里,我们将 instructions 分为清晰 sections。Persona 定义 agent 应如何呈现自己。Capabilities 告诉 agent 有哪些 tools 可用。Constraints 防止不想要的 behaviors。Output format 确保 responses 一致且可用。

接下来,定义 lead qualification tool:

from azure.ai.projects.models import FunctionTool

qualify_lead_tool = FunctionTool(
    name="qualify_lead",
    description="Evaluates a lead based on company information and returns qualification status",
    parameters={
        "type": "object",
        "properties": {
            "company_name": {"type": "string", "description": "Name of the company"},

Optional fields,也就是 industrybudget,之所以被标记为 optional,是因为 leads 并不总是一开始就披露这些信息。Agent 会使用 required fields 进行 qualification;当关键信号缺失时,则给出较低 confidence score。

            "company_size": {"type": "string", "enum": ["small", "medium", "enterprise"]},
            "industry": {"type": "string", "description": "Industry sector"},
            "budget_range": {"type": "string", "description": "Stated budget range"}
        },
        "required": ["company_name", "company_size"]
    }
)

Tool definition 包含详细 description,帮助 agent 理解何时以及如何使用该 tool。Parameters 指明 tool 需要哪些信息,并标注 required 和 optional fields。

该 tool 实现 requirements 中的 lead qualification step,也就是基于 company size、industry 和 stated budget 给 leads 打分。通过在 tool schema 中编码这些 parameters,我们确保 agent 始终收集 required data。

现在用 instructions 和 tools 创建 agent:

sales_agent = project_client.agents.create_agent(
    model=os.getenv("MODEL_DEPLOYMENT_NAME"),
    name="sales-assistant",
    instructions=SALES_AGENT_INSTRUCTIONS,
    tools=[qualify_lead_tool]  # Add more tools as needed
)

此时,sales-automation agent 已 provisioned,instructions 已加载,required tools 已连接,并且针对 representative lead 的 smoke test 已成功完成。从这里开始,该 agent 已准备好由处理真实 inbound leads 的 application code 调用。下一节将转向 operational side:production patterns,包括 tracing、evaluation、monitoring 和 continuous refinement,用于确保这样的 agent 在处理 live traffic 时保持健康。

Running the Sales Agent

Agent 创建完成后,我们模拟一次 customer interaction:

# Simulate a customer interaction
thread = project_client.agents.threads.create()

project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",
    content="Hi, I am from Acme Corp, a 500-person company in healthcare. We are looking for enterprise software with a budget around $50k."
)

run = project_client.agents.runs.create_and_wait(
    thread_id=thread.id,
    agent_id=sales_agent.id
)

在这段代码中,agent 会处理 message,识别相关信息,例如 company size、industry、budget,并调用 qualify_lead tool。根据 qualification result,它会生成合适 response,例如向 qualified leads 提议安排 meeting,或将 unqualified leads 引导到 self-service resources。

此时,sales agent 已完全配置:它拥有明确 persona、lead qualification tool,并连接了 specialist agents。它已经准备好进行 testing。

Production considerations

在 production 中部署 sales agents 时,应基于真实世界 implementations 考虑以下实践:

这些建议来自 Microsoft 发布的 agent deployment guides 和 partner reference architectures。

Error Handling:Tool calls 可能因 network issues、API rate limits 或 invalid data 而失败。应实施 retry logic 和 graceful degradation。如果 CRM update 失败,agent 仍应完成 conversation,并将 update 排队稍后执行。

Timeout Management:为 tool execution 设置合适 timeouts。Calendar APIs 在 peak hours 可能较慢。对 external tool calls 来说,30–60 秒 timeout 通常合理。

Logging and Compliance:记录所有 agent interactions,用于 training data 和 compliance。Sales conversations 可能根据你的行业受到 regulatory requirements 约束。

Cost Optimization:使用 Model Router 自动为 simple queries 选择 cost-effective models,并将 GPT-4o 保留给 complex qualification decisions。这可以显著降低成本。

在 production deployment 前,始终使用 edge cases 测试你的 agent。如果 user 提供 incomplete information 会怎样?如果 user 提出 off-topic questions 会怎样?如果 user 试图提取 sensitive information 会怎样?应预判这些 scenarios,并相应更新 instructions。

构建 agent 只是开始。为了确保 sales agent 在数千次 customer interactions 中可靠运行,你需要系统化的 testing 和 refinement 方法。最后一节中,我们将覆盖 Foundry 中可用的 tools 和 techniques,用于验证并持续改善 agent behavior。

Testing and refining agent behavior

一个在 development 中运行完美的 agent,在面对真实 user input 时,可能会在 production 中意外失败。Customers 会用你没有预料到的方式提问,edge cases 会出现,model updates 也可能微妙改变 behavior。Microsoft Foundry 提供 observability 和 evaluation tools,帮助你尽早发现问题,并持续改进 agents。

本节将覆盖 agents 的 testing levels,如何使用 Foundry tracing 和 observability features,以及使 agents 随时间保持良好表现的 continuous refinement process。

Testing levels for agents

Agent testing 分三个 levels,每个 level 捕获不同类型的问题:

Agent testing 遵循标准 pyramid pattern:底部是大量快速 unit tests,中间是较少 integration tests,顶部是少量 end-to-end tests。

Unit testing:隔离测试 individual tool functions。qualify_lead function 是否返回正确 scores?schedule_meeting function 是否正确处理 timezone conversions?这些 tests 运行很快,并能捕获 implementation bugs。

Integration testing:使用 mock tools 测试 agent。Agent 是否在每个 scenario 中调用正确 tool?是否能 graceful handle tool errors?是否能从 user messages 中提取正确 parameters?

End-to-end testing:测试完整 conversations。Agent 是否能跨 multiple turns 维护 context?是否能针对典型 user journeys 达成 desired outcome?是否能在 unexpected inputs 下不崩溃?

下面是为 agent 设置 integration tests 的示例。下面代码是一个刻意简化的 integration test,不是 unit test,也不是 load test。我们没有 mock agent runtime;我们在 live Foundry project 上针对真实 run loop 进行 end-to-end 测试,并使用少量 representative scenarios 作为 regression test suite 的替代。

在 production 中,你会在每次 deployment 上运行类似 harness,将 responses 持久化到 comparison store,并使用 Foundry Evaluation SDK 对它们评分。

代码流程如下:test_scenarios list 定义 inputs 和 expected behaviors;对每个 scenario,我们创建 fresh thread,避免 assertions 被之前 conversation state 污染;post user message;运行 agent 直到 completion;并根据 scenario expectations 检查最终 assistant message。

# Define test scenarios
test_scenarios = [
    {
        "input": "I am from a 500-person healthcare company with $50k budget",
        "expected_tool": "qualify_lead",
        "expected_result": "qualified"
    },
    {
        "input": "Schedule a demo for next Friday at 2pm",
        "expected_tool": "schedule_meeting"
    },
    {
        "input": "I want to speak with a human",
        "expected_action": "escalate"
    }
]

# Run tests
for scenario in test_scenarios:
    thread = project_client.agents.threads.create()

    project_client.agents.messages.create(
        thread_id=thread.id,
        role="user",
        content=scenario["input"]
    )

    run = project_client.agents.runs.create_and_wait(
        thread_id=thread.id,
        agent_id=sales_agent.id
    )

    # Verify expected behavior
    assert_expected_behavior(run, scenario)

image.png

图 6.7:Integration test output for the sales-automation agent。每个 scenario list 都创建 fresh thread,发送 user input,并端到端运行 agent

Foundry observability features

Microsoft Foundry 提供多种 observability capabilities,帮助你理解和改善 agent behavior。

首先,Tracing(GA) 通过 Application Insights integration,提供 agent execution 的 end-to-end visibility。你可以查看 agent 执行的每一步、调用的 tool calls,以及消耗的 tokens。这对 debug unexpected behavior 至关重要。图 6.8 展示了一个 representative sales-automation run 的 Tracing 样子:每一行都是 agent 执行的一个 step,其中 model call、tool invocation 以及对应 span 都记录在 run 的 parent trace ID 下。

image.png

图 6.8:Tracing in Foundry Agent Service — sales automation run 中每一步 latency、token usage 和 tool calls 被捕获到 Application Insights

接下来,Evaluation(GA) 允许你针对 test datasets 运行系统化 evaluations,以基于 relevance、coherence 和 task completion 等 dimensions 衡量 agent quality。你可以设置在每次 deployment 上自动运行的 evaluations。图 6.9 展示了基于 gold-set test data 运行后的 Evaluation dashboard:每一行是一个 test case,按 relevance、coherence 和 task-completion dimensions 评分,顶部汇总 aggregate pass rates。

image.png

图 6.9:Evaluation results in Foundry — sales automation agent 在 gold-set test data 上的 relevance、coherence 和 task-completion aggregate scores

最后,Monitoring(GA) 用于跟踪 agent performance over time,通过 metrics dashboards 显示 run counts、latency 和 error rates。你可以为可能表示问题的 anomalies 设置 alerts。

从 development 一开始就启用 tracing,而不是等问题发生后再启用。拥有 historical trace data 会让 production issues 出现时的 debug 容易得多。

Content safety dashboard 提供 guardrail activity 的专用视图。

image.png

图 6.10:Custom Content safety dashboard with Blocked Requests

Continuous refinement process

改进 agent 是一个 iterative process。基于 production implementations,下面是一个效果较好的 refinement cycle。下图中的五步 cycle 展示了运行 production agents 的 teams 每周都会做的事情。

新的 traces 和 feedback 会通过 Monitor 步骤进入;recurring failure patterns 会在 Analyze 中浮现;candidate fixes 会在 Hypothesize 中被草拟;这些 fixes 会在 Test 中基于 eval datasets 验证;表现最好的方案会在 Deploy 中发布。随后 agent 回到 production,循环继续。图中推荐的节奏是:weekly instruction tuning、monthly tool / model changes、quarterly architecture reviews。这种节奏既足够紧凑,能持续学习,又足够结构化,避免发布 regressions。

image.png

图 6.11:Continuous Agent Refinement Cycle。五个步骤:Monitor、Analyze、Hypothesize、Test、Deploy

即使是很小的 instruction changes,也可能显著影响 agent behavior。部署 updates 前务必充分测试。保留 instructions 的 version history,这样必要时可以 rollback。

在本节中,你学习了如何在多个 levels 测试 agents,如何使用 Foundry observability features 进行 debugging 和 monitoring,以及如何实施 continuous refinement process。这些实践对于在 production 中维护 high-quality agents 至关重要。

Summary

本章中,你从 model consumer 转变为 agent builder。你学习了 AI agents 与传统 chatbots 的区别:autonomy、tool use、memory、reasoning 和 adaptability。你学习了 Microsoft Foundry Agent Service,并通过 portal 和 SDK 两种方式创建 agents。

你探索了使用 Connected Agents 进行 multi-agent orchestration,理解什么时候需要多个 specialists,什么时候一个设计良好的 single agent 就足够。你构建了一个 practical sales automation agent,展示了真实世界 patterns;并学习了如何使用 Foundry observability tools 测试和持续优化 agent behavior。

本章关键结论包括:AI agent 由四个核心 components 组成:agent core,也就是带 instructions 的 LLM;memory;tools;以及 knowledge。Microsoft Foundry Agent Service 于 2025 年 5 月达到 general availability(API version 2025-05-01),Connected Agents 现在支持 multi-agent orchestration,而不依赖 external frameworks。

有效 agent instructions 应清晰定义 persona、capabilities、constraints 和 output format。Testing 应在多个 levels 上执行,包括 unit、integration 和 end-to-end,以确保 reliability。Agent development 本质上是 iterative 的,包含持续循环:collecting feedback、analyzing performance、refining behavior、evaluating results 和 redeploying。

在 feature maturity 方面,GA features 包括 Agent Service Core、Connected Agents、Model Router、Tracing、Evaluation 和 Monitoring;而 Computer Use Tool、Browser Automation 和 Java SDK 等 capabilities 当前处于 preview。

下一章中,我们将探索 advanced agent capabilities,包括 custom tool development、与 enterprise systems 集成,以及在 governance 和 compliance considerations 下大规模部署 agents。

Further reading

有关本章完整 code samples,请访问本书 GitHub repository。其他有用资源如下:

  • Microsoft Foundry Agent Service Documentation:
    https://learn.microsoft.com/en-us/azure/foundry/
  • Python SDK Samples:
    https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/ai/azure-ai-projects