Partager via


Agents de la Fonderie de Microsoft

Microsoft Agent Framework prend en charge la création d’agents qui utilisent le service Foundry Agent. Vous pouvez créer des instances d’agent basées sur un service persistant avec l’historique de conversation géré par le service.

Getting Started

Ajoutez les packages NuGet requis à votre projet.

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

Créer des agents Foundry

Pour commencer, vous devez créer un client pour vous connecter au service 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());

Avertissement

DefaultAzureCredential est pratique pour le développement, mais nécessite une considération minutieuse en production. En production, envisagez d’utiliser des informations d’identification spécifiques (par exemple ManagedIdentityCredential) pour éviter les problèmes de latence, la détection involontaire des informations d’identification et les risques de sécurité potentiels liés aux mécanismes de secours.

Pour utiliser le service Agent, vous devez créer une ressource d’agent dans le service. Cette opération peut être effectuée à l’aide du Kit de développement logiciel (SDK) Azure.AI.Agents.Persistent ou de l’aide de Microsoft Agent Framework.

Utilisation du Kit de développement logiciel (SDK) persistant

Créez un agent persistant et récupérez-le en tant que AIAgent à l'aide de 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."));

Utilisation des helpers d’Agent Framework

Vous pouvez également créer et renvoyer un AIAgent en une seule étape :

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

Réutilisation des agents de fonderie

Vous pouvez réutiliser les agents Foundry existants en les récupérant à l’aide de leurs ID.

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

Conseil / Astuce

Consultez les exemples .NET pour obtenir des exemples exécutables complets.

Utilisation de l’agent

L’agent standard AIAgent prend en charge toutes les opérations standard AIAgent.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Paramétrage

Variables d’environnement

Avant d’utiliser les agents Foundry, vous devez configurer ces variables d’environnement :

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"

Vous pouvez également fournir ces valeurs directement dans votre code.

Installation

Ajoutez le package Azure AI Agent Framework à votre projet :

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

Getting Started

Authentification

Les agents foundry utilisent les informations d’identification Azure pour l’authentification. L’approche la plus simple consiste à utiliser AzureCliCredential après l’exécution az login. Tous les clients Azure AI acceptent un paramètre unifié credential qui prend en charge TokenCredential, AsyncTokenCredentialou un fournisseur de jetons pouvant être appelé , la mise en cache et l’actualisation des jetons sont gérées automatiquement.

from azure.identity.aio import AzureCliCredential

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

Créer des agents Foundry

Création d'un agent basique

La façon la plus simple de créer un agent consiste à utiliser les AzureAIAgentClient variables d’environnement :

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

Configuration explicite

Vous pouvez également fournir une configuration explicitement au lieu d’utiliser des variables d’environnement :

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

Utilisation d’agents de fonderie existants

Utilisation d’un agent existant

Si vous disposez d’un agent existant dans Foundry, vous pouvez l’utiliser en fournissant son 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())

Créer et gérer des agents persistants

Pour plus de contrôle sur le cycle de vie des agents, vous pouvez créer des agents persistants à l’aide du client 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())

Fonctionnalités de l’agent

Options de filtrage de contenu et de raisonnement

Lors de la création d’agents via des fournisseurs de projets Azure AI, vous pouvez définir default_options pour activer le raisonnement du modèle et le filtrage de contenu IA responsable.

Utiliser reasoning pour les modèles compatibles avec le raisonnement :

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(

Utilisez rai_config pour appliquer une stratégie RAI configurée.

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(

Outils de fonction

Vous pouvez fournir des outils de fonction personnalisés aux agents 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())

Interpréteur de code

Les agents Foundry prennent en charge l’exécution du code via l’interpréteur de code hébergé :

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

Réponses en continu

Obtenez des réponses au fur et à mesure qu’elles sont générées à l’aide de la diffusion en continu :

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

Utilisation de l’agent

L’agent est standard BaseAgent et prend en charge toutes les opérations d’agent standard.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Étapes suivantes