Tool calling이란 무엇인가요?
Tool calling은 시스템이 API, 데이터베이스 또는 커스텀 함수와 같은 외부 서비스와 매끄럽게 상호작용할 수 있도록 하여, 정적인 모델을 동적인 실세계 도구로 탈바꿈시켜요. 개발자는 tools 배열 안에 커스텀 도구를 정의하고 목적, 입력, 출력을 지정할 수 있어요. 그러면 모델은 JSON 형식으로 tool call 시그니처를 동적으로 생성하여 다음과 같은 다양한 기능을 활용할 수 있게 해줘요.
- API 호출: LLM이 API를 호출하여 날씨, 주가, 뉴스 등 실시간 데이터를 가져올 수 있어요.
- 데이터베이스 쿼리: 모델이 데이터베이스와 상호작용하여 특정 데이터를 가져올 수 있어요.
- 자동화 작업: LLM이 워크플로우나 자동화 도구(예: Zapier 또는 기타 RPA 플랫폼)를 트리거할 수 있어요.
- 코드 실행: 모델이 코드를 생성하고 Tool calling을 통해 즉시 실행할 수 있어요.
예시
예시 1: 날씨 데이터 요청
요청
from openai import OpenAI # openai==1.52.2
import json
client = OpenAI(
api_key="UPSTAGE_API_KEY_INJECT",
base_url="https://api.upstage.ai/v1"
)
# Step 1: 함수 설정 및 정의
# 동일한 날씨를 반환하도록 하드코딩된 더미 함수 예시입니다.
# 프로덕션 환경에서는 백엔드 API 또는 외부 API가 될 수 있습니다.
def get_current_weather(location, unit="fahrenheit"):
"""Get the current weather in a given location"""
if unit is None:
unit = "fahrenheit"
if "seoul" in location.lower():
return json.dumps({"location": "Seoul", "temperature": "10", "unit": unit})
elif "san francisco" in location.lower():
return json.dumps(
{"location": "San Francisco", "temperature": "72", "unit": unit}
)
elif "paris" in location.lower():
return json.dumps({"location": "Paris", "temperature": "22", "unit": unit})
else:
return json.dumps({"location": location, "temperature": "unknown"})
# Step 2: 쿼리와 사용 가능한 도구들을 모델에 전송
def run_conversation():
messages = [
{
"role": "user",
"content": "What's the weather like in Seoul?",
}
]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
"additionalProperties": False,
},
},
}
]
# Step 3: 모델이 tool call을 요청했는지 확인
# 모델은 쿼리가 외부 데이터(예: 실시간 날씨)를 필요로 한다고 판단하고, 날씨 API 같은 관련 도구를 호출하기로 결정합니다.
response = client.chat.completions.create(
model="solar-pro4",
messages=messages,
tools=tools,
tool_choice="auto",
parallel_tool_calls=False
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
if not tool_calls:
return response
# Step 4: tool calls 실행
# 모델이 반환한 JSON 응답이 항상 유효하지 않을 수 있으므로, 적절히 에러를 처리하세요.
if tool_calls:
available_functions = {
"get_current_weather": get_current_weather,
} # 여기에서 필요에 따라 여러 함수를 정의할 수 있습니다.
messages.append(response_message) # 어시스턴트의 응답을 대화 히스토리에 추가
# Step 5: 각 tool call을 처리하고 결과를 모델에 제공
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions.get(function_name)
if function_to_call is None:
raise ValueError(f"Tool not allowed: {function_name}")
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as exc:
raise ValueError("Tool arguments must be valid JSON") from exc
if not isinstance(function_args, dict):
raise ValueError("Tool arguments must be a JSON object")
unexpected = set(function_args) - {"location", "unit"}
if unexpected:
raise ValueError(f"Unexpected tool arguments: {sorted(unexpected)}")
location = function_args.get("location")
unit = function_args.get("unit", "fahrenheit")
if not isinstance(location, str) or not location.strip():
raise ValueError("location must be a non-empty string")
if unit not in {"celsius", "fahrenheit"}:
raise ValueError("unit must be celsius or fahrenheit")
function_response = function_to_call(
location=location,
unit=unit,
) # 제공된 인자로 함수 호출
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
) # 함수 응답을 대화 히스토리에 추가
# Step 6: 업데이트된 대화 히스토리를 사용하여 모델에서 새로운 응답을 생성
second_response = client.chat.completions.create(
model="solar-pro4",
messages=messages,
)
return second_response # 모델의 최종 응답을 반환
response = run_conversation()
print(response.choices[0].message.content)응답
The current weather in Seoul is 10 degrees Celsius.예시 2: 구조화된 데이터에서 정보 가져오기
요청
import json
import os
from typing import List
from openai import OpenAI # openai==1.52.2
import pandas as pd
client = OpenAI(
api_key="UPSTAGE_API_KEY_INJECT",
base_url="https://api.upstage.ai/v1"
)
# Step 1. 설정 및 구조화된 데이터 생성
# Tool calling 기능을 보여주기 위해 하드코딩된 더미 데이터입니다.
# 프로덕션 환경에서는 내부 데이터베이스가 될 수 있습니다.
# 데이터 생성 (MAU와 매출)
mau_data = [
{"Month": 1, "Service": "LLM", "MAU": 100},
{"Month": 1, "Service": "Embedding", "MAU": 50},
{"Month": 2, "Service": "LLM", "MAU": 150},
{"Month": 2, "Service": "Embedding", "MAU": 70},
{"Month": 3, "Service": "LLM", "MAU": 300},
{"Month": 3, "Service": "Embedding", "MAU": 80},
{"Month": 4, "Service": "LLM", "MAU": 350},
{"Month": 4, "Service": "Embedding", "MAU": 150},
]
mau = pd.DataFrame(mau_data)
revenue_data = [
{"Month": 1, "Service": "LLM", "Revenue": 1000},
{"Month": 1, "Service": "Embedding", "Revenue": 500},
{"Month": 2, "Service": "LLM", "Revenue": 1500},
{"Month": 2, "Service": "Embedding", "Revenue": 700},
{"Month": 3, "Service": "LLM", "Revenue": 3000},
{"Month": 3, "Service": "Embedding", "Revenue": 800},
{"Month": 4, "Service": "LLM", "Revenue": 3500},
{"Month": 4, "Service": "Embedding", "Revenue": 1500},
]
revenue = pd.DataFrame(revenue_data)
# Step 2. 함수 정의
# query_data 함수는 지정된 월(month)과 서비스(service)를 기반으로 MAU 또는 Revenue 테이블에서 데이터를 필터링하도록 설계되었습니다.
# 이러한 기준에 따라 필터링된 DataFrame을 반환합니다.
# 이 함수는 Tool calling 메커니즘의 일부로 LLM에 의해 활용되어 쿼리에 동적으로 답변할 것입니다.
# 예시 질문
question = "Use the query_data tool to find Revenue for service LLM in months 1, 2, and 3."
def query_data(table_name: str, month: List[int], service: str) -> pd.DataFrame:
"""
Query data from the given table based on month and service.
"""
if table_name == "MAU":
data = mau
elif table_name == "Revenue":
data = revenue
else:
raise ValueError(f"Table name {table_name} not found.")
return data[(data["Month"].isin(month)) & (data["Service"] == service)]
# Step 3. Tool calling을 위한 tools 정의
# 이 블록은 query_data 함수를 LLM에 사용 가능한 옵션으로 등록하는 tools 배열을 정의합니다.
# 사용 가능한 함수와 예상 파라미터에 대한 정보를 모델에 제공하여, 대화 중에 모델이 함수를 동적으로 호출할 수 있도록 합니다.
tools = [
{
"type": "function",
"function": {
"name": "query_data",
"description": "Query MAU or Revenue data for specified months and service.",
"parameters": {
"type": "object",
"properties": {
"table_name": {
"type": "string",
"description": "The table name to query.",
"enum": ["MAU", "Revenue"],
},
"month": {
"type": "array",
"items": {"type": "integer"},
"description": "The list of months to query.",
},
"service": {
"type": "string",
"description": "Which service to query.",
"enum": ["LLM", "Embedding"],
},
},
"required": ["table_name", "month", "service"],
"additionalProperties": False,
},
},
}
]
# Step 4. 사용자 메시지와 초기 LLM 응답
# LLM은 1분기 LLM 매출에 대해 묻는 사용자 메시지를 받습니다. 이와 함께 query_data를 포함한 tools 목록이 제공되어, 모델이 tool call 여부를 결정할 수 있습니다.
# 모델이 query_data 함수를 사용해야 한다고 판단하면 요청을 생성하며, 이는 다음 단계에서 처리됩니다.
messages = [
{
"role": "user",
"content": question,
}
]
response = client.chat.completions.create(
model="solar-pro4",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "query_data"}},
parallel_tool_calls=True, # Parallel tool calling 활성화
)
# Step 5. 함수 실행 및 tool call 처리
# LLM의 응답에는 모델이 query_data 함수를 호출하기로 선택했음을 나타내는 tool_call이 포함됩니다.
# tool call에는 함수 이름과 인자가 포함되며, 이를 추출하고 파싱합니다.
# 추출된 인자를 사용하여 query_data 함수가 실행됩니다.
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
if not tool_calls:
raise RuntimeError("The model did not return the required tool call")
tool_call = tool_calls[0]
# 사용 가능한 함수 정의
available_functions = {
"query_data": query_data,
}
messages.append(response_message)
# 함수 이름과 해당하는 호출 가능한 함수 가져오기
function_name = tool_call.function.name
function_to_call = available_functions.get(function_name)
if function_to_call is None:
raise ValueError(f"Tool not allowed: {function_name}")
# tool call에서 함수 인자 파싱
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as exc:
raise ValueError("Tool arguments must be valid JSON") from exc
if not isinstance(function_args, dict):
raise ValueError("Tool arguments must be a JSON object")
unexpected = set(function_args) - {"table_name", "month", "service"}
if unexpected:
raise ValueError(f"Unexpected tool arguments: {sorted(unexpected)}")
table_name = function_args.get("table_name")
month = function_args.get("month")
service = function_args.get("service")
if table_name not in {"MAU", "Revenue"}:
raise ValueError("table_name must be MAU or Revenue")
if (
not isinstance(month, list)
or not month
or not all(type(value) is int for value in month)
):
raise ValueError("month must be a non-empty array of integers")
if service not in {"LLM", "Embedding"}:
raise ValueError("service must be LLM or Embedding")
# 파싱한 인자로 함수 실행
function_response = function_to_call(
table_name=table_name,
month=month,
service=service,
)
function_response = json.dumps(function_response.to_dict(orient="records"))
# Step 6. 함수 출력으로 대화 확장
# 함수의 출력은 메시지로 대화에 추가됩니다.
# 이후 모델은 함수의 결과를 바탕으로 대화를 계속 이어가도록 프롬프트를 받습니다.
# 함수의 응답을 대화 히스토리에 추가
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
# 업데이트된 메시지 히스토리를 LLM에 전송하여 대화를 계속 진행
second_response = client.chat.completions.create(
model="solar-pro4",
messages=messages,
)
print(second_response.choices[0].message.content)응답
The revenue for LLM in the 1st quarter was $1000 in January, $1500 in February, and $3000 in March.Parallel tool calling
Parallel tool calling은 모델이 단일 응답에서 여러 tool calls를 생성하도록 하여, 서로 독립적인 tool calls를 동시에 실행할 수 있게 해줘요. 여러 출처에서 데이터를 동시에 가져와야 할 때 특히 유용해요.
Parallel tool calling 활성화 방법
API 요청에서 parallel_tool_calls=True로 설정해주세요.
response = client.chat.completions.create(
model="solar-pro4",
messages=messages,
tools=tools,
tool_choice="auto",
parallel_tool_calls=True
)모델이 여러 개의 독립적인 tool calls가 필요하다고 판단하면(예: 세 도시의 날씨를 한 번에 조회), 단일 응답으로 여러 개의 tool_calls를 반환해요. 반환된 parallel tool calls를 모두 처리하고 그 결과를 대화에 추가한 후 다음 API 호출을 진행해주세요.
Responses API 사용하기
Solar Pro 4와 Solar Mini 4에서 Responses API를 사용할 수 있어요.
함수를 선언하고 반환된 호출을 코드에서 실행한 다음, 결과를 function_call_output으로 돌려보내세요. Python 예시는 요청부터 도구 실행 결과 전달까지 전체 흐름을 보여주고, cURL 예시는 최초 요청을 보여줘요.
import json
from openai import OpenAI
client = OpenAI(
api_key="UPSTAGE_API_KEY",
base_url="https://api.upstage.ai/v1",
)
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}
]
first = client.responses.create(
model="solar-pro4",
input="What's the weather in Seoul?",
tools=tools,
)
call = next(item for item in first.output if item.type == "function_call")
result = {"temp_c": 23, "sky": "clear"} # run the tool yourself
# Send the history back with the tool result appended.
history = [{"role": "user", "content": "What's the weather in Seoul?"}]
history += [item.model_dump(exclude_none=True) for item in first.output]
history.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result),
}
)
second = client.responses.create(model="solar-pro4", input=history, tools=tools)
print(second.output_text)