> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crazyrouter.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Function Calling

> Python으로 구현하는 Function Calling 전체 예제

> 업데이트: 2026-06-06

## 개요

Function Calling은 모델이 사용자가 정의한 함수를 호출하여 외부 시스템과 상호작용할 수 있게 합니다. 모델은 함수를 직접 실행하지 않고, 함수명과 파라미터를 반환하며, 사용자의 코드가 이를 실행한 후 결과를 모델에 다시 전달합니다.

## 전체 예제

```python theme={null}
import json
from openai import OpenAI

client = OpenAI(api_key="sk-xxx", base_url="https://api.crazyrouter.com/v1")

# 1. 도구 정의
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "지정한 도시의 날씨 정보를 가져옵니다",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "도시명, 예: 베이징"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "온도 단위"
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_products",
            "description": "상품을 검색합니다",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "검색 키워드"},
                    "max_price": {"type": "number", "description": "최고 가격"}
                },
                "required": ["query"]
            }
        }
    }
]

# 2. 함수 구현 모의
def get_weather(city, unit="celsius"):
    return {"city": city, "temperature": 22, "unit": unit, "condition": "맑음"}

def search_products(query, max_price=None):
    return [{"name": f"{query} 상품A", "price": 99}, {"name": f"{query} 상품B", "price": 199}]

# 3. 대화 루프
messages = [{"role": "user", "content": "베이징 오늘 날씨 어때? 우산도 좀 검색해줘"}]

response = client.chat.completions.create(
    model="gpt-5.5",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

message = response.choices[0].message

# 4. 도구 호출 처리
if message.tool_calls:
    messages.append(message)

    for tool_call in message.tool_calls:
        func_name = tool_call.function.name
        args = json.loads(tool_call.function.arguments)

        if func_name == "get_weather":
            result = get_weather(**args)
        elif func_name == "search_products":
            result = search_products(**args)

        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result, ensure_ascii=False)
        })

    # 5. 최종 응답 받기
    final = client.chat.completions.create(
        model="gpt-5.5",
        messages=messages,
        tools=tools
    )
    print(final.choices[0].message.content)
```

## 특정 함수 강제 호출

```python theme={null}
response = client.chat.completions.create(
    model="gpt-5.5",
    messages=messages,
    tools=tools,
    tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
```

## 지원 모델

현재 문서의 OpenAI 호환 Function Calling 예제에서는 다음 검증된 모델을 우선 사용하는 것을 권장합니다:

* `gpt-5.5`

<Note>
  `gpt-5.5`의 도구 호출은 2026년 3월 23일 Crazyrouter 프로덕션 환경에서 실측이 완료되었습니다. 다른 제조사 모델의 도구 호출 기능은 연동 형식과 지원 세부사항이 다를 수 있으므로 각 전용 페이지를 우선 참고하십시오.
</Note>
