🤖 AI/ML

Function Calling

Function Calling

The ability of an LLM to perform tasks by calling external functions/APIs. Core to AI agents.

📖 Detailed Explanation

Function Calling is a capability in which an LLM (large language model) analyzes natural language input and selects and calls an appropriate external function or API. The model does not execute code directly; instead, it outputs in JSON format which function should be called with which parameters.

Since OpenAI first introduced it in GPT-3.5/4 in 2023, it has become a standard feature across Google Gemini, Anthropic Claude, and even open-source models. This is because AI agents must interact with the outside world in order to perform real tasks.

The principle of operation is simple: when a developer defines a schema (name, description, parameters) for the available functions, the LLM analyzes the user's request and determines the appropriate function and arguments. The developer takes this output, executes the actual function, and passes the result back to the LLM.

In practice, Function Calling is at the core of every AI agent implementation, such as a chatbot querying a reservation system, an AI assistant sending an email, or a data analysis bot querying a DB. As of 2025, it is combined with RAG and MCP (Model Context Protocol) to build even more powerful agent systems.

💻 Code Example

# OpenAI Function Calling 예제
from openai import OpenAI
import json

client = OpenAI()

# 1. 사용 가능한 함수 정의 (스키마)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "특정 도시의 현재 날씨를 조회합니다",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "도시 이름 (예: 서울)"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["city"]
            }
        }
    }
]

# 2. LLM에게 사용자 요청 전달
response = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[{"role": "user", "content": "서울 날씨 알려줘"}],
    tools=tools,
    tool_choice="auto"  # LLM이 자동으로 함수 호출 결정
)

# 3. Function Call 결과 확인
tool_call = response.choices[0].message.tool_calls[0]
print(f"호출할 함수: {tool_call.function.name}")
print(f"전달할 인자: {tool_call.function.arguments}")
# 출력: 호출할 함수: get_weather
# 출력: 전달할 인자: {"city": "서울", "unit": "celsius"}

# 4. 실제 함수 실행 후 결과를 LLM에게 다시 전달
def get_weather(city: str, unit: str = "celsius") -> dict:
    # 실제로는 API 호출
    return {"temp": 15, "condition": "맑음", "city": city}

result = get_weather(**json.loads(tool_call.function.arguments))
# 이 결과를 다시 대화에 추가하여 자연스러운 응답 생성

🗣️ Say It Like This in Practice

💬 In a Meeting
"We designed this chatbot with Function Calling to handle order lookup, delivery tracking, and even refund requests all at once. It integrates with the existing REST API as is, so it can be done without any backend changes."
💬 In an Interview
"The key point of Function Calling is that the LLM decides 'which function to call with which arguments,' while the actual execution is controlled by the developer. This separation is what makes security and error handling possible."
💬 In a Technical Discussion
"You can think of MCP (Model Context Protocol) as a standardization of Function Calling. Multiple LLMs can share the same toolset, so you can build agents without vendor lock-in."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Writing function schema descriptions carelessly

The LLM decides whether to call a function based on the function description (description). Accuracy improves when you write specifically, such as "Retrieves the order history for the last 30 days by user ID," rather than "Retrieve data."

❌
Executing LLM output immediately without validation

The LLM may call incorrect parameters or functions that do not exist. Always execute only after allowlist validation and parameter type checking.

✅
The right way: add the function execution result back into the conversation

After a Function Call, you must pass the result back with role: "tool" so that the LLM can generate a natural response. If you skip this step, you make the mistake of showing only JSON to the user.

🔗 Related Terms

📚 Learn More