Przejdź do głównej treści
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"
}

Documentation Index

Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt

Use this file to discover all available pages before exploring further.

CometAPI kieruje Chat Completions do wielu dostawców — w tym OpenAI, Claude i Gemini — za pośrednictwem jednego interfejsu zgodnego z OpenAI. Przełączaj się między modelami, zmieniając parametr model; większość SDK zgodnych z OpenAI działa po ustawieniu base_url na https://api.cometapi.com/v1.
Różne modele obsługują różne podzbiory parametrów i zwracają nieco inne pola odpowiedzi. Na przykład reasoning_effort dotyczy tylko modeli rozumujących (o-series, GPT-5.1+), a niektóre modele nie obsługują logprobs ani n > 1.
W przypadku modeli OpenAI Pro, modeli rozumujących o-series oraz modeli Codex użyj zamiast tego endpointu Responses. Te rodziny modeli mają pełniejsze wsparcie w API Responses.

Role wiadomości

RolaOpis
systemUstawia zachowanie i osobowość asystenta. Umieszczana na początku konwersacji.
developerZastępuje system w nowszych modelach (o1+). Dostarcza instrukcje, których model powinien przestrzegać niezależnie od danych wejściowych użytkownika.
userWiadomości od użytkownika końcowego.
assistantPoprzednie odpowiedzi modelu, używane do utrzymania historii konwersacji.
toolWyniki wywołań narzędzi/funkcji. Musi zawierać tool_call_id pasujące do oryginalnego wywołania narzędzia.
W przypadku nowszych modeli (GPT-4.1, seria GPT-5, o-series) w wiadomościach z instrukcjami preferuj developer zamiast system. Oba działają, ale developer zapewnia silniejsze podążanie za instrukcjami.

Wysyłanie danych wejściowych Multimodal

Wiele modeli obsługuje obrazy i audio obok tekstu. Aby wysyłać wiadomości Multimodal, użyj formatu tablicowego dla content:
{
  "role": "user",
  "content": [
    {"type": "text", "text": "Describe this image"},
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.png",
        "detail": "high"
      }
    }
  ]
}
Parametr detail kontroluje głębokość analizy obrazu:
  • low — szybciej, używa mniej tokenów (stały koszt)
  • high — szczegółowa analiza, zużywa więcej tokenów
  • auto — model decyduje (domyślnie)

Stream odpowiedzi

Aby otrzymywać dane wyjściowe przyrostowo, ustaw stream na true. Odpowiedź jest dostarczana jako Server-Sent Events (SSE), gdzie każde zdarzenie zawiera obiekt 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]
Aby uwzględnić statystyki użycia tokenów w odpowiedziach strumieniowych, ustaw stream_options.include_usage na true. Dane o użyciu pojawią się w ostatnim chunka przed [DONE].

Żądanie ustrukturyzowanego wyjścia

Aby wymusić na modelu zwracanie poprawnego JSON zgodnego z określonym schematem, użyj response_format:
{
  "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
      }
    }
  }
}
Tryb JSON Schema (json_schema) gwarantuje, że wyjście będzie dokładnie zgodne z Twoim schematem. Tryb JSON Object (json_object) gwarantuje jedynie poprawny JSON — struktura nie jest wymuszana.

Wywoływanie narzędzi i funkcji

Aby umożliwić modelowi wywoływanie zewnętrznych funkcji, podaj definicje narzędzi:
{
  "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"
}
Gdy model zdecyduje się wywołać narzędzie, odpowiedź będzie miała finish_reason: "tool_calls", a tablica message.tool_calls będzie zawierać nazwę funkcji i argumenty. Następnie wykonujesz funkcję i odsyłasz wynik jako wiadomość tool z pasującym tool_call_id.

Uwagi między dostawcami

ParametrOpenAI GPTClaude (przez compat)Gemini (przez compat)
temperature0–20–10–2
top_p0–10–10–1
n1–128tylko 11–8
stopDo 4Do 4Do 5
tools
response_format✅ (json_schema)
logprobs
reasoning_effortseria o, GPT-5.1+❌ (użyj thinking dla natywnego Gemini)
  • max_tokens — Parametr starszego typu. Działa z większością modeli, ale jest przestarzały dla nowszych modeli OpenAI.
  • max_completion_tokens — Zalecany parametr dla modeli GPT-4.1, serii GPT-5 i modeli z serii o. Wymagany dla modeli reasoning, ponieważ obejmuje zarówno output tokens, jak i reasoning tokens.
CometAPI automatycznie obsługuje mapowanie podczas routingu do różnych dostawców.
  • system — Tradycyjna rola instrukcji. Działa ze wszystkimi modelami.
  • developer — Wprowadzona wraz z modelami o1. Zapewnia silniejsze podążanie za instrukcjami w nowszych modelach. W starszych modelach wraca do zachowania system.
Używaj developer w nowych projektach ukierunkowanych na modele GPT-4.1+ lub modele z serii o.

FAQ

Jak obsługiwać limity szybkości?

Gdy napotkasz 429 Too Many Requests, zaimplementuj exponential backoff:
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

Jak zachować kontekst rozmowy?

Uwzględnij pełną historię rozmowy w tablicy 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?"},
]

Co oznacza finish_reason?

WartośćZnaczenie
stopNaturalne zakończenie lub osiągnięcie sekwencji stop.
lengthOsiągnięto limit max_tokens lub max_completion_tokens.
tool_callsModel wywołał jedno lub więcej wywołań narzędzi/funkcji.
content_filterDane wyjściowe zostały odfiltrowane z powodu polityki treści.

Jak kontrolować koszty?

  1. Użyj max_completion_tokens, aby ograniczyć długość odpowiedzi.
  2. Wybieraj opłacalne modele (np. gpt-5.4-mini lub gpt-5.4-nano do prostszych zadań).
  3. Zachowuj zwięzłość promptów — unikaj zbędnego kontekstu.
  4. Monitoruj użycie tokenów w polu odpowiedzi usage.

Autoryzacje

Authorization
string
header
wymagane

Bearer token authentication. Use your CometAPI key.

Treść

application/json
model
string
domyślnie:gpt-5.4
wymagane

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

Przykład:

"gpt-4.1"

messages
object[]
wymagane

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
domyślnie: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.

Wymagany zakres: 0 <= x <= 2
top_p
number
domyślnie: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.

Wymagany zakres: 0 <= x <= 1
n
integer
domyślnie: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
domyślnie: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.

Wymagany zakres: -2 <= x <= 2
frequency_penalty
number
domyślnie:0

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

Wymagany zakres: -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
domyślnie:auto

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

logprobs
boolean
domyślnie: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.

Wymagany zakres: 0 <= x <= 20
reasoning_effort
enum<string>

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

Dostępne opcje:
low,
medium,
high
stream_options
object

Options for streaming. Only valid when stream is true.

service_tier
enum<string>

Specifies the processing tier.

Dostępne opcje:
auto,
default,
flex,
priority

Odpowiedź

Successful chat completion response.

id
string

Unique completion identifier.

Przykład:

"chatcmpl-abc123"

object
enum<string>
Dostępne opcje:
chat.completion
Przykład:

"chat.completion"

created
integer

Unix timestamp of creation.

Przykład:

1774412483

model
string

The model used (may include version suffix).

Przykład:

"gpt-5.4-2025-07-16"

choices
object[]

Array of completion choices.

usage
object
service_tier
string
Przykład:

"default"

system_fingerprint
string | null
Przykład:

"fp_490a4ad033"