Condividi tramite


Microsoft Foundry Agents

Microsoft Agent Framework supporta la creazione di agenti che usano il servizio Foundry Agent. È possibile creare istanze dell'agente persistenti basate sul servizio con la cronologia di chat gestita dal servizio.

Come iniziare

Aggiungere i pacchetti NuGet necessari al progetto.

dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease

Creare gli agenti Foundry

Come primo passaggio è necessario creare un client per connettersi al servizio Agent.

using System;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;

var persistentAgentsClient = new PersistentAgentsClient(
    "https://<myresource>.services.ai.azure.com/api/projects/<myproject>",
    new DefaultAzureCredential());

Avviso

DefaultAzureCredential è utile per lo sviluppo, ma richiede un'attenta considerazione nell'ambiente di produzione. Nell'ambiente di produzione prendere in considerazione l'uso di credenziali specifiche ,ad esempio ManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.

Per usare il servizio Agent, è necessario creare una risorsa agente nel servizio. A tale scopo, è possibile usare Azure.AI.Agents.Persistent SDK o gli helper di Microsoft Agent Framework.

Uso dell'SDK permanente

Crea un agente persistente e recuperalo come oggetto AIAgent usando il PersistentAgentsClient.

// Create a persistent agent
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

// Retrieve the agent that was just created as an AIAgent using its ID
AIAgent agent1 = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);

// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));

Uso degli helper di Agent Framework

È anche possibile creare e restituire un oggetto AIAgent in un unico passaggio:

AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

Riutilizzo degli agenti di fonderia

È possibile riutilizzare gli agenti Foundry esistenti recuperandoli usando i relativi ID.

AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");

Uso dell'agente

L'agente è uno standard AIAgent e supporta tutte le operazioni standard AIAgent .

Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.

Configurazione

Variabili di ambiente

Importante

AzureAIAgentClient (Foundry Agent Service v1) e AzureAIClient (Foundry Agent Service v2) richiedono entrambi un endpoint del progetto Azure AI Foundry (formato: https://<your-project>.services.ai.azure.com/api/projects/<project-id>), non un endpoint della risorsa OpenAI di Azure. Per usare questo provider, è necessario disporre di un progetto Azure AI Foundry . Se invece si ha una risorsa OpenAI di Azure autonoma, vedere la pagina del provider OpenAI di Azure.

Prima di usare Gli agenti Foundry, è necessario configurare queste variabili di ambiente:

export AZURE_AI_PROJECT_ENDPOINT="https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"

In alternativa, è possibile specificare questi valori direttamente nel codice.

Installazione

Aggiungere il pacchetto azure per intelligenza artificiale di Agent Framework al progetto:

pip install agent-framework-azure-ai --pre

Come iniziare

Autenticazione

Gli agenti foundry usano le credenziali di Azure per l'autenticazione. L'approccio più semplice consiste nell'usare AzureCliCredential dopo aver eseguito az login. Tutti i client di Intelligenza artificiale di Azure accettano un parametro unificato credential che supporta TokenCredential, AsyncTokenCredentialo un provider di token chiamabile: la memorizzazione nella cache e l'aggiornamento dei token vengono gestiti automaticamente.

from azure.identity.aio import AzureCliCredential

async with AzureCliCredential() as credential:
    # Use credential with Azure AI agent client

Creare gli agenti Foundry

Creazione dell'agente di base

Il modo più semplice per creare un agente consiste nell'usare con le AzureAIAgentClient variabili di ambiente:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(credential=credential).as_agent(
            name="HelperAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Configurazione esplicita

È anche possibile specificare la configurazione in modo esplicito anziché usare le variabili di ambiente:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(
            project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
            model_deployment_name="gpt-4o-mini",
            credential=credential,
            agent_name="HelperAgent"
        ).as_agent(
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Uso di agenti Foundry esistenti

Uso di un agente esistente

Se si dispone di un agente esistente in Foundry, è possibile usarlo specificandone l'ID:

import asyncio
from agent_framework import Agent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        Agent(
            chat_client=AzureAIAgentClient(
                credential=credential,
                agent_id="<existing-agent-id>"
            ),
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Creare e gestire agenti persistenti

Per un maggiore controllo sul ciclo di vita dell'agente, è possibile creare agenti permanenti usando il client di Azure AI Projects:

import asyncio
import os
from agent_framework import Agent
from agent_framework.azure import AzureAIAgentClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AIProjectClient(
            endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            credential=credential
        ) as project_client,
    ):
        # Create a persistent agent
        created_agent = await project_client.agents.create_agent(
            model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
            name="PersistentAgent",
            instructions="You are a helpful assistant."
        )

        try:
            # Use the agent
            async with Agent(
                chat_client=AzureAIAgentClient(
                    project_client=project_client,
                    agent_id=created_agent.id
                ),
                instructions="You are a helpful assistant."
            ) as agent:
                result = await agent.run("Hello!")
                print(result.text)
        finally:
            # Clean up the agent
            await project_client.agents.delete_agent(created_agent.id)

asyncio.run(main())

Funzionalità dell'agente

Opzioni di ragionamento e filtro del contenuto

Quando si creano agenti tramite provider di progetti di Intelligenza artificiale di Azure, è possibile impostare default_options per abilitare il ragionamento dei modelli e il filtro dei contenuti di intelligenza artificiale responsabile.

Usare reasoning per i modelli con supporto per il ragionamento:

from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.models import Reasoning
from azure.identity.aio import AzureCliCredential
    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(

Usare rai_config per applicare un criterio RAI configurato:

from azure.ai.projects.models import RaiConfig
from azure.identity.aio import AzureCliCredential
async def main() -> None:
    print("=== Azure AI Agent with Content Filtering ===\n")

    # Replace with your RAI policy from Azure AI Foundry portal
    rai_policy_name = (
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/"
        "Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{policyName}"
    )

    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        # Create agent with content filtering enabled via default_options
        agent = await provider.create_agent(

Strumenti per le funzioni

È possibile fornire strumenti di funzione personalizzati agli agenti Foundry:

import asyncio
from typing import Annotated
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25°C."

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(credential=credential).as_agent(
            name="WeatherAgent",
            instructions="You are a helpful weather assistant.",
            tools=get_weather
        ) as agent,
    ):
        result = await agent.run("What's the weather like in Seattle?")
        print(result.text)

asyncio.run(main())

Interprete di codice

Gli agenti Foundry supportano l'esecuzione del codice tramite l'interprete di codice ospitato:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(credential=credential) as client,
        client.as_agent(
            name="CodingAgent",
            instructions="You are a helpful assistant that can write and execute Python code.",
            tools=client.get_code_interpreter_tool(),
        ) as agent,
    ):
        result = await agent.run("Calculate the factorial of 20 using Python code.")
        print(result.text)

asyncio.run(main())

Risposte in streaming

Ricevere le risposte man mano che vengono generate, utilizzando lo streaming:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(credential=credential).as_agent(
            name="StreamingAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run("Tell me a short story", stream=True):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

asyncio.run(main())

Uso dell'agente

L'agente è uno standard BaseAgent e supporta tutte le operazioni dell'agente standard.

Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.

Passaggi successivi