> 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.

# MiniMax Chat Completions

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

BeatAPI 키 하나로 OpenAI Chat Completions 엔드포인트에서 MiniMax M3와 M3.1 Flash를 호출합니다.- 현재 모든 MiniMax 모델이 엔드포인트 `POST /v1/chat/completions` 하나를 사용합니다. `model`만 바꿔 전환하세요.
- 스트리밍과 함수 호출, 1M 토큰 컨텍스트 창. `MiniMax-M3`는 프롬프트가 512,000토큰을 넘으면 요금이 두 배가 되고, `MiniMax-M3.1-Flash`는 프롬프트 길이와 관계없이 같은 요금입니다.
- OpenAI SDK와 호환됩니다. 기본 URL을 바꾸고 BeatAPI 키를 사용하세요.
- 같은 모델이 [OpenAI Responses](/text-api/minimax/responses)와 [Anthropic Messages](/text-api/minimax/messages)에서도 응답합니다.텍스트 요청의 기본 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 | 참고                                                                             |
| -------------------- | --------- | --------- | ---------------------------------------------- | -------------- | -------------- | ------------------------------------------------------------------------------ |
| `MiniMax-M3`         | 1,048,576 | 128,000   | 롱 컨텍스트 코딩, 인식, 에이전트 계획을 위한 MiniMax 멀티모달 모델     | \$0.12         | \$0.48         | 롱 컨텍스트 코딩, 인식, 에이전트 계획을 위한 MiniMax 멀티모달 모델. 프롬프트가 512,000토큰을 넘으면 요금이 두 배가 됩니다. |
| `MiniMax-M3.1-Flash` | 1,000,000 | —         | 에이전트 추론, 도구 사용, 코딩, 롱 컨텍스트를 위한 MiniMax의 저비용 모델 | \$0.06         | \$0.24         | `MiniMax-M3`보다 저렴하며, 컨텍스트 창 전체에 같은 요금이 적용됩니다. 롱 컨텍스트 등급이 없습니다.                 |- 가격은 할인이 적용된 기본 등급입니다. 롱 컨텍스트 등급, 캐시 입력 요금, 캐시 쓰기는 이 표에 없습니다. [가격표](https://beatapi.io/pricing)를 참고하세요.
- `—`는 카탈로그에서 해당 수치를 공개하지 않는다는 뜻입니다.## 빠른 시작서버에 `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": "MiniMax-M3",
  "max_tokens": 2000,
  "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="MiniMax-M3",
    max_tokens=2000,
    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": "MiniMax-M3",
  "max_tokens": 2000,
  "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입니다.**허용 값**: `MiniMax-M3`, `MiniMax-M3.1-Flash`- 각 ID는 별개의 모델이며 다른 모델의 별칭이 아닙니다.
- 키로 `GET /v1/models`를 호출해 사용 가능한 모델을 확인하세요.
- ID는 대소문자를 구분합니다. `MiniMax-M3`와 `MiniMax-M3.1-Flash`는 소문자로 바꾸지 말고 적힌 그대로 보내세요.messages
object[]
필수대화 내용이며 오래된 메시지부터 나열합니다. 각 메시지에는 `role`(`system`, `user`, `assistant` 또는 `tool`)와 `content`가 있습니다.max_tokens
integer
선택생성 토큰의 상한이며, 추론 토큰을 포함합니다.- 게이트웨이는 이 값을 위 표에 있는 모델의 최대 출력과 비교하지 않습니다. 그 값 이하로 설정하세요.
- `max_tokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요.추론 모델은 추론을 먼저 작성합니다. `max_tokens`가 너무 작으면 추론이 한도를 모두 써 버려 `content`가 비고 `finish_reason`이 `length`가 됩니다. 둘 다 담을 여유를 두고, `length`가 보이면 값을 높이세요.stream
boolean
선택기본값: false답변을 서버 전송 이벤트로 반환합니다. 아래 스트리밍 섹션을 참고하세요.**기본값**: `false`temperature
number
선택샘플링 온도입니다. 이 값이나 `top_p` 중 하나만 바꾸세요.top_p
number
선택누클리어스 샘플링 임계값입니다.stop
string | string[]
선택생성을 멈추는 하나 이상의 시퀀스입니다.tools
object[]
선택모델이 호출할 수 있는 함수 정의입니다. 모델은 `tool_calls`로 답하며, 각 결과는 일치하는 `tool_call_id`를 담은 이어지는 `tool` 메시지로 반환하세요.tool_choice
string | object
선택모델이 도구를 호출할 수 있는지, 반드시 호출해야 하는지, 호출하면 안 되는지 정합니다. 사용할 값은 해당 모델로 테스트하세요.## 롱 컨텍스트 가격`MiniMax-M3`는 프롬프트가 **512,000토큰**을 넘으면 상위 요금으로 바뀌며, 상위 요금은 요청 전체에 적용되어 입력, 캐시 입력, 출력이 모두 두 배가 됩니다. 점진적으로 오르지 않고 계단식으로 바뀌므로, 기준을 한 토큰만 넘어도 요청 전체가 상위 요금으로 과금됩니다.위 모델 표와 [가격표](https://beatapi.io/pricing)의 `MiniMax-M3` 가격은 기준 미만 프롬프트에 적용되는 기본 요금입니다. 긴 대화 기록을 보내기 전에 전체 프롬프트 크기를 추정하세요.`MiniMax-M3.1-Flash`에는 롱 컨텍스트 등급이 없습니다. 모델 표의 입력·출력 가격이 1,000,000토큰 컨텍스트 창까지 프롬프트 길이와 관계없이 적용됩니다. 캐시 입력은 1M 토큰당 \$0.006입니다.## 응답스트리밍하지 않는 호출은 JSON 객체 하나를 반환합니다. 아래는 축약한 예시입니다.```json
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "created": 1791993600,
  "model": "MiniMax-M3",
  "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[].message.reasoning_content` | `string`   | 추론하는 모델의 추론 텍스트입니다. 출력으로 과금됩니다.                                        |
| `choices[].message.tool_calls`        | `object[]` | 모델이 실행을 요청한 함수 호출입니다. `finish_reason`이 `tool_calls`일 때 있습니다.           |
| `choices[].finish_reason`             | `string`   | 완전한 답변이면 `stop`, 도구 요청이면 `tool_calls`, `max_tokens`에 도달하면 `length`입니다. |
| `usage`                               | `object`   | 토큰 수입니다. 호출은 실제 토큰 사용량으로 계량됩니다.                                        |## 스트리밍`"stream": true`를 설정하세요. 답변은 `chat.completion.chunk` 이벤트로 도착하고 `data: [DONE]`로 끝납니다.- 응답은 `text/event-stream`이며, 스트리밍하지 않으면 `application/json`입니다.
- 텍스트는 `choices[0].delta.content`로 도착합니다. 추론 모델은 `delta.reasoning_content`로 추론을 먼저 보냅니다.
- 모델 호출 전에 발생한 실패는 스트림 이벤트가 아니라 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]
```## 오류| 오류 또는 증상                                    | 원인                                                 | 해결 방법                                             |
| ------------------------------------------- | -------------------------------------------------- | ------------------------------------------------- |
| `content`가 비어 있고 `finish_reason`이 `length`임 | 추론 모델이 `max_tokens` 예산을 추론에 모두 썼습니다.               | 모델의 최대 출력 범위 안에서 `max_tokens`를 높이세요.              |
| `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).## 참고- MiniMax는 [OpenAI Responses](/text-api/minimax/responses)와 [Anthropic Messages](/text-api/minimax/messages)에서도 응답합니다.
- 이 페이지는 MiniMax 텍스트 모델을 다룹니다. MiniMax H3 영상 모델은 영상 API를 사용합니다.
- `low`부터 `high`까지의 `reasoning_effort`는 `MiniMax-M3.1-Flash`에서 추론 토큰을 생성하는 것으로 확인되었습니다. 추론 토큰은 출력으로 과금되므로, `max_tokens`는 답변뿐 아니라 추론까지 고려해 잡으세요.
- `MiniMax-M3.1-Flash`에 이미지를 보내려면 `image_url` 콘텐츠 파트에 base64 데이터 URL로 인라인 포함하세요.
- API 키는 신뢰할 수 있는 서버에 두고, 응답의 요청 ID를 기록하며, `429`, `500`, `503`만 재시도하세요.

