Delen via


Azure AI Foundry-agents

Microsoft Agent Framework biedt ondersteuning voor het maken van agents die gebruikmaken van de Azure AI Foundry Agents-service . U kunt service-gebaseerde persistente agentexemplaren maken met gespreksthreads die door de service worden beheerd.

Aan de slag komen

Voeg de vereiste NuGet-pakketten toe aan uw project.

dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease

Azure AI Foundry-agents maken

Als eerste stap moet u een client maken om verbinding te maken met de Azure AI Foundry Agents-service.

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());

Als u de Azure AI Foundry Agents-service wilt gebruiken, moet u een agentresource in de service maken. U kunt dit doen met behulp van de Azure.AI.Agents.Persistent SDK of met behulp van Microsoft Agent Framework-helpers.

De permanente SDK gebruiken

Maak een persistent agent en haal deze op als een AIAgent met behulp van 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."));

Agent Framework-helpers gebruiken

U kunt ook een AIAgent in één stap maken en retourneren:

AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

Azure AI Foundry-agents hergebruiken

U kunt bestaande Azure AI Foundry-agents opnieuw gebruiken door ze op te halen met behulp van hun id's.

AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");

De agent gebruiken

De agent is een standaard AIAgent en ondersteunt alle standaard AIAgent bewerkingen.

Voor meer informatie over hoe je agents uitvoert en ermee werkt, raadpleeg de Aan de slag met agent-tutorials.

Configuratie

Omgevingsvariabelen

Voordat u Azure AI Foundry-agents gebruikt, moet u deze omgevingsvariabelen instellen:

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"

U kunt deze waarden ook rechtstreeks in uw code opgeven.

Installatie

Voeg het Azure AI-pakket agentframework toe aan uw project:

pip install agent-framework-azure-ai --pre

Aan de slag komen

Authenticatie

Azure AI Foundry-agents gebruiken Azure-referenties voor verificatie. De eenvoudigste methode is om te gebruiken AzureCliCredential na het uitvoeren az login:

from azure.identity.aio import AzureCliCredential

async with AzureCliCredential() as credential:
    # Use credential with Azure AI agent client

Azure AI Foundry-agents maken

Basisagent maken

De eenvoudigste manier om een agent te maken, is het gebruik van de AzureAIAgentClient omgevingsvariabelen:

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).as_agent(
            name="HelperAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Expliciete configuratie

U kunt ook expliciet configuratie opgeven in plaats van omgevingsvariabelen te gebruiken:

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"
        ).as_agent(
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

Bestaande Azure AI Foundry-agents gebruiken

Een bestaande agent gebruiken via ID

Als u een bestaande agent in Azure AI Foundry hebt, kunt u deze gebruiken door de id op te geven:

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())

Permanente agents maken en beheren

Voor meer controle over de levenscyclus van agents kunt u permanente agents maken met behulp van de Azure AI Projects-client:

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())

Agent functies

Functiehulpmiddelen

U kunt aangepaste functiehulpprogramma's opgeven voor Azure AI Foundry-agents:

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).as_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())

Code-interpreter

Azure AI Foundry-agents ondersteunen het uitvoeren van code via de gehoste code-interpreter:

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).as_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())

Streamingreacties

Antwoorden ophalen terwijl ze worden gegenereerd met behulp van 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).as_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())

De agent gebruiken

De agent is een standaard BaseAgent en ondersteunt alle standaardagentbewerkingen.

Voor meer informatie over hoe je agents uitvoert en ermee werkt, raadpleeg de Aan de slag met agent-tutorials.

Volgende stappen