Udostępnij przez


OpenAI ChatCompletion Agents

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

Wprowadzenie

Dodaj wymagane pakiety NuGet do projektu.

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

Tworzenie agenta OpenAI ChatCompletion

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

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.

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 OpenAIChatClient

Tworzenie agenta OpenAI ChatCompletion

Tworzenie podstawowego agenta

Najprostszym sposobem utworzenia agenta uzupełniania czatu:

async def basic_example():
    # Create an agent using OpenAI ChatCompletion
    agent = OpenAIChatClient().create_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("Hello, how can you help me?")
    print(result.text)

Korzystanie z konfiguracji jawnej

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

async def explicit_config_example():
    agent = OpenAIChatClient(
        ai_model_id="gpt-4o-mini",
        api_key="your-api-key-here",
    ).create_agent(
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What can you do?")
    print(result.text)

Funkcje agenta

Narzędzia funkcji

Wyposażyć agenta w funkcje niestandardowe:

from typing import Annotated
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get weather for")]
) -> str:
    """Get the weather for a given location."""
    # Your weather API implementation here
    return f"The weather in {location} is sunny with 25°C."

async def tools_example():
    agent = ChatAgent(
        chat_client=OpenAIChatClient(),
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Add tools to the agent
    )

    result = await agent.run("What's the weather like in Tokyo?")
    print(result.text)

Odpowiedzi w strumieniowaniu

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

async def streaming_example():
    agent = OpenAIChatClient().create_agent(
        name="StoryTeller",
        instructions="You are a creative storyteller.",
    )

    print("Assistant: ", end="", flush=True)
    async for chunk in agent.run_stream("Tell me a short story about AI."):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()  # New line after streaming

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