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

# OpenAI 네이티브 형식(ChatCompletions)

> OpenAI 호환 범용 텍스트 채팅 API

## 소개

OpenAI 호환 대규모 언어 모델을 사용해 대화형 응답을 생성하는 범용 텍스트 채팅 API입니다. 통합 API 인터페이스를 통해 OpenAI, Claude, DeepSeek, Grok, Tongyi Qianwen 등 여러 주요 대형 모델을 호출할 수 있습니다.

## 인증

<ParamField header="Authorization" type="string" required>
  Bearer Token, 예: `Bearer sk-xxxxxxxxxx`
</ParamField>

## 요청 매개변수

<ParamField body="model" type="string" required>
  모델 식별자, 지원 모델:

  * OpenAI 시리즈: `gpt-5.5`, `gpt-5.4`, `gpt-5.4-pro`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-4o` 등
  * Claude 시리즈: `claude-opus-4-8`, `claude-opus-4-7`, `claude-opus-4-6`, `claude-sonnet-4-5-20250929`, `claude-haiku-4-5-20251001` 등
  * DeepSeek 시리즈: `deepseek-v4-pro`, `deepseek-v4-flash`, `deepseek-v3-1-250821`, `deepseek-v3`, `deepseek-r1` 등
  * Grok 시리즈: `grok-4`, `grok-4-fast-reasoning`, `grok-3` 등
  * Gemini 시리즈: `gemini-3.1-pro-preview`, `gemini-3-pro-preview`, `gemini-3-flash-preview`, `nano-banana-pro` 및 `-thinking/-nothinking` / `-thinking-<budget>` / `-thinking-low/-thinking-high` 변형
  * 국산 모델: `glm-5`, `glm-4.7`, `doubao-seed-1-8-251228` (Doubao Seed 시리즈), `qwen3-coder-plus`, `kimi-k2.5` 등
</ParamField>

<ParamField body="messages" type="array" required>
  대화 메시지 목록, 각 요소는 `role`(user/system/assistant)과 `content`를 포함합니다
</ParamField>

<ParamField body="temperature" type="number" default="0.7">
  무작위성 제어, 0-2 범위, 값이 높을수록 응답이 더 무작위적입니다
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  스트리밍 출력 사용 여부, SSE 형식의 청크 데이터를 반환합니다
</ParamField>

<ParamField body="max_tokens" type="number">
  생성할 최대 토큰 수, 응답 길이를 제어합니다
</ParamField>

<ParamField body="top_p" type="number">
  핵 샘플링 매개변수, 0-1 범위, 생성 다양성을 제어합니다
</ParamField>

## 기본 예시

<Tabs>
  <Tab title="비스트리밍 요청">
    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "glm-5",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant"},
          {"role": "user", "content": "Briefly introduce artificial intelligence"}
        ],
        "temperature": 0.7
      }'
    ```
  </Tab>

  <Tab title="스트리밍 요청 (SSE)">
    ```bash theme={null}
    curl -N -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "doubao-seed-1-8-251228",
        "stream": true,
        "messages": [
          {"role": "system", "content": "You are a helpful assistant"},
          {"role": "user", "content": "Briefly introduce artificial intelligence"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Python Example">
    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.gravitex.ai/v1"
    )

    # Non-streaming
    completion = client.chat.completions.create(
        model="glm-5",
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": "Briefly introduce artificial intelligence"}
        ],
        temperature=0.7
    )
    print(completion.choices[0].message.content)

    # Streaming
    stream = client.chat.completions.create(
        model="doubao-seed-1-8-251228",
        messages=[
            {"role": "user", "content": "Briefly introduce artificial intelligence"}
        ],
        stream=True
    )
    for chunk in stream:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")
    ```
  </Tab>
</Tabs>

<ResponseExample>
  ```json theme={null}
  {
    "id": "chatcmpl-xxx",
    "object": "chat.completion",
    "created": 1234567890,
    "model": "glm-5",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Artificial intelligence is a branch of computer science that aims to create intelligent machines..."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 100,
      "total_tokens": 125
    }
  }
  ```
</ResponseExample>

## 고급 기능

### 도구 호출 (Functions / Tools)

GPT, Claude, DeepSeek, Grok, Tongyi Qianwen 등의 모델에 적용 가능한 OpenAI 호환 도구 호출 형식을 지원합니다.

