裝載式 Microsoft Agent Framework Agent 做為 Foundry 裝載式 Agent

使用 Microsoft Agent Framework 託管套件,透過適用於 Foundry 託管代理程式的通訊協定來公開 Agent Framework 代理程式。 託管套件讓你能將代理邏輯保留在程式碼中,而 Foundry 則管理託管的執行時、會話、擴展、身份和協定端點。

在本文中,您將建立一個最簡化的 Agent Framework 代理程式,透過 Responses 或 Invocations 通訊協定公開它,透過 HTTP 測試其運作,並使用 Azure Developer CLI 將其部署至 Foundry。

Microsoft Foundry Skill 可協助實作配接器、測試通訊協定,並搭配 azd 進行部署。

先決條件

  • Azure 訂用帳戶。 免費創建一個
  • Foundry 專案
  • 一個已部署的聊天模型,例如 gpt-4.1gpt-4o
  • 專案中的 Foundry Project Manager 角色,可部署裝載式的 Agent。 詳情請參見 部署託管代理
  • Azure CLI已登入(az login),所以 DefaultAzureCredential 可以進行認證。
  • Python 3.10 或更新版本。
  • .NET 10 SDK 或更新版本。

安裝套件

安裝 Agent Framework 與 Foundry 主機套件:

pip install -U agent-framework agent-framework-foundry-hosting azure-identity python-dotenv

agent_framework_foundry_hosting 套件提供 Foundry 協定的主機伺服器:

  • ResponsesHostServer 適用於 OpenAI 相容的 /responses 端點。
  • InvocationsHostServer 用於通用 /invocations 端點。

將 Agent Framework 和 Foundry 的主機套件加入你的專案:

dotnet add package Microsoft.Agents.AI
dotnet add package Microsoft.Agents.AI.Foundry.Hosting
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity

對於 Invocations 協定,也新增 Invocations 伺服器套件:

dotnet add package Azure.AI.AgentServer.Invocations

這些套件提供 Foundry 協定的主機擴充:

  • AddFoundryResponsesMapFoundryResponses執行 OpenAI 相容的 AddFoundryResponses 端點。
  • AddInvocationsServerMapInvocationsServer處理泛用的 MapInvocationsServer 端點。

選擇主機協定

託管代理可以暴露一個或多個協定。 大多數對話式代理程式都應先從 Responses 開始。

Protocol 終點 何時使用
回應 /responses 你想要的是支援 OpenAI 的聊天、串流、回應歷史和對話串程。
祈禱 /invocations 你需要自訂的 JSON 形狀、類似 webhook 的端點,或是非對話式處理。

關於協定行為與會話的背景,請參見「託管代理」及「管理託管代理會話」。

設定環境變數

設定專案端點及本地開發的模型部署名稱:

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

在 PowerShell 中:

$env:FOUNDRY_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4.1"

當同一程式碼在 Foundry 中以託管代理執行時,平台會在執行階段注入 FOUNDRY_PROJECT_ENDPOINTAZURE_AI_MODEL_DEPLOYMENT_NAME

回應協定

當你想要一個支援 OpenAI 的聊天端點,具備串流功能、回應歷史和對話串程時,請使用 Responses 協定。

建立回應主機

建立一個以最小代理框架代理命名的檔案 main.py ,該代理使用了 Foundry 模型。

import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from agent_framework_foundry_hosting import ResponsesHostServer
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

# Load environment variables from a .env file when present.
load_dotenv()


def main() -> None:
    client = FoundryChatClient(
        project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
        credential=DefaultAzureCredential(),
    )

    agent = Agent(
        client=client,
        instructions="You are a friendly assistant. Keep your answers brief.",
        # The hosting infrastructure manages conversation history, so the
        # service doesn't need to store it.
        default_options={"store": False},
    )

    server = ResponsesHostServer(agent)
    server.run()


if __name__ == "__main__":
    main()

這段程式碼片段的作用:透過 FoundryChatClient 建立一個由 Foundry 模型支援的 Agent Framework 代理程式,然後將該代理程式傳遞給 ResponsesHostServer。 主機會啟動 HTTP 伺服器,並透過 POST /responses 公開代理程式。 預設會將伺服器繫結至連接埠 8088

參考資料:Microsoft Agent Framework 文件

在本地執行應用程式:

python main.py

Program.cs建立一個包含最小代理框架代理的檔案,該代理透過 Responses 協定使用 Foundry 模型。

