Partager via


Agents d'OpenAI

Microsoft Agent Framework prend en charge trois types de clients OpenAI distincts, chacun ciblant une surface d’API différente avec différentes fonctionnalités d’outil :

Type de Client API Idéal pour
Complétion des conversations API de complétion de chat Agents simples, prise en charge d’un modèle large
Réponses API de réponses Agents complets avec des outils hébergés (interpréteur de code, recherche de fichiers, recherche web, MCP hébergé)
Assistants Assistants API Agents gérés par le serveur avec interpréteur de code et recherche de fichiers

Conseil / Astuce

Pour les équivalents Azure OpenAI (AzureOpenAIChatClient, AzureOpenAIResponsesClient, AzureOpenAIAssistantsClient), consultez la page du fournisseur Azure OpenAI. La prise en charge de l’outil est identique.

Getting Started

Ajoutez les packages NuGet requis à votre projet.

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

Client d’achèvement de conversation

Le client Chat Completion offre un moyen simple de créer des agents à l’aide de l’API ChatCompletion.

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
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."));

Outils pris en charge : Outils de fonction, recherche web, outils MCP locaux.

Réponses client

Le client Réponses fournit la prise en charge des outils les plus riches, notamment l’interpréteur de code, la recherche de fichiers, la recherche web et le MCP hébergé.

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
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."));

Outils pris en charge : Outils de fonction, approbation des outils, interpréteur de code, recherche de fichiers, recherche web, mcP hébergé, outils MCP locaux.

Assistants Client

Le client Assistants crée des agents gérés par le serveur avec l’interpréteur de code intégré et la recherche de fichiers.

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var assistantsClient = client.GetAssistantClient();

// Assistants are managed server-side
AIAgent agent = assistantsClient.AsAIAgent(
    instructions: "You are a data analysis assistant.",
    name: "DataHelper");

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

Outils pris en charge : Outils de fonction, interpréteur de code, recherche de fichiers, outils MCP locaux.

Conseil / Astuce

Consultez les exemples .NET pour obtenir des exemples exécutables complets.

Utilisation de l’agent

Les trois types de clients produisent une norme AIAgent qui prend en charge les mêmes opérations d’agent (streaming, threads, middleware).

Pour plus d’informations, consultez les didacticiels De prise en main.

Installation

pip install agent-framework --pre

Paramétrage

Chaque type de client utilise différentes variables d’environnement :

Fin de la conversation instantanée

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

Responses

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

Assistants

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

Client de finalisation de chat

OpenAIChatClient utilise l’API de complétion de chat — l'option la plus simple avec une large prise en charge des modèles.

import asyncio
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = OpenAIChatClient().as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )
    result = await agent.run("Hello, how can you help me?")
    print(result)

asyncio.run(main())

Outils pris en charge : Outils de fonction, recherche web, outils MCP locaux.

Recherche web avec achèvement de chat

async def web_search_example():
    client = OpenAIChatClient()
    web_search = client.get_web_search_tool()

    agent = client.as_agent(
        name="SearchBot",
        instructions="You can search the web for current information.",
        tools=web_search,
    )
    result = await agent.run("What are the latest developments in AI?")
    print(result)

Réponses Client

OpenAIResponsesClient utilise l’API Réponses ( option la plus riche en fonctionnalités avec les outils hébergés).

import asyncio
from agent_framework.openai import OpenAIResponsesClient

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

Outils pris en charge : Outils de fonction, approbation des outils, interpréteur de code, recherche de fichiers, recherche web, mcP hébergé, outils MCP locaux.

Outils hébergés avec le client de réponses

Le client Réponses fournit des get_*_tool() méthodes pour chaque type d’outil hébergé :

async def hosted_tools_example():
    client = OpenAIResponsesClient()

    # Each tool is created via a client method
    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)

Assistants Client

OpenAIAssistantProvider utilise l’API Assistants : agents gérés par le serveur avec interpréteur de code et recherche de fichiers intégrés. Le fournisseur gère automatiquement le cycle de vie de l’Assistant.

import asyncio
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI()
    provider = OpenAIAssistantProvider(client)

    agent = await provider.create_agent(
        name="DataAnalyst",
        model="gpt-4o-mini",
        instructions="You analyze data using code execution.",
    )

    try:
        result = await agent.run("Calculate the first 20 prime numbers.")
        print(result)
    finally:
        await provider.delete_agent(agent.id)

asyncio.run(main())

Outils pris en charge : Outils de fonction, interpréteur de code, recherche de fichiers, outils MCP locaux.

Fonctionnalités courantes

Les trois types de clients prennent en charge ces fonctionnalités d’agent standard :

Outils de fonction

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 = OpenAIResponsesClient().as_agent(
        instructions="You are a weather assistant.",
        tools=get_weather,
    )
    result = await agent.run("What's the weather in Tokyo?")
    print(result)

Conversations à plusieurs tours

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

Diffusion en continu

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

Utilisation de l’agent

Tous les types de clients produisent une norme Agent qui prend en charge les mêmes opérations.

Pour plus d’informations, consultez les didacticiels De prise en main.

Prochaines étapes