메인 콘텐츠로 건너뛰기
POST
/
v1
/
chat
/
completions
from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key="<COMETAPI_KEY>", ) completion = client.chat.completions.create( model="gpt-5.4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"}, ], ) print(completion.choices[0].message)
{
  "id": "chatcmpl-DNA27oKtBUL8TmbGpBM3B3zhWgYfZ",
  "object": "chat.completion",
  "created": 1774412483,
  "model": "gpt-4.1-nano-2025-04-14",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Four",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 29,
    "completion_tokens": 2,
    "total_tokens": 31,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": "fp_490a4ad033"
}

개요

채팅 완성 엔드포인트는 대규모 언어 모델과 상호작용할 때 가장 널리 사용되는 API입니다. 이 엔드포인트는 여러 메시지로 구성된 대화를 받아 모델의 응답을 반환합니다. CometAPI는 이 엔드포인트를 OpenAI, Anthropic Claude(호환성 레이어를 통해), Google Gemini 등 여러 제공업체로 단일 통합 인터페이스를 통해 라우팅합니다. model 파라미터만 변경하면 모델을 간단히 전환할 수 있습니다.
이 엔드포인트는 OpenAI Chat Completions 형식을 따릅니다. 대부분의 OpenAI 호환 SDK와 도구는 base_urlhttps://api.cometapi.com/v1로 변경하는 것만으로 CometAPI와 함께 사용할 수 있습니다.

중요 참고 사항

모델별 동작 — 모델마다 지원하는 파라미터의 하위 집합이 다를 수 있으며, 반환되는 응답 필드도 약간씩 다를 수 있습니다. 예를 들어 reasoning_effort는 추론 모델(o-series, GPT-5.1+)에만 적용되며, 일부 모델은 logprobs 또는 n > 1을 지원하지 않을 수 있습니다.
응답 패스스루 — CometAPI는 모델 응답을 수정 없이 그대로 전달합니다(제공업체 간 라우팅 시 형식 정규화를 제외). 이를 통해 원본 API와 일관된 출력을 받을 수 있습니다.
OpenAI Pro 모델 — OpenAI Pro 시리즈 모델(예: o1-pro)의 경우 대신 responses 엔드포인트를 사용하세요.

메시지 역할

역할설명
system어시스턴트의 동작과 성격을 설정합니다. 대화 시작 부분에 배치됩니다.
developer최신 모델(o1+)에서는 system을 대체합니다. 사용자 입력과 관계없이 모델이 따라야 하는 지침을 제공합니다.
user최종 사용자가 보내는 메시지입니다.
assistant이전 모델 응답으로, 대화 기록을 유지하는 데 사용됩니다.
tool도구/함수 호출의 결과입니다. 원래 도구 호출과 일치하는 tool_call_id를 반드시 포함해야 합니다.
최신 모델(GPT-4.1, GPT-5 시리즈, o-series)에서는 지침 메시지에 system보다 developer를 사용하는 것을 권장합니다. 둘 다 동작하지만, developer가 지침 준수 동작을 더 강하게 제공합니다.

멀티모달(Multimodal) 입력

많은 모델이 텍스트와 함께 이미지와 오디오를 지원합니다. 멀티모달 메시지를 보내려면 content에 배열 형식을 사용하세요:
{
  "role": "user",
  "content": [
    {"type": "text", "text": "Describe this image"},
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.png",
        "detail": "high"
      }
    }
  ]
}
detail 파라미터는 이미지 분석 깊이를 제어합니다:
  • low — 더 빠르며, 더 적은 토큰을 사용합니다(고정 비용)
  • high — 더 자세한 분석, 더 많은 토큰 소비
  • auto — 모델이 결정합니다(기본값)

스트리밍(Streaming)

streamtrue로 설정하면 응답은 Server-Sent Events (SSE) 형식으로 전달됩니다. 각 이벤트에는 점진적으로 생성되는 content를 담은 chat.completion.chunk 객체가 포함됩니다:
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}

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

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

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

data: [DONE]
스트리밍 응답에 토큰 사용량 통계를 포함하려면 stream_options.include_usagetrue로 설정하세요. usage 데이터는 [DONE] 직전의 마지막 chunk에 표시됩니다.

구조화된 출력

