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

# Create Chat Completion

> OpenAI 호환 요청 및 응답 형식으로 채팅 모델을 호출합니다.

**엔드포인트:** `POST /chat/completions`

대부분의 모델 API 연동은 이 인터페이스를 사용해야 합니다. 요청 본문에 `model`과 `messages`가 포함되면 YouRouter는 OpenAI 호환 completion 응답을 반환합니다. 시각 기능을 지원하는 모델의 경우 `messages[].content`에 이미지 입력을 포함할 수 있습니다.

## 요청

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": "Reply with exactly: connected"
      }
    ]
  }'
```

## OpenAI SDK

<CodeGroup>
  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["YOUROUTER_API_KEY"],
      base_url="https://api.yourouter.ai/v1",
  )

  completion = client.chat.completions.create(
      model="gpt-4o",
      messages=[{"role": "user", "content": "Reply with exactly: connected"}],
  )

  print(completion.choices[0].message.content)
  ```

  ```javascript Node.js theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: process.env.YOUROUTER_API_KEY,
    baseURL: 'https://api.yourouter.ai/v1',
  });

  const completion = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Reply with exactly: connected' }],
  });

  console.log(completion.choices[0].message.content);
  ```
</CodeGroup>

## 요청 헤더

| 헤더              | 필수  | 설명                                                                            |
| --------------- | --- | ----------------------------------------------------------------------------- |
| `Authorization` | 예   | `Bearer <YOUROUTER_API_KEY>`                                                  |
| `Content-Type`  | 예   | `application/json`을 사용합니다.                                                    |
| `vendor`        | 아니오 | `auto` 사용 또는 생략 시 자동 라우팅. `openai`, `anthropic`, `google` 등으로 상위를 고정할 수 있습니다. |

## 요청 본문 매개변수

<ResponseField name="model" type="string" required>
  호출할 모델 ID(예: `gpt-4o`, `claude-sonnet-4-20250514`, `gemini-2.5-flash`).
</ResponseField>

<ResponseField name="messages" type="array" required>
  순서가 있는 대화 메시지 배열. 각 메시지는 `role`과 `content`를 포함합니다.
</ResponseField>

<ResponseField name="stream" type="boolean" default="false">
  true이면 SSE 조각으로 결과를 반환합니다.
</ResponseField>

<ResponseField name="temperature" type="number">
  모델이 지원할 때 출력 무작위성을 조절합니다.
</ResponseField>

<ResponseField name="max_tokens" type="integer">
  모델이 지원할 때 출력 토큰 수를 제한합니다.
</ResponseField>

<ResponseField name="tools" type="array">
  함수 호출 또는 도구 호출을 지원하는 모델에 도구 정의를 전달합니다.
</ResponseField>

## 멀티모달 이미지 입력

시각을 지원하는 모델의 경우 `content`를 블록 배열로 설정하고 최소 하나의 `text` 블록과 하나의 `image_url` 블록을 포함하세요.

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Describe this image in one sentence."
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/image.jpg"
            }
          }
        ]
      }
    ]
  }'
```

비공개 이미지에는 base64 data URL을 사용할 수 있습니다.

```json theme={null}
{
  "type": "image_url",
  "image_url": {
    "url": "data:image/jpeg;base64,<BASE64_IMAGE>"
  }
}
```

### PDF 파일 입력

대상 모델과 상위 제공업체가 OpenAI 호환 파일 콘텐츠 블록을 지원하는 경우 `messages[].content`에 PDF를 전달할 수 있습니다. `file_data` 값은 PDF 원본 바이트를 base64로 인코딩한 값이어야 합니다.

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "file",
            "file": {
              "filename": "document.pdf",
              "file_data": "<BASE64_PDF>"
            }
          },
          {
            "type": "text",
            "text": "Extract a summary and key conclusions from this PDF."
          }
        ]
      }
    ]
  }'
```

<Note>
  PDF 입력은 모든 모델에서 지원되는 것은 아닙니다. Gemini 네이티브 또는 Claude 네이티브 PDF 동작이 필요하면 [멀티모달 가이드](/ko/guides/multimodal)의 provider-native 예시를 참고하세요.
</Note>

Gemini 네이티브 및 Claude 네이티브 형식 예시는 [멀티모달 가이드](/ko/guides/multimodal)를 참고하세요.

## 응답

성공 응답은 OpenAI Chat Completions 구조를 따릅니다.

```json theme={null}
{
  "id": "chatcmpl_example",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "connected"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 1,
    "total_tokens": 13
  }
}
```

어시스턴트 텍스트는 보통 다음 위치에 있습니다.

```text theme={null}
choices[0].message.content
```

## 제공업체 라우팅

기본적으로 자동 라우팅입니다.

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

제공업체를 고정하려면 `vendor`를 보냅니다.

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "vendor: openai" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

## 스트리밍

`stream`을 `true`로 설정하면 SSE로 증분 결과를 반환합니다.

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "stream": true,
    "messages": [
      {
        "role": "user",
        "content": "Explain model routing in two sentences."
      }
    ]
  }'
```

## 일반적인 오류

| 상태 코드 | 원인                      | 확인 사항                                |
| ----- | ----------------------- | ------------------------------------ |
| `400` | 본문이 잘못되었거나 지원하지 않는 매개변수 | `model`, `messages`, JSON 형식을 확인하세요. |
| `401` | API 키가 없거나 잘못됨          | `Authorization` 헤드를 확인하세요.           |
| `429` | 제공업체 속도 제한 또는 동시성 제한    | 백오프로 재시도하거나 자동 라우팅으로 전환하세요.          |
| `500` | 게이트웨이 또는 상위 제공업체 오류     | 안전하게 재시도하고 지원을 위해 요청 ID를 보관하세요.      |

모델 ID와 제공업체 고정에 대한 더 많은 예시는 [모델](/ko/model)과 [라우팅 가이드](/ko/guides/router)를 참고하세요.
