Compartilhar via


Usando um agente como uma ferramenta de função

Este tutorial mostra como usar um agente como uma ferramenta de função, para que um agente possa chamar outro agente como uma ferramenta.

Pré-requisitos

Para pré-requisitos e instalação de pacotes NuGet, consulte a etapa Criar e executar um agente simples neste tutorial.

Criar e usar um agente como uma ferramenta de função

Você pode usar um AIAgent como uma ferramenta de função chamando o agente .AsAIFunction() e fornecendo-o como uma ferramenta para outro agente. Isso permite que você componha agentes e crie fluxos de trabalho mais avançados.

Primeiro, crie uma ferramenta de função como um método C# e decore-a com descrições, se necessário. Esta ferramenta será usada pelo seu agente, que está exposto como uma função.

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

Crie um AIAgent que use a ferramenta de funções.

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

AIAgent weatherAgent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
     .GetChatClient("gpt-4o-mini")
     .CreateAIAgent(
        instructions: "You answer questions about the weather.",
        name: "WeatherAgent",
        description: "An agent that answers questions about the weather.",
        tools: [AIFunctionFactory.Create(GetWeather)]);

Agora, crie um agente principal e forneça weatherAgent como uma ferramenta de função, chamando .AsAIFunction() para converter weatherAgent em uma ferramenta de função.

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
     .GetChatClient("gpt-4o-mini")
     .CreateAIAgent(instructions: "You are a helpful assistant who responds in French.", tools: [weatherAgent.AsAIFunction()]);

Invoque o agente principal normalmente. Agora, é possível chamar o agente meteorológico como uma funcionalidade, e ele deve responder em francês.

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

Este tutorial mostra como usar um agente como uma ferramenta de função, para que um agente possa chamar outro agente como uma ferramenta.

Pré-requisitos

Para pré-requisitos e instalação de pacotes, consulte a etapa Criar e executar um agente simples neste tutorial.

Criar e usar um agente como uma ferramenta de função

Você pode usar uma função de ferramenta com ChatAgent chamando .as_tool() no agente e fornecendo-o como uma ferramenta para outro agente. Isso permite que você componha agentes e crie fluxos de trabalho mais avançados.

Primeiro, crie uma ferramenta de criação de função que será usada pelo agente e que é exposta como uma função.

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 cloudy with a high of 15°C."

Crie um ChatAgent que use a ferramenta de funções.

from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

weather_agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    name="WeatherAgent",
    description="An agent that answers questions about the weather.",
    instructions="You answer questions about the weather.",
    tools=get_weather
)

Agora, crie um agente principal e forneça weather_agent como uma ferramenta de função, chamando .as_tool() para converter weather_agent em uma ferramenta de função.

main_agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    instructions="You are a helpful assistant who responds in French.",
    tools=weather_agent.as_tool()
)

Invoque o agente principal normalmente. Agora, é possível chamar o agente meteorológico como uma funcionalidade, e ele deve responder em francês.

result = await main_agent.run("What is the weather like in Amsterdam?")
print(result.text)

Você também pode personalizar o nome da ferramenta, a descrição e o nome do argumento ao converter um agente em uma ferramenta:

# Convert agent to tool with custom parameters
weather_tool = weather_agent.as_tool(
    name="WeatherLookup",
    description="Look up weather information for any location",
    arg_name="query",
    arg_description="The weather query or location"
)

main_agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    instructions="You are a helpful assistant who responds in French.",
    tools=weather_tool
)

Próximas etapas