Krok 2. Dodawanie narzędzi

Narzędzia umożliwiają agentowi wywoływanie niestandardowych funkcji , takich jak pobieranie danych pogodowych, wykonywanie zapytań względem bazy danych lub wywoływanie interfejsu API.

Przed dodaniem narzędzi zapoznaj się z najlepszymi rozwiązaniami dotyczącymi zabezpieczeń zatwierdzania narzędzi , aby zdecydować, które operacje wymagają potwierdzenia przez człowieka.

Zdefiniuj narzędzie jako dowolną metodę z atrybutem [Description] :

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

Utwórz agenta za pomocą narzędzia:

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)]);

Warning

DefaultAzureCredential jest wygodne do programowania, ale wymaga starannego rozważenia w środowisku produkcyjnym. W środowisku produkcyjnym rozważ użycie określonego poświadczenia (np. ManagedIdentityCredential), aby uniknąć problemów z opóźnieniami, niezamierzonego sondowania poświadczeń i potencjalnych zagrożeń bezpieczeństwa wynikających z mechanizmów awaryjnych.

Agent automatycznie wywoła narzędzie, gdy będzie to konieczne.

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

Tip

Zobacz tutaj , aby zapoznać się z pełną aplikacją przykładową z możliwością uruchamiania.

Kompletny przykład definiuje narzędzie za pomocą dekoratora @tool, tworzy agenta z tym narzędziem i uruchamia agenta:

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

Zapoznaj się z pełnym przykładem kompletnego pliku możliwego do uruchomienia.

Zdefiniuj narzędzie przy użyciu polecenia 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
})

Utwórz agenta za pomocą narzędzia:

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

Agent automatycznie wywoła narzędzie, gdy będzie to konieczne.

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

Tip

Zapoznaj się z pełnym przykładem kompletnego pliku możliwego do uruchomienia.

Następne kroki

Głębiej: