Nota
O acesso a esta página requer autorização. Podes tentar iniciar sessão ou mudar de diretório.
O acesso a esta página requer autorização. Podes tentar mudar de diretório.
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 por 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 os Agentes do Azure AI Foundry existentes recuperando-os usando suas IDs.
AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");
Usando o agente
O agente é um padrão AIAgent e suporta todas as operações padrão AIAgent .
Consulte os tutoriais de introdução ao agente para obter mais informações sobre como executar e interagir com agentes.
Configuração
Variáveis de ambiente
Antes de usar o Azure AI Foundry Agents, você precisa configurar estas 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 Agentes do Azure AI Foundry usam credenciais do Azure para autenticação. A abordagem mais simples é usar AzureCliCredential depois de executar 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 agentes
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 existentes do Azure AI Foundry
Usando um agente existente usando a 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 Azure AI Projects:
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())
Funcionalidades do agente
Ferramentas de Função
Você pode fornecer ferramentas de função personalizadas para 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())
Intérprete 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 de Transmissão
Obtenha respostas à medida que são geradas através do 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 BaseAgent padrão e suporta todas as operações padrão de um agente.
Consulte os tutoriais de introdução ao agente para obter mais informações sobre como executar e interagir com agentes.