> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# GPT Chat Completions

POST https://direct.beatapi.io/v1/chat/completions
Content-Type: application/json

BeatAPI 키 하나로 OpenAI Chat Completions 엔드포인트에서 GPT-6.1 Terra, GPT-6.1 Sol, GPT-6 Astra, GPT-6 Sol, GPT-6 Luna를 호출합니다.- 현재 모든 GPT 모델이 엔드포인트 `POST /v1/chat/completions` 하나를 사용합니다. `model`만 바꿔 전환하세요.
- 텍스트·이미지 입력, 텍스트 출력, 스트리밍, 구조화된 출력, 추론 강도 설정. GPT-6.1 Terra와 Sol의 도구 호출에는 Responses가 필요합니다.
- OpenAI SDK와 호환됩니다. 기본 URL을 바꾸고 BeatAPI 키를 사용하세요.
- 추론과 도구 호출을 새로 연동한다면 [OpenAI Responses](/text-api/gpt/responses) 형식을 권장합니다.텍스트 요청의 기본 URL로는 `https://direct.beatapi.io`를 사용하세요. Cloudflare의 100초 제한을 받지 않으므로 스트리밍하지 않는 긴 요청도 끊기지 않습니다. `https://api.beatapi.io`도 동작하며, 네트워크에서 `direct.beatapi.io`에 접근할 수 없을 때의 대안입니다. 키, 모델, 가격은 양쪽이 같습니다. 이미지와 영상 API는 `https://api.beatapi.io`만 사용합니다.POST/v1/chat/completions실행해 보기API Explorer에서 이 엔드포인트를 엽니다. BeatAPI API 키를 입력하고 전송하세요. 실제 호출이며 본인 잔액에서 과금됩니다.## 모델`model`에 다음 ID 중 하나를 보내세요. 각각 별개의 모델이며, 서로의 별칭으로 취급하지 마세요.| 모델 ID           | 컨텍스트(토큰)  | 최대 출력(토큰) | 포지셔닝                                                         | 입력, 1M 토큰당 USD | 출력, 1M 토큰당 USD | 참고                                                                                         |
| --------------- | --------- | --------- | ------------------------------------------------------------ | -------------- | -------------- | ------------------------------------------------------------------------------------------ |
| `gpt-6.1-terra` | 1,050,000 | 128,000   | 시각적 추론, 컴퓨터 사용, 일상 작업                                        | \$0.40         | \$2.00         | 추론 강도 `none`\~`max`, 기본값 `medium`. 도구 호출에는 Responses가 필요합니다. 입력 토큰 272K 초과 시 상위 요금이 적용됩니다. |
| `gpt-6.1-sol`   | 1,050,000 | 128,000   | 코딩, 컴퓨터 사용, 전문 업무를 위한 GPT-6.1 Sol. 도구 호출에는 Responses를 사용하세요. | \$0.80         | \$4.00         | 추론 강도 `low`\~`max`. 입력 토큰 272K 초과 시 상위 요금이 적용됩니다.                                          |
| `gpt-6-astra`   | 1,000,000 | 128,000   | 가장 강력한 GPT 모델: 복잡한 추론, 코딩, 컴퓨터 사용, 리서치, 문서 작업                | \$4.00         | \$20.00        | 입력 토큰 272K 초과 시 상위 요금이 적용됩니다.                                                              |
| `gpt-6-sol`     | 1,050,000 | 128,000   | 일상적인 코딩, 리서치, 에이전트 작업을 더 낮은 가격에 처리하는 중간 등급 GPT-6 모델          | \$0.80         | \$4.00         | GPT-6.1 Sol, GPT-5.6 Sol과는 별개의 모델입니다.                                                      |
| `gpt-6-luna`    | 1,050,000 | 128,000   | 집중적인 대량 작업을 위한 비용 효율적인 GPT-6 모델                              | \$0.04         | \$0.20         | 추출, 분류, 라우팅 같은 집중적인 대량 작업.                                                                 |- 가격은 할인이 적용된 기본 등급입니다. 롱 컨텍스트 등급, 캐시 입력 요금, 캐시 쓰기는 이 표에 없습니다. [가격표](https://beatapi.io/pricing)를 참고하세요.
- `—`는 카탈로그에서 해당 수치를 공개하지 않는다는 뜻입니다.이 계열의 이전 ID도 계속 동작하며 [레거시 모델](/text-api/legacy-models)에 나와 있습니다.## 빠른 시작서버에 `openai` 패키지를 설치하고 키는 `BEATAPI_API_KEY`에 보관하세요. 브라우저 코드에는 절대 넣지 마세요. 아래는 요청 예시이며 실제로 기록된 모델 출력이 아닙니다.`choices[0].message.content`에서 답변을 읽은 다음 `finish_reason`과 `usage`를 확인하세요. HTTP 200만으로는 답변이 작업 요구를 충족한다고 볼 수 없으니 애플리케이션에서 검증하세요. 텍스트 요청은 바로 반환되므로 `/v1/tasks`를 폴링하지 마세요.```bash title="cURL"
curl --request POST \
  --url https://direct.beatapi.io/v1/chat/completions \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}'
``````python title="Python"
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["BEATAPI_API_KEY"], base_url="https://direct.beatapi.io/v1")
completion = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[
      {
        "role": "user",
        "content": "Design a resilient webhook retry strategy for a payments API."
      }
    ],
)
print(completion.choices[0].message.content)
``````javascript title="JavaScript"
import OpenAI from "openai";

