Compartilhar via


Agentes do Azure AI Foundry

O Microsoft Agent Framework dá suporte à criação de agentes que usam o serviço Azure AI Foundry Agents , você pode criar instâncias de agente persistentes baseadas em serviço com threads de conversa gerenciados pelo serviço.

Introdução

Adicione os pacotes NuGet necessários ao seu projeto.

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

Criando agentes do Azure AI Foundry

Como primeira etapa, você precisa criar um cliente para se conectar ao serviço Azure AI Foundry Agents.

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

Para usar o serviço Azure AI Foundry Agents, você precisa criar um recurso de agente no serviço. Isso pode ser feito usando o SDK Azure.AI.Agents.Persistent ou usando auxiliares do Microsoft Agent Framework.

Usando o SDK Persistente

Crie um agente persistente e recupere-o como um AIAgent usando o 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."));

Usando os auxiliares do Agent Framework

Você também pode criar e retornar um AIAgent em uma etapa:

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

Reutilizando agentes do Azure AI Foundry

Você pode reutilizar agentes do Azure AI Foundry existentes recuperando-os usando suas IDs.

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

Usando o agente

O agente é um AIAgent padrão e oferece suporte a todas as operações padrão AIAgent.

Consulte os tutoriais de introdução do Agente para obter mais informações sobre como executar e interagir com agentes.

Configuração

Variáveis de ambiente

Antes de usar os Azure AI Foundry Agents, você precisa configurar essas variáveis de 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"

Como alternativa, você pode fornecer esses valores diretamente em seu código.

Installation

Adicione o pacote de IA do Azure do Agent Framework ao seu projeto:

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

Introdução

Authentication

Os Azure AI Foundry Agents usam credenciais do Azure para autenticação. A abordagem mais simples é usar AzureCliCredential após a execução az login:

from azure.identity.aio import AzureCliCredential

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

Criando agentes do Azure AI Foundry

Criação básica de agente

A maneira mais simples de criar um agente é usando as AzureAIAgentClient variáveis de ambiente com:

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

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

asyncio.run(main())

Configuração explícita

Você também pode fornecer configuração explicitamente em vez de usar variáveis de 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",
            async_credential=credential,
            agent_name="HelperAgent"
        ).create_agent(
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Usando agentes do Azure AI Foundry existentes

Usando um agente existente pelo ID

Se você tiver um agente existente no Azure AI Foundry, poderá usá-lo fornecendo sua ID:

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

async def main():
    async with (
        AzureCliCredential() as credential,
        ChatAgent(
            chat_client=AzureAIAgentClient(
                async_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())

Criando e gerenciando agentes persistentes

Para obter mais controle sobre o ciclo de vida do agente, você pode criar agentes persistentes usando o cliente de Projetos de IA do Azure:

import asyncio
import os
from agent_framework import ChatAgent
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 ChatAgent(
                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())

Recursos do agente

Ferramentas de Funções

Você pode fornecer ferramentas de função personalizadas aos agentes do Azure AI 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(async_credential=credential).create_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())

Interpretador de Código

Os agentes do Azure AI Foundry dão suporte à execução de código por meio do interpretador de código hospedado:

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

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

asyncio.run(main())

Respostas do streaming

Obtenha respostas conforme elas são geradas usando streaming:

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

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

asyncio.run(main())

Usando o agente

O agente é um padrão BaseAgent e dá suporte a todas as operações de agente padrão.

Consulte os tutoriais de introdução do Agente para obter mais informações sobre como executar e interagir com agentes.

Próximas etapas