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 AI Foundry Agents . Vous pouvez créer des instances d’agent basées sur un service persistant avec des threads de conversation gérés par le service.
Getting Started
Ajoutez les packages NuGet requis à votre projet.
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease
Créer des agents Azure AI Foundry
Pour commencer, vous devez créer un client pour vous connecter au service 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());
Pour utiliser le service Azure AI Foundry Agents, vous devez créer une ressource d’agent dans le service. Cette opération peut être effectuée à l’aide du Kit de développement logiciel (SDK) Azure.AI.Agents.Persistent ou de l’aide de Microsoft Agent Framework.
Utilisation du Kit de développement logiciel (SDK) persistant
Créez un agent persistant et récupérez-le en tant que AIAgent à l'aide de 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."));
Utilisation des helpers d’Agent Framework
Vous pouvez également créer et renvoyer un AIAgent en une seule étape :
AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
Réutilisation d’agents Azure AI Foundry
Vous pouvez réutiliser les agents Azure AI Foundry existants en les récupérant à l’aide de leurs ID.
AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");
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 AI Foundry, vous devez configurer ces variables d’environnement :
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"
Vous pouvez également fournir ces valeurs directement dans votre code.
Installation
Ajoutez le package Azure AI Agent Framework à votre projet :
pip install agent-framework-azure-ai --pre
Getting Started
Authentication
Les agents Azure AI Foundry 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.aio import AzureCliCredential
async with AzureCliCredential() as credential:
# Use credential with Azure AI agent client
Créer des agents Azure AI Foundry
Création d'un agent basique
La façon la plus simple de créer un agent consiste à utiliser les AzureAIAgentClient variables d’environnement :
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())
Configuration explicite
Vous pouvez également fournir une configuration explicitement au lieu d’utiliser des variables d’environnement :
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())
Utilisation d’agents Azure AI Foundry existants
Utilisation d’un agent existant par ID
Si vous disposez d’un agent existant dans Azure AI Foundry, vous pouvez l’utiliser en fournissant son 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())
Créer et gérer des agents persistants
Pour plus de contrôle sur le cycle de vie des agents, vous pouvez créer des agents persistants à l’aide du client 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())
Fonctionnalités de l’agent
Outils de fonction
Vous pouvez fournir des outils de fonction personnalisés aux agents 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())
Interpréteur de code
Les agents Azure AI Foundry prennent en charge l’exécution du code via l’interpréteur de code hébergé :
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())
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 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())
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.