Partilhar via


Assistentes e Agentes da OpenAI

O Microsoft Agent Framework suporta a criação de agentes que utilizam o serviço OpenAI Assistants .

Advertência

A API OpenAI Assistants foi preterida e será encerrada. Para obter mais informações, consulte a documentação do OpenAI.

Introdução

Adicione os pacotes NuGet necessários ao seu projeto.

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

Criar um Agente de Assistentes OpenAI

Como primeiro passo, você precisa criar um cliente para se conectar ao serviço OpenAI.

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

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

A OpenAI suporta múltiplos serviços que fornecem capacidades de chamada de modelos. Este exemplo utiliza o cliente Assistants para criar um agente baseado em 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

Para usar o serviço OpenAI Assistants, você precisa criar um recurso de assistente no serviço. Isso pode ser feito usando o SDK do OpenAI ou usando auxiliares do Microsoft Agent Framework.

Usando o OpenAI SDK

Crie um assistente e recupere-o como um AIAgent usando o cliente.

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

Utilização de ajudantes do Agent Framework

Você também pode criar e retornar um AIAgent em uma etapa:

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

Reutilizando assistentes OpenAI

Você pode reutilizar assistentes OpenAI existentes recuperando-os usando seus IDs.

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

Usando o agente

O agente é um AIAgent padrão e suporta todas as operações padrão de um agente.

Para mais informações sobre como gerir e interagir com agentes, consulte os tutoriais de Início de Agentes.

Pré-requisitos

Instale o pacote do Microsoft Agent Framework.

pip install agent-framework --pre

Configuração

Variáveis de ambiente

Configure as variáveis de ambiente necessárias para autenticação OpenAI:

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

Como alternativa, você pode usar um .env arquivo na raiz do projeto:

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

Introdução

Importar as classes necessárias do Agent Framework:

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

Criar um Agente de Assistentes OpenAI

Criação básica de agentes

A maneira mais simples de criar um agente é usando o OpenAIAssistantsClient que cria e gerencia assistentes automaticamente:

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)

Usando a configuração explícita

Você pode fornecer configuração explícita em vez de depender de variáveis de ambiente:

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)

Usando um assistente existente

Você pode reutilizar assistentes OpenAI existentes fornecendo seus IDs:

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)

Funcionalidades do agente

Ferramentas de Função

Pode equipar o seu assistente com funções personalizadas:

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)

Intérprete de código

Habilite seu assistente para executar código 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)

Permita que o seu assistente pesquise entre documentos carregados:

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)

Gerenciamento de threads

Mantenha o contexto da conversa ao longo de múltiplas interações:

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"

Trabalhar com Assistentes Existentes

Você pode reutilizar assistentes OpenAI existentes fornecendo seus IDs:

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)

Respostas de Transmissão

Obtenha respostas à medida que são geradas para uma melhor experiência do utilizador:

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

Usando o agente

O agente é um BaseAgent padrão e suporta todas as operações padrão de um agente.

Para mais informações sobre como gerir e interagir com agentes, consulte os tutoriais de Início de Agentes.

Próximos passos