Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
En este tutorial se muestra cómo usar un agente como herramienta de función para que un agente pueda llamar a otro agente como herramienta.
Prerrequisitos
Para conocer los requisitos previos e instalar paquetes NuGet, consulte el paso Creación y ejecución de un agente sencillo en este tutorial.
Creación y uso de un agente como herramienta de función
Puede usar AIAgent como herramienta de función llamando .AsAIFunction() al agente y usándola como herramienta para otro agente. Esto le permite crear agentes y crear flujos de trabajo más avanzados.
En primer lugar, cree una herramienta de función como un método de C# y decora con descripciones si es necesario. Esta herramienta será utilizada por su agente que está expuesta como una función.
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.";
Cree un AIAgent que use la herramienta de función.
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)]);
Ahora, cree un agente principal y proporcione el weatherAgent como una herramienta de función llamando al .AsAIFunction() para convertir el weatherAgent en una herramienta de función.
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 al agente principal de manera habitual. Ahora puede llamar al agente meteorológico como herramienta y debe responder en francés.
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
En este tutorial se muestra cómo usar un agente como herramienta de función para que un agente pueda llamar a otro agente como herramienta.
Prerrequisitos
Para conocer los requisitos previos e instalar paquetes, consulte el paso Crear y ejecutar un agente sencillo en este tutorial.
Creación y uso de un agente como herramienta de función
Puede usar ChatAgent como una herramienta funcional llamando a .as_tool() en el agente y proporcionándola como herramienta a otro agente. Esto le permite crear agentes y crear flujos de trabajo más avanzados.
En primer lugar, cree una herramienta funcional que usará el agente y que está expuesta como una función.
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."
Cree un ChatAgent que utilice la herramienta de funciones.
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
)
Ahora, cree un agente principal y proporcione el weather_agent como una herramienta de función llamando al .as_tool() para convertir el weather_agent en una herramienta de función.
main_agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
instructions="You are a helpful assistant who responds in French.",
tools=weather_agent.as_tool()
)
Invoque al agente principal de manera habitual. Ahora puede llamar al agente meteorológico como herramienta y debe responder en francés.
result = await main_agent.run("What is the weather like in Amsterdam?")
print(result.text)
También puede personalizar el nombre, la descripción y el nombre del argumento de la herramienta al convertir un agente en una herramienta:
# 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
)