Udostępnij przez


Azure OpenAI Agents

Platforma Microsoft Agent Framework obsługuje trzy różne typy klientów usługi Azure OpenAI, z których każda jest przeznaczona dla innej powierzchni interfejsu API z różnymi możliwościami narzędzi:

Typ klienta API Najlepsze dla
Uzupełnianie czatu Interfejs API uzupełniania czatów Proste agenty, szerokie wsparcie modeli
Odpowiedzi API odpowiedzi W pełni funkcjonalne agenty z udostępnionymi narzędziami (interpreter kodu, wyszukiwanie plików, wyszukiwanie webowe, udostępniona aplikacja MCP)
Asystenci Interfejs API asystentów Agenci zarządzani serwerem z interpreterem kodu i wyszukiwaniem plików

Tip

W przypadku bezpośrednich odpowiedników openAI (OpenAIChatClient, OpenAIResponsesClient, OpenAIAssistantsClient), zobacz stronę dostawcy OpenAI. Obsługa narzędzi jest identyczna.

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

Wszystkie typy klientów usługi Azure OpenAI zaczynają się od utworzenia elementu AzureOpenAIClient:

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;

AzureOpenAIClient client = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new DefaultAzureCredential());

Ostrzeżenie

DefaultAzureCredential jest wygodne do programowania, ale wymaga starannego rozważenia w środowisku produkcyjnym. W środowisku produkcyjnym rozważ użycie określonego poświadczenia (np. ManagedIdentityCredential), aby uniknąć problemów z opóźnieniami, niezamierzonego sondowania poświadczeń i potencjalnych zagrożeń bezpieczeństwa wynikających z mechanizmów awaryjnych.

Klient kompletacji czatu

Klient Chat Completion zapewnia prosty sposób tworzenia agentów za pomocą API ChatCompletion.

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

AIAgent agent = chatClient.AsAIAgent(
    instructions: "You are good at telling jokes.",
    name: "Joker");

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

Obsługiwane narzędzia: Narzędzia funkcji, wyszukiwanie w Internecie, lokalne narzędzia MCP.

Klient odpowiedzi

Klient Odpowiedzi zapewnia najbogatszą obsługę narzędzi, w tym interpreter kodu, wyszukiwanie plików, wyszukiwanie w Internecie i hostowaną aplikację MCP.

var responsesClient = client.GetResponseClient("gpt-4o-mini");

AIAgent agent = responsesClient.AsAIAgent(
    instructions: "You are a helpful coding assistant.",
    name: "CodeHelper");

Console.WriteLine(await agent.RunAsync("Write a Python function to sort a list."));

Obsługiwane narzędzia: Narzędzia funkcji, zatwierdzanie narzędzi, interpreter kodu, wyszukiwanie plików, wyszukiwanie w Internecie, hostowane MCP, lokalne narzędzia MCP.

Klient asystentów

Klient Asystentów tworzy agentów zarządzanych przez serwer z wbudowanym interpreterem kodu i wyszukiwaniem plików.

var assistantsClient = client.GetAssistantClient();

AIAgent agent = assistantsClient.AsAIAgent(
    instructions: "You are a data analysis assistant.",
    name: "DataHelper");

Console.WriteLine(await agent.RunAsync("Analyze trends in the uploaded data."));

Obsługiwane narzędzia: Narzędzia funkcji, interpreter kodu, wyszukiwanie plików, lokalne narzędzia MCP.

Narzędzia funkcji

Niestandardowe narzędzia funkcji można udostępnić dowolnym agentom usługi Azure OpenAI:

using System.ComponentModel;
using Microsoft.Extensions.AI;

[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.";

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
     .GetChatClient(deploymentName)
     .AsAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);

Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));

Odpowiedzi w strumieniowaniu

await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate."))
{
    Console.Write(update);
}

Tip

Zobacz przykłady dla platformy .NET , aby uzyskać pełne przykłady możliwych do uruchomienia.

Korzystanie z agenta

Wszystkie trzy typy klientów tworzą standard AIAgent obsługujący te same operacje agenta (przesyłanie strumieniowe, wątki, oprogramowanie pośredniczące).

Aby uzyskać więcej informacji, zobacz samouczki Rozpoczęcie pracy.

Instalacja

pip install agent-framework --pre

Konfiguracja

Każdy typ klienta używa różnych zmiennych środowiskowych:

Uzupełnianie czatu

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

Responses

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

Assistants

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

Opcjonalnie można również ustawić:

AZURE_OPENAI_API_VERSION="2024-10-21"  # Default API version
AZURE_OPENAI_API_KEY="<your-api-key>"  # If not using Azure CLI authentication