using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;

var projectEndpoint = new Uri(
    Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set."));

var deployment =
    Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME")
    ?? "gpt-4o";

// Create the agent via the AI project client using the Responses API.
AIAgent agent = new AIProjectClient(projectEndpoint, new DefaultAzureCredential())
    .AsAIAgent(
        model: deployment,
        instructions: "You are a friendly assistant. Keep your answers brief.",
        name: "assistant",
        description: "A simple general-purpose AI assistant");

// Host the agent as a Foundry hosted agent using the Responses API.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);

var app = builder.Build();
app.MapFoundryResponses();
app.Run();

這段程式碼片段的作用:從 Foundry 專案用戶端建立一個 AIAgent,使用 AddFoundryResponses 將其註冊為 Foundry Responses 主機,並使用 POST /responses 對應 MapFoundryResponses 端點。 預設情況下,主機會服務於埠 8088口。

Reference: AIProjectClient | DefaultAzureCredential

在本地執行應用程式:

dotnet run

測試回覆端點

向本地伺服器發送一個非串流的回應請求。

Bash:

curl -sS -H "Content-Type: application/json" \
  -X POST http://localhost:8088/responses \
  -d '{"input":"Give me one practical tip for testing hosted agents.","stream":false}'

PowerShell:

$body = @{
  input  = "Give me one practical tip for testing hosted agents."
  stream = $false
} | ConvertTo-Json

Invoke-RestMethod `
    -Uri http://localhost:8088/responses `
    -Method Post `
    -Body $body `
    -ContentType "application/json"

伺服器會以包含回應文字與回應 ID 的 JSON 物件回應。 串流回應時,設 streamtrue。 主機會發出回應 API 伺服器發送的事件,例如 response.createdresponse.output_text.deltaresponse.completed

多回合對話

要繼續對話,請在下一個請求欄位傳遞先前的回應 ID previous_response_id

curl -sS -H "Content-Type: application/json" \
  -X POST http://localhost:8088/responses \
  -d '{"input":"Can you make that more concise?","previous_response_id":"<previous-response-id>","stream":false}'

當代理在 Foundry 中執行時,同樣的模式也會透過託管代理回應端點運作。 如果後續回合也需要相同的託管沙盒檔案系統,請包含 agent_session_id 或使用 conversation ID。 詳情請參見 管理託管代理會話

呼叫協定

當你的呼叫者無法使用 Responses API 請求表單,或你的情境不是聊天對話時,請使用 Invocations 協定。 呼叫主機透過 agent_session_id 查詢參數與回應標頭管理會話狀態。

建立召喚主機

使用與回應範例相同的代理設定,但 start InvocationsHostServer 而非 ResponsesHostServer

import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from agent_framework_foundry_hosting import InvocationsHostServer
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

# Load environment variables from a .env file when present.
load_dotenv()


def main() -> None:
    client = FoundryChatClient(
        project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
        credential=DefaultAzureCredential(),
    )

    agent = Agent(
        client=client,
        instructions="You are a friendly assistant. Keep your answers brief.",
        default_options={"store": False},
    )

    server = InvocationsHostServer(agent)
    server.run()


if __name__ == "__main__":
    main()

此程式碼片段的作用:透過 POST /invocations 託管 Agent Framework 代理程式。 主機透過查詢參數與回應標頭管理每個會話狀態 agent_session_id

參考資料:Microsoft Agent Framework 文件

Invocations 通訊協定會使用你所實作的 InvocationHandler 來處理每個請求。 註冊 Invocations 伺服器和處理常式,然後對應端點。

using Azure.AI.AgentServer.Invocations;
using Microsoft.Agents.AI;

var builder = WebApplication.CreateBuilder(args);

// Register your agent and the Invocations server services.
builder.Services.AddInvocationsServer();
builder.Services.AddScoped<InvocationHandler, MyInvocationHandler>();

var app = builder.Build();

// Map the Invocations protocol endpoints:
//   POST /invocations              - invoke the agent
//   GET  /invocations/{id}         - get result
//   POST /invocations/{id}/cancel  - cancel
app.MapInvocationsServer();
app.Run();

這個程式碼片段的作用:註冊 Invocations 伺服器服務和你的 InvocationHandler 實作,然後將 /invocations 端點對應起來。 你實作 MyInvocationHandler 時會定義每個請求的處理方式。 完整的處理程序範例請參見 .NET 調用範例

參考資料: AddInvocationsServer

測試 Invocations 端點

向本地伺服器發送請求:

curl -sS -X POST http://localhost:8088/invocations \
  -H "Content-Type: application/json" \
  -d '{"message":"My name is Alice.","stream":false}'

對於多回合對話,請在下一個請求中重複使用 agent_session_id 回應標頭的值作為 agent_session_id 查詢參數:

curl -sS -X POST "http://localhost:8088/invocations?agent_session_id=<session-id>" \
  -H "Content-Type: application/json" \
  -d '{"message":"What is my name?"}'

該平台不會儲存 Invocations 協議的對話紀錄。 使用 agent_session_id 查詢參數將後續呼叫路由到同一託管沙箱。

部署

使用 Azure Developer CLI (azd) 部署 。 流程使用 範例清單和 Docker 來建立代理容器映像,並推送至 Foundry 託管的代理執行環境。

託管的 Agent 部署需要具備專案中的 Foundry 專案管理者角色。 詳情請參見 部署託管代理

安裝 Azure Developer CLI 擴充套件

安裝 AI 代理擴充功能並在初始化樣本前登入:

azd ext install azure.ai.agents
azd auth login

Docker 必須在本地執行,因為 azd ai agent run 它建置的是範例 Dockerfile 中宣告的容器映像。 關於指令細節,請參閱 Azure 開發者 CLI 參考

從範例清單初始化

建立一個新資料夾,並從範例清單初始化。 把清單網址替換成你想用的範例。

mkdir my-agent-framework-agent
cd my-agent-framework-agent

azd ai agent init -m https://github.com/microsoft/agent-framework/blob/main/python/samples/04-hosting/foundry-hosted-agents/responses/basic/agent.manifest.yaml
mkdir my-agent-framework-agent
cd my-agent-framework-agent

azd ai agent init -m https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-ChatClientAgent/agent.manifest.yaml

請依照 azd ai agent init 的提示。 如果你還沒有 Foundry 專案和模型部署,初始化流程可以引導你建立它們。

佈建 Azure 資源

若初始化專案使用新的 Foundry 專案與模型部署,請先配置 Azure 資源:

azd provision

此指令建立一個資源群組,包含 Foundry 實例、一個具模型部署的 Foundry 專案、一個 Application Insights 實例,以及用於託管代理映像的容器登錄檔等資源。

在本機執行容器

透過以下方式在 azd本地執行代理主機:

azd ai agent run

主機在 http://localhost:8088 上提供服務。 在另一個終端機中,呼叫本地協定端點:

azd ai agent invoke --local "Hello!"

你也可以使用 curl 直接呼叫端點:

curl -X POST http://localhost:8088/responses \
  -H "Content-Type: application/json" \
  -d '{"input": "Hello!"}'

部署至鑄造廠

部署代理:

azd deploy

部署時會將代理程式打包成容器映像,推送到已配置的容器登錄檔,然後推送到 Foundry 託管代理執行環境。

Foundry 的託管基礎設施會將執行時環境變數注入代理程式,包括:

  • FOUNDRY_PROJECT_ENDPOINT:已部署代理程式的 Foundry 專案端點 URL。
  • AZURE_AI_MODEL_DEPLOYMENT_NAME:在 azd ai agent init 期間所選取的模型部署名稱。
  • APPLICATIONINSIGHTS_CONNECTION_STRING:專案應用洞察實例的連接字串。

欲了解完整的部署概念、權限及管理細節,請參閱部署託管 代理 程式及 管理託管代理生命週期

故障排除

利用此檢查清單診斷使用代理框架開發託管代理時的常見問題。

無法在代管容器中連線到模型

確認託管代理版本包含 AZURE_AI_MODEL_DEPLOYMENT_NAME,且代理身份有權呼叫 Foundry 專案。 平台設定 FOUNDRY_PROJECT_ENDPOINT;你的程式碼在 Foundry 執行時應該會讀取這個變數。

對話狀態不再繼續

對於 Responses 通訊協定,在後續輪次中傳入 previous_response_idconversation ID。

對於 Invocations 協定,平台不會儲存對話紀錄。 使用 agent_session_id 查詢參數將後續呼叫路由到同一託管沙箱。

協定版本不符

如果升級後請求失敗,請確認你的清單和主機套件都使用協定版本 2.0.0。 協定版本 1.0.0 已不再支援。

後續步驟