AIDiscount优汇智
홈 / 블로그

함수 호출과 도구 사용: 실전 가이드

OpenAI 호환 API와 Anthropic Messages에서 함수 호출이 동작하는 방식을, 함수를 호출하고 결과를 돌려주는 완전한 멀티턴 예제와 함께 설명합니다.

2026-11-25 · 4분 분량 · AIDiscount 팀

Function callingTool useAPIPython

함수 호출(도구 사용이라고도 합니다)은 모델이 직접 답하는 대신 코드에 함수 실행을 요청하게 해 줍니다. 날씨 API를 조회하거나, 데이터베이스를 쿼리하거나, 계산을 수행한 뒤 그 결과로 답변을 마무리합니다. 모델은 아무것도 직접 실행하지 않습니다. 특정 인수로 함수를 호출해 달라는 요청만 반환하고, 실제로 실행할지는 여러분의 코드가 결정합니다.

요청 구조

사용할 수 있는 함수를 각각 JSON Schema로 설명합니다. 이름, 설명, 인수의 구조가 들어갑니다.

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, e.g. Tokyo"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["city"],
        },
    },
}]

모델은 함수 설명과 매개변수 설명을 보고 언제, 어떻게 함수를 호출할지 결정합니다. 그러니 타입 시그니처만 적지 말고, 다른 사람에게 함수를 설명하듯 작성하세요.

완전한 멀티턴 예제

도구 호출로 대화가 끝나지 않습니다. 모델이 멈추면 여러분이 함수를 실행하고, 결과를 새 메시지로 돌려보내 모델이 이어서 답하게 합니다.

import json
from openai import OpenAI

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

def get_weather(city, unit="celsius"):
    return {"city": city, "temperature": 18, "unit": unit, "condition": "cloudy"}

messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]

resp = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
msg = resp.choices[0].message
messages.append(msg)

if msg.tool_calls:
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
    final = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
    print(final.choices[0].message.content)

이 예제의 핵심은 다음과 같습니다. 도구 결과보다 어시스턴트의 도구 호출 메시지를 먼저 추가하고, 각 tool_call_id를 그것이 응답하는 호출과 맞추며, content는 문자열로 보냅니다(객체는 json.dumps로 인코딩).

한 턴에 여러 도구 호출

모델은 예를 들어 세 도시의 날씨를 조회하는 것처럼 여러 도구 호출을 한 번에 요청할 수 있습니다. msg.tool_calls를 순회하며 호출마다 고유한 tool_call_id를 가진 "role": "tool" 메시지를 하나씩 추가한 뒤 모델을 다시 호출하세요.

Anthropic Messages 형식

구조가 다릅니다. 각 도구의 스키마는 function.parameters 대신 input_schema에 들어가고, 도구 호출은 tool_use 콘텐츠 블록으로 도착하며, 결과는 user 메시지 안의 tool_result 콘텐츠 블록으로 돌려보냅니다.

import anthropic

client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a city",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
}]

messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]
resp = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
messages.append({"role": "assistant", "content": resp.content})

tool_use = next(b for b in resp.content if b.type == "tool_use")
result = get_weather(**tool_use.input)
messages.append({
    "role": "user",
    "content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": json.dumps(result)}],
})
final = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
print(final.content[0].text)

도구 사용 강제하기 또는 끄기

기본적으로 도구 호출 여부는 모델이 결정합니다. 특정 도구 하나를 강제하려면 tool_choice={"type": "function", "function": {"name": "get_weather"}}(OpenAI 형식) 또는 tool_choice={"type": "tool", "name": "get_weather"}(Anthropic 형식)를 전달하세요. 도구 정의는 유지한 채 한 요청에서만 도구 호출을 막으려면 tool_choice="none"(OpenAI 형식) 또는 tool_choice={"type": "none"}(Anthropic 형식)를 설정하세요.

자주 하는 실수

  • 도구 결과를 잘못된 role로 반환함. OpenAI 형식은 "role": "tool"을 요구하며, 결과를 일반 user나 assistant 메시지로 보내면 받지 않습니다.
  • 어시스턴트의 도구 호출 메시지를 돌려보내지 않음. 모델이 결과와 연결하려면 대화 기록에서 자신의 도구 호출을 볼 수 있어야 합니다.
  • content에 JSON 문자열 대신 Python 객체를 그대로 보냄. 항상 json.dumps로 직렬화하세요.
  • 함수를 실행하기 전에 인수를 검증하지 않음. 도구 호출 인수는 모델에서 온 신뢰할 수 없는 입력으로 취급하세요. 특히 데이터베이스 쿼리나 셸 명령에 사용하기 전에는 타입과 범위를 검증해야 합니다.

모델 선택

AIDiscount의 최신 모델은 대부분 도구 호출을 지원하며, 마켓플레이스의 모델 페이지에서 기능(capabilities) 항목으로 확인할 수 있습니다. 도구 호출을 지원하는 몇몇 모델의 현재 가격은 다음과 같습니다.

모델입력 / 100만 토큰출력 / 100만 토큰공식 가격 대비
GPT-6 Luna
gpt-6-luna
$0.05$0.3040% 할인
Claude Opus 4.8
claude-opus-4-8
$0.375$1.87592.5% 할인
DeepSeek V4 Pro
deepseek-v4-pro
$0.3857$1.157141.6% 할인
Kimi K3
kimi-k3
$1.714$8.57142.9% 할인
GLM-5.3
glm-5.3
$0.6857$2.4045.5% 할인

가격은 이 페이지를 생성할 때 모델 목록에서 가져온 값이며 변경될 수 있습니다. 현재 가격은 모델 목록에서 확인하세요.

AIDiscount로 시작해 보세요. API 키 하나로 OpenAI 및 Anthropic 호환 도구를 사용할 수 있습니다. 사용한 만큼만 결제하며 월 요금이 없습니다.
무료 계정 만들기API 문서 보기

관련 가이드

언어

English · 简体中文 · 繁體中文 · 日本語 · 한국어 · Español · Français · Deutsch · Português · Русский