Wszyscy klienci używają poświadczeń platformy Azure do uwierzytelniania. Najprostszym podejściem jest, aby AzureCliCredential po uruchomieniu az login polecenia.

Klient uzupełniania czatu

AzureOpenAIChatClient korzysta z interfejsu API uzupełniania konwersacji — najprostszej opcji z szeroką obsługą modeli.

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

async def main():
    agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
        name="Joker",
        instructions="You are good at telling jokes.",
    )
    result = await agent.run("Tell me a joke about a pirate.")
    print(result)

asyncio.run(main())

Obsługiwane narzędzia: Narzędzia funkcji, wyszukiwanie w Internecie, lokalne narzędzia MCP.

Klient odpowiedzi

AzureOpenAIResponsesClient korzysta z interfejsu API 'Responses' — najbardziej zaawansowanej opcji z narzędziami hostowanymi.

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

async def main():
    agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
        name="FullFeaturedAgent",
        instructions="You are a helpful assistant with access to many tools.",
    )
    result = await agent.run("Write and run a Python script that calculates fibonacci numbers.")
    print(result)

asyncio.run(main())

Odpowiedzi klienta wykorzystujące punkt końcowy projektu Azure AI Foundry

AzureOpenAIResponsesClient Można również utworzyć z punktu końcowego projektu Azure AI Foundry:

from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential

client = AzureOpenAIResponsesClient(
    project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
    deployment_name="gpt-4o-mini",
    credential=AzureCliCredential(),
)
agent = client.as_agent(
    name="FoundryResponsesAgent",
    instructions="You are a helpful assistant.",
)

Obsługiwane narzędzia: Narzędzia funkcji, zatwierdzanie narzędzi, interpreter kodu, wyszukiwanie plików, wyszukiwanie w Internecie, hostowane MCP, lokalne narzędzia MCP.

Hostowane narzędzia z klientem Response

Klient Responses udostępnia metody get_*_tool() dla każdego typu hostowanego narzędzia:

async def hosted_tools_example():
    client = AzureOpenAIResponsesClient(credential=AzureCliCredential())

    code_interpreter = client.get_code_interpreter_tool()
    web_search = client.get_web_search_tool()
    file_search = client.get_file_search_tool(vector_store_ids=["vs_abc123"])
    mcp_tool = client.get_mcp_tool(
        name="GitHub",
        url="https://api.githubcopilot.com/mcp/",
        approval_mode="never_require",
    )

    agent = client.as_agent(
        name="PowerAgent",
        instructions="You have access to code execution, web search, files, and GitHub.",
        tools=[code_interpreter, web_search, file_search, mcp_tool],
    )
    result = await agent.run("Search the web for Python best practices, then write a summary.")
    print(result)

Klient asystentów

AzureOpenAIAssistantsClient korzysta z interfejsu API Asystentów — agentów zarządzanych przez serwer z wbudowanym interpreterem kodu i wyszukiwaniem plików. Zwróć uwagę na async with menedżera kontekstu na potrzeby automatycznego zarządzania cyklem życia asystenta.

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

async def main():
    async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
        name="DataAnalyst",
        instructions="You analyze data using code execution.",
    ) as agent:
        result = await agent.run("Calculate the first 20 prime numbers.")
        print(result)

asyncio.run(main())

Obsługiwane narzędzia: Narzędzia funkcji, interpreter kodu, wyszukiwanie plików, lokalne narzędzia MCP.

Typowe funkcje

Wszystkie trzy typy klientów obsługują następujące standardowe funkcje agenta:

Narzędzia funkcji

from agent_framework import tool

@tool
def get_weather(location: str) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny, 25°C."

async def example():
    agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
        instructions="You are a weather assistant.",
        tools=get_weather,
    )
    result = await agent.run("What's the weather in Tokyo?")
    print(result)

Konwersacje wieloetapowe

async def thread_example():
    agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
        instructions="You are a helpful assistant.",
    )
    session = await agent.create_session()

    result1 = await agent.run("My name is Alice", session=session)
    print(result1)
    result2 = await agent.run("What's my name?", session=session)
    print(result2)  # Remembers "Alice"

Streaming

async def streaming_example():
    agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
        instructions="You are a creative storyteller.",
    )
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run("Tell me a short story about AI.", stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

Korzystanie z agenta

Wszystkie typy klientów tworzą standard Agent , który obsługuje te same operacje.

Aby uzyskać więcej informacji, zobacz samouczki Rozpoczęcie pracy.

Dalsze kroki