<Tabs>
  <Tab title="1단계: 모델이 도구 호출 반환">
    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "glm-5",
        "messages": [
          {"role": "user", "content": "What'\''s the weather in Shanghai?"}
        ],
        "tools": [
          {
            "type": "function",
            "function": {
              "name": "get_weather",
              "description": "Get weather information by city",
              "parameters": {
                "type": "object",
                "properties": {
                  "city": {"type": "string"}
                },
                "required": ["city"]
              }
            }
          }
        ],
        "tool_choice": "auto"
      }'
    ```
  </Tab>

  <Tab title="2단계: 도구 실행 결과 반환">
    모델이 `tool_calls`를 반환한 후에는 도구를 실행하고 결과를 모델에 다시 전달해야 합니다:

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "glm-5",
        "messages": [
          {"role": "user", "content": "What'\''s the weather in Shanghai?"},
          {
            "role": "assistant",
            "tool_calls": [
              {
                "id": "call_xxx",
                "type": "function",
                "function": {
                  "name": "get_weather",
                  "arguments": "{\"city\":\"Shanghai\"}"
                }
              }
            ]
          },
          {
            "role": "tool",
            "tool_call_id": "call_xxx",
            "content": "{\"temp\":\"22°C\",\"condition\":\"Cloudy\",\"aqi\":53}"
          }
        ]
      }'
    ```

    <Note>
      * `tool_call_id`는 1단계에서 반환된 ID와 일치해야 합니다
      * 도구 실행이 실패하면 읽을 수 있는 오류 정보를 반환하여 이후 완성이 차단되지 않도록 합니다
      * 2단계에서도 스트리밍 출력을 지원합니다
    </Note>
  </Tab>
</Tabs>

### 구조화된 출력 (JSON Schema)

`response_format` 매개변수를 통해 출력 형식을 제어할 수 있으며, GPT, Claude, Grok 등의 모델에 적용됩니다.

```bash theme={null}
curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "model": "doubao-seed-1-8-251228",
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "Answer",
        "schema": {
          "type": "object",
          "properties": {
            "summary": {"type": "string"}
          },
          "required": ["summary"]
        }
      }
    },
    "messages": [
      {"role": "user", "content": "Return a JSON containing a summary field"}
    ]
  }'
```

<Tip>
  엄격한 구조화된 출력이 필요한 경우 `temperature` 값을 낮추는 것(예: 0.1-0.3)과 적절한 `max_tokens` 설정을 권장하여 일관성을 높입니다.
</Tip>

### 사고(Thinking) 기능

일부 모델은 사고(Thinking/Reasoning) 기능을 지원하여, 응답 생성 시 추론 과정을 표시할 수 있습니다. 모델마다 구현 방식이 다릅니다:

