Partager via


Agents des Assistants OpenAI

Microsoft Agent Framework prend en charge la création d’agents qui utilisent le service Assistants OpenAI .

Avertissement

L’API Assistants OpenAI est déconseillée et sera arrêtée. Pour plus d’informations, consultez la documentation OpenAI.

Getting Started

Ajoutez les packages NuGet requis à votre projet.

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

Créer un agent d’assistants OpenAI

Pour commencer, vous devez créer un client pour vous connecter au service OpenAI.

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

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

OpenAI prend en charge plusieurs services qui fournissent toutes des fonctionnalités d’appel de modèle. Cet exemple utilise le client Assistants pour créer un agent basé sur Assistants.

#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

Pour utiliser le service Assistants OpenAI, vous devez créer une ressource Assistant dans le service. Cette opération peut être effectuée à l’aide du Kit de développement logiciel (SDK) OpenAI ou de l’aide de Microsoft Agent Framework.

Utilisation du Kit de développement logiciel (SDK) OpenAI

Créez un assistant et récupérez-le sous forme de AIAgent en utilisant le client.

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

Utilisation des helpers d’Agent Framework

Vous pouvez également créer et renvoyer un AIAgent en une seule étape :

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

Réutilisation des assistants OpenAI

Vous pouvez réutiliser les assistants OpenAI existants en les récupérant à l’aide de leurs ID.

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

Utilisation de l’agent

L’agent est standard AIAgent et prend en charge toutes les opérations d’agent standard.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Prerequisites

Installez le package Microsoft Agent Framework.

pip install agent-framework --pre

Paramétrage

Variables d’environnement

Configurez les variables d’environnement requises pour l’authentification OpenAI :

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

Vous pouvez également utiliser un .env fichier à la racine de votre projet :

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

Getting Started

Importez les classes requises à partir d’Agent Framework :

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

Créer un agent d’assistants OpenAI

Création d'un agent basique

La façon la plus simple de créer un agent consiste à utiliser celui OpenAIAssistantsClient qui crée et gère automatiquement les assistants :

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)

Utilisation de la configuration explicite

Vous pouvez fournir une configuration explicite au lieu de vous appuyer sur des variables d’environnement :

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)

Utilisation d’un Assistant existant

Vous pouvez réutiliser les assistants OpenAI existants en fournissant leurs ID :

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)

Fonctionnalités de l’agent

Outils de fonction

Vous pouvez équiper votre assistant avec des fonctions personnalisées :

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)

Interpréteur de code

Permettre à votre assistant d’exécuter du code 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)

Permettre à votre assistant d'effectuer des recherches dans des documents téléversés.

from agent_framework import HostedFileSearchTool, HostedVectorStoreContent

async def create_vector_store(client: OpenAIAssistantsClient) -> tuple[str, HostedVectorStoreContent]:
    """Create a vector store with sample documents."""
    file = await client.client.files.create(
        file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."), 
        purpose="user_data"
    )
    vector_store = await client.client.vector_stores.create(
        name="knowledge_base",
        expires_after={"anchor": "last_active_at", "days": 1},
    )
    result = await client.client.vector_stores.files.create_and_poll(
        vector_store_id=vector_store.id, 
        file_id=file.id
    )
    if result.last_error is not None:
        raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")

    return file.id, HostedVectorStoreContent(vector_store_id=vector_store.id)

async def delete_vector_store(client: OpenAIAssistantsClient, file_id: str, vector_store_id: str) -> None:
    """Delete the vector store after using it."""
    await client.client.vector_stores.delete(vector_store_id=vector_store_id)
    await client.client.files.delete(file_id=file_id)

async def file_search_example():
    print("=== OpenAI Assistants Client Agent with File Search Example ===\n")

    client = OpenAIAssistantsClient()
    async with ChatAgent(
        chat_client=client,
        instructions="You are a helpful assistant that searches files in a knowledge base.",
        tools=HostedFileSearchTool(),
    ) as agent:
        query = "What is the weather today? Do a file search to find the answer."
        file_id, vector_store = await create_vector_store(client)

        print(f"User: {query}")
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run_stream(
            query, tool_resources={"file_search": {"vector_store_ids": [vector_store.vector_store_id]}}
        ):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()  # New line after streaming

        await delete_vector_store(client, file_id, vector_store.vector_store_id)

Gestion des threads

Maintenez le contexte de conversation entre plusieurs interactions :

async def thread_example():
    async with OpenAIAssistantsClient().create_agent(
        name="Assistant",
        instructions="You are a helpful assistant.",
    ) as agent:
        # Create a persistent thread for conversation context
        thread = agent.get_new_thread()

        # First interaction
        first_query = "My name is Alice"
        print(f"User: {first_query}")
        first_result = await agent.run(first_query, thread=thread)
        print(f"Agent: {first_result.text}")

        # Second interaction - agent remembers the context
        second_query = "What's my name?"
        print(f"User: {second_query}")
        second_result = await agent.run(second_query, thread=thread)
        print(f"Agent: {second_result.text}")  # Should remember "Alice"

Utilisation d’Assistants existants

Vous pouvez réutiliser les assistants OpenAI existants en fournissant leurs ID :

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 OpenAIAssistantsClient(
            async_client=client,
            assistant_id=assistant.id
        ).create_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)

Réponses en continu

Obtenez des réponses à mesure qu’elles sont générées pour une meilleure expérience utilisateur :

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

Utilisation de l’agent

L’agent est standard BaseAgent et prend en charge toutes les opérations d’agent standard.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Étapes suivantes