Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O Microsoft Agent Framework dá suporte à criação de agentes que usam o serviço de ChatCompletion do Azure OpenAI .
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 ChatCompletion 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 escolher o serviço ChatCompletion para criar um agente baseado em ChatCompletion.
var chatCompletionClient = client.GetChatClient("gpt-4o-mini");
Por fim, crie o agente usando o CreateAIAgent método de extensão no ChatCompletionClient.
AIAgent agent = chatCompletionClient.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."));
Recursos do agente
Ferramentas de Funções
Você pode fornecer ferramentas de função personalizadas para agentes de ChatCompletion do Azure OpenAI:
using System;
using System.ComponentModel;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
=> $"The weather in {location} is cloudy with a high of 15°C.";
// Create the chat client and agent, and provide the function tool to the agent.
AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new AzureCliCredential())
.GetChatClient(deploymentName)
.CreateAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);
// Non-streaming agent interaction with function tools.
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Respostas do streaming
Obtenha respostas conforme elas são geradas usando streaming:
AIAgent agent = chatCompletionClient.CreateAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
// Invoke the agent with streaming support.
await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate."))
{
Console.Write(update);
}
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 agentes de ChatCompletion do Azure OpenAI, você precisa configurar essas variáveis de ambiente:
export AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
Opcionalmente, você também pode definir:
export AZURE_OPENAI_API_VERSION="2024-10-21" # Default API version
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 usam credenciais do Azure para autenticação. A abordagem mais simples é usar AzureCliCredential após a execução az login:
from azure.identity import AzureCliCredential
credential = AzureCliCredential()
Criando um Agente de ChatCompletion do Azure OpenAI
Criação básica de agente
A maneira mais simples de criar um agente é usando as AzureOpenAIChatClient variáveis de ambiente com:
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIChatClient(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 AzureOpenAIChatClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIChatClient(
endpoint="https://<myresource>.openai.azure.com",
deployment_name="gpt-4o-mini",
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())
Recursos do agente
Ferramentas de Funções
Você pode fornecer ferramentas de função personalizadas para agentes de ChatCompletion do Azure OpenAI:
import asyncio
from typing import Annotated
from agent_framework.azure import AzureOpenAIChatClient
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 = AzureOpenAIChatClient(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())
Respostas do streaming
Obtenha respostas conforme elas são geradas usando streaming:
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIChatClient(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 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.