<Tabs>
  <Tab title="DeepSeek">
    DeepSeek 모델은 `thinking` 필드를 통해 사고 기능을 활성화할 수 있습니다:

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "deepseek-v3-1-250821",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant"},
          {"role": "user", "content": "Give a medium-difficulty geometry problem and solve it step by step"}
        ],
        "thinking": {"type": "enabled"}
      }'
    ```

    <Note>
      * 기본 `thinking.type`은 `"disabled"`이며, 활성화하려면 `"enabled"`로 명시적으로 설정해야 합니다
      * 사고 기능의 출력 형태는 모델 버전에 따라 다를 수 있습니다
      * 더 나은 대화형 경험을 위해 `stream: true`와 함께 사용하는 것을 권장합니다
    </Note>
  </Tab>

  <Tab title="Tongyi Qianwen">
    Tongyi Qianwen은 심층 사고 기능을 지원하며, 스트리밍 출력이 필요합니다:

    ```bash theme={null}
    curl -N -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3-omni-flash",
        "stream": true,
        "enable_thinking": true,
        "parameters": {
          "incremental_output": true
        },
        "messages": [
          {"role": "system", "content": "You are an excellent mathematician"},
          {"role": "user", "content": "What is the formula for Tower of Hanoi"}
        ]
      }'
    ```

    **추론 과정을 content에 인라인 삽입**:

    클라이언트가 `reasoning_content`를 표시하지 않는 경우, `gravitex_thinking_to_content: true`를 사용하여 추론 내용을 `content`에 인라인으로 삽입할 수 있습니다:

    ```bash theme={null}
    curl -N -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3-omni-flash",
        "stream": true,
        "enable_thinking": true,
        "gravitex_thinking_to_content": true,
        "parameters": {
          "incremental_output": true
        },
        "messages": [
          {"role": "user", "content": "What is the formula for Tower of Hanoi"}
        ]
      }'
    ```

    <Warning>
      Tongyi Qianwen의 심층 사고 기능은 반드시 `stream: true`와 함께 사용해야 합니다. `enable_thinking: true`를 설정했지만 `stream: false`인 경우, 업스트림 오류를 방지하기 위해 시스템이 자동으로 심층 사고를 비활성화합니다.
    </Warning>
  </Tab>

  <Tab title="Gemini">
    Gemini OpenAI 호환 전체 문서(필드 매핑, `extra_body`, 사용량, thinking)는 [Gemini OpenAI 형식(Chat)](/ko/api-reference/endpoint/gemini-chat-openai)을 참조하세요. 빠른 참조:

    * **모델 접미사**: `-thinking`(자동 예산); `-thinking-<number>` 정밀 예산(예: `gemini-2.5-flash-thinking-8192`); `-nothinking` 비활성화; `gemini-3-pro-preview-thinking-low/high`로 레벨 직접 지정
    * **extra\_body 설정**: `extra_body.google.thinking_config.thinking_budget` + `include_thoughts`; 특수 값: `-1` 자동 활성화, `0` 비활성화, `>0` 특정 예산; `stream: true` 필요
    * **reasoning\_effort**: `-thinking` 사용 시 `max_tokens`가 설정되지 않은 경우 사용 가능(`low/medium/high` ≈ 예산의 20%/50%/80%)
    * **Gemini 3 Pro Preview**: `thinking_level`(`LOW`/`HIGH`, 기본값 HIGH) 사용, 검색과 조합 가능
    * **검색 활성화**: 권장 OpenAI 호환 도구 `"tools":[{"type":"function","function":{"name":"googleSearch"}}]`; 또는 `extra_body.google.tools:[{"googleSearch":{}}]`로 전달
    * **참고**: thinking 어댑터는 서버 측에서 활성화되어야 합니다; thinking 예산은 출력 토큰에 포함됩니다; `reasoning_content`를 보려면 `stream: true`를 사용하세요

    예시(2.5, 특정 예산):

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gemini-3-flash-preview",
        "messages": [
          {"role":"user","content":"Give a medium-difficulty geometry problem and analyze it step by step."}
        ],
        "extra_body": {
          "google": {
            "thinking_config": { "thinking_budget": 6000, "include_thoughts": true }
          }
        },
        "stream": true
      }'
    ```

    예시(3 Pro Preview thinking + 검색):

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gemini-3-pro-preview",
        "messages": [
          {"role":"user","content":"Google search the weather in Guangzhou today"}
        ],
        "generationConfig": {
          "thinkingConfig": { "thinkingLevel": "LOW" }
        },
        "tools": [
          { "type": "function", "function": { "name": "googleSearch" } }
        ],
        "stream": true
      }'
    ```
  </Tab>
</Tabs>

### Tongyi Qianwen 확장 기능

Tongyi Qianwen 모델은 검색, 음성 인식 등의 확장 기능을 지원합니다. 모든 확장 매개변수는 `parameters` 객체에 넣어야 합니다.

<Tabs>
  <Tab title="검색 기능">
    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3-omni-flash",
        "messages": [
          {"role": "user", "content": "Please first search for recent common misconceptions about Fermat'\''s Last Theorem, then answer"}
        ],
        "stream": true,
        "enable_thinking": true,
        "parameters": {
          "enable_search": true,
          "search_options": {
            "region": "CN",
            "recency_days": 30
          },
          "incremental_output": true
        }
      }'
    ```
  </Tab>

  <Tab title="음성 인식">
    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3-omni-flash",
        "messages": [
          {"role": "user", "content": "Hello"}
        ],
        "parameters": {
          "asr_options": {
            "language": "zh"
          }
        }
      }'
    ```
  </Tab>
</Tabs>

<Note>
  Tongyi Qianwen의 모든 확장 매개변수(`enable_search`, `search_options`, `asr_options`, `temperature`, `top_p` 등)는 요청 본문 최상위가 아닌 `parameters` 객체에 넣어야 합니다.
</Note>

### 웹 검색 기능

일부 모델은 실시간 웹 검색을 지원하여 최신 정보에 접근하고 응답에 인용 출처를 포함할 수 있습니다.

<Tabs>
  <Tab title="Claude 웹 검색">
    Claude 모델은 `web_search_options` 매개변수로 웹 검색 기능을 활성화할 수 없으므로, 도구 호출을 통해서만 구현할 수 있으며 네트워크 및 프롬프트 이유로 불안정할 수 있습니다. 자세한 내용은 위의 도구 호출(Functions / Tools)을 참조하세요.

    **기본 예시**(도구 호출 흐름 표시):

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "glm-5",
        "messages": [
          {"role": "user", "content": "What are the latest news about artificial intelligence?"},
          {
            "role": "assistant",
            "content": "I'\''ll help you search for the latest news about artificial intelligence.",
            "tool_calls": [
              {
                "id": "toolu_xxx",
                "type": "function",
                "function": {
                  "name": "WebSearch",
                  "arguments": "{\"query\": \"artificial intelligence latest news 2025\"}"
                }
              }
            ]
          },
          {
            "role": "tool",
            "tool_call_id": "toolu_xxx",
            "name": "WebSearch",
            "content": "Web search results for query: \"artificial intelligence latest news 2025\"..."
          }
        ],
        "web_search_options": {
          "search_context_size": "medium"
        }
      }'
    ```

    **위치 정보 포함 예시**(도구 호출 흐름 표시):

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "glm-5",
        "messages": [
          {"role": "user", "content": "What'\''s the weather in Shanghai today?"},
          {
            "role": "assistant",
            "content": "I'\''ll help you search for today'\''s weather in Shanghai.",
            "tool_calls": [
              {
                "id": "toolu_xxx",
                "type": "function",
                "function": {
                  "name": "WebSearch",
                  "arguments": "{\"query\": \"Shanghai today weather\"}"
                }
              }
            ]
          },
          {
            "role": "tool",
            "tool_call_id": "toolu_xxx",
            "name": "WebSearch",
            "content": "Web search results for query: \"Shanghai today weather\"..."
          }
        ],
        "web_search_options": {
          "search_context_size": "medium",
          "user_location": {
            "approximate": {
              "timezone": "Asia/Shanghai",
              "country": "CN",
              "region": "Shanghai",
              "city": "Shanghai"
            }
          }
        }
      }'
    ```

    <Note>
      * 검색 기능은 응답 시간과 토큰 소비(검색 결과 내용 포함)를 증가시킵니다
      * 검색 결과는 응답에 인용 출처가 자동으로 포함됩니다
      * 지원 모델: Claude Sonnet 4, Claude 3 Opus 등
      * 다중 턴 대화에서 도구 호출과 결과는 메시지 기록에 표시되며, 모델은 이전 검색 결과를 바탕으로 대화를 이어갈 수 있습니다
    </Note>

    <Note type="warning">
      **안정성 안내**:

      * 웹 검색 기능은 업스트림 프록시 서비스 및 외부 검색 서비스에 의존하며, 다음과 같은 불안정성이 있을 수 있습니다:
        * **네트워크 변동**: 네트워크 연결 문제로 검색 요청이 타임아웃되거나 실패할 수 있습니다
        * **서비스 제한**: 검색 서비스에 속도 제한, 타임아웃 제한 또는 일시적 사용 불가가 있을 수 있습니다
        * **검색 결과 품질**: 일부 쿼리는 관련 정보를 찾지 못하거나 검색 결과 품질이 낮을 수 있습니다
        * **모델 판단**: 모델은 질문에 따라 검색 필요 여부를 자동으로 판단하며, 일부 경우 검색이 트리거되지 않을 수 있습니다
      * 이는 웹 검색 기능의 고유한 특성입니다. 다음을 권장합니다:
        * 중요한 시나리오에서 재시도 메커니즘 구현
        * 검색 실패 시 우아한 성능 저하 처리(예: 모델의 지식 베이스로 답변)
        * 실시간성이 매우 높은 시나리오에서 웹 검색에 전적으로 의존하지 않기
    </Note>
  </Tab>

  <Tab title="Grok 실시간 검색">
    Grok 모델은 `search_parameters` 매개변수를 통해 실시간 검색을 지원합니다.

    <ParamField body="search_parameters" type="object">
      검색 매개변수 설정

      * `mode` (선택): 검색 모드, 옵션:
        * `"off"`: 검색 비활성화
        * `"auto"`: 모델이 검색 필요 여부를 자동 판단(권장)
        * `"on"`: 검색 강제 사용
      * `return_citations` (선택): 응답에 인용 링크 반환 여부, 기본값 `true`
    </ParamField>

    **기본 예시**:

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "grok-4",
        "messages": [
          {"role": "user", "content": "What are the latest developments in AI in 2026?"}
        ],
        "search_parameters": {
          "mode": "auto"
        }
      }'
    ```

    **검색 강제 예시**:

    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "grok-4",
        "messages": [
          {"role": "user", "content": "What are the latest tech news?"}
        ],
        "search_parameters": {
          "mode": "on",
          "return_citations": true
        }
      }'
    ```

    **Python Example**:

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

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.gravitex.ai/v1"
    )

    completion = client.chat.completions.create(
        model="grok-4",
        messages=[
            {"role": "user", "content": "What are the latest developments in AI in 2026?"}
        ],
        extra_body={
            "search_parameters": {
                "mode": "auto"
            }
        }
    )
    print(completion.choices[0].message.content)
    ```

    <Note>
      * 모델이 검색 필요 여부를 자동 판단하도록 `"auto"` 모드 사용을 권장합니다
      * 검색 기능은 응답 시간을 증가시키지만 최신 실시간 정보에 접근할 수 있습니다
      * 지원 모델: `grok-4`, `grok-3` 시리즈 등
      * 검색 결과는 응답에 인용 출처가 포함됩니다
    </Note>
  </Tab>
