Partilhar 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 obter pré-requisitos e instalar 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 ferramenta de função chamando .AsAIFunction() no agente e fornecendo-o como 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 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 utilize 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 numa 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 pode chamar o agente meteorológico como ferramenta e 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 obter pré-requisitos e instalar 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 ChatAgent ferramenta como função chamando .as_tool() o 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 funcional que será utilizada pelo seu agente, exposta como tal 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 utilize a ferramenta de funcionalidades.

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 numa 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 pode chamar o agente meteorológico como ferramenta e 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óximos passos