Agen yang Dihosting oleh Foundry

agen Hosted di Microsoft Foundry Agent Service memungkinkan Anda menyebarkan agen Agent Framework sebagai aplikasi dalam kontainer ke infrastruktur yang dikelola Microsoft. Platform ini menangani penskalaan, persistensi status sesi, keamanan, dan manajemen siklus hidup sehingga Anda dapat fokus pada logika agen Anda.

Dengan integrasi hosting Kerangka Kerja Agen, Anda dapat mengambil apa pun Agent atau alur kerja dan mengeksposnya melalui protokol Respons atau Pemanggilan Foundry dengan kode minimal.

Kapan menggunakan agen yang dihosting

Pilih Agen yang dihosting Foundry saat Anda ingin:

  • Infrastruktur terkelola — tidak perlu mengonfigurasi kontainer, server web, atau aturan penskalakan sendiri.
  • Manajemen sesi bawaan — platform mempertahankan $HOME dan file diunggah melalui giliran dan periode idle.
  • Identitas agen khusus — setiap agen yang disebarkan mendapatkan identitas Entra sendiri untuk akses aman ke model, alat, dan layanan hilir.
  • Titik akhir yang kompatibel dengan OpenAI — klien dapat berinteraksi dengan agen Anda menggunakan SDK yang kompatibel dengan OpenAI melalui protokol Respons.

Note

Agen yang dihosting oleh Foundry saat ini masih dalam pratinjau. Lihat dokumentasi agen yang dihosting Foundry untuk ketersediaan, batas, dan harga terbaru.

Prasyarat

Untuk pengujian lokal, Anda juga perlu:

Pasang paket hosting NuGet:

dotnet add package Microsoft.Agents.AI.Foundry.Hosting --prerelease
dotnet add package Azure.AI.Projects --prerelease
  • Python 3.10 atau yang lebih baru

Instal paket hosting Python.

pip install agent-framework agent-framework-foundry-hosting

Protokol respons

Protokol Respons adalah titik awal yang direkomendasikan untuk sebagian besar agen. Ini mengekspos titik akhir yang kompatibel /responses dengan OpenAI, dan platform mengelola riwayat percakapan, streaming, dan siklus hidup sesi secara otomatis.

using Azure.AI.AgentServer.Core;
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";

AIAgent agent = new AIProjectClient(projectEndpoint, new DefaultAzureCredential())
    .AsAIAgent(
        model: deployment,
        instructions: "You are a helpful AI assistant.",
        name: "my-agent");

var builder = AgentHost.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.RegisterProtocol("responses", endpoints => endpoints.MapFoundryResponses());

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

AgentHost.CreateBuilder menciptakan host aplikasi yang telah dikonfigurasi sebelumnya untuk lingkungan hosting Foundry. AddFoundryResponses mendaftarkan agen Anda dengan penangan protokol Responses, dan MapFoundryResponses memetakan titik akhir HTTP /responses.

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

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 helpful AI assistant.",
    default_options={"store": False},
)

server = ResponsesHostServer(agent)
server.run()

ResponsesHostServer mengelilingi agen Anda dan mengeksposnya melalui protokol Foundry Responses. Pengaturan store ke False dalam default_options menghindari riwayat percakapan duplikat, karena infrastruktur hosting mengelola riwayat secara otomatis.

Protokol pemanggilan

Protokol Pemanggilan memberi Anda kontrol penuh atas permintaan dan respons HTTP. Gunakan saat Anda memerlukan payload kustom, pemrosesan non-percakapan, atau protokol streaming yang tidak kompatibel dengan OpenAI.

Dengan protokol Pemanggilan di C#, Anda menerapkan kustom InvocationHandler untuk memproses permintaan masuk:

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

var builder = AgentHost.CreateBuilder(args);

builder.Services.AddSingleton<AIAgent, MyAgent>();
builder.Services.AddInvocationsServer();
builder.Services.AddScoped<InvocationHandler, MyInvocationHandler>();

builder.RegisterProtocol("invocations", endpoints => endpoints.MapInvocationsServer());

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

Metode ini AddInvocationsServer mendaftarkan layanan protokol Invokasi. Anda menerapkan InvocationHandler untuk menentukan bagaimana agen Anda memproses setiap permintaan.

Untuk pengaturan ringan, gunakan InvocationsHostServer dari agent_framework_foundry_hosting paket. Ini membungkus agen Anda yang mirip dengan ResponsesHostServer dan menangani manajemen sesi secara otomatis:

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

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()