</Tabs>

### GPT 파일 입력 (Responses API)

GPT-5 등의 모델은 파일 입력 기능을 지원하며, `/v1/chat/completions`가 아닌 `/v1/responses` 엔드포인트를 통해 호출해야 합니다.

<Tabs>
  <Tab title="파일 URL로 업로드">
    외부 URL을 연결하여 PDF 파일을 업로드할 수 있습니다:

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

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.gravitex.ai/v1/responses?api-version=2025-03-01-preview"
    )

    response = client.responses.create(
        model="gpt-5.2",
        input=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_text",
                        "text": "Analyze this letter and summarize its key points"
                    },
                    {
                        "type": "input_file",
                        "file_url": "https://www.example.com/document.pdf"
                    }
                ]
            }
        ]
    )
    print(response.output_text)
    ```
  </Tab>

  <Tab title="Base64 인코딩으로 업로드">
    Base64로 인코딩된 입력으로 전송:

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

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.gravitex.ai/v1"
    )

    with open("document.pdf", "rb") as f:
        data = f.read()

    base64_string = base64.b64encode(data).decode("utf-8")

    response = client.responses.create(
        model="gpt-5.2",
        input=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_file",
                        "filename": "document.pdf",
                        "file_data": f"data:application/pdf;base64,{base64_string}"
                    },
                    {
                        "type": "input_text",
                        "text": "What is the main content of this document?"
                    }
                ]
            }
        ]
    )
    print(response.output_text)
    ```
  </Tab>
