Bagikan melalui


Menggunakan perangkat fungsi dengan agen

Langkah tutorial ini menunjukkan kepada Anda cara menggunakan alat fungsi dengan agen, yang didasarkan pada layanan Penyelesaian Obrolan Azure OpenAI.

Penting

Tidak semua jenis agen mendukung alat fitur. Beberapa mungkin hanya mendukung alat bawaan kustom, tanpa mengizinkan pemanggil untuk menyediakan fungsi mereka sendiri. Langkah ini menggunakan ChatClientAgent, yang mendukung alat fungsi.

Prasyarat

Untuk prasyarat dan menginstal paket NuGet, lihat langkah Membuat dan menjalankan agen sederhana dalam tutorial ini.

Membuat agen dengan alat fungsi

Alat fungsi hanyalah kode kustom yang Anda inginkan agar agen dapat memanggil saat diperlukan. Anda dapat mengubah metode C# apa pun menjadi alat fungsi, dengan menggunakan AIFunctionFactory.Create metode untuk membuat AIFunction instans dari metode .

Jika Anda perlu memberikan deskripsi tambahan tentang fungsi atau parameternya ke agen, sehingga dapat lebih akurat memilih antara fungsi yang berbeda, Anda dapat menggunakan System.ComponentModel.DescriptionAttribute atribut pada metode dan parameternya.

Berikut adalah contoh perangkat fungsi sederhana yang mensimulasikan pengambilan cuaca untuk lokasi tertentu. Ini dihiasi dengan atribut deskripsi untuk memberikan deskripsi tambahan tentang dirinya sendiri dan parameter lokasinya kepada agen.

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

Saat membuat agen, Anda sekarang dapat menyediakan alat kepada agen dengan meneruskan daftar alat ke metode 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)]);

Peringatan

DefaultAzureCredential nyaman untuk pengembangan tetapi membutuhkan pertimbangan yang cermat dalam produksi. Dalam produksi, pertimbangkan untuk menggunakan kredensial tertentu (misalnya, ManagedIdentityCredential) untuk menghindari masalah latensi, pemeriksaan kredensial yang tidak diinginkan, dan potensi risiko keamanan dari mekanisme fallback.

Sekarang Anda hanya dapat menjalankan agen seperti biasa, dan agen akan dapat memanggil GetWeather alat fungsi ketika diperlukan.

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

Petunjuk / Saran

Lihat sampel .NET untuk contoh lengkap yang dapat dijalankan.

Penting

Tidak semua jenis agen mendukung alat fitur. Beberapa mungkin hanya mendukung alat bawaan kustom, tanpa mengizinkan pemanggil untuk menyediakan fungsi mereka sendiri. Langkah ini menggunakan agen yang dibuat melalui klien obrolan, yang memang mendukung alat fungsional.

Prasyarat

Untuk prasyarat dan menginstal paket Python, lihat langkah Membuat dan menjalankan agen sederhana dalam tutorial ini.

Membuat agen dengan alat fungsi

Alat fungsi hanyalah kode kustom yang Anda inginkan agar agen dapat memanggil saat diperlukan. Anda dapat mengubah fungsi Python apa pun menjadi alat fungsi dengan meneruskannya ke parameter agen tools saat membuat agen.

Jika Anda perlu memberikan deskripsi tambahan tentang fungsi atau parameternya ke agen, sehingga dapat memilih lebih akurat antara fungsi yang berbeda, Anda dapat menggunakan anotasi jenis Python dengan Annotated dan Pydantic Field untuk memberikan deskripsi.

Berikut adalah contoh perangkat fungsi sederhana yang mensimulasikan pengambilan cuaca untuk lokasi tertentu. Ini menggunakan anotasi jenis untuk memberikan deskripsi tambahan tentang fungsi dan parameter lokasinya kepada agen.

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

Anda juga dapat menggunakan @tool dekorator untuk secara eksplisit menentukan nama dan deskripsi fungsi:

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

Jika Anda tidak menentukan parameter name dan description di dekorasi @tool, kerangka kerja akan secara otomatis menggunakan nama fungsi dan docstring sebagai alternatif.

Saat membuat agen, Anda sekarang dapat menyediakan fungsi alat ke agen, dengan meneruskannya ke parameter 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
)

Sekarang Anda hanya dapat menjalankan agen seperti biasa, dan agen akan dapat memanggil get_weather alat fungsi ketika diperlukan.

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

asyncio.run(main())

Membuat kelas dengan beberapa alat fungsi

Anda juga dapat membuat kelas yang berisi beberapa alat fungsi sebagai metode. Ini dapat berguna untuk mengelompokkan fungsi terkait atau ketika Anda ingin mengoper status di antara fungsi-fungsi tersebut.


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

Saat membuat agen, Anda sekarang dapat menyediakan semua metode kelas sebagai fungsi:

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

Anda juga dapat mendekorasi fungsi dengan dekorator @tool yang sama seperti sebelumnya.

Contoh lengkap

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

Langkah selanjutnya