Ana içeriğe atla
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"
}

Genel Bakış

Chat Completions endpoint’i, büyük dil modelleriyle etkileşim kurmak için en yaygın kullanılan API’dir. Birden fazla mesajdan oluşan bir konuşmayı kabul eder ve modelin yanıtını döndürür. CometAPI bu endpoint’i, tek bir birleşik arayüz üzerinden OpenAI, Anthropic Claude (uyumluluk katmanı aracılığıyla), Google Gemini ve diğerleri dahil olmak üzere birden fazla sağlayıcıya yönlendirir. model parametresini basitçe değiştirerek modeller arasında geçiş yapabilirsiniz.
Bu endpoint, OpenAI Chat Completions biçimini izler. base_url değerini https://api.cometapi.com/v1 olarak değiştirerek OpenAI uyumlu SDK ve araçların çoğu CometAPI ile çalışır.

Önemli Notlar

Modele özgü davranış — Farklı modeller, parametrelerin farklı alt kümelerini destekleyebilir ve biraz farklı yanıt alanları döndürebilir. Örneğin, reasoning_effort yalnızca reasoning modelleri için geçerlidir (o-series, GPT-5.1+) ve bazı modeller logprobs veya n > 1 desteği sunmayabilir.
Yanıt doğrudan aktarımı — CometAPI, model yanıtlarını değiştirmeden iletir (sağlayıcılar arasında yönlendirme yaparken yalnızca biçim normalizasyonu hariç), böylece orijinal API ile tutarlı çıktı alırsınız.
OpenAI Pro modelleri — OpenAI Pro serisi modeller için (ör. o1-pro) bunun yerine responses endpoint’ini kullanın.

Mesaj Rolleri

RoleDescription
systemAsistanın davranışını ve kişiliğini belirler. Konuşmanın başına yerleştirilir.
developerDaha yeni modellerde system yerine kullanılır (o1+). Kullanıcı girdisinden bağımsız olarak modelin izlemesi gereken talimatları sağlar.
userSon kullanıcıdan gelen mesajlar.
assistantÖnceki model yanıtları; konuşma geçmişini korumak için kullanılır.
toolAraç/function çağrılarından gelen sonuçlar. Orijinal araç çağrısıyla eşleşen tool_call_id içermelidir.
Daha yeni modeller için (GPT-4.1, GPT-5 serisi, o-series), talimat mesajlarında system yerine developer kullanılması tercih edilir. İkisi de çalışır, ancak developer talimatlara daha güçlü uyum davranışı sağlar.

Multimodal Girdi

Birçok model, metnin yanında görsel ve ses desteği sunar. Multimodal mesajlar göndermek için content alanında dizi biçimini kullanın:
{
  "role": "user",
  "content": [
    {"type": "text", "text": "Describe this image"},
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.png",
        "detail": "high"
      }
    }
  ]
}
detail parametresi, görsel analizinin derinliğini kontrol eder:
  • low — daha hızlıdır, daha az token kullanır (sabit maliyet)
  • high — ayrıntılı analiz, daha fazla token tüketilir
  • auto — modele bırakılır (varsayılan)

Streaming

stream true olarak ayarlandığında, yanıt Server-Sent Events (SSE) olarak iletilir. Her event, artımlı içerik içeren bir chat.completion.chunk nesnesi barındırır:
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]
Streaming yanıtlarına token kullanım istatistiklerini dahil etmek için stream_options.include_usage değerini true olarak ayarlayın. Kullanım verileri, [DONE] öncesindeki son chunk içinde görünür.

Structured Outputs

