Étape 2 : Ajouter des outils

Les outils permettent à votre agent d’appeler des fonctions personnalisées, telles que l’extraction de données météorologiques, l’interrogation d’une base de données ou l’appel d’une API.

Avant d’ajouter des outils, passez en revue les meilleures pratiques de sécurité d’approbation des outils pour déterminer quelles opérations nécessitent une confirmation humaine.

Définissez un outil comme n’importe quelle méthode avec un [Description] attribut :

using System.ComponentModel;

[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
    => $"The weather in {location} is cloudy with a high of 15°C.";

Créez un agent avec l’outil :

using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a helpful assistant.",
        tools: [AIFunctionFactory.Create(GetWeather)]);

Avertissement

DefaultAzureCredential est pratique pour le développement, mais nécessite une considération minutieuse en production. En production, envisagez d’utiliser des informations d’identification spécifiques (par exemple ManagedIdentityCredential) pour éviter les problèmes de latence, la détection involontaire des informations d’identification et les risques de sécurité potentiels liés aux mécanismes de secours.

L’agent appelle automatiquement votre outil en cas de pertinence :

Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));

Tip

Consultez cet article pour obtenir un exemple d’application exécutable complet.

L’exemple complet définit un outil avec le @tool décorateur, crée un agent avec l’outil et exécute l’agent :

import asyncio

from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential


# This read-only sample tool can run without approval.
@tool(approval_mode="never_require")
def get_weather(location: str) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny."


async def main() -> None:
    agent = Agent(
        client=FoundryChatClient(
            project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
            model="gpt-6-luna",
            credential=AzureCliCredential(),
        ),
        instructions="Use the weather tool to answer questions.",
        tools=[get_weather],
    )
    print(await agent.run("What's the weather like in Seattle?"))


if __name__ == "__main__":
    asyncio.run(main())

Tip

Consultez l’exemple complet du fichier exécutable complet.

Définissez un outil à l’aide de functool:

import (
    "context"
    "fmt"

    "github.com/microsoft/agent-framework-go/tool"
    "github.com/microsoft/agent-framework-go/tool/functool"
)

var weatherTool = functool.MustNew(functool.Config{
    Name:        "weather",
    Description: "Get the current weather for a given location",
}, func(_ context.Context, location string) (string, error) {
    return fmt.Sprintf("The weather in %s is cloudy with a high of 15°C.", location), nil
})

Créez un agent avec l’outil :

a := foundryprovider.NewAgent(
    endpoint,
    token,
    foundryprovider.ModelDeployment(model),
    foundryprovider.AgentConfig{
        Instructions: "You are a helpful assistant",
        Config: agent.Config{
            Tools: []tool.Tool{weatherTool},
        },
    },
)

L’agent appelle automatiquement votre outil en cas de pertinence :

resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
fmt.Println(resp, err)

Tip

Consultez l’exemple complet du fichier exécutable complet.

Étapes suivantes

Aller plus loin :