response_format을 사용하면 모델이 특정 스키마에 맞는 유효한 JSON을 반환하도록 강제할 수 있습니다:
{
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "result",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "answer": {"type": "string"},
          "confidence": {"type": "number"}
        },
        "required": ["answer", "confidence"],
        "additionalProperties": false
      }
    }
  }
}
JSON Schema 모드(json_schema)는 출력이 여러분의 스키마와 정확히 일치함을 보장합니다. JSON Object 모드(json_object)는 유효한 JSON만 보장하며, 구조 자체는 강제되지 않습니다.

도구 / 함수 호출(Function Calling)

도구 정의를 제공하면 모델이 외부 함수를 호출할 수 있습니다:
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "City name"}
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}
모델이 도구 호출을 하기로 결정하면 응답에는 finish_reason: "tool_calls"가 포함되고, message.tool_calls 배열에는 함수 이름과 인자가 들어 있습니다. 그런 다음 해당 함수를 실행하고, 일치하는 tool_call_id와 함께 결과를 tool 메시지로 다시 보내야 합니다.

응답 필드

필드설명
id고유한 완성 식별자입니다(예: chatcmpl-abc123).
object항상 chat.completion입니다.
model응답을 생성한 모델입니다(버전 접미사가 포함될 수 있음).
choices완성 선택지 배열입니다(일반적으로 n > 1이 아닌 경우 1개).
choices[].messagerole, content, 그리고 선택적으로 tool_calls를 포함하는 assistant의 응답 메시지입니다.
choices[].finish_reason모델이 중단된 이유입니다: stop, length, tool_calls, 또는 content_filter.
usage토큰 소비 내역입니다: prompt_tokens, completion_tokens, total_tokens, 그리고 세부 하위 집계.
system_fingerprint디버깅 재현성을 위한 백엔드 구성 지문입니다.

공급자 간 참고 사항

ParameterOpenAI GPTClaude (via compat)Gemini (via compat)
temperature0–20–10–2
top_p0–10–10–1
n1–1281만 가능1–8
stop최대 4개최대 4개최대 5개
tools
response_format✅ (json_schema)
logprobs
reasoning_efforto-series, GPT-5.1+❌ (Gemini 네이티브에서는 thinking 사용)
  • max_tokens — 레거시 파라미터입니다. 대부분의 모델에서 작동하지만 최신 OpenAI 모델에서는 더 이상 권장되지 않습니다.
  • max_completion_tokens — GPT-4.1, GPT-5 시리즈, o-series 모델에 권장되는 파라미터입니다. 출력 토큰과 추론 토큰을 모두 포함하므로 reasoning 모델에서는 필수입니다.
CometAPI는 서로 다른 공급자로 라우팅할 때 이 매핑을 자동으로 처리합니다.
  • system — 전통적인 지시 역할입니다. 모든 모델에서 작동합니다.
  • developer — o1 모델과 함께 도입되었습니다. 최신 모델에서 더 강한 지시 준수를 제공합니다. 구형 모델에서는 system 동작으로 대체됩니다.
GPT-4.1+ 또는 o-series 모델을 대상으로 하는 새 프로젝트에는 developer를 사용하세요.

FAQ

속도 제한은 어떻게 처리하나요?

429 Too Many Requests가 발생하면 지수 백오프를 구현하세요:
import time
import random
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.cometapi.com/v1",
    api_key="<COMETAPI_KEY>",
)

def chat_with_retry(messages, max_retries=3):
    for i in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-5.4",
                messages=messages,
            )
        except RateLimitError:
            if i < max_retries - 1:
                wait_time = (2 ** i) + random.random()
                time.sleep(wait_time)
            else:
                raise

대화 컨텍스트는 어떻게 유지하나요?

