Udostępnij przez


Agenci Asystentów OpenAI

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

Ostrzeżenie

Interfejs API Asystentów OpenAI jest przestarzały i zostanie zamknięty. Aby uzyskać więcej informacji, zobacz dokumentację interfejsu OpenAI.

Wprowadzenie

Dodaj wymagane pakiety NuGet do projektu.

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

Tworzenie agenta Asystenta OpenAI

Pierwszym krokiem jest utworzenie klienta w celu nawiązania połączenia z usługą OpenAI.

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

OpenAIClient client = new OpenAIClient("<your_api_key>");

OpenAI obsługuje wiele usług, które oferują możliwości wywoływania modelu. Użyjemy klienta Asystentów do utworzenia agenta opartego na Asystentach.

#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var assistantClient = client.GetAssistantClient();
#pragma warning restore OPENAI001

Aby korzystać z usługi Asystentów OpenAI, musisz utworzyć zasób asystenta w usłudze. Można to zrobić przy użyciu OpenAI SDK lub pomocniczych narzędzi Microsoft Agent Framework.

Korzystanie z zestawu OpenAI SDK

Utwórz asystenta i pobierz go jako AIAgent za pomocą klienta.

// Create a server-side assistant
var createResult = await assistantClient.CreateAssistantAsync(
    "gpt-4o-mini",
    new() { Name = "Joker", Instructions = "You are good at telling jokes." });

// Retrieve the assistant as an AIAgent
AIAgent agent1 = await assistantClient.GetAIAgentAsync(createResult.Value.Id);

// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));

Korzystanie z pomocników programu Agent Framework

Możesz również utworzyć i zwrócić element AIAgent w jednym kroku:

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

Ponowne wykorzystanie asystentów OpenAI

Możesz ponownie użyć istniejących asystentów OpenAI, pobierając je przy użyciu ich identyfikatorów.

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

Korzystanie z agenta

Agent jest standardowy AIAgent 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.

Wymagania wstępne

Zainstaluj pakiet programu Microsoft Agent Framework.

pip install agent-framework --pre

Konfiguracja

Zmienne środowiskowe

Skonfiguruj wymagane zmienne środowiskowe na potrzeby uwierzytelniania openAI:

# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"  # or your preferred model

Alternatywnie możesz użyć pliku .env w katalogu głównym projektu.

OPENAI_API_KEY=your-openai-api-key
OPENAI_CHAT_MODEL_ID=gpt-4o-mini

Wprowadzenie

Zaimportuj wymagane klasy z programu Agent Framework:

import asyncio
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIAssistantsClient

Tworzenie agenta Asystenta OpenAI

Tworzenie podstawowego agenta

Najprostszym sposobem utworzenia agenta jest użycie programu OpenAIAssistantsClient , który automatycznie tworzy asystentów i zarządza nimi:

async def basic_example():
    # Create an agent with automatic assistant creation and cleanup
    async with OpenAIAssistantsClient().create_agent(
        instructions="You are a helpful assistant.",
        name="MyAssistant"
    ) as agent:
        result = await agent.run("Hello, how are you?")
        print(result.text)

Korzystanie z konfiguracji jawnej

Możesz podać jawną konfigurację zamiast polegać na zmiennych środowiskowych:

async def explicit_config_example():
    async with OpenAIAssistantsClient(
        ai_model_id="gpt-4o-mini",
        api_key="your-api-key-here",
    ).create_agent(
        instructions="You are a helpful assistant.",
    ) as agent:
        result = await agent.run("What's the weather like?")
        print(result.text)

Korzystanie z istniejącego asystenta

Możesz ponownie użyć istniejących asystentów openAI, podając ich identyfikatory:

from openai import AsyncOpenAI

async def existing_assistant_example():
    # Create OpenAI client directly
    client = AsyncOpenAI()

    # Create or get an existing assistant
    assistant = await client.beta.assistants.create(
        model="gpt-4o-mini",
        name="WeatherAssistant",
        instructions="You are a weather forecasting assistant."
    )

    try:
        # Use the existing assistant with Agent Framework
        async with ChatAgent(
            chat_client=OpenAIAssistantsClient(
                async_client=client,
                assistant_id=assistant.id
            ),
            instructions="You are a helpful weather agent.",
        ) as agent:
            result = await agent.run("What's the weather like in Seattle?")
            print(result.text)
    finally:
        # Clean up the assistant
        await client.beta.assistants.delete(assistant.id)

Funkcje agenta

Narzędzia funkcji

Asystenta można wyposażyć w funkcje niestandardowe:

from typing import Annotated
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 25°C."

async def tools_example():
    async with ChatAgent(
        chat_client=OpenAIAssistantsClient(),
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Provide tools to the agent
    ) as agent:
        result = await agent.run("What's the weather like in Tokyo?")
        print(result.text)

Interpreter kodów

Włącz asystenta do wykonywania kodu w języku Python:

from agent_framework import HostedCodeInterpreterTool

async def code_interpreter_example():
    async with ChatAgent(
        chat_client=OpenAIAssistantsClient(),
        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 100 using Python code.")
        print(result.text)

Odpowiedzi w strumieniowaniu

Uzyskuj odpowiedzi w miarę ich generowania w celu lepszego doświadczenia użytkownika.

async def streaming_example():
    async with OpenAIAssistantsClient().create_agent(
        instructions="You are a helpful assistant.",
    ) as agent:
        print("Assistant: ", end="", flush=True)
        async for chunk in agent.run_stream("Tell me a story about AI."):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()  # New line after streaming is complete

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