response_format kullanarak modelin belirli bir şemayla eşleşen geçerli JSON döndürmesini zorunlu kılın:
{
  "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 modu (json_schema), çıktının şemanızla tam olarak eşleşmesini garanti eder. JSON Object modu (json_object) ise yalnızca geçerli JSON olmasını garanti eder — yapı zorunlu kılınmaz.

Tool / Function Calling

Tool tanımları sağlayarak modelin harici fonksiyonları çağırmasını etkinleştirin:
{
  "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"
}
Model bir tool çağırmaya karar verdiğinde, yanıtta finish_reason: "tool_calls" bulunur ve message.tool_calls dizisi fonksiyon adını ve argümanlarını içerir. Ardından fonksiyonu çalıştırır ve sonucu eşleşen tool_call_id ile bir tool mesajı olarak geri gönderirsiniz.

Response Fields

AlanAçıklama
idBenzersiz completion tanımlayıcısı (örn. chatcmpl-abc123).
objectHer zaman chat.completion olur.
modelYanıtı üreten modeldir (sürüm soneki içerebilir).
choicesCompletion seçenekleri dizisi (n > 1 olmadıkça genellikle 1).
choices[].messagerole, content ve isteğe bağlı olarak tool_calls içeren assistant yanıt mesajı.
choices[].finish_reasonModelin neden durduğunu belirtir: stop, length, tool_calls veya content_filter.
usageToken tüketimi dökümü: prompt_tokens, completion_tokens, total_tokens ve ayrıntılı alt sayımlar.
system_fingerprintHata ayıklama için yeniden üretilebilirliğe yönelik backend yapılandırma parmak izi.

Sağlayıcılar Arası Notlar

ParameterOpenAI GPTClaude (compat üzerinden)Gemini (compat üzerinden)
temperature0–20–10–2
top_p0–10–10–1
n1–128Yalnızca 11–8
stopEn fazla 4En fazla 4En fazla 5
tools
response_format✅ (json_schema)
logprobs
reasoning_efforto-series, GPT-5.1+❌ (Gemini native için thinking kullanın)
  • max_tokens — Eski parametre. Çoğu modelle çalışır ancak daha yeni OpenAI modelleri için kullanımdan kaldırılmaktadır.
  • max_completion_tokens — GPT-4.1, GPT-5 serisi ve o-series modelleri için önerilen parametre. Hem output tokens hem de reasoning tokens içerdiği için reasoning modelleri için gereklidir.
CometAPI, farklı sağlayıcılara yönlendirirken eşlemeyi otomatik olarak yapar.
  • system — Geleneksel instruction rolü. Tüm modellerle çalışır.
  • developer — o1 modelleriyle tanıtıldı. Daha yeni modeller için daha güçlü instruction-following sağlar. Eski modellerde system davranışına geri düşer.
GPT-4.1+ veya o-series modellerini hedefleyen yeni projelerde developer kullanın.

SSS

Rate limit’ler nasıl ele alınır?

429 Too Many Requests ile karşılaşıldığında, exponential backoff uygulayın:
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

Konuşma bağlamı nasıl korunur?

Tüm konuşma geçmişini messages dizisine ekleyin:
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 ne anlama gelir?

ValueMeaning
stopDoğal şekilde tamamlandı veya bir stop sequence’e ulaştı.
lengthmax_tokens veya max_completion_tokens sınırına ulaşıldı.
tool_callsModel bir veya daha fazla tool/function call çağırdı.
content_filterÇıktı, içerik politikası nedeniyle filtrelendi.

Maliyetler nasıl kontrol edilir?

  1. Çıktı uzunluğunu sınırlamak için max_completion_tokens kullanın.
  2. Maliyet açısından verimli modeller seçin (ör. daha basit görevler için gpt-5.4-mini veya gpt-5.4-nano).
  3. Prompt’ları kısa tutun — gereksiz bağlamdan kaçının.
  4. usage yanıt alanında token kullanımını izleyin.

Yetkilendirmeler

Authorization
string
header
gerekli

Bearer token authentication. Use your CometAPI key.

Gövde

application/json
model
string
varsayılan:gpt-5.4
gerekli

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

Örnek:

"gpt-4.1"

messages
object[]
gerekli

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
varsayılan: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.

Gerekli aralık: 0 <= x <= 2
top_p
number
varsayılan: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.

Gerekli aralık: 0 <= x <= 1
n
integer
varsayılan: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
varsayılan: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.

Gerekli aralık: -2 <= x <= 2
frequency_penalty
number
varsayılan:0

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

Gerekli aralık: -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
varsayılan:auto

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

logprobs
boolean
varsayılan: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.

Gerekli aralık: 0 <= x <= 20
reasoning_effort
enum<string>

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

Mevcut seçenekler:
low,
medium,
high
stream_options
object

Options for streaming. Only valid when stream is true.

service_tier
enum<string>

Specifies the processing tier.

Mevcut seçenekler:
auto,
default,
flex,
priority

Yanıt

200 - application/json

Successful chat completion response.

id
string

Unique completion identifier.

Örnek:

"chatcmpl-abc123"

object
enum<string>
Mevcut seçenekler:
chat.completion
Örnek:

"chat.completion"

created
integer

Unix timestamp of creation.

Örnek:

1774412483

model
string

The model used (may include version suffix).

Örnek:

"gpt-5.4-2025-07-16"

choices
object[]

Array of completion choices.

usage
object
service_tier
string
Örnek:

"default"

system_fingerprint
string | null
Örnek:

"fp_490a4ad033"