const client = new OpenAI({ apiKey: process.env.BEATAPI_API_KEY, baseURL: "https://direct.beatapi.io/v1" });
const completion = await client.chat.completions.create({
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
});
console.log(completion.choices[0].message.content);
```## 엔드포인트와 인증`POST https://direct.beatapi.io/v1/chat/completions`Authorization
string
필수`Bearer <BEATAPI_API_KEY>`. 키는 `sk-` 접두사가 있든 없든 동작합니다.## 요청 파라미터표준 OpenAI Chat Completions 필드를 받습니다. 요청 형식이 호환된다고 해서 모든 제조사별 옵션이나 도구가 지원되는 것은 아니므로, 사용하는 옵션은 직접 테스트하세요.model
string
필수정확한 모델 ID입니다.**허용 값**: `gpt-6.1-terra`, `gpt-6.1-sol`, `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`- 계속 동작하는 이전 ID(`gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`)는 [레거시 모델](/text-api/legacy-models)에 있습니다.
- 키로 `GET /v1/models`를 호출해 사용 가능한 모델을 확인하세요.messages
object[]
필수대화 내용이며 오래된 메시지부터 나열합니다. 각 메시지에는 `role`와 `content`가 있습니다. `content`는 문자열이거나 텍스트·이미지 입력용 파트 배열입니다.- 이 페이지의 모든 GPT 모델이 이미지 입력을 지원합니다.max_tokens
integer
선택생성 토큰의 상한입니다.- 게이트웨이는 1,073,741,823까지의 값을 받으며, 그보다 크면 `400 bad_request`입니다.
- 게이트웨이는 이 값을 위 표에 있는 모델의 최대 출력과 비교하지 않습니다. 그 값 이하로 설정하세요.
- `max_tokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요.stream
boolean
선택기본값: false답변을 서버 전송 이벤트로 반환합니다. 아래 스트리밍 섹션을 참고하세요.**기본값**: `false`reasoning_effort
string
선택모델이 답하기 전에 추론하는 양입니다. `medium`으로 시작한 다음, 실제 워크로드에서 한 단계 낮은 값과 높은 값을 평가해 보세요.**허용 값**: `none`, `low`, `medium`, `high`, `xhigh`, `max`**모델별**- `gpt-6.1-terra`: `none`, `low`, `medium`(기본값), `high`, `xhigh`, `max`.
- `gpt-6.1-sol`: `low`, `medium`, `high`, `xhigh`, `max`. `none`과 `minimal`은 지원하지 않습니다.
- `gpt-5.6-sol`: `none`, `low`, `medium`, `high`, `xhigh`, `max`.
- `gpt-5.6-terra`: `none`, `low`, `medium`, `high`, `xhigh`, `max`.
- `gpt-5.6-luna`: `none`, `low`, `medium`, `high`, `xhigh`, `max`.tools
object[]
선택모델이 호출할 수 있는 함수 정의입니다. 도구 결과는 이어지는 `tool` 메시지로 반환하세요.- `gpt-6.1-terra`와 `gpt-6.1-sol`의 도구 호출은 Chat Completions 대신 [Responses](/text-api/gpt/responses)를 사용하세요.response_format
object
선택구조화된 출력을 요청합니다(예: JSON 스키마).## 응답스트리밍하지 않는 호출은 JSON 객체 하나를 반환합니다. 아래는 축약한 예시입니다.```json
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "created": 1791993600,
  "model": "gpt-6-luna",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Retry with exponential backoff and jitter, and make every handler idempotent."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 16,
    "total_tokens": 35
  }
}
```### 응답 필드| 필드                          | 타입       | 설명                                              |
| --------------------------- | -------- | ----------------------------------------------- |
| `id`                        | `string` | 완료 ID입니다. 지원과 과금 감사를 위해 요청 ID와 함께 기록하세요.        |
| `model`                     | `string` | 응답한 모델입니다.                                      |
| `choices[].message.content` | `string` | 답변 텍스트입니다.                                      |
| `choices[].finish_reason`   | `string` | 완전한 답변이면 `stop`입니다. 잘린 답변이나 도구 요청은 따로 처리해야 합니다. |
| `usage`                     | `object` | 토큰 수입니다. 호출은 실제 토큰 사용량으로 계량됩니다.                 |## 스트리밍`"stream": true`를 설정하세요. BeatAPI는 서버 전송 이벤트 스트림을 변환하지 않고 전달하므로, 이벤트 객체는 OpenAI SDK와 호환됩니다.- 응답은 `text/event-stream`이며, 스트리밍하지 않으면 `application/json`입니다.
- 모델 호출 전에 발생한 실패는 스트림 이벤트가 아니라 HTTP 상태와 함께 일반 JSON 오류로 반환됩니다.
- 명시적인 시간 제한을 설정하고, 스트리밍 응답은 안전하게 다시 연결하세요.```text
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Retry"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" with backoff"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```## 오류| 오류 또는 증상                    | 원인                                                 | 해결 방법                                             |
| --------------------------- | -------------------------------------------------- | ------------------------------------------------- |
| 모델이 지원하지 않는 추론 강도로 인한 `400` | 예: `gpt-6.1-sol`에 `none`.                          | 모델이 지원하는 값을 사용하세요. 위의 `reasoning_effort`를 참고하세요.  |
| `402 insufficient_credits`  | 잔액이 요청 가격보다 적습니다. 대개 `max_tokens`가 너무 크기 때문입니다.    | 충전하거나 `max_tokens`를 낮추세요.                         |
| `403 forbidden`             | 계정이 무료 크레딧 상태인데 모델이 무료 목록에 없거나, 모델이 키의 그룹 밖에 있습니다. | 충전하거나, 무료 모델을 쓰거나, 그룹에서 해당 모델에 접근할 수 있는 키를 사용하세요. |
| `404 not_found`             | 알 수 없는 모델 ID이거나 이 키에서 사용할 수 없습니다.                  | `GET /v1/models`로 사용 가능한 모델을 확인하세요.               |
| `429 rate_limit_exceeded`   | 계정 또는 무료 모델 한도에 도달했습니다.                            | `Retry-After`만큼 기다린 뒤 재시도하세요.                     |### HTTP 오류 요약인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.| HTTP 상태 | 코드                                                         | 조치                                                             |
| ------- | ---------------------------------------------------------- | -------------------------------------------------------------- |
| 400     | `bad_request`, `content_policy_violation`                  | 요청이나 입력을 수정하세요. 그대로 다시 보내지 마세요.                                |
| 401     | `missing_api_key`, `invalid_api_key`                       | 키를 확인하세요. 재시도하지 마세요.                                           |
| 402     | `insufficient_credits`                                     | 충전하거나 키 한도를 높이세요. `max_tokens`가 너무 크면 발생할 수 있습니다.              |
| 403     | `forbidden`                                                | 모델이 키의 그룹이나 IP 허용 목록 밖에 있거나, 무료 크레딧으로 이 모델을 호출할 수 없습니다.        |
| 404     | `not_found`                                                | 알 수 없는 모델입니다. `GET /v1/models`로 사용 가능한 모델 목록을 확인하세요.           |
| 429     | `rate_limit_exceeded`                                      | `Retry-After` 또는 `retry_after_seconds`만큼 기다린 뒤 백오프를 두고 재시도하세요. |
| 500     | `internal_error`, `temporary_error`                        | 백오프를 적용해 한두 번 재시도하세요.                                          |
| 503     | `model_unavailable`, `upstream_timeout`, `temporary_error` | 백오프를 적용해 재시도하거나 다른 모델을 사용하세요.                                  |전체 코드 표와 재시도 정책: [오류](/errors#text-endpoints).## 참고- GPT 모델은 [OpenAI Responses](/text-api/gpt/responses)에서도 응답합니다.
- 입력 토큰이 272K를 넘으면 `gpt-6.1-terra`, `gpt-6.1-sol`, `gpt-6-astra`는 요청 전체에 상위 등급을 적용합니다. 롱 컨텍스트 워크로드의 예산을 잡기 전에 [가격표](https://beatapi.io/pricing)를 확인하세요.
- API 키는 신뢰할 수 있는 서버에 두고, 응답의 요청 ID를 기록하며, `429`, `500`, `503`만 재시도하세요.

Reference: https://docs.beatapi.io/api-reference/text-api/gpt-chat-completions

## Authentication

- `Authorization` header (bearer token, required) — API 키를 `Authorization: Bearer <BEATAPI_API_KEY>`로 보내세요.

## Servers

- `https://direct.beatapi.io` (Direct, default)
- `https://api.beatapi.io` (API)

## Request

### Body (application/json)

This endpoint expects an object.

- `model` (enum, required) — 정확한 모델 ID입니다. 계속 동작하는 이전 ID(`gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`)는 [레거시 모델](/text-api/legacy-models)에 있습니다. 키로 `GET /v1/models`를 호출해 사용 가능한 모델을 확인하세요. `gpt-6.1-terra`, `gpt-6.1-sol`, `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`
  - Allowed values: `gpt-6.1-terra`, `gpt-6.1-sol`, `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`
- `messages` (list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItems, required) — 대화 내용이며 오래된 메시지부터 나열합니다. 각 메시지에는 `role`와 `content`가 있습니다. `content`는 문자열이거나 텍스트·이미지 입력용 파트 배열입니다. 이 페이지의 모든 GPT 모델이 이미지 입력을 지원합니다.
- `max_tokens` (integer, optional) — 생성 토큰의 상한입니다. 게이트웨이는 1,073,741,823까지의 값을 받으며, 그보다 크면 `400 bad_request`입니다. 게이트웨이는 이 값을 위 표에 있는 모델의 최대 출력과 비교하지 않습니다. 그 값 이하로 설정하세요. `max_tokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요.
- `stream` (boolean, optional, default: false) — 답변을 서버 전송 이벤트로 반환합니다. 아래 스트리밍 섹션을 참고하세요.
- `reasoning_effort` (enum, optional) — 모델이 답하기 전에 추론하는 양입니다. `medium`으로 시작한 다음, 실제 워크로드에서 한 단계 낮은 값과 높은 값을 평가해 보세요. `gpt-6.1-terra`: `none`, `low`, `medium`(기본값), `high`, `xhigh`, `max`. `gpt-6.1-sol`: `low`, `medium`, `high`, `xhigh`, `max`. `none`과 `minimal`은 지원하지 않습니다. `gpt-5.6-sol`: `none`, `low`, `medium`, `high`, `xhigh`, `max`. `gpt-5.6-terra`: `none`, `low`, `medium`, `high`, `xhigh`, `max`. `gpt-5.6-luna`: `none`, `low`, `medium`, `high`, `xhigh`, `max`. `none`, `low`, `medium`, `high`, `xhigh`, `max`
  - Allowed values: `none`, `low`, `medium`, `high`, `xhigh`, `max`
- `tools` (list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolsItems, optional) — 모델이 호출할 수 있는 함수 정의입니다. 도구 결과는 이어지는 `tool` 메시지로 반환하세요. `gpt-6.1-terra`와 `gpt-6.1-sol`의 도구 호출은 Chat Completions 대신 [Responses](/text-api/gpt/responses)를 사용하세요.
- `response_format` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaResponseFormat, optional) — 구조화된 출력을 요청합니다(예: JSON 스키마).

## Response

### 200

스트리밍하지 않는 호출은 JSON 객체 하나를 반환합니다. 아래는 축약한 예시입니다.

- `id` (string, optional) — 완료 ID입니다. 지원과 과금 감사를 위해 요청 ID와 함께 기록하세요.
- `model` (string, optional) — 응답한 모델입니다.
- `choices` (list of V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItems, optional)
- `usage` (V1ChatCompletionsPostResponsesContentApplicationJsonSchemaUsage, optional) — 토큰 수입니다. 호출은 실제 토큰 사용량으로 계량됩니다.

## Errors

### 400 Bad Request Error

`bad_request`, `content_policy_violation` 요청이나 입력을 수정하세요. 그대로 다시 보내지 마세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 401 Unauthorized Error

`missing_api_key`, `invalid_api_key` 키를 확인하세요. 재시도하지 마세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 402 Payment Required Error

`insufficient_credits` 충전하거나 키 한도를 높이세요. `max_tokens`가 너무 크면 발생할 수 있습니다. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 403 Forbidden Error

`forbidden` 모델이 키의 그룹이나 IP 허용 목록 밖에 있거나, 무료 크레딧으로 이 모델을 호출할 수 없습니다. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 404 Not Found Error

`not_found` 알 수 없는 모델입니다. `GET /v1/models`로 사용 가능한 모델 목록을 확인하세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 429 Too Many Requests Error

`rate_limit_exceeded` `Retry-After` 또는 `retry_after_seconds`만큼 기다린 뒤 백오프를 두고 재시도하세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 500 Internal Server Error

`internal_error`, `temporary_error` 백오프를 적용해 한두 번 재시도하세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 503 Service Unavailable Error

`model_unavailable`, `upstream_timeout`, `temporary_error` 백오프를 적용해 재시도하거나 다른 모델을 사용하세요. 인증, 라우팅, 요청 속도 제한, 알 수 없는 모델 실패는 모델 호출 전에 BeatAPI 오류 형식(`error.code`, `error.message`, `retryable`, `request_id`)으로 응답합니다. 그 밖의 모든 실패는 OpenAI SDK 형식 `{"error": {"message", "type", "code"}}`를 유지하며, 코드는 `error.code`에 있고 요청 id는 `message`로 끝납니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

## Types

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItems

- `role` (string, required)
- `content` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContent, optional, nullable)
- `name` (string, optional)
- `tool_call_id` (string, optional)
- `tool_calls` (list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsToolCallsItems, optional)

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolsItems

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaResponseFormat

구조화된 출력을 요청합니다(예: JSON 스키마).

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItems

- `message` (V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessage, optional)
- `finish_reason` (string, optional) — 완전한 답변이면 `stop`입니다. 잘린 답변이나 도구 요청은 따로 처리해야 합니다.

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaUsage

토큰 수입니다. 호출은 실제 토큰 사용량으로 계량됩니다.

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContent

- string
- list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1Items

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsToolCallsItems

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessage

- `content` (string, optional) — 답변 텍스트입니다.

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1Items

- `type` (string, optional)
- `text` (string, optional)
- `image_url` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsImageUrl, optional)
- `source` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsSource, optional)

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsImageUrl

- string
- V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsImageUrl1

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsSource

- `type` (string, optional)
- `media_type` (string, optional)
- `data` (string, optional)
- `url` (string, optional)

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1ItemsImageUrl1

- `url` (string, optional)
- `detail` (string, optional)

## Examples

**Request**

```json
{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}
```

**Response**

```json
{
  "id": "chatcmpl-example",
  "model": "gpt-6-luna",
  "choices": [
    {
      "message": {
        "content": "Retry with exponential backoff and jitter, and make every handler idempotent.",
        "role": "assistant"
      },
      "finish_reason": "stop",
      "index": 0
    }
  ],
  "usage": {
    "completion_tokens": 16,
    "prompt_tokens": 19,
    "total_tokens": 35
  },
  "created": 1791993600,
  "object": "chat.completion"
}
```

**SDK Code**

```python 빠른 시작
import requests

url = "https://direct.beatapi.io/v1/chat/completions"

payload = {
    "model": "gpt-6-luna",
    "messages": [
        {
            "role": "user",
            "content": "Design a resilient webhook retry strategy for a payments API."
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 빠른 시작
const url = 'https://direct.beatapi.io/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"gpt-6-luna","messages":[{"role":"user","content":"Design a resilient webhook retry strategy for a payments API."}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 빠른 시작
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://direct.beatapi.io/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 빠른 시작
require 'uri'
require 'net/http'

url = URI("https://direct.beatapi.io/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java 빠른 시작
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://direct.beatapi.io/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}")
  .asString();
```

```php 빠른 시작
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://direct.beatapi.io/v1/chat/completions', [
  'body' => '{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 빠른 시작
using RestSharp;

var client = new RestClient("https://direct.beatapi.io/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 빠른 시작
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "gpt-6-luna",
  "messages": [
    [
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    ]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://direct.beatapi.io/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```