PART 10 - 강의 2/3

Tool Use와 Function Calling

LLM이 외부 세계와 상호작용하는 방법

01

Function Calling이란?

LLM이 외부 도구를 호출하는 방법

Function Calling은 LLM이 외부 도구나 함수를 호출할 수 있게 해주는 기능입니다. LLM은 사용자의 요청을 분석하여 어떤 함수를 어떤 인자로 호출해야 하는지 결정하고, 구조화된 JSON 형태로 출력합니다.

핵심 개념
LLM은 함수를 직접 실행하지 않습니다.
함수 호출 요청을 JSON으로 출력하고, 실제 실행은 애플리케이션이 담당합니다.

Function Calling 흐름

사용자 요청
"서울 날씨 알려줘"
->
LLM 분석
함수 선택 & 인자 결정
->
Function Call
{"name": "get_weather"}
->
실제 실행
API 호출
->
결과 해석
응답 생성
->
최종 응답
"서울은 15도입니다"
02

Tool 정의 방법

JSON Schema로 도구 정의하기

LLM에게 사용 가능한 도구를 알려주기 위해 JSON Schema 형식으로 도구를 정의합니다. 이 정의에는 함수명, 설명, 매개변수 스키마가 포함됩니다.

Tool Definition Schema
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "지정된 도시의 현재 날씨 정보를 조회합니다",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "도시 이름 (예: Seoul, Tokyo)"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "온도 단위"
        }
      },
      "required": ["city"]
    }
  }
}
LLM Output Example
// 사용자: "서울 날씨 알려줘"
// LLM이 생성한 Function Call:

{
  "id": "call_abc123",
  "type": "function",
  "function": {
    "name": "get_weather",
    "arguments": "{\"city\": \"Seoul\", \"unit\": \"celsius\"}"
  }
}

// 실행 결과를 LLM에게 전달하면
// 자연스러운 응답을 생성
좋은 Tool 정의의 핵심

description을 상세하게 작성하세요. LLM은 이 설명을 보고 언제 이 도구를 사용할지 결정합니다. 모호한 설명은 잘못된 도구 선택으로 이어집니다.

03

주요 LLM Provider의 Tool Use

각 Provider별 Function Calling 지원 방식

각 LLM 제공자마다 Function Calling을 지원하는 방식이 조금씩 다릅니다.

GPT-4 / GPT-4o
Parallel Function Calling 지원
가장 성숙한 구현
tools: [{type: "function", ...}]
Claude 3 / 3.5
Tool Use로 명명
XML 형식도 지원
tools: [{name, description, input_schema}]
Gemini Pro
Function Declarations 사용
Grounding 기능 내장
tools: [{function_declarations: [...]}]
Mistral Large
OpenAI 호환 형식
오픈소스 모델도 지원
tools: [{type: "function", ...}]

상세 비교

Provider Parallel Calls Forced Tool Use Streaming 특이사항
OpenAI 지원 tool_choice 지원 가장 성숙한 구현
Claude 지원 tool_choice 지원 XML 형식도 지원
Gemini 지원 tool_config 지원 Grounding 기능 내장
Mistral 지원 tool_choice 지원 오픈소스 모델도 지원
04

Tool Schema 생성기

직접 Tool Schema를 만들어보세요

직접 Tool Schema를 만들어보세요. 왼쪽에 정보를 입력하면 오른쪽에 JSON Schema가 생성됩니다.

Tool Schema Builder
Function Name
Description
Parameters
Generated JSON Schema
{ "type": "function", "function": { "name": "", "description": "", "parameters": { "type": "object", "properties": {}, "required": [] } } }
05

구현 예시

OpenAI와 Claude API 사용법

OpenAI API 사용 예시

Python
from openai import OpenAI
import json

client = OpenAI()

# 1. Tool 정의
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string"}
                },
                "required": ["city"]
            }
        }
    }
]

# 2. 실제 함수 구현
def get_weather(city):
    # 실제로는 외부 API 호출
    return {"temp": 15, "condition": "Sunny"}

# 3. LLM 호출
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "서울 날씨 알려줘"}],
    tools=tools
)

# 4. Tool Call 처리
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)

    # 5. 실제 함수 실행
    result = get_weather(**args)

    # 6. 결과를 LLM에게 전달
    final_response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "user", "content": "서울 날씨 알려줘"},
            response.choices[0].message,
            {
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(result)
            }
        ]
    )

Claude (Anthropic) API 사용 예시

Python
import anthropic

client = anthropic.Anthropic()

# Tool 정의 (Claude 형식)
tools = [
    {
        "name": "get_weather",
        "description": "지정된 도시의 현재 날씨를 조회합니다",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "도시 이름"
                }
            },
            "required": ["city"]
        }
    }
]

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[
        {"role": "user", "content": "서울 날씨 어때?"}
    ]
)

# stop_reason이 "tool_use"인지 확인
if response.stop_reason == "tool_use":
    tool_use = response.content[1]  # tool_use block
    # tool_use.name, tool_use.input 사용
06

Best Practices

효과적이고 안전한 Tool Use를 위한 가이드

01
명확한 설명 작성
description에 언제, 왜 이 도구를 사용해야 하는지 명확히 기술하세요. LLM은 이 설명을 보고 도구 선택을 결정합니다.
02
단일 책임 원칙
각 도구는 하나의 명확한 작업만 수행하도록 설계하세요. 복잡한 작업은 여러 도구로 분리합니다.
03
필수 파라미터 최소화
required 파라미터는 꼭 필요한 것만 지정하고, 나머지는 합리적인 기본값을 제공하세요.
!
입력 검증 필수
LLM이 생성한 인자를 맹신하지 마세요. 항상 타입 검증과 범위 확인을 수행합니다.
!
권한 제어
위험한 작업(삭제, 결제 등)은 추가 확인 절차를 거치거나 별도 권한 체크를 구현하세요.
X
무한 루프 방지
최대 반복 횟수를 설정하여 무한 Tool Call 루프를 방지하세요. 비용과 시간 제한도 설정합니다.
보안 주의사항

Function Calling을 통해 실행되는 코드는 LLM의 출력에 의존합니다. SQL Injection, Command Injection 등의 공격에 취약할 수 있으므로, 모든 입력을 철저히 검증하고 sanitize 해야 합니다.

SUMMARY

핵심 요약

  • Function Calling은 LLM이 외부 도구/함수를 호출할 수 있게 해주는 기능
  • LLM은 함수를 직접 실행하지 않고, JSON 형태의 호출 요청만 생성
  • Tool 정의 시 description을 상세하게 작성하는 것이 중요
  • OpenAI, Claude, Gemini, Mistral 등 주요 Provider가 지원
  • 보안: 입력 검증, 권한 제어, 무한 루프 방지 필수