</Tabs>

<Note>
  * 파일 크기 제한: 단일 파일 50MB 이하, 단일 요청의 모든 파일 총 크기 50MB 이하
  * 지원 모델: `gpt-4o`, `gpt-4o-mini`, `gpt-5-chat` 및 텍스트·이미지 입력을 지원하는 기타 모델
</Note>

### Grok 추론(Reasoning) 기능

Grok 모델(특히 `grok-4-fast-reasoning`)은 추론 기능을 지원합니다. 활성화 시 `usage.completion_tokens_details.reasoning_tokens`에 추론 과정에서 소비된 토큰 수가 표시됩니다. 자세한 내용은 아래 [usage 필드 설명](#usage-필드-설명)을 참고하세요.

## usage 필드 설명

`/v1/chat/completions` 호출 시 응답의 `usage` 객체에 토큰 사용량 통계가 포함됩니다. 먼저 **공통 필드**(일반 대화 모델 시나리오)를 설명하고, 특정 시나리오에서만 0이 아닌 값이 나타나는 **전용 필드**를 설명합니다.

### 공통 필드

적용 범위: GPT 시리즈, Claude 대화/사고 모델, Gemini, DeepSeek 등 `/v1/chat/completions`를 통한 텍스트 대화 시나리오. 게이트웨이가 내부적으로 Claude Messages 프로토콜 또는 이미지 생성 모델을 호출할 때만 나타나는 필드는 포함하지 않습니다 — [특수 시나리오 전용 필드](#특수-시나리오-전용-필드)를 참고하세요.

```json theme={null}
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1752345600,
  "model": "gpt-5.6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "모델의 응답 내용입니다"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 120,
    "completion_tokens": 85,
    "total_tokens": 205,

    "prompt_tokens_details": {
      "cached_tokens": 30,
      "cache_write_tokens": 5,
      "text_tokens": 0,
      "audio_tokens": 0,
      "image_tokens": 0
    },
    "completion_tokens_details": {
      "text_tokens": 0,
      "audio_tokens": 0,
      "image_tokens": 0,
      "reasoning_tokens": 42,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },

    "input_tokens": 120,
    "output_tokens": 85,
    "input_tokens_details": null
  }
}
```

| 필드                                                                                    | 값이 있는 경우                                                   | 설명                                                                                  |
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `prompt_tokens`                                                                       | 항상                                                         | 입력 토큰 총수                                                                            |
| `completion_tokens`                                                                   | 항상                                                         | 출력 토큰 총수                                                                            |
| `total_tokens`                                                                        | 항상                                                         | `prompt_tokens + completion_tokens`                                                 |
| `prompt_tokens_details.cached_tokens`                                                 | 모델/채널이 prompt caching을 지원할 때                               | 캐시 히트로 캐시 요금이 적용되는 입력 토큰 수(OpenAI 네이티브 캐시, Gemini 암시적 캐시, Claude 캐시 읽기 모두 이 필드에 반영) |
| `prompt_tokens_details.cache_write_tokens`                                            | GPT-5.6 이상, 명시적 prompt cache 활성화 시                         | 이번 요청에서 새로 캐시에 기록된 토큰 수, 캐시 기록 요금 적용                                                |
| `prompt_tokens_details.audio_tokens`                                                  | 오디오 입력 모델 사용 시(예: `gpt-4o-audio-preview`)                  | 입력 오디오 부분에서 소비된 토큰 수                                                                |
| `prompt_tokens_details.text_tokens` / `image_tokens`                                  | 대부분의 순수 텍스트 대화에서 `0`                                       | 입력 텍스트/이미지 토큰 분류, 순수 텍스트 대화에서는 보통 채워지지 않지만 필드 자체는 항상 존재                             |
| `completion_tokens_details.reasoning_tokens`                                          | 추론 모델만(GPT o1/o3/GPT-5 시리즈, Claude 확장 사고, Gemini thinking) | 내부 추론에 소비된 토큰 수, 최종 응답 텍스트에는 나타나지 않지만 출력 요금 적용                                      |
| `completion_tokens_details.audio_tokens`                                              | 오디오 출력 모델 사용 시                                             | 출력 오디오 부분에서 소비된 토큰 수                                                                |
| `completion_tokens_details.accepted_prediction_tokens` / `rejected_prediction_tokens` | OpenAI Predicted Outputs 사용 시                              | 예측 내용에 일치/불일치한 토큰 수, 불일치 부분도 출력 요금 적용                                               |
| `completion_tokens_details.text_tokens` / `image_tokens`                              | 순수 텍스트 대화에서 `0`                                            | 아래 「image\_tokens 관련」 참고                                                            |
| `input_tokens` / `output_tokens`                                                      | 항상                                                         | `prompt_tokens` / `completion_tokens`와 동일한 값, 일부 업스트림 프로토콜 호환용 별칭                   |
| `input_tokens_details`                                                                | 대화 시나리오에서 대부분 `null`                                       | 예약 필드, 일반 대화 요청에서는 채워지지 않음                                                          |

<Note>
  * `prompt_tokens_details` / `completion_tokens_details` 객체는 응답에 **항상 존재**하며, 내부 하위 필드가 모두 `0`이어도 생략되지 않습니다. `0`은 「미지원」이 아니라 「이번 요청에서 사용되지 않음」을 의미합니다.
  * `completion_tokens_details.image_tokens`(및 `prompt_tokens_details.image_tokens`)는 필드 구조가 항상 존재하기 때문에 공통 문서에 포함되지만, **0이 아닌 값은 특수 시나리오**(Claude/이미지 생성 모델)에서만 나타납니다. [특수 시나리오 전용 필드](#특수-시나리오-전용-필드)를 참고하세요.
  * `reasoning_tokens`는 모델 간 공통 개념입니다. 업스트림이 OpenAI 추론 모델, Claude 확장 사고, Gemini thinking 중 어느 것이든, 해당 호출에서 「사고」 기능이 활성화되면 이 단일 필드에 반영됩니다.
</Note>

### 특수 시나리오 전용 필드

다음 필드는 특정 경우에만 0이 아닌 값이 나타납니다. 요청은 `/v1/chat/completions`로 들어가지만, 게이트웨이가 내부적으로 다른 프로토콜(Claude Messages 프로토콜 / 이미지 생성 모델)로 변환해 업스트림을 호출하고, 변환된 `usage`에 「네이티브 프로토콜 전용」필드가 포함됩니다.

#### 시나리오 1: 내부적으로 Claude 호출 (`/v1/chat/completions` → `/v1/messages`)

OpenAI 형식으로 Claude 모델을 요청하면 게이트웨이가 요청을 Anthropic Messages 프로토콜로 변환하고, Claude의 `usage`를 OpenAI 형식으로 다시 변환합니다. Claude의 캐시 메커니즘은 OpenAI보다 세분화되어 있으며(5분/1시간 TTL 2단계 요금), 아래 전용 필드로 표현됩니다:

```json theme={null}
"usage": {
  "prompt_tokens": 120,
  "completion_tokens": 85,
  "total_tokens": 205,
  "prompt_tokens_details": {
    "cached_tokens": 30,
    "cached_creation_tokens": 10
  },
  "completion_tokens_details": {
    "reasoning_tokens": 42
  },
  "claude_cache_creation_5_m_tokens": 8,
  "claude_cache_creation_1_h_tokens": 2
}
```

| 필드                                             | 설명                                                                                                              |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `prompt_tokens_details.cached_creation_tokens` | Claude의 `cache_creation_input_tokens`에 해당: 이번 요청에서 prompt cache 기록을 위해 추가로 소비된 입력 토큰 수(이 총수가 아래 두 필드로 TTL별 분류됨) |
| `claude_cache_creation_5_m_tokens`             | 위 `cached_creation_tokens` 중 **5분** TTL 등급으로 캐시에 기록된 토큰 수                                                       |
| `claude_cache_creation_1_h_tokens`             | 위 `cached_creation_tokens` 중 **1시간** TTL 등급으로 캐시에 기록된 토큰 수(해당 등급 단가가 더 높음)                                      |

`prompt_tokens_details.cached_tokens`, `completion_tokens_details.reasoning_tokens`도 Claude 모델 호출 시 값이 있습니다(각각 Claude 캐시 읽기 토큰 수, 확장 사고 토큰 수에 해당). 하지만 이 두 필드는 모델 간 공통 필드로 [공통 필드](#공통-필드)에서 이미 설명했습니다.

#### 시나리오 2: 내부적으로 이미지 생성 모델 호출 (`/v1/chat/completions` → `/v1/images/generations` 의미)

일부 이미지 생성 모델(예: Gemini 네이티브 이미지 출력, `gpt-image` 시리즈)은 원래 공식 `/v1/images/generations` 인터페이스의 `usage` 구조(`input_tokens`/`output_tokens` + 모달리티 분류)를 사용합니다. 사용자가 `/v1/chat/completions`로 대화형 이미지 생성을 호출하면 게이트웨이가 이 정보를 chat 형식 `usage`에 매핑합니다:

```json theme={null}
"usage": {
  "prompt_tokens": 50,
  "completion_tokens": 1290,
  "total_tokens": 1340,
  "prompt_tokens_details": {
    "text_tokens": 50,
    "image_tokens": 0
  },
  "completion_tokens_details": {
    "text_tokens": 0,
    "image_tokens": 1290
  },
  "generated_images": 1
}
```

| 필드                                       | 설명                                                                                                       |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `completion_tokens_details.image_tokens` | 공식 `/v1/images/generations`의 이미지 출력 토큰 수, chat 형식으로 매핑 후 이 필드에 반영, 이미지 요금 비율(`ImageCompletionRatio`)로 과금 |
| `prompt_tokens_details.image_tokens`     | 입력에 이미지가 포함된 경우(예: 이미지 편집/이미지-투-이미지) 소비된 이미지 토큰 수                                                        |
| `generated_images`                       | 업스트림에서 실제 생성된 이미지 장수(장당 과금 모델은 토큰 수 대신 이 값으로 과금, 「4장 요청했지만 1장만 생성」 시 과다 과금 방지)                           |

#### 시나리오 3: 채널 프로토콜 차이로 인한 필드

다음 두 필드는 「변환」된 것이 아니라 특정 채널에서 업스트림 응답 필드를 그대로 전달한 것입니다. 주류 모델을 정상 사용하면 거의 만나지 않습니다:

| 필드                        | 발생 조건                                           | 설명                                                                                                                                                   |
| ------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt_cache_hit_tokens` | DeepSeek 채널, 업스트림이 DeepSeek 고유 필드명으로 캐시 정보 반환 시 | DeepSeek 공식 API는 캐시 히트를 `cached_tokens`가 아닌 `prompt_cache_hit_tokens`로 표현. 게이트웨이는 공통 `prompt_tokens_details.cached_tokens`에도 동기 매핑하지만 원본 필드도 최상위에 유지 |
| `cost`                    | OpenRouter 채널, 업스트림 응답에 USD 비용 포함 시             | OpenRouter 전용 필드, 일반 채널(공식 OpenAI/Claude/Gemini 등)에서는 나타나지 않음                                                                                        |

## 응답 형식

<Tabs>
  <Tab title="비스트리밍 응답">
    ```json theme={null}
    {
      "id": "chatcmpl-xxx",
      "object": "chat.completion",
      "created": 1234567890,
      "model": "glm-5",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Response content..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 25,
        "completion_tokens": 100,
        "total_tokens": 125
      }
    }
    ```

    `usage` 필드 전체 설명은 위 [usage 필드 설명](#usage-필드-설명)을 참고하세요.
  </Tab>

  <Tab title="스트리밍 응답">
    스트리밍 응답은 SSE(Server-Sent Events) 형식으로 반환되며, 각 청크에는 부분 내용이 포함됩니다:

    ```json theme={null}
    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"doubao-seed-1-8-251228","choices":[{"index":0,"delta":{"content":"回"},"finish_reason":null}]}

    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"doubao-seed-1-8-251228","choices":[{"index":0,"delta":{"content":"复"},"finish_reason":null}]}

    data: [DONE]
    ```

    마지막 청크에는 보통 `usage` 통계가 포함됩니다.
  </Tab>
</Tabs>

## 오류 처리

| 예외 유형               | 발생 시나리오               | 반환 메시지                                                   |
| ------------------- | --------------------- | -------------------------------------------------------- |
| AuthenticationError | 유효하지 않거나 권한 없는 API 키  | Error: Invalid or unauthorized API key                   |
| NotFoundError       | 모델이 존재하지 않거나 지원되지 않음  | Error: Model \[model] does not exist or is not supported |
| APIConnectionError  | 네트워크 중단 또는 서버 미응답     | Error: Cannot connect to API server                      |
| APIError            | 요청 형식 오류 및 기타 서버 측 예외 | API request failed: \[error details]                     |

## 지원 모델 시리즈

### OpenAI 시리즈

* GPT-5.5, GPT-5.4 family (5.4 / Pro / Mini / Nano), GPT-4o, GPT-4o Mini

### Claude 시리즈 (Anthropic)

* Claude Sonnet 4, Claude 3 Opus, Claude 3 Haiku

### DeepSeek 시리즈

* DeepSeek V3, DeepSeek R1

### Grok 시리즈 (xAI)

* Grok-4, Grok-3, Grok-3-fast, Grok-4-fast-reasoning

### Tongyi Qianwen 시리즈 (Qwen)

* Qwen3-omni-flash 등

### Doubao Seed 시리즈

* doubao-seed-1-8-251228 등

### 기타 모델

* Gemini 시리즈, GLM 시리즈(glm-5 포함), Kimi 시리즈 등

전체 모델 목록은 [모델 정보 페이지](/ko/api-reference/models)를 참조하세요.

## 참고 사항

<Note>
  * `messages` 목록에서 `system` 역할은 모델 동작을 설정하고, `user` 역할은 사용자 질문용입니다
  * 다중 턴 대화는 기록(`assistant` 역할 응답 포함)을 추가해야 합니다
  * `openai` 라이브러리 필요: `pip install openai`
  * 모델마다 특정 기능 지원 수준이 다를 수 있으므로, 사용 전 해당 모델 문서를 확인하는 것을 권장합니다
</Note>

<Tip>
  * 스트리밍 출력을 사용하면 첫 토큰 응답 시간과 대화형 경험을 개선할 수 있습니다
  * 도구 호출에는 모델 응답이 차단되지 않도록 적절한 타임아웃 및 재시도 메커니즘이 필요합니다
  * Tongyi Qianwen 확장 매개변수는 반드시 `parameters` 객체에 넣어야 합니다
</Tip>

## 관련 자료

<Columns cols={2}>
  <Card title="FAQ" icon="question-circle" href="/ko/faq/chat-completions">
    채팅 인터페이스 FAQ 보기
  </Card>

  <Card title="모델 목록" icon="list" href="/ko/api-reference/models">
    지원되는 모든 모델 정보 보기
  </Card>
</Columns>
