다음을 통해 공유


Azure AI 에이전트 함수 호출

Azure AI 에이전트는 함수 호출을 지원하므로 도우미에 대한 함수 구조를 설명한 다음 해당 인수와 함께 호출해야 하는 함수를 반환할 수 있습니다.

참고 항목

실행은 만든 후 10분 후에 만료됩니다. 만료 전에 도구 출력을 제출해야 합니다.

사용량 지원

Azure AI 파운드리 지원 Python SDK C# SDK JavaScript SDK REST API 기본 에이전트 설정 표준 에이전트 설정
✔️ ✔️ ✔️ ✔️ ✔️ ✔️

에이전트가 호출할 함수 정의

먼저 에이전트가 호출할 함수를 정의합니다. 에이전트가 호출할 함수를 만들 때 문서 문자열에 필요한 매개 변수를 사용하여 해당 함수의 구조를 설명합니다. 모든 함수 정의를 단일 파일에 user_functions.py 포함하면 기본 스크립트로 가져올 수 있습니다.

import json
import datetime
from typing import Any, Callable, Set, Dict, List, Optional

def fetch_weather(location: str) -> str:
    """
    Fetches the weather information for the specified location.

    :param location (str): The location to fetch weather for.
    :return: Weather information as a JSON string.
    :rtype: str
    """
    # In a real-world scenario, you'd integrate with a weather API.
    # Here, we'll mock the response.
    mock_weather_data = {"New York": "Sunny, 25°C", "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
    weather = mock_weather_data.get(location, "Weather data not available for this location.")
    weather_json = json.dumps({"weather": weather})
    return weather_json

# Statically defined user functions for fast reference
user_functions: Set[Callable[..., Any]] = {
    fetch_weather,
}

전체 일련의 함수 정의에 대한 예제는 GitHub의 Python 파일을 참조하세요. 이 파일을 아래 예제에서 참조 user_functions.py 합니다.

클라이언트 및 에이전트 만들기

아래 샘플에서는 클라이언트를 만들고 에 정의된 user_functions함수를 처리하는 데 사용할 클라이언트를 정의 toolset 합니다.

toolset: 도구 집합 매개 변수를 사용하는 경우 함수 정의 및 설명뿐만 아니라 해당 구현도 제공합니다. SDK는 create_and_run_process 또는 스트리밍 내에서 이러한 함수를 실행합니다. 이러한 함수는 정의에 따라 호출됩니다.

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.projects.models import FunctionTool, ToolSet
from user_functions import user_functions # user functions which can be found in a user_functions.py file.

# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
# It should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
# Customers need to login to Azure subscription via Azure CLI and set the environment variables

project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(),
    conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)

# Initialize agent toolset with user functions
functions = FunctionTool(user_functions)
toolset = ToolSet()
toolset.add(functions)

agent = project_client.agents.create_agent(
    model="gpt-4o-mini", name="my-agent", instructions="You are a weather bot. Use the provided functions to help answer questions.", toolset=toolset
)
print(f"Created agent, ID: {agent.id}")

스레드 만들기

# Create thread for communication
thread = project_client.agents.create_thread()
print(f"Created thread, ID: {thread.id}")

# Create message to thread
message = project_client.agents.create_message(
    thread_id=thread.id,
    role="user",
    content="Hello, send an email with the datetime and weather information in New York?",
)
print(f"Created message, ID: {message.id}")

실행을 만들고 출력을 확인합니다.

# Create and process agent run in thread with tools
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
print(f"Run finished with status: {run.status}")

if run.status == "failed":
    print(f"Run failed: {run.last_error}")

# Delete the agent when done
project_client.agents.delete_agent(agent.id)
print("Deleted agent")

# Fetch and log all messages
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")

참고 항목