Udostępnij przez


Agenci usługi Azure OpenAI ChatCompletion

Program Microsoft Agent Framework obsługuje tworzenie agentów korzystających z usługi Azure OpenAI ChatCompletion .

Wprowadzenie

Dodaj wymagane pakiety NuGet do projektu.

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

Tworzenie agenta azure OpenAI ChatCompletion

Pierwszym krokiem jest utworzenie klienta w celu nawiązania połączenia z usługą 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());

Usługa Azure OpenAI obsługuje wiele usług, które zapewniają możliwości wywoływania modelu. Musimy wybrać usługę ChatCompletion, aby utworzyć agenta opartego na chatCompletion.

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

Na koniec utwórz agenta CreateAIAgent przy użyciu metody rozszerzenia w pliku 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."));

Funkcje agenta

Narzędzia funkcji

Możesz udostępnić niestandardowe narzędzia funkcji agentom usługi 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?"));

Odpowiedzi w strumieniowaniu

Uzyskaj odpowiedzi w trybie transmisji strumieniowej podczas ich generowania.

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

Korzystanie z agenta

Agent jest standardowy AIAgent i obsługuje wszystkie standardowe AIAgent operacje.

Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające Agenta.

Konfiguracja

Zmienne środowiskowe

Przed rozpoczęciem korzystania z agentów azure OpenAI ChatCompletion należy skonfigurować następujące zmienne środowiskowe:

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

Opcjonalnie można również ustawić:

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

Instalacja

Dodaj pakiet Agent Framework do projektu:

pip install agent-framework --pre

Wprowadzenie

Authentication

Agenci usługi Azure OpenAI używają poświadczeń platformy Azure do uwierzytelniania. Najprostszym podejściem jest użycie AzureCliCredential po uruchomieniu az login.

from azure.identity import AzureCliCredential

credential = AzureCliCredential()

Tworzenie agenta azure OpenAI ChatCompletion

Tworzenie podstawowego agenta

Najprostszym sposobem utworzenia agenta jest użycie zmiennych AzureOpenAIChatClient środowiskowych:

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

Jawna konfiguracja

Możesz również jawnie podać konfigurację zamiast używać zmiennych środowiskowych:

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

Funkcje agenta

Narzędzia funkcji

Możesz udostępnić niestandardowe narzędzia funkcji agentom usługi 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())

Odpowiedzi w strumieniowaniu

Uzyskiwanie odpowiedzi podczas ich generowania przy użyciu przesyłania strumieniowego:

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

Korzystanie z agenta

Agent jest standardowy BaseAgent i obsługuje wszystkie standardowe operacje agenta.

Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające Agenta.

Dalsze kroki