전체 대화 기록을 messages 배열에 포함하세요:
messages = [
    {"role": "developer", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Python?"},
    {"role": "assistant", "content": "Python is a high-level programming language..."},
    {"role": "user", "content": "What are its main advantages?"},
]

finish_reason는 무엇을 의미하나요?

ValueMeaning
stop자연스럽게 완료되었거나 중지 시퀀스에 도달했습니다.
lengthmax_tokens 또는 max_completion_tokens 한도에 도달했습니다.
tool_calls모델이 하나 이상의 도구/함수 호출을 실행했습니다.
content_filter콘텐츠 정책으로 인해 출력이 필터링되었습니다.

비용은 어떻게 제어하나요?

  1. 출력 길이를 제한하려면 max_completion_tokens를 사용하세요.
  2. 비용 효율적인 모델을 선택하세요(예: 더 단순한 작업에는 gpt-5.4-mini 또는 gpt-5.4-nano).
  3. 프롬프트(Prompt)는 간결하게 유지하세요 — 중복된 컨텍스트는 피하세요.
  4. usage 응답 필드에서 토큰(Token) 사용량을 모니터링하세요.

인증

Authorization
string
header
필수

Bearer token authentication. Use your CometAPI key.

본문

application/json
model
string
기본값:gpt-5.4
필수

Model ID to use for this request. See the Models page for current options.

예시:

"gpt-4.1"

messages
object[]
필수

A list of messages forming the conversation. Each message has a role (system, user, assistant, or developer) and content (text string or multimodal content array).

stream
boolean

If true, partial response tokens are delivered incrementally via server-sent events (SSE). The stream ends with a data: [DONE] message.

temperature
number
기본값:1

Sampling temperature between 0 and 2. Higher values (e.g., 0.8) produce more random output; lower values (e.g., 0.2) make output more focused and deterministic. Recommended to adjust this or top_p, but not both.

필수 범위: 0 <= x <= 2
top_p
number
기본값:1

Nucleus sampling parameter. The model considers only the tokens whose cumulative probability reaches top_p. For example, 0.1 means only the top 10% probability tokens are considered. Recommended to adjust this or temperature, but not both.

필수 범위: 0 <= x <= 1
n
integer
기본값:1

Number of completion choices to generate for each input message. Defaults to 1.

stop
string

Up to 4 sequences where the API will stop generating further tokens. Can be a string or an array of strings.

max_tokens
integer

Maximum number of tokens to generate in the completion. The total of input + output tokens is capped by the model's context length.

presence_penalty
number
기본값:0

Number between -2.0 and 2.0. Positive values penalize tokens based on whether they have already appeared, encouraging the model to explore new topics.

필수 범위: -2 <= x <= 2
frequency_penalty
number
기본값:0

Number between -2.0 and 2.0. Positive values penalize tokens proportionally to how often they have appeared, reducing verbatim repetition.

필수 범위: -2 <= x <= 2
logit_bias
object

A JSON object mapping token IDs to bias values from -100 to 100. The bias is added to the model's logits before sampling. Values between -1 and 1 subtly adjust likelihood; -100 or 100 effectively ban or force selection of a token.

user
string

A unique identifier for your end-user. Helps with abuse detection and monitoring.

max_completion_tokens
integer

An upper bound for the number of tokens to generate, including visible output tokens and reasoning tokens. Use this instead of max_tokens for GPT-4.1+, GPT-5 series, and o-series models.

response_format
object

Specifies the output format. Use {"type": "json_object"} for JSON mode, or {"type": "json_schema", "json_schema": {...}} for strict structured output.

tools
object[]

A list of tools the model may call. Currently supports function type tools.

tool_choice
기본값:auto

Controls how the model selects tools. auto (default): model decides. none: no tools. required: must call a tool.

logprobs
boolean
기본값:false

Whether to return log probabilities of the output tokens.

top_logprobs
integer

Number of most likely tokens to return at each position (0-20). Requires logprobs to be true.

필수 범위: 0 <= x <= 20
reasoning_effort
enum<string>

Controls the reasoning effort for o-series and GPT-5.1+ models.

사용 가능한 옵션:
low,
medium,
high
stream_options
object

Options for streaming. Only valid when stream is true.

service_tier
enum<string>

Specifies the processing tier.

사용 가능한 옵션:
auto,
default,
flex,
priority

응답

200 - application/json

Successful chat completion response.

id
string

Unique completion identifier.

예시:

"chatcmpl-abc123"

object
enum<string>
사용 가능한 옵션:
chat.completion
예시:

"chat.completion"

created
integer

Unix timestamp of creation.

예시:

1774412483

model
string

The model used (may include version suffix).

예시:

"gpt-5.4-2025-07-16"

choices
object[]

Array of completion choices.

usage
object
service_tier
string
예시:

"default"

system_fingerprint
string | null
예시:

"fp_490a4ad033"