Delen via


Azure OpenAI ChatCompletion-agenten

Microsoft Agent Framework ondersteunt het maken van agents die gebruikmaken van de Azure OpenAI ChatCompletion-service .

Aan de slag komen

Voeg de vereiste NuGet-pakketten toe aan uw project.

dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

Een Azure OpenAI ChatCompletion-agent maken

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

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 ondersteunt meerdere services die allemaal mogelijkheden bieden voor het aanroepen van modellen. Kies de ChatCompletion-service om een op ChatCompletion gebaseerde agent te maken.

var chatCompletionClient = client.GetChatClient("gpt-4o-mini");

Maak ten slotte de agent met behulp van de AsAIAgent extensiemethode op de ChatCompletionClient.

AIAgent agent = chatCompletionClient.AsAIAgent(
    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."));

Agent functies

Functiehulpmiddelen

U kunt aangepaste functiehulpprogramma's opgeven voor Azure OpenAI ChatCompletion-agents:

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)
     .AsAIAgent(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?"));

Streamingreacties

Antwoorden ophalen terwijl ze worden gegenereerd met behulp van streaming:

AIAgent agent = chatCompletionClient.AsAIAgent(
    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);
}

De agent gebruiken

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

Zie de zelfstudies om aan de slag te gaan met agents voor meer informatie over het uitvoeren en gebruiken van agents.

Configuratie

Omgevingsvariabelen

Voordat u Azure OpenAI ChatCompletion-agents gebruikt, moet u deze omgevingsvariabelen instellen:

export AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"

U kunt desgewenst ook het volgende instellen:

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

Installatie

Voeg het Agent Framework-pakket toe aan uw project:

pip install agent-framework-core --pre

Aan de slag komen

Authenticatie

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

from azure.identity import AzureCliCredential

credential = AzureCliCredential()

Een Azure OpenAI ChatCompletion-agent maken

Basisagent maken

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

import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

async def main():
    agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_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())

Expliciete configuratie

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

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

Agent functies

Functiehulpmiddelen

U kunt aangepaste functiehulpprogramma's opgeven voor Azure OpenAI ChatCompletion-agents:

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

Threads gebruiken voor contextbeheer

Gesprekscontext onderhouden voor meerdere interacties:

import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

async def main():
    agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_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())

Streamingreacties

Antwoorden ophalen terwijl ze worden gegenereerd met behulp van streaming:

import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

async def main():
    agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_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())

De agent gebruiken

De agent is een standaard BaseAgent en ondersteunt alle standaardagentbewerkingen.

Zie de zelfstudies om aan de slag te gaan met agents voor meer informatie over het uitvoeren en gebruiken van agents.

Volgende stappen