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 OpenAI Responses .
Introdução
Adicione os pacotes NuGet necessários ao seu projeto.
dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
Criando um Agente de Respostas do Azure OpenAI
Como primeira etapa, você precisa criar um cliente para se conectar ao serviço Azure OpenAI.
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI;
AzureOpenAIClient client = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com/"),
new AzureCliCredential());
O Azure OpenAI dá suporte a vários serviços que fornecem recursos de chamada de modelo. Precisamos selecionar o serviço "Responses" para criar um agente baseado no "Responses".
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var responseClient = client.GetOpenAIResponseClient("gpt-4o-mini");
#pragma warning restore OPENAI001
Finalmente, crie o agente usando o método de extensão CreateAIAgent no ResponseClient.
AIAgent agent = responseClient.CreateAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
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 os agentes do Azure OpenAI Responses, você precisa configurar estas variáveis de ambiente:
export AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
export AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o-mini"
Opcionalmente, você também pode definir:
export AZURE_OPENAI_API_VERSION="preview" # Required for Responses API
export AZURE_OPENAI_API_KEY="<your-api-key>" # If not using Azure CLI authentication
Installation
Adicione o pacote do Agent Framework ao seu projeto:
pip install agent-framework --pre
Introdução
Authentication
Os agentes do Azure OpenAI Responses usam credenciais do Azure para autenticação. A abordagem mais simples é usar AzureCliCredential depois de executar az login:
from azure.identity import AzureCliCredential
credential = AzureCliCredential()
Criando um Agente de Respostas do Azure OpenAI
Criação básica de agentes
A maneira mais simples de criar um agente é usando as AzureOpenAIResponsesClient variáveis de ambiente com:
import asyncio
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
instructions="You are good at telling jokes.",
name="Joker"
)
result = await agent.run("Tell me a joke about a pirate.")
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 AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIResponsesClient(
endpoint="https://<myresource>.openai.azure.com",
deployment_name="gpt-4o-mini",
api_version="preview",
credential=AzureCliCredential()
).create_agent(
instructions="You are good at telling jokes.",
name="Joker"
)
result = await agent.run("Tell me a joke about a pirate.")
print(result.text)
asyncio.run(main())
Funcionalidades do agente
Ferramentas de Função
Você pode fornecer ferramentas de função personalizadas para agentes do Azure OpenAI Responses:
import asyncio
from typing import Annotated
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity 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():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
instructions="You are a helpful weather assistant.",
tools=get_weather
)
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 OpenAI Responses dão suporte à execução de código por meio do interpretador de código hospedado:
import asyncio
from agent_framework import ChatAgent, HostedCodeInterpreterTool
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
async with ChatAgent(
chat_client=AzureOpenAIResponsesClient(credential=AzureCliCredential()),
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 AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
instructions="You are a helpful assistant."
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story about a robot"):
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.