Reference: https://docs.beatapi.io/api-reference/text-api/minimax-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는 별개의 모델이며 다른 모델의 별칭이 아닙니다. 키로 `GET /v1/models`를 호출해 사용 가능한 모델을 확인하세요. ID는 대소문자를 구분합니다. `MiniMax-M3`와 `MiniMax-M3.1-Flash`는 소문자로 바꾸지 말고 적힌 그대로 보내세요. `MiniMax-M3`, `MiniMax-M3.1-Flash`
  - Allowed values: `MiniMax-M3`, `MiniMax-M3.1-Flash`
- `messages` (list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItems, required) — 대화 내용이며 오래된 메시지부터 나열합니다. 각 메시지에는 `role`(`system`, `user`, `assistant` 또는 `tool`)와 `content`가 있습니다.
- `max_tokens` (integer, optional) — 생성 토큰의 상한이며, 추론 토큰을 포함합니다. 게이트웨이는 이 값을 위 표에 있는 모델의 최대 출력과 비교하지 않습니다. 그 값 이하로 설정하세요. `max_tokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요. 추론 모델은 추론을 먼저 작성합니다. `max_tokens`가 너무 작으면 추론이 한도를 모두 써 버려 `content`가 비고 `finish_reason`이 `length`가 됩니다. 둘 다 담을 여유를 두고, `length`가 보이면 값을 높이세요.
- `stream` (boolean, optional, default: false) — 답변을 서버 전송 이벤트로 반환합니다. 아래 스트리밍 섹션을 참고하세요.
- `temperature` (double, optional) — 샘플링 온도입니다. 이 값이나 `top_p` 중 하나만 바꾸세요.
- `top_p` (double, optional) — 누클리어스 샘플링 임계값입니다.
- `stop` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaStop, optional) — 생성을 멈추는 하나 이상의 시퀀스입니다.
- `tools` (list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolsItems, optional) — 모델이 호출할 수 있는 함수 정의입니다. 모델은 `tool_calls`로 답하며, 각 결과는 일치하는 `tool_call_id`를 담은 이어지는 `tool` 메시지로 반환하세요.
- `tool_choice` (V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolChoice, optional) — 모델이 도구를 호출할 수 있는지, 반드시 호출해야 하는지, 호출하면 안 되는지 정합니다. 사용할 값은 해당 모델로 테스트하세요.

## 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)

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaStop

생성을 멈추는 하나 이상의 시퀀스입니다.

- string
- list of string

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolsItems

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaToolChoice

모델이 도구를 호출할 수 있는지, 반드시 호출해야 하는지, 호출하면 안 되는지 정합니다. 사용할 값은 해당 모델로 테스트하세요.

- string
- map from string to any

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItems

- `message` (V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessage, optional)
- `finish_reason` (string, optional) — 완전한 답변이면 `stop`, 도구 요청이면 `tool_calls`, `max_tokens`에 도달하면 `length`입니다.

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaUsage

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

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContent

- string
- list of V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1Items

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsToolCallsItems

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessage

- `content` (string, optional) — 답변 텍스트입니다.
- `reasoning_content` (string, optional) — 추론하는 모델의 추론 텍스트입니다. 출력으로 과금됩니다.
- `tool_calls` (list of V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessageToolCallsItems, optional) — 모델이 실행을 요청한 함수 호출입니다. `finish_reason`이 `tool_calls`일 때 있습니다.

### V1ChatCompletionsPostRequestBodyContentApplicationJsonSchemaMessagesItemsContentOneOf1Items

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

### V1ChatCompletionsPostResponsesContentApplicationJsonSchemaChoicesItemsMessageToolCallsItems

### 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": "MiniMax-M3",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ],
  "max_tokens": 2000
}
```

**Response**

```json
{
  "id": "chatcmpl-example",
  "model": "MiniMax-M3",
  "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": "MiniMax-M3",
    "messages": [
        {
            "role": "user",
            "content": "Design a resilient webhook retry strategy for a payments API."
        }
    ],
    "max_tokens": 2000
}
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":"MiniMax-M3","messages":[{"role":"user","content":"Design a resilient webhook retry strategy for a payments API."}],"max_tokens":2000}'
};

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\": \"MiniMax-M3\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ],\n  \"max_tokens\": 2000\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\": \"MiniMax-M3\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ],\n  \"max_tokens\": 2000\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\": \"MiniMax-M3\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ],\n  \"max_tokens\": 2000\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": "MiniMax-M3",
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ],
  "max_tokens": 2000
}',
  '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\": \"MiniMax-M3\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ],\n  \"max_tokens\": 2000\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 빠른 시작
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "MiniMax-M3",
  "messages": [
    [
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    ]
  ],
  "max_tokens": 2000
] 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()
```