Untuk kontrol penuh atas penanganan permintaan, gunakan InvocationAgentServerHost dari azure.ai.agentserver.invocations paket secara langsung dan terapkan handler pemanggil Anda sendiri:

import os
from collections.abc import AsyncGenerator

from agent_framework import Agent, AgentSession
from agent_framework.foundry import FoundryChatClient
from azure.ai.agentserver.invocations import InvocationAgentServerHost
from azure.identity import DefaultAzureCredential
from starlette.requests import Request
from starlette.responses import JSONResponse, Response, StreamingResponse

_sessions: dict[str, AgentSession] = {}

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},
)

app = InvocationAgentServerHost()


@app.invoke_handler
async def handle_invoke(request: Request):
    """Handle streaming multi-turn chat."""
    data = await request.json()
    session_id = request.state.session_id
    stream = data.get("stream", False)
    user_message = data.get("message", None)

    if user_message is None:
        return Response(content="Missing 'message' in request", status_code=400)

    session = _sessions.setdefault(session_id, AgentSession(session_id=session_id))

    if stream:

        async def stream_response() -> AsyncGenerator[str]:
            async for update in agent.run(user_message, session=session, stream=True):
                yield update.text

        return StreamingResponse(
            stream_response(),
            media_type="text/event-stream",
            headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
        )

    response = await agent.run([user_message], session=session, stream=stream)
    return JSONResponse({"response": response.text})


if __name__ == "__main__":
    app.run()

Peringatan

Penyimpanan sesi dalam memori dalam contoh handler kustom hilang saat menghidupkan ulang. Gunakan penyimpanan tahan lama (misalnya, Cosmos DB) dalam produksi.

Note

Dukungan Go untuk agen yang dihosting Foundry akan segera hadir. Lihat repositori Agent Framework Go untuk status terbaru.

Tip

Lihat sampel Python atau sampel C# untuk contoh proyek agen yang dihosting. Atau gunakan perintah azd ai agent init untuk menginisiasi sebuah proyek agen baru yang di-host dari awal. Lihat panduan mulai cepat ini untuk instruksi langkah demi langkah.

Beroperasi secara lokal

Azure Developer CLI (azd) menyediakan cara term mudah untuk menjalankan dan menguji agen yang dihosting secara lokal.

Menginisialisasi proyek

Buat folder baru dan inisialisasi dari manifes sampel:

mkdir my-hosted-agent && cd my-hosted-agent
azd ai agent init -m <path-to-agent.manifest.yaml>

Tip

Manifes dapat menjadi jalur ke file YAML lokal atau URL ke manifes jarak jauh.

Mengatur variabel lingkungan

export FOUNDRY_PROJECT_ENDPOINT="https://<account>.services.ai.azure.com/api/projects/<project>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="<your-model-deployment>"

Jalankan host agen

azd ai agent run

Host agen dimulai pada http://localhost:8088.

Memanggil agen

azd ai agent invoke --local "Hello!"

Atau gunakan curl:

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

Atau di PowerShell:

(Invoke-WebRequest -Uri http://localhost:8088/responses -Method POST -ContentType "application/json" -Body '{"input": "Hello!"}').Content

Menyebarkan ke Foundry

Setelah Anda memverifikasi agen Anda secara lokal, sebarkan ke Microsoft Foundry:

  1. Memprovisikan sumber daya (jika Anda belum memiliki proyek Foundry):

    azd provision
    

    Ini membuat grup sumber daya dengan instans Foundry, proyek, penyebaran model, Application Insights, dan registri kontainer.

  2. Sebarkan agen:

    azd deploy
    

    Ini mengemas agen Anda sebagai image kontainer, mengunggahnya ke Azure Container Registry, dan mendeploykannya ke Foundry Agent Service.

Infrastruktur hosting Foundry secara otomatis menyuntikkan variabel lingkungan berikut ke dalam kontainer agen Anda saat runtime:

Variabel Description
FOUNDRY_PROJECT_ENDPOINT URL titik akhir untuk proyek Foundry.
AZURE_AI_MODEL_DEPLOYMENT_NAME Nama penyebaran model (dikonfigurasi selama azd ai agent init).
APPLICATIONINSIGHTS_CONNECTION_STRING String koneksi dari Application Insights untuk telemetri.

Setelah ditempatkan, agen Anda dapat diakses melalui titik akhir yang khusus di Foundry dan juga dapat diuji dari portal Foundry.

Langkah berikutnya