Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Microsoft Agent Framework prend en charge la création d’agents qui utilisent le service Azure OpenAI ChatCompletion .
Getting Started
Ajoutez les packages NuGet requis à votre projet.
dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
Créer un agent Azure OpenAI ChatCompletion
Pour commencer, vous devez créer un client pour vous connecter au service 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());
Azure OpenAI prend en charge plusieurs services qui fournissent toutes des fonctionnalités d’appel de modèle. Choisissez le service ChatCompletion pour créer un agent basé sur ChatCompletion.
var chatCompletionClient = client.GetChatClient("gpt-4o-mini");
Enfin, créez l’agent à l’aide de la méthode d’extension CreateAIAgent sur le 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."));
Fonctionnalités de l’agent
Outils de fonction
Vous pouvez fournir des outils de fonction personnalisés aux agents Azure OpenAI ChatCompletion :
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?"));
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 :
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);
}
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 Azure OpenAI ChatCompletion, vous devez configurer ces variables d’environnement :
export AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
Si vous le souhaitez, vous pouvez également définir :
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
Ajoutez le package Agent Framework à votre projet :
pip install agent-framework --pre
Getting Started
Authentication
Les agents Azure OpenAI utilisent les informations d’identification Azure pour l’authentification. L’approche la plus simple consiste à utiliser AzureCliCredential après l’exécution az login:
from azure.identity import AzureCliCredential
credential = AzureCliCredential()
Créer un agent Azure OpenAI ChatCompletion
Création d'un agent basique
La façon la plus simple de créer un agent consiste à utiliser les AzureOpenAIChatClient variables d’environnement :
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())
Configuration explicite
Vous pouvez également fournir une configuration explicitement au lieu d’utiliser des variables d’environnement :
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())
Fonctionnalités de l’agent
Outils de fonction
Vous pouvez fournir des outils de fonction personnalisés aux agents Azure OpenAI ChatCompletion :
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())
Utilisation de threads pour la gestion du contexte
Maintenez le contexte de conversation entre plusieurs interactions :
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 programming assistant."
)
# Create a new thread for conversation context
thread = agent.get_new_thread()
# First interaction
result1 = await agent.run("I'm working on a Python web application.", thread=thread, store=True)
print(f"Assistant: {result1.text}")
# Second interaction - context is preserved
result2 = await agent.run("What framework should I use?", thread=thread, store=True)
print(f"Assistant: {result2.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 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())
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.