Megosztás:


Függvényeszközök használata ügynök mellett

Ez az oktatóanyag lépés bemutatja, hogyan használhat függvényeszközöket egy ügynökkel, ahol az ügynök az Azure OpenAI Csevegés befejezése szolgáltatásra épül.

Fontos

Nem minden ügynöktípus támogatja a funkció eszközöket. Egyesek csak egyéni beépített eszközöket támogathatnak, és nem teszik lehetővé, hogy a hívó saját függvényeket adjon meg. Ez a lépés egy ChatClientAgent, amely támogatja a függvényeszközöket.

Előfeltételek

Az előfeltételekről és a NuGet-csomagok telepítéséről lásd az egyszerű ügynök létrehozása és futtatása lépést ebben az oktatóanyagban.

Az ügynök létrehozása funkcióeszközökkel

A funkcióeszközök olyan egyéni kódok, amelyeket az ügynök szükség esetén meghívhat. Bármely C#-metódust függvényeszközsé alakíthat, ha a AIFunctionFactory.Create metódus használatával létrehoz egy példányt AIFunction a metódusból.

Ha további leírásokat kell adnia a függvényről vagy annak paramétereiről az ügynöknek, hogy pontosabban tudjon választani a különböző függvények között, használhatja az System.ComponentModel.DescriptionAttribute attribútumot a metóduson és annak paraméterein.

Íme egy példa egy egyszerű függvényeszközre, amely meghamisít egy adott hely időjárását. Leírási attribútumokkal van díszítve, hogy további leírásokat adjon magáról és helyparaméteréről az ügynöknek.

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

Az ügynök létrehozásakor mostantól a függvényeszközt is átadhatja az ügynöknek, ha átadja az eszközök listáját a AsAIAgent metódusnak.

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

Figyelmeztetés

DefaultAzureCredential a fejlesztéshez kényelmes, de a termelési környezetben gondos megfontolást igényel. Éles környezetben fontolja meg egy adott hitelesítő adat (pl. ManagedIdentityCredential) használatát a késési problémák elkerülése, a hitelesítő adatok nem szándékos próbálgatásának és a tartalék mechanizmusokból eredő esetleges biztonsági kockázatok elkerülése érdekében.

Most már csak a szokásos módon futtathatja az ügynököt, és szükség esetén az ügynök meghívhatja a GetWeather függvényeszközt.

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

Jótanács

A teljes futtatható példákért tekintse meg a .NET-mintákat .

Fontos

Nem minden ügynöktípus támogatja a funkció eszközöket. Egyesek csak egyéni beépített eszközöket támogathatnak, és nem teszik lehetővé, hogy a hívó saját függvényeket adjon meg. Ez a lépés a chat ügyfeleken keresztül létrehozott ügynököket használja, amelyek támogatják a funkcióeszközöket.

Előfeltételek

Az előfeltételekről és a Python-csomagok telepítéséről lásd a Hozzon létre és futtasson egy egyszerű ügynököt lépést ebben az oktatóanyagban.

Az ügynök létrehozása funkcióeszközökkel

A funkcióeszközök olyan egyéni kódok, amelyeket az ügynök szükség esetén meghívhat. Bármely Python-függvényt függvényeszközzé alakíthat, ha az ügynök tools paraméterének adja meg az ügynök létrehozásakor.

Ha további leírásokat kell adnia a függvényről vagy annak paramétereiről az ügynöknek, hogy pontosabban tudjon választani a különböző függvények között, a Python típusjegyzeteivel Annotated és Pydantic-jával Field leírásokat adhat meg.

Íme egy példa egy egyszerű függvényeszközre, amely meghamisít egy adott hely időjárását. Típusjegyzetekkel további leírásokat ad meg a függvényről és a helyparaméterről az ügynök számára.

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

A @tool dekorátor segítségével egyértelműen megadhatja a függvény nevét és leírását.

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

Ha nem adja meg a name és description paramétereket a @tool dekorátorban, a keretrendszer automatikusan a függvény nevét és a doksorját használja tartalékként.

Az ügynök létrehozásakor most már megadhatja a függvényeszközt az ügynöknek, ha átadja azt a tools paraméternek.

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
)

Most már csak a szokásos módon futtathatja az ügynököt, és szükség esetén az ügynök meghívhatja a get_weather függvényeszközt.

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

asyncio.run(main())

Osztály létrehozása több függvényeszközzel

Létrehozhat egy olyan osztályt is, amely metódusként több függvényeszközt tartalmaz. Ez hasznos lehet a kapcsolódó függvények közös rendszerezéséhez, vagy ha állapotot szeretne átadni közöttük.


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

Az ügynök létrehozásakor mostantól függvényként is megadhatja az osztály összes metódusát:

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

A funkciókat ugyanazzal @tool a dekorátorral is díszítheti, mint korábban.

Teljes példa

# 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())

Következő lépések