Compartir a través de


Uso de herramientas funcionales con un agente

En este paso del tutorial se muestra cómo usar herramientas funcionales con un agente, el cual se basa en el servicio de finalización de chat de Azure OpenAI.

Importante

No todos los tipos de agente admiten herramientas funcionales. Algunos solo pueden admitir herramientas integradas personalizadas, sin permitir que el autor de la llamada proporcione sus propias funciones. En este paso se usa un ChatClientAgent, que admite herramientas funcionales.

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.

Crea el agente con herramientas funcionales

Las herramientas de funciones son solo código personalizado al que desea que el agente pueda llamar cuando sea necesario. Puede convertir cualquier método de C# en una herramienta de función mediante el AIFunctionFactory.Create método para crear una AIFunction instancia del método .

Si necesita proporcionar descripciones adicionales sobre la función o sus parámetros para el agente, de modo que pueda elegir con mayor precisión entre distintas funciones, puede usar el System.ComponentModel.DescriptionAttribute atributo en el método y sus parámetros.

Este es un ejemplo de una herramienta de función simple que falsifica la obtención del tiempo para una ubicación determinada. Está decorado con atributos de descripción para proporcionar descripciones adicionales sobre sí mismo y su parámetro de ubicación al agente.

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

Al crear el agente, ahora puede proporcionar una herramienta de función al agente pasando una lista de herramientas al método AsAIAgent.

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

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new DefaultAzureCredential())
     .GetChatClient("gpt-4o-mini")
     .AsAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);

Advertencia

DefaultAzureCredential es conveniente para el desarrollo, pero requiere una consideración cuidadosa en producción. En producción, considere usar una credencial específica (por ejemplo, ManagedIdentityCredential) para evitar problemas de latencia, sondeos de credenciales no deseados y posibles riesgos de seguridad de los mecanismos de respaldo.

Ahora solo puede ejecutar el agente como es normal y el agente podrá llamar a la GetWeather herramienta de función cuando sea necesario.

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

Sugerencia

Consulte los ejemplos de .NET para obtener ejemplos completos de ejecución.

Importante

No todos los tipos de agente admiten herramientas funcionales. Algunos solo pueden admitir herramientas integradas personalizadas, sin permitir que el autor de la llamada proporcione sus propias funciones. En este paso se usan agentes creados a través de clientes de chat, que admiten herramientas de funciones.

Prerrequisitos

Para conocer los requisitos previos e instalar paquetes de Python, consulte el paso Creación y ejecución de un agente sencillo en este tutorial.

Crea el agente con herramientas funcionales

Las herramientas de funciones son solo código personalizado al que desea que el agente pueda llamar cuando sea necesario. Puede convertir cualquier función de Python en una herramienta de función pasándola al parámetro del tools agente al crear el agente.

Si necesita proporcionar descripciones adicionales sobre la función o sus parámetros para el agente, de modo que pueda elegir con mayor precisión entre distintas funciones, puede usar las anotaciones de tipo de Python con Annotated y Pydantic Field para proporcionar descripciones.

Este es un ejemplo de una herramienta de función simple que falsifica la obtención del tiempo para una ubicación determinada. Usa anotaciones de tipo para proporcionar descripciones adicionales sobre la función y su parámetro de ubicación para el agente.

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

También puede usar el @tool decorador para especificar explícitamente el nombre y la descripción de la función:

from typing import Annotated
from pydantic import Field
from agent_framework import tool

@tool(name="weather_tool", description="Retrieves weather information for any location")
def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    return f"The weather in {location} is cloudy with a high of 15°C."

Si no especifica los name parámetros y description en el @tool decorador, el marco usará automáticamente el nombre de la función y docstring como reserva.

Al crear el agente, ahora puede proporcionar la herramienta de función al agente, pasándolo al parámetro tools.

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

agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
    instructions="You are a helpful assistant",
    tools=get_weather
)

Ahora solo puede ejecutar el agente como es normal y el agente podrá llamar a la get_weather herramienta de función cuando sea necesario.

async def main():
    result = await agent.run("What is the weather like in Amsterdam?")
    print(result.text)

asyncio.run(main())

Creación de una clase con varias herramientas de función

También puede crear una clase que contenga varias herramientas de función como métodos. Esto puede ser útil para organizar funciones relacionadas juntas o cuando se desea transmitir el estado entre ellas.


class WeatherTools:
    def __init__(self):
        self.last_location = None

    def get_weather(
        self,
        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."

    def get_weather_details(self) -> int:
        """Get the detailed weather for the last requested location."""
        if self.last_location is None:
            return "No location specified yet."
        return f"The detailed weather in {self.last_location} is cloudy with a high of 15°C, low of 7°C, and 60% humidity."

Al crear el agente, ahora puede proporcionar todos los métodos de la clase como funciones:

tools = WeatherTools()
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
    instructions="You are a helpful assistant",
    tools=[tools.get_weather, tools.get_weather_details]
)

También puede decorar las funciones con el mismo @tool decorador que antes.

Ejemplo completo

# Copyright (c) Microsoft. All rights reserved.

import asyncio
from typing import Annotated, Any

from agent_framework import tool
from agent_framework.openai import OpenAIResponsesClient
from pydantic import Field

"""
AI Function with kwargs Example

This example demonstrates how to inject custom keyword arguments (kwargs) into an AI function
from the agent's run method, without exposing them to the AI model.

This is useful for passing runtime information like access tokens, user IDs, or
request-specific context that the tool needs but the model shouldn't know about
or provide.
"""


# Define the function tool with **kwargs to accept injected arguments
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
    **kwargs: Any,
) -> str:
    """Get the weather for a given location."""
    # Extract the injected argument from kwargs
    user_id = kwargs.get("user_id", "unknown")

    # Simulate using the user_id for logging or personalization
    print(f"Getting weather for user: {user_id}")

    return f"The weather in {location} is cloudy with a high of 15°C."


async def main() -> None:
    agent = OpenAIResponsesClient().as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather assistant.",
        tools=[get_weather],
    )

    # Pass the injected argument when running the agent
    # The 'user_id' kwarg will be passed down to the tool execution via **kwargs
    response = await agent.run("What is the weather like in Amsterdam?", user_id="user_123")

    print(f"Agent: {response.text}")


if __name__ == "__main__":
    asyncio.run(main())
# Copyright (c) Microsoft. All rights reserved.

import asyncio
from typing import Annotated, Any

from agent_framework import tool
from agent_framework.openai import OpenAIResponsesClient
from pydantic import Field

"""
AI Function with kwargs Example

This example demonstrates how to inject custom keyword arguments (kwargs) into an AI function
from the agent's run method, without exposing them to the AI model.

This is useful for passing runtime information like access tokens, user IDs, or
request-specific context that the tool needs but the model shouldn't know about
or provide.
"""


# Define the function tool with **kwargs to accept injected arguments
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
    **kwargs: Any,
) -> str:
    """Get the weather for a given location."""
    # Extract the injected argument from kwargs
    user_id = kwargs.get("user_id", "unknown")

    # Simulate using the user_id for logging or personalization
    print(f"Getting weather for user: {user_id}")

    return f"The weather in {location} is cloudy with a high of 15°C."


async def main() -> None:
    agent = OpenAIResponsesClient().as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather assistant.",
        tools=[get_weather],
    )

    # Pass the injected argument when running the agent
    # The 'user_id' kwarg will be passed down to the tool execution via **kwargs
    response = await agent.run("What is the weather like in Amsterdam?", user_id="user_123")

    print(f"Agent: {response.text}")


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

Pasos siguientes