이 자습서 단계에서는 에이전트와 함께 함수 도구를 사용하는 방법을 보여 줍니다. 여기서 에이전트는 Azure OpenAI 채팅 완료 서비스를 기반으로 합니다.
중요합니다
모든 에이전트 형식이 함수 도구를 지원하는 것은 아닙니다. 일부는 호출자가 자체 함수를 제공하도록 허용하지 않고 사용자 지정 기본 제공 도구만 지원할 수 있습니다. 이 단계에서는 함수를 지원하는 ChatClientAgent를 사용합니다.
필수 조건
필수 구성 요소 및 NuGet 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.
함수 도구를 사용하여 에이전트 만들기
함수 도구는 필요할 때 에이전트가 호출할 수 있도록 하는 사용자 지정 코드일 뿐입니다.
AIFunctionFactory.Create 메서드를 사용하여 C# 메서드에서 인스턴스를 만들면 어떤 C# 메서드라도 함수 도구로 AIFunction 할 수 있습니다.
다른 함수 중에서 더 정확하게 선택할 수 있도록 함수 또는 해당 매개 변수에 대한 추가 설명을 에이전트에 제공해야 하는 경우 메서드와 해당 매개 변수에 특성을 사용할 System.ComponentModel.DescriptionAttribute 수 있습니다.
다음은 지정된 위치에 대한 날씨를 가짜로 만드는 간단한 함수 도구의 예입니다. 자체 및 해당 위치 매개 변수에 대한 추가 설명을 에이전트에 제공하기 위해 설명 특성으로 데코레이팅됩니다.
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.";
이제 에이전트를 만들 때, CreateAIAgent 메서드에 도구 목록을 전달하여 에이전트용 함수 도구를 사용할 수 있습니다.
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 AzureCliCredential())
.GetChatClient("gpt-4o-mini")
.CreateAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);
이제 에이전트를 정상적으로 실행할 수 있으며 필요한 경우 에이전트가 GetWeather 함수 도구를 호출할 수 있습니다.
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
중요합니다
모든 에이전트 형식이 함수 도구를 지원하는 것은 아닙니다. 일부는 호출자가 자체 함수를 제공하도록 허용하지 않고 사용자 지정 기본 제공 도구만 지원할 수 있습니다. 이 단계에서는 함수 도구를 지원하는 채팅 클라이언트를 통해 만든 에이전트를 사용합니다.
필수 조건
필수 구성 요소 및 Python 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.
함수 도구를 사용하여 에이전트 만들기
함수 도구는 필요할 때 에이전트가 호출할 수 있도록 하는 사용자 지정 코드일 뿐입니다.
에이전트를 만들 때 Python 함수를 에이전트의 tools 매개 변수에 전달하여 함수 도구로 전환할 수 있습니다.
다른 함수 중에서 더 정확하게 선택할 수 있도록 함수 또는 해당 매개 변수에 대한 추가 설명을 에이전트에 제공해야 하는 경우 Python의 형식 주석과 Annotated Pydantic을 Field 사용하여 설명을 제공할 수 있습니다.
다음은 지정된 위치에 대한 날씨를 가짜로 만드는 간단한 함수 도구의 예입니다. 형식 주석을 사용하여 함수 및 해당 위치 매개 변수에 대한 추가 설명을 에이전트에 제공합니다.
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."
데코레이터를 ai_function 사용하여 함수의 이름과 설명을 명시적으로 지정할 수도 있습니다.
from typing import Annotated
from pydantic import Field
from agent_framework import ai_function
@ai_function(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."
데코레이터에서 name 매개 변수 및 description 매개 변수를 ai_function 지정하지 않으면 프레임워크는 자동으로 함수의 이름과 문서 문자열을 대체로 사용합니다.
에이전트를 만들 때 이제 함수 도구를 매개 변수에 전달하여 에이전트에 tools 제공할 수 있습니다.
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
instructions="You are a helpful assistant",
tools=get_weather
)
이제 에이전트를 정상적으로 실행할 수 있으며 필요한 경우 에이전트가 get_weather 함수 도구를 호출할 수 있습니다.
async def main():
result = await agent.run("What is the weather like in Amsterdam?")
print(result.text)
asyncio.run(main())
여러 함수 도구를 사용하여 클래스 만들기
여러 함수 도구를 메서드로 포함하는 클래스를 만들 수도 있습니다. 관련 함수를 함께 구성하거나 관련 함수 간에 상태를 전달하려는 경우에 유용할 수 있습니다.
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."
에이전트를 만들 때 이제 클래스의 모든 메서드를 함수로 제공할 수 있습니다.
tools = WeatherTools()
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
instructions="You are a helpful assistant",
tools=[tools.get_weather, tools.get_weather_details]
)
이전과 동일한 ai_function 데코레이터를 사용하여 함수를 데코레이트할 수도 있습니다.