Skip to main content
POST
CometAPI instrada Chat Completions a più provider, tra cui OpenAI, Claude e Gemini, tramite un’unica interfaccia compatibile con OpenAI. Passa da un modello all’altro modificando il parametro model; la maggior parte degli SDK compatibili con OpenAI funziona impostando base_url su https://api.cometapi.com/v1.
I parametri della richiesta e i campi della risposta possono variare significativamente tra i provider di modelli. Consulta la documentazione ufficiale del provider del modello che utilizzi ogni volta che hai bisogno dell’elenco completo dei parametri o di un comportamento specifico del provider. Ad esempio, reasoning_effort si applica solo ai modelli di ragionamento (o-series, GPT-5.1+) e alcuni modelli non supportano logprobs o n > 1.
Per i modelli OpenAI Pro, i modelli di ragionamento o-series e i modelli Codex, utilizza l’ Responses endpoint. Queste famiglie di modelli hanno un supporto più completo nell’API Responses.

Ruoli dei messaggi

Per i modelli più recenti (GPT-4.1, serie GPT-5, o-series), preferisci developer a system per i messaggi di istruzioni. Entrambi funzionano, ma developer offre un comportamento di maggiore aderenza alle istruzioni.

Inviare input multimodale

Molti modelli supportano immagini e audio oltre al testo. Per inviare messaggi multimodali, utilizza il formato array per content:
Il parametro detail controlla la profondità dell’analisi delle immagini:
  • low — più veloce, utilizza meno tokens (costo fisso)
  • high — analisi dettagliata, consuma più tokens
  • auto — decide il modello (impostazione predefinita)

Trasmettere le risposte in streaming

Per ricevere output incrementale, imposta stream su true. La risposta viene fornita come Server-Sent Events (SSE), in cui ogni evento contiene un oggetto chat.completion.chunk:
Per includere statistiche sull’utilizzo dei token nelle risposte in streaming, imposta stream_options.include_usage su true. I dati di utilizzo vengono visualizzati nel chunk finale prima di [DONE].

Richiedere output strutturato

Per forzare il modello a restituire JSON valido conforme a uno schema specifico, utilizza response_format:
La modalità JSON Schema (json_schema) garantisce che l’output corrisponda esattamente al tuo schema. La modalità oggetto JSON (json_object) garantisce solo JSON valido: la struttura non viene applicata.

Chiamare strumenti e funzioni

Per consentire al modello di chiamare funzioni esterne, fornisci le definizioni degli strumenti:
Quando il modello decide di chiamare uno strumento, la risposta conterrà finish_reason: "tool_calls" e l’array message.tool_calls conterrà il nome della funzione e gli argomenti. Esegui quindi la funzione e invia il risultato come messaggio tool con il tool_call_id corrispondente.

Note tra provider

  • max_tokens — Il parametro legacy. Funziona con la maggior parte dei modelli, ma è deprecato per i modelli OpenAI più recenti.
  • max_completion_tokens — Il parametro consigliato per i modelli GPT-4.1, della serie GPT-5 e o-series. È obbligatorio per i modelli di ragionamento poiché include sia i token di output sia i token di ragionamento.
CometAPI gestisce automaticamente la mappatura durante l’instradamento a provider diversi.
  • system — Il ruolo di istruzioni tradizionale. Funziona con tutti i modelli.
  • developer — Introdotto con i modelli o1. Offre una maggiore aderenza alle istruzioni per i modelli più recenti. Nei modelli meno recenti ricorre al comportamento di system.
Usa developer per i nuovi progetti destinati ai modelli GPT-4.1+ o o-series.

FAQ

Come gestire i limiti di velocità?

Quando riscontri 429 Too Many Requests, implementa un backoff esponenziale:

Come mantenere il contesto della conversazione?

Includi la cronologia completa della conversazione nell’array messages:

Cosa significa finish_reason?

Come controllare i costi?

  1. Usa max_completion_tokens per limitare la lunghezza dell’output.
  2. Usa gpt-5.6-terra per un equilibrio tra intelligenza e costo, oppure gpt-5.6-luna per carichi di lavoro efficienti e ad alto volume.
  3. Mantieni i prompt concisi: evita contesto ridondante.
  4. Monitora l’utilizzo dei token nel campo della risposta usage.

Autorizzazioni

Authorization
string
header
obbligatorio

Bearer token authentication. Use your CometAPI key.

Corpo

application/json
model
string
predefinito:gpt-5.6-sol
obbligatorio

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

Esempio:

"gpt-4.1"

messages
object[]
obbligatorio

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

Intervallo richiesto: 0 <= x <= 2
top_p
number
predefinito: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.

Intervallo richiesto: 0 <= x <= 1
n
integer
predefinito: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
predefinito: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.

Intervallo richiesto: -2 <= x <= 2
frequency_penalty
number
predefinito:0

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

Intervallo richiesto: -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
predefinito:auto

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

logprobs
boolean
predefinito: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.

Intervallo richiesto: 0 <= x <= 20
reasoning_effort
enum<string>

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

Opzioni disponibili:
low,
medium,
high
stream_options
object

Options for streaming. Only valid when stream is true.

service_tier
enum<string>

Specifies the processing tier.

Opzioni disponibili:
auto,
default,
flex,
priority

Risposta

Successful chat completion response.

id
string

Unique completion identifier.

Esempio:

"chatcmpl-abc123"

object
enum<string>

Object type. Non-streaming responses use chat.completion.

Opzioni disponibili:
chat.completion
Esempio:

"chat.completion"

created
integer

Unix timestamp of creation.

Esempio:

1774412483

model
string

The model used (may include version suffix).

Esempio:

"gpt-5.4-2026-03-05"

choices
object[]

Array of completion choices.

usage
object

Token accounting for this request. Billing uses these counts.

service_tier
string

Service tier that processed the request, when the provider reports one.

Esempio:

"default"

system_fingerprint
string | null

Provider backend configuration fingerprint, when the provider reports one.

Esempio:

"fp_490a4ad033"