본문으로 건너뛰기

Chat Completions

채팅 완성을 생성합니다. OpenAI Chat Completions API와 호환됩니다.

POST/v1/chat/completions
AI SDK·Messages·Responses·Images 연결은 퀵스타트 방법 탭을 보세요.
chat.ts

OpenAI Chat Completions API

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "plm_xxxxxxxxxxxxxxxx",
  baseURL: "https://apirouter.pleum.ai/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-5.5",
  messages: [{ role: "user", content: "Why is the sky blue?" }],
});

console.log(response.choices[0].message.content);

요청 본문#

파라미터타입필수설명
modelstring필수모델 ID. GET /v1/models에서 전체 목록 확인. model@provider 형식(예: claude-sonnet-4-6@anthropic)으로 특정 프로바이더에 고정할 수도 있습니다. <family>-latest 표기(예: mistral-medium-latest)는 그 패밀리의 최신 릴리스로 자동 해석됩니다.
messagesarray필수{role, content} 배열. role은 system | user | assistant.
temperaturenumber선택0.0 ~ 2.0.
max_tokensinteger선택1 이상(글로벌 상한 없음). 기본값 4096. 모델의 최대 출력(카탈로그 max_output)보다 크게 지정하면 오류 없이 그 값으로 낮춰 처리합니다. 입력과 출력의 합이 컨텍스트 창을 넘을 때만 400을 받습니다. 크레딧 사전 홀드 금액 산정에 사용되므로 필요한 만큼만 지정하는 것을 권장.
streamboolean선택true면 SSE 스트리밍 응답. 기본값 false.
top_pnumber선택0.0 ~ 1.0. 누클리어스 샘플링.
stopstring | string[]선택생성을 중단할 시퀀스.
toolsarray선택함수 호출 도구 정의(OpenAI 형식). 툴 콜링 참고.
tool_choicestring | object선택"auto" · "none" 또는 특정 도구 강제 객체.
response_formatobject선택{"type": "json_object"} 등. 구조화 출력 참고.
seedinteger선택결정적 샘플링 시드. 지원 여부는 모델에 따라 다릅니다.
frequency_penaltynumber선택-2.0 ~ 2.0.
presence_penaltynumber선택-2.0 ~ 2.0.
parallel_tool_callsboolean선택병렬 도구 호출 허용 여부.
logit_biasobject선택토큰 ID를 키로, 바이어스 값을 값으로 하는 맵.
reasoning_effortstring선택minimal | none | low | medium | high | xhigh | max. 프로바이더별 형식으로 자동 번역됩니다. 추론 모델 참고.
thinkingboolean선택reasoning_effort의 편의 별칭 — true는 medium, false는 none. 둘 다 보내면 reasoning_effort가 우선합니다.
reasoningobject선택OpenRouter 호환 객체 {effort|enabled, max_tokens}. reasoning_effort로 흡수됩니다(우선순위: effort > enabled > max_tokens 버킷 ≥6000 high / ≥2500 medium / 나머지 low).
service_tierstring선택auto | default | flex | background | priority/fast | ultrafast. OpenAI 계열에만 전달(지연/비용 트레이드오프). 요금은 응답에 보고된 실제 계층 기준 — fast/priority 2배, flex 0.5배, ultrafast 6배. 지원 모델은 GET /v1/models의 supported_parameters에 service_tier가 있는 모델입니다.
reasoning_modestring선택standard | pro. GPT-5.6 Sol/Terra/Luna의 품질 우선(pro) 모드.
pluginsarray선택[{"id": "web", ...}] 웹 검색 플러그인. 웹 검색 참고.
providerobject선택{order, only, ignore, sort, max_price, has, require_zdr, disallow_prompt_training, quantization_only, quantization_exclude, min_context, require_no_training, residency_in} 프로바이더 라우팅 설정. sort는 price | latency | throughput | ttft | tps 중 하나이며 order가 있으면 무시됩니다. has는 implicit-caching만 받습니다. quantization_only와 quantization_exclude를 함께 보내면 400입니다. 레이턴시 라우팅 참고.
trace_idstring선택최대 128자. weighted 라우팅 정책의 sticky 시드 — 같은 trace_id는 항상 같은 모델로 라우팅됩니다.
modelstring필수

Model ID to route to. Also accepts model@provider.

messagesobject[]필수

Conversation turns. Minimum length 1.

rolestring필수

system | user | assistant | tool | function

contentstring | ContentPart[] | null선택

Plain text, multimodal parts, or null when tool_calls is set.

namestring선택

Tool or function name for tool/function roles.

tool_callsobject[]선택

OpenAI-format tool calls from the assistant.

tool_call_idstring선택

Id referenced by a role=tool result message.

reasoning_detailsobject[]선택

Opaque prior-turn reasoning blocks passed through to the provider.

temperaturenumber선택

Sampling temperature.

range: 0.0–2.0

max_tokensinteger선택

Minimum 1. There is no global upper bound. A value above the model's max_output is lowered to that maximum instead of failing; a 400 is returned only when input plus output cannot fit the context window.

default: 4096

max_completion_tokensinteger선택

OpenAI reasoning alias; copied onto max_tokens when set. Minimum 1, capped per model like max_tokens.

streamboolean선택

default: false

stream_optionsobject선택

Accepted but ignored. A final usage chunk is always sent on a stream.

modalities("text" | "audio")[]선택

Include "audio" to request audio output. Audio output works only with stream set to false; a streaming request returns 400.

audioobject선택

Audio output options. Send it together with "audio" in modalities.

voicestring필수
formatstring필수

enum: wav mp3 flac opus pcm16

top_pnumber선택

range: 0.0–1.0

stopstring | string[]선택
toolsobject[]선택

OpenAI-format function tools.

