Partager via


Agents de Complétion de Chat OpenAI

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

Getting Started

Ajoutez les packages NuGet requis à votre projet.

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

Créer un agent OpenAI ChatCompletion

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. Choisissez le service ChatCompletion pour créer un agent basé sur ChatCompletion.

var chatCompletionClient = client.GetChatClient("gpt-4o-mini");

Enfin, créez l’agent à l’aide de la méthode d’extension CreateAIAgent sur le 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."));

Utilisation de l’agent

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

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 OpenAIChatClient

Créer un agent OpenAI ChatCompletion

Création d'un agent basique

La façon la plus simple de créer un agent d’achèvement de conversation :

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)

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():
    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)

Fonctionnalités de l’agent

Outils de fonction

Équipez votre agent 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 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)

Activer les fonctionnalités de recherche web en temps réel :

from agent_framework import HostedWebSearchTool

async def web_search_example():
    agent = OpenAIChatClient(model_id="gpt-4o-search-preview").create_agent(
        name="SearchBot",
        instructions="You are a helpful assistant that can search the web for current information.",
        tools=HostedWebSearchTool(),
    )

    result = await agent.run("What are the latest developments in artificial intelligence?")
    print(result.text)

Outils MCP (Model Context Protocol)

Connectez-vous aux serveurs MCP locaux pour les fonctionnalités étendues :

from agent_framework import MCPStreamableHTTPTool

async def local_mcp_example():
    agent = OpenAIChatClient().create_agent(
        name="DocsAgent",
        instructions="You are a helpful assistant that can help with Microsoft documentation.",
        tools=MCPStreamableHTTPTool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
        ),
    )

    result = await agent.run("How do I create an Azure storage account using az cli?")
    print(result.text)

Gestion des threads

Maintenez le contexte de conversation entre plusieurs interactions :

async def thread_example():
    agent = OpenAIChatClient().create_agent(
        name="Agent",
        instructions="You are a helpful assistant.",
    )

    # 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"

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():
    agent = OpenAIChatClient().create_agent(
        name="StoryTeller",
        instructions="You are a creative storyteller.",
    )

    print("Agent: ", 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

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