Freigeben über


OpenAI-Antwort-Agenten

Das Microsoft Agent Framework unterstützt das Erstellen von Agents, die den OpenAI-Antwortdienst verwenden.

Erste Schritte

Fügen Sie dem Projekt die erforderlichen NuGet-Pakete hinzu.

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

Erstellen eines OpenAI-Antwort-Agents

Als ersten Schritt müssen Sie einen Client erstellen, um eine Verbindung mit dem OpenAI-Dienst herzustellen.

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

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

OpenAI unterstützt mehrere Dienste, die alle Modellanruffunktionen bereitstellen. Wir müssen den Antwortdienst auswählen, um einen antwortenbasierten Agent zu erstellen.

#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var responseClient = client.GetOpenAIResponseClient("gpt-4o-mini");
#pragma warning restore OPENAI001

Erstellen Sie schließlich den Agenten mithilfe der CreateAIAgent Erweiterungsmethode auf dem ResponseClient.

AIAgent agent = responseClient.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."));

Den Agent verwenden

Der Agent ist ein AIAgent Standard und unterstützt alle AIAgent Standardoperationen.

Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Einführungstutorials für Agenten.

Voraussetzungen

Installieren Sie das Microsoft Agent Framework-Paket.

pip install agent-framework --pre

Konfiguration

Umgebungsvariablen

Richten Sie die erforderlichen Umgebungsvariablen für die OpenAI-Authentifizierung ein:

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

Alternativ können Sie eine .env Datei im Projektstamm verwenden:

OPENAI_API_KEY=your-openai-api-key
OPENAI_RESPONSES_MODEL_ID=gpt-4o

Erste Schritte

Importieren Sie die erforderlichen Klassen aus dem Agent Framework:

import asyncio
from agent_framework.openai import OpenAIResponsesClient

Erstellen eines OpenAI-Antwort-Agents

Grundlegende Agent-Erstellung

Die einfachste Möglichkeit zum Erstellen eines Antwort-Agents:

async def basic_example():
    # Create an agent using OpenAI Responses
    agent = OpenAIResponsesClient().create_agent(
        name="WeatherBot",
        instructions="You are a helpful weather assistant.",
    )

    result = await agent.run("What's a good way to check the weather?")
    print(result.text)

Verwendung der expliziten Konfiguration

Sie können eine explizite Konfiguration bereitstellen, anstatt sich auf Umgebungsvariablen zu verlassen:

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

    result = await agent.run("Tell me about AI.")
    print(result.text)

Grundlegende Verwendungsmuster

Streaming-Antworten

Erhalten Sie Antworten, wenn sie generiert werden, um eine bessere Benutzererfahrung zu erzielen:

async def streaming_example():
    agent = OpenAIResponsesClient().create_agent(
        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

Agentfeatures

Schlussfolgerungsmodelle

Verwenden Sie erweiterte Argumentationsfähigkeiten mit Modellen wie GPT-5:

from agent_framework import HostedCodeInterpreterTool, TextContent, TextReasoningContent

async def reasoning_example():
    agent = OpenAIResponsesClient(ai_model_id="gpt-5").create_agent(
        name="MathTutor",
        instructions="You are a personal math tutor. When asked a math question, "
                    "write and run code to answer the question.",
        tools=HostedCodeInterpreterTool(),
        reasoning={"effort": "high", "summary": "detailed"},
    )

    print("Assistant: ", end="", flush=True)
    async for chunk in agent.run_stream("Solve: 3x + 11 = 14"):
        if chunk.contents:
            for content in chunk.contents:
                if isinstance(content, TextReasoningContent):
                    # Reasoning content in gray text
                    print(f"\033[97m{content.text}\033[0m", end="", flush=True)
                elif isinstance(content, TextContent):
                    print(content.text, end="", flush=True)
    print()

Strukturierte Ausgabe

Antworten in strukturierten Formaten abrufen:

from pydantic import BaseModel
from agent_framework import AgentRunResponse

class CityInfo(BaseModel):
    """A structured output for city information."""
    city: str
    description: str

async def structured_output_example():
    agent = OpenAIResponsesClient().create_agent(
        name="CityExpert",
        instructions="You describe cities in a structured format.",
    )

    # Non-streaming structured output
    result = await agent.run("Tell me about Paris, France", response_format=CityInfo)

    if result.value:
        city_data = result.value
        print(f"City: {city_data.city}")
        print(f"Description: {city_data.description}")

    # Streaming structured output
    structured_result = await AgentRunResponse.from_agent_response_generator(
        agent.run_stream("Tell me about Tokyo, Japan", response_format=CityInfo),
        output_format_type=CityInfo,
    )

    if structured_result.value:
        tokyo_data = structured_result.value
        print(f"City: {tokyo_data.city}")
        print(f"Description: {tokyo_data.description}")

Funktionstools

Rüsten Sie Ihren Agent mit benutzerdefinierten Funktionen aus:

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 = OpenAIResponsesClient().create_agent(
        instructions="You are a helpful weather assistant.",
        tools=get_weather,
    )

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

Bildgenerierung

Generieren Sie Bilder mithilfe der Antwort-API:

from agent_framework import DataContent, UriContent

async def image_generation_example():
    agent = OpenAIResponsesClient().create_agent(
        instructions="You are a helpful AI that can generate images.",
        tools=[{
            "type": "image_generation",
            "size": "1024x1024",
            "quality": "low",
        }],
    )

    result = await agent.run("Generate an image of a sunset over the ocean.")

    # Check for generated images in the response
    for content in result.contents:
        if isinstance(content, (DataContent, UriContent)):
            print(f"Image generated: {content.uri}")

Codedolmetscher

Aktivieren Sie Ihren Assistenten zum Ausführen von Python-Code:

from agent_framework import HostedCodeInterpreterTool

async def code_interpreter_example():
    agent = OpenAIResponsesClient().create_agent(
        instructions="You are a helpful assistant that can write and execute Python code.",
        tools=HostedCodeInterpreterTool(),
    )

    result = await agent.run("Calculate the factorial of 100 using Python code.")
    print(result.text)

Den Agent verwenden

Der Agent ist ein Standard BaseAgent und unterstützt alle Standard-Agent-Vorgänge.

Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Einführungstutorials für Agenten.

Nächste Schritte