typestring선택

example: function

functionobject선택
namestring선택
descriptionstring선택
parametersobject선택
tool_choicestring | object선택
response_formatobject선택
seedinteger선택
frequency_penaltynumber선택

range: -2.0–2.0

presence_penaltynumber선택

range: -2.0–2.0

parallel_tool_callsboolean선택
logit_biasobject선택
reasoning_effortstring선택

enum: minimal none low medium high xhigh max

thinkingboolean선택

Alias absorbed into reasoning_effort (true means medium, false means none).

service_tierstring선택

enum: auto default flex background priority fast ultrafast

reasoning_modestring선택

enum: standard pro

pluginsobject[]선택
providerobject선택

Routing-only; stripped before upstream.

orderstring[]선택
onlystring[]선택
ignorestring[]선택
sortstring선택

Ignored when order is set.

enum: price latency throughput ttft tps

max_pricenumber | object선택
hasstring[]선택

enum: implicit-caching

require_zdrboolean선택
disallow_prompt_trainingboolean선택
quantization_onlystring[]선택

Cannot be sent together with quantization_exclude (400).

quantization_excludestring[]선택

Cannot be sent together with quantization_only (400).

min_contextinteger선택
require_no_trainingboolean선택

Keep only providers whose training use is 'no'. Providers marked 'yes' or unknown are excluded.

residency_instring[]선택

Keep only providers whose data residency is in this list. Providers with unknown residency are excluded.

modelsstring[]선택

Cross-model fallback list; routing-only. Max 10.

trace_idstring선택

Sticky seed for weighted policies. Max 128 chars. Routing-only.

userstring선택
tagsstring[]선택

표준 샘플링 · 도구 파라미터(top_p ~ reasoning_effort)는 검증 없이 라우팅된 프로바이더로 그대로 전달(패스스루)되며, 모델이 지원하지 않는 파라미터는 프로바이더가 무시하거나 에러를 반환할 수 있습니다. n(다중 choice)은 지원하지 않습니다 — 항상 단일 응답만 반환됩니다.

request body
{
  "model": "gpt-5.5",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello"}
  ],
  "temperature": 0.7,
  "max_tokens": 4096,
  "stream": false
}

응답#

OpenAI 형식의 choices / usage를 반환합니다. 비용은 응답을 보낸 뒤 정산되므로 cost(원화 비용·환율·마크업)는 정산이 끝난 경우에만 본문에 포함됩니다. 본문에 없으면 응답 헤더 X-Request-Id 값으로 GET /v1/generation?id=…를 호출하거나 대시보드 사용량에서 확인하세요. 비용 확인 위치 표도 참고하세요.

200 OK
{
  "id": "chatcmpl-9f3c2b7a5e1d4c8a9b0e6d7f1a2b3c4d",
  "object": "chat.completion",
  "created": 1767225600,
  "model": "gpt-5.5",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "Hello! How can I help you?"},
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 12,
    "total_tokens": 36
  },
  "cost": {"usd": 0.00048, "krw": 0.7, "fx_rate": 1342.48, "markup_rate": 0.0}
}

스트리밍#

stream: true로 요청하면 text/event-stream으로 텍스트 조각이 전송되고, 마지막 이벤트에 usage가 포함됩니다. 비용은 X-Request-Id로 조회하세요.

SSE stream
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello! "}}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"How can I help you?"}}]}

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

data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":8,"total_tokens":20}}

data: [DONE]

프롬프트 캐싱#

PleumRouter는 프롬프트 캐싱을 지원합니다. OpenAI · Google Gemini · DeepSeek는 별도 설정 없이 자동 캐싱됩니다 — 반복되는 입력 접두사(긴 시스템 프롬프트, 참고 문서 등)가 프로바이더 측에서 자동으로 캐싱되고, 캐시 적중분은 정가보다 낮은 할인 단가로 과금되어 비용이 절감됩니다.

Anthropic(Claude)은 명시적 캐싱을 사용합니다. content 파트에 cache_control: {"type": "ephemeral"}를 붙여 캐시 분기점을 지정하세요. 그 위치까지의 접두사가 캐싱됩니다. 멀티턴 호출에는 cache_control을 붙이지 않아도 캐시 분기점이 자동으로 주입됩니다. 규칙은 자동 프롬프트 캐싱 문서를 참고하세요.

request body (explicit caching)
{
  "model": "claude-sonnet-4-6",
  "messages": [
    {
      "role": "system",
      "content": [
        {
          "type": "text",
          "text": "<large reusable context: docs, schema, instructions...>",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {"role": "user", "content": "Answer based on the context above."}
  ]
}

캐시가 적중하면 응답 usage에 prompt_tokens_details.cached_tokens(적중 토큰)가 추가됩니다. Anthropic은 캐시 기록 토큰을 cache_creation_input_tokens로 함께 반환합니다. 할인은 GET /v1/models의 cache_read_usd에 캐시 읽기 단가가 있는 모델에 적용됩니다.

usage (cache hit)
"usage": {
  "prompt_tokens": 10240,
  "completion_tokens": 120,
  "total_tokens": 10360,
  "prompt_tokens_details": {"cached_tokens": 10000},
  "cache_creation_input_tokens": 0
}

과금 방식#

응답이 시작되기 전에 실패한 호출은 과금되지 않습니다. 성공한 호출은 실제 토큰 사용량으로 정산되며 최소 0.1 크레딧이 차감됩니다. 스트리밍 도중 끊기면 이미 전송된 토큰은 과금됩니다.

공급자의 일시 장애는 서버가 자동으로 재시도하거나 다른 공급자로 전환합니다. 그래도 실패하면 오류가 반환되고, 응답이 시작되기 전의 실패에는 크레딧이 차감되지 않습니다.