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

# Create a chat completion

지정된 채팅 대화에 대한 모델 응답 요청을 보냅니다. 스트리밍 및 비스트리밍 모드를 모두 지원합니다. OpenAI Chat Completions API 형식과 호환됩니다.

## 인증

<ParamField header="Authorization" type="string" required>
  Bearer 토큰. API 키를 Authorization 헤더의 Bearer 토큰으로 사용하세요.

  Format: `Bearer <SUNRA_KEY>`
</ParamField>

## 요청

이 엔드포인트는 JSON 객체를 받습니다.

<ParamField body="messages" type="object[]" required>
  대화의 메시지 목록.

  <Expandable title="속성">
    <ParamField body="role" type="string" required>
      메시지 작성자의 역할. 지원되는 값: `system`, `user`, `assistant`, `tool`.
    </ParamField>

    <ParamField body="content" type="string | object[]" required>
      메시지의 내용. 문자열 또는 멀티모달 입력을 위한 콘텐츠 파트 배열을 지정할 수 있습니다.
    </ParamField>

    <ParamField body="name" type="string">
      참여자의 선택적 이름. 동일한 역할의 참여자를 구분하기 위해 모델에 정보를 제공합니다.
    </ParamField>

    <ParamField body="tool_calls" type="object[]">
      함수 호출 등 모델이 생성한 도구 호출. `assistant` 메시지에만 존재합니다.
    </ParamField>

    <ParamField body="tool_call_id" type="string">
      이 메시지가 응답하는 도구 호출. `tool` 메시지에만 존재합니다.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="model" type="string" required>
  완성에 사용할 모델. 사용 가능한 모델은 [sunra.ai/models](https://sunra.ai/models)에서 확인하세요.
</ParamField>

<ParamField body="stream" type="boolean" default={false}>
  `true`로 설정하면 부분 메시지 델타가 서버 전송 이벤트(SSE)로 전송됩니다.
</ParamField>

<ParamField body="max_tokens" type="integer">
  완성에서 생성할 최대 토큰 수. 입력 토큰과 생성된 토큰의 총 길이는 모델의 컨텍스트 길이에 의해 제한됩니다.
</ParamField>

<ParamField body="temperature" type="number" default={1}>
  0에서 2 사이의 샘플링 온도. 0.8과 같은 높은 값은 출력을 더 무작위로 만들고, 0.2와 같은 낮은 값은 더 집중적이고 결정론적으로 만듭니다.
</ParamField>

<ParamField body="top_p" type="number" default={1}>
  핵 샘플링 매개변수(0-1). temperature 샘플링의 대안으로, 모델이 top\_p 확률 질량을 가진 토큰을 고려합니다.
</ParamField>

<ParamField body="frequency_penalty" type="number" default={0}>
  -2.0에서 2.0 사이의 숫자. 양수 값은 텍스트에서의 기존 빈도를 기반으로 새 토큰에 페널티를 부과하여, 모델이 같은 문장을 그대로 반복할 가능성을 줄입니다.
</ParamField>

<ParamField body="presence_penalty" type="number" default={0}>
  -2.0에서 2.0 사이의 숫자. 양수 값은 텍스트에 이미 나타났는지 여부를 기반으로 새 토큰에 페널티를 부과하여, 모델이 새로운 주제에 대해 이야기할 가능성을 높입니다.
</ParamField>

<ParamField body="stop" type="string | string[]">
  API가 추가 토큰 생성을 중단하는 최대 4개의 시퀀스.
</ParamField>

<ParamField body="n" type="integer" default={1}>
  각 입력 메시지에 대해 생성할 채팅 완성 선택지 수.
</ParamField>

<ParamField body="logprobs" type="boolean" default={false}>
  출력 토큰의 로그 확률을 반환할지 여부. true인 경우, 메시지 내용에 반환된 각 출력 토큰의 로그 확률을 반환합니다.
</ParamField>

<ParamField body="top_logprobs" type="integer">
  각 토큰 위치에서 반환할 가장 가능성 높은 토큰 수를 지정하는 0에서 20 사이의 정수. 이 매개변수를 사용하려면 `logprobs`를 `true`로 설정해야 합니다.
</ParamField>

<ParamField body="response_format" type="object">
  모델이 출력해야 하는 형식을 지정하는 객체.

  <Expandable title="속성">
    <ParamField body="type" type="string" required>
      응답 형식의 유형. 지원되는 값: `text`, `json_object`, `json_schema`.
    </ParamField>

    <ParamField body="json_schema" type="object">
      JSON 스키마 객체. type이 `json_schema`인 경우 필수입니다.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="seed" type="integer">
  지정된 경우, 시스템은 동일한 seed와 매개변수를 가진 반복 요청이 동일한 결과를 반환하도록 최선의 노력으로 결정론적 샘플링을 수행합니다.
</ParamField>

<ParamField body="tools" type="object[]">
  모델이 호출할 수 있는 도구 목록. 현재 함수만 도구로 지원됩니다.

  <Expandable title="속성">
    <ParamField body="type" type="string" required>
      도구의 유형. 현재 `function`만 지원됩니다.
    </ParamField>

    <ParamField body="function" type="object" required>
      함수 정의.

      <Expandable title="속성">
        <ParamField body="name" type="string" required>
          호출할 함수의 이름.
        </ParamField>

        <ParamField body="description" type="string">
          함수가 수행하는 작업에 대한 설명.
        </ParamField>

        <ParamField body="parameters" type="object">
          함수가 허용하는 매개변수로, JSON Schema 객체로 설명됩니다.
        </ParamField>

        <ParamField body="strict" type="boolean" default={false}>
          엄격한 스키마 준수를 활성화할지 여부.
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="tool_choice" type="string | object">
  모델이 어떤 도구를 호출할지(호출하는 경우) 제어합니다. `none`은 모델이 도구를 호출하지 않음을 의미합니다. `auto`는 모델이 메시지 생성 또는 도구 호출 중에서 선택할 수 있음을 의미합니다. `required`는 모델이 하나 이상의 도구를 호출해야 함을 의미합니다. `{"type": "function", "function": {"name": "my_function"}}`을 통해 특정 함수를 지정할 수도 있습니다.
</ParamField>

<ParamField body="parallel_tool_calls" type="boolean" default={true}>
  도구 사용 시 병렬 함수 호출을 활성화할지 여부.
</ParamField>

<ParamField body="user" type="string">
  최종 사용자를 나타내는 고유 식별자로, 남용 모니터링 및 감지에 도움이 될 수 있습니다.
</ParamField>

## 응답

채팅 완성 성공 응답.

<ResponseField name="id" type="string">
  채팅 완성의 고유 식별자.
</ResponseField>

<ResponseField name="object" type="string">
  객체 유형. 항상 `chat.completion`.
</ResponseField>

<ResponseField name="created" type="integer">
  채팅 완성이 생성된 시점의 Unix 타임스탬프(초 단위).
</ResponseField>

<ResponseField name="model" type="string">
  채팅 완성에 사용된 모델.
</ResponseField>

<ResponseField name="choices" type="object[]">
  채팅 완성 선택지 목록. `n`이 1보다 큰 경우 둘 이상일 수 있습니다.

  <Expandable title="속성">
    <ResponseField name="index" type="integer">
      선택지 목록에서의 인덱스.
    </ResponseField>

    <ResponseField name="message" type="object">
      모델이 생성한 채팅 완성 메시지.

      <Expandable title="속성">
        <ResponseField name="role" type="string">
          이 메시지 작성자의 역할. 항상 `assistant`.
        </ResponseField>

        <ResponseField name="content" type="string | null">
          메시지의 내용.
        </ResponseField>

        <ResponseField name="tool_calls" type="object[]">
          함수 호출 등 모델이 생성한 도구 호출.

          <Expandable title="속성">
            <ResponseField name="id" type="string">
              도구 호출의 ID.
            </ResponseField>

            <ResponseField name="type" type="string">
              도구의 유형. 현재 `function`만 지원됩니다.
            </ResponseField>

            <ResponseField name="function" type="object">
              모델이 호출한 함수.

              <Expandable title="속성">
                <ResponseField name="name" type="string">
                  호출할 함수의 이름.
                </ResponseField>

                <ResponseField name="arguments" type="string">
                  모델이 JSON 형식으로 생성한 함수 호출 인자.
                </ResponseField>
              </Expandable>
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="finish_reason" type="string">
      모델이 토큰 생성을 중단한 이유. `stop`, `length`, `tool_calls`, 또는 `content_filter`일 수 있습니다.
    </ResponseField>

    <ResponseField name="logprobs" type="object | null">
      선택지에 대한 로그 확률 정보.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  완성 요청의 사용량 통계.

  <Expandable title="속성">
    <ResponseField name="prompt_tokens" type="integer">
      프롬프트의 토큰 수.
    </ResponseField>

    <ResponseField name="completion_tokens" type="integer">
      생성된 완성의 토큰 수.
    </ResponseField>

    <ResponseField name="total_tokens" type="integer">
      요청에 사용된 총 토큰 수(프롬프트 + 완성).
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="system_fingerprint" type="string | null">
  모델이 실행되는 백엔드 구성을 나타내는 핑거프린트. `seed` 매개변수와 함께 사용하여 백엔드 변경 사항을 파악할 수 있습니다.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api-llm.sunra.ai/v1/chat/completions \
    -H "Authorization: Bearer <SUNRA_KEY>" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "openai/gpt-4o",
      "messages": [
        {
          "role": "system",
          "content": "You are a helpful assistant."
        },
        {
          "role": "user",
          "content": "What is the capital of France?"
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api-llm.sunra.ai/v1/chat/completions",
      headers={
          "Authorization": "Bearer <SUNRA_KEY>",
          "Content-Type": "application/json"
      },
      json={
          "model": "openai/gpt-4o",
          "messages": [
              {"role": "system", "content": "You are a helpful assistant."},
              {"role": "user", "content": "What is the capital of France?"}
          ]
      }
  )
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api-llm.sunra.ai/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": "Bearer <SUNRA_KEY>",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "openai/gpt-4o",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "What is the capital of France?" }
      ]
    })
  });
  const data = await response.json();
  console.log(data);
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "openai/gpt-4o",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "The capital of France is Paris."
        },
        "finish_reason": "stop",
        "logprobs": null
      }
    ],
    "system_fingerprint": "fp_44709d6fcb",
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 8,
      "total_tokens": 33
    }
  }
  ```
</ResponseExample>
