AI Agents 入門課程 · 第 14 課 / 共 18 課

探索 Microsoft Agent Framework (MAF)

原文:Microsoft AI Agents for Beginners · MIT 授權

本課概覽

一句話:Microsoft Agent Framework (MAF) 是微軟統一的 AI Agent 開發框架,提供從 Agent 建立、工具整合、多 Agent 協作,到上線觀測與安全控管的完整解決方案。

本課將涵蓋:

學習目標

完成本課後,你將能夠:

認識 Microsoft Agent Framework

Microsoft Agent Framework (MAF) 是微軟統一的 AI Agent 開發框架。它提供足夠的靈活性來應對各種 Agentic 場景,包括:

五種編排模式

模式說明適用場景
循序編排 (Sequential)逐步執行的 Agent 工作流程固定步驟的資料處理管線
並行編排 (Concurrent)多個 Agent 同時執行任務同時查詢多個資料來源
群組對話 (Group Chat)多 Agent 共同討論協作需要多方意見的決策場景
交接編排 (Handoff)Agent 完成子任務後交給下一個 Agent多階段的客服流程
磁性編排 (Magnetic)管理者 Agent 動態建立任務清單並協調子 Agent複雜的專案管理情境

上線必備四大支柱

支柱說明
可觀測性 (Observability)透過 OpenTelemetry 追蹤 Agent 的每一步:工具調用、編排步驟、推理流程,並在 Microsoft Foundry 儀表板中監控效能
安全性 (Security)原生託管於 Microsoft Foundry,內建角色存取控制 (RBAC)、私有資料處理與內容安全防護
持久性 (Durability)Agent 執行緒與工作流程可暫停、恢復、從錯誤中復原,支援長時間執行的流程
人機迴圈 (Control)支援 Human-in-the-loop,任務可標記為需要人工核准

互通性設計

MAF 關鍵概念

1. Agent 建立

建立 Agent 需要定義推論服務(LLM 提供者)、一組指令以及一個 name

使用 Azure OpenAI

agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    instructions="You are good at recommending trips to customers based on their preferences.",
    name="TripRecommender"
)

使用 Microsoft Foundry Agent Service

AzureAIAgentClient(async_credential=credential).create_agent(
    name="HelperAgent",
    instructions="You are a helpful assistant."
) as agent

使用 OpenAI Responses / ChatCompletion API

agent = OpenAIResponsesClient().create_agent(
    name="WeatherBot",
    instructions="You are a helpful weather assistant.",
)
agent = OpenAIChatClient().create_agent(
    name="HelpfulAssistant",
    instructions="You are a helpful assistant.",
)

使用 MiniMax(OpenAI 相容 API,支援 204K tokens 上下文)

agent = OpenAIChatClient(
    base_url="https://api.minimax.io/v1",
    api_key=os.environ["MINIMAX_API_KEY"],
    model_id="MiniMax-M3"
).create_agent(
    name="HelpfulAssistant",
    instructions="You are a helpful assistant.",
)

使用 A2A 協定的遠端 Agent

agent = A2AAgent(
    name=agent_card.name,
    description=agent_card.description,
    agent_card=agent_card,
    url="https://your-a2a-agent-host"
)

2. Agent 執行

使用 .run(非串流)或 .run_stream(串流)方法:

# 非串流
result = await agent.run("What are good places to visit in Amsterdam?")
print(result.text)

# 串流
async for update in agent.run_stream("What are the good places to visit in Amsterdam?"):
    if update.text:
        print(update.text, end="", flush=True)

每次執行可自訂 max_tokens、可用 tools 甚至更換 model。這在特定任務需要特定模型或工具時非常有用。

3. 工具 (Tools)

工具可以在定義 Agent 時指定,也可以在執行時才提供:

def get_attractions(
    location: Annotated[str, Field(description="The location to get the top tourist attractions for")],
) -> str:
    """Get the top tourist attractions for a given location."""
    return f"The top attractions for {location} are."

# 建立 Agent 時定義工具
agent = ChatAgent(
    chat_client=OpenAIChatClient(),
    instructions="You are a helpful assistant",
    tools=[get_attractions]
)

# 也可以在執行時才提供工具
result = await agent.run(
    "What's the best place to visit in Seattle?",
    tools=[get_attractions]  # 僅本次執行可用
)

4. Agent 執行緒 (Threads)

Thread 用來處理多輪對話。可以持久化儲存以便後續使用:

# 建立新執行緒
thread = agent.get_new_thread()

# 使用執行緒執行
response = await agent.run(
    "Hello, I am here to help you book travel. Where would you like to go?",
    thread=thread
)

# 序列化以儲存
serialized_thread = await thread.serialize()

# 從儲存中恢復
resumed_thread = await agent.deserialize_thread(serialized_thread)

5. Middleware(中介層)

MAF 提供兩種 Middleware,讓你在 Agent 與工具/LLM 之間插入自訂邏輯:

Function Middleware

在 Agent 呼叫函式/工具前後執行:

async def logging_function_middleware(
    context: FunctionInvocationContext,
    next: Callable[[FunctionInvocationContext], Awaitable[None]],
) -> None:
    """記錄函式執行的 Function Middleware"""
    print(f"[Function] Calling {context.function.name}")
    await next(context)
    print(f"[Function] {context.function.name} completed")

Chat Middleware

在 Agent 與 LLM 之間攔截請求:

async def logging_chat_middleware(
    context: ChatContext,
    next: Callable[[ChatContext], Awaitable[None]],
) -> None:
    """記錄 AI 互動的 Chat Middleware"""
    print(f"[Chat] Sending {len(context.messages)} messages to AI")
    await next(context)
    print("[Chat] AI response received")

6. Agent 記憶體 (Memory)

類型說明範例
In-Memory Storage應用程式執行期間儲存在 Thread 中的記憶thread = agent.get_new_thread()
Persistent Messages跨 Session 持久化對話歷史,使用 chat_message_store_factory自訂 ChatMessageStore
Dynamic Memory在 Agent 執行前注入的動態記憶,可儲存在外部服務如 mem0Mem0Provider 整合
# Dynamic Memory with Mem0
from agent_framework.mem0 import Mem0Provider

memory_provider = Mem0Provider(
    api_key="your-mem0-api-key",
    user_id="user_123",
    application_id="my_app"
)

agent = ChatAgent(
    chat_client=OpenAIChatClient(),
    instructions="You are a helpful assistant with memory.",
    context_providers=memory_provider
)

7. 可觀測性 (Observability)

MAF 整合 OpenTelemetry 提供 Tracing 和 Metrics:

from agent_framework.observability import get_tracer, get_meter

tracer = get_tracer()
meter = get_meter()

with tracer.start_as_current_span("my_custom_span"):
    # 你的自訂邏輯
    pass

counter = meter.create_counter("my_custom_counter")
counter.add(1, {"key": "value"})

Workflow(工作流程)

MAF 的 Workflow 是預先定義的步驟來完成任務,Agent 作為這些步驟中的元件。Workflow 支援多 Agent 編排檢查點 (Checkpointing) 來保存狀態。

核心元件

Executor(執行器)

接收輸入訊息、執行指派任務、產生輸出訊息,推動工作流程。可以是 AI Agent 或自訂邏輯。

Edge(邊)

定義訊息在 Workflow 中的流向:

類型說明
Direct Edge簡單的一對一連接
Conditional Edge滿足特定條件時觸發(例如飯店無空房時建議其他選項)
Switch-case Edge根據條件將訊息路由到不同 Executor(例如 VIP 客戶走專屬流程)
Fan-out Edge一對多:將同一訊息發送給多個目標
Fan-in Edge多對一:收集多個 Executor 的訊息匯入單一目標

事件 (Events)

提供對 Workflow 執行的觀測:

from agent_framework import WorkflowBuilder

builder = WorkflowBuilder()
builder.add_edge(source_executor, target_executor)
builder.set_start_executor(source_executor)
workflow = builder.build()

進階 MAF 模式

在 Microsoft Foundry 上託管 LangChain / LangGraph Agent

MAF 是框架互通的 — 不限定只用 MAF 寫的 Agent。如果你已有 LangChain 或 LangGraph 建立的 Agent,可以將它作為 Microsoft Foundry 託管 Agent 來執行,讓 Foundry 管理執行環境、Session、擴展、身份驗證和協定端點,而你的 Agent 邏輯仍留在 LangGraph 中。

步驟

1. 安裝託管套件

pip install -U "langchain-azure-ai[hosting]>=1.2.4" azure-identity

2. 選擇託管協定

協定Host 類別端點使用時機
ResponsesResponsesHostServer/responses需要 OpenAI 相容的對話、串流、回應歷史和對話執行緒 — 對話型 Agent 的推薦預設
InvocationsInvocationsHostServer/invocations需要自訂 JSON 格式、Webhook 端點,或非對話式處理

3. 設定環境變數

export FOUNDRY_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
export FOUNDRY_MODEL_NAME="gpt-5-mini"

4. 透過 Responses 協定暴露 LangGraph Agent

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_azure_ai.agents.hosting import ResponsesHostServer

_AZURE_AI_SCOPE = "https://ai.azure.com/.default"

def build_chat_model() -> ChatOpenAI:
    project_endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"].rstrip("/")
    deployment = os.environ.get("FOUNDRY_MODEL_NAME", "gpt-5-mini")
    credential = DefaultAzureCredential()
    project = AIProjectClient(endpoint=project_endpoint, credential=credential)
    openai_client = project.get_openai_client()
    token_provider = get_bearer_token_provider(credential, _AZURE_AI_SCOPE)
    return ChatOpenAI(
        model=deployment,
        base_url=str(openai_client.base_url),
        api_key=token_provider,
    )

def main() -> None:
    graph = create_agent(build_chat_model(), tools=[])
    port = int(os.environ.get("PORT", "8088"))
    ResponsesHostServer(graph).run(port=port)

if __name__ == "__main__":
    main()

關鍵行為

本課重點回顧

  1. MAF 是微軟統一的 Agent 框架,支援五種編排模式(循序、並行、群組對話、交接、磁性)
  2. 核心概念:Agent → Tool → Thread → Middleware → Memory → Observability,六大模組環環相扣
  3. Workflow 提供 Executor + Edge + Event 的結構化編排,支援 Checkpoint 和人機迴圈
  4. 框架互通:可以在 Foundry 上託管 LangChain / LangGraph Agent,不限定使用 MAF 原生 Agent
  5. 上線就緒:內建 OpenTelemetry 觀測、RBAC 安全、持久性執行緒和 Human-in-the-loop 控制

原始資源