Aracılığıyla paylaş


Aracıyla fonksiyon araçlarını kullanma

Bu öğretici adım, Azure OpenAI Sohbet Tamamlama hizmetine dayalı olarak oluşturulmuş bir ajanın işlev araçlarıyla nasıl kullanılacağını gösterir.

Önemli

Tüm aracı türleri işlev araçlarını desteklemez. Bazıları, çağıranın kendi işlevlerini sağlamasına izin vermeden yalnızca özel yerleşik araçları destekleyebilir. Bu adımda işlev araçlarını destekleyen bir ChatClientAgentkullanılır.

Önkoşullar

Önkoşullar ve NuGet paketlerini yükleme için bu öğreticideki Basit bir aracı oluşturma ve çalıştırma adımına bakın.

İşlev araçlarıyla aracı oluşturma

İşlev araçları yalnızca aracının gerektiğinde çağırabilmesini istediğiniz özel kodlardır. AIFunctionFactory.Create yöntemini kullanarak herhangi bir C# yöntemini işlev AIFunction aracı haline getirebilirsiniz, bu yöntemden bir örnek oluşturarak.

Farklı işlevler arasında daha doğru seçim yapmak için işlev veya parametreleri hakkında aracıya ek açıklamalar sağlamanız gerekiyorsa, yönteminde ve parametrelerinde özniteliğini kullanabilirsiniz System.ComponentModel.DescriptionAttribute .

Burada, belirli bir konumun hava durumunu alma sahtesini gösteren basit bir işlev aracı örneği verilmiştir. Kendisi ve konum parametresi hakkında aracıya ek açıklamalar sağlamak için açıklama öznitelikleriyle donatılmıştır.

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

Aracıyı oluştururken, AsAIAgent yöntemine bir araç listesi geçirerek aracıya işlev aracını artık sağlayabilirsiniz.

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

Uyarı

DefaultAzureCredential geliştirme için uygundur ancak üretimde dikkatli bir şekilde dikkate alınması gerekir. Üretimde gecikme sorunları, istenmeyen kimlik bilgisi yoklama ve geri dönüş mekanizmalarından kaynaklanan olası güvenlik risklerini önlemek için belirli bir kimlik bilgisi (ör ManagedIdentityCredential. ) kullanmayı göz önünde bulundurun.

Artık ajanı her zamanki gibi çalıştırabilirsiniz ve ajan gerektiğinde işlev aracını GetWeather çağırabilir.

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

Tip

Çalıştırılabilir örneklerin tamamı için .NET örneklerine bakın.

Önemli

Tüm aracı türleri işlev araçlarını desteklemez. Bazıları, çağıranın kendi işlevlerini sağlamasına izin vermeden yalnızca özel yerleşik araçları destekleyebilir. Bu adım, işlev araçlarını destekleyen sohbet istemcileri aracılığıyla oluşturulan aracıları kullanır.

Önkoşullar

Önkoşullar ve Python paketlerini yükleme için bu öğreticideki Basit bir aracı oluşturma ve çalıştırma adımına bakın.

İşlev araçlarıyla aracı oluşturma

İşlev araçları yalnızca aracının gerektiğinde çağırabilmesini istediğiniz özel kodlardır. Herhangi bir Python işlevini aracıyı oluştururken aracının tools parametresine geçirerek işlev aracısına dönüştürebilirsiniz.

Farklı işlevler arasında daha doğru seçim yapmak için işlev veya parametreleri hakkında aracıya ek açıklamalar sağlamanız gerekiyorsa, açıklama sağlamak için Python'ın tür ek açıklamalarını ve Pydantic'in Annotated açıklamalarını Field kullanabilirsiniz.

Burada, belirli bir konumun hava durumunu alma sahtesini gösteren basit bir işlev aracı örneği verilmiştir. Tür tanımlamalarını, aracıya işlev ve konum parametresi hakkında ek açıklamalar sağlamak için kullanır.

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

Ayrıca, işlevin @tool adını ve açıklamasını açıkça belirtmek için dekoratör de kullanabilirsiniz:

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

Dekoratörde namedescription ve @tool parametrelerini belirtmezseniz, çerçeve otomatik olarak işlevin adını ve docstring'i geri dönüş olarak kullanır.

Aracıyı oluştururken işlev aracını tools parametresine geçirerek artık aracıya sağlayabilirsiniz.

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
)

Artık ajanı her zamanki gibi çalıştırabilirsiniz ve ajan gerektiğinde işlev aracını get_weather çağırabilir.

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

asyncio.run(main())

Birden çok işlev aracıyla sınıf oluşturma

Yöntem olarak birden çok işlev aracı içeren bir sınıf da oluşturabilirsiniz. Bu, ilgili işlevleri birlikte düzenlemek veya aralarında durum geçirmek istediğinizde yararlı olabilir.


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

Aracıyı oluştururken artık sınıfın tüm yöntemlerini işlev olarak sağlayabilirsiniz:

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

Ayrıca işlevleri daha önce olduğu gibi aynı @tool dekoratörle süsleyebilirsiniz.

Tam örnek

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

Sonraki Adımlar