> ## 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.

# Een chat completion maken

> Gebruik CometAPI POST /v1/chat/completions om gesprekken met meerdere berichten naar chatmodellen te sturen, met bedieningselementen voor streaming, temperature en max_tokens.

CometAPI routeert Chat Completions naar meerdere providers — waaronder OpenAI, Claude en Gemini — via één OpenAI-compatibele interface. Wissel tussen modellen door de parameter `model` te wijzigen; de meeste OpenAI-compatibele SDK's werken door `base_url` in te stellen op `https://api.cometapi.com/v1`.

<Warning>
  Aanvraagparameters en antwoordvelden kunnen aanzienlijk verschillen tussen modelproviders. Raadpleeg altijd de officiële documentatie van de provider achter het model dat je gebruikt wanneer je de volledige parameterlijst of providerspecifiek gedrag nodig hebt. Zo geldt `reasoning_effort` alleen voor reasoning-modellen (o-series, GPT-5.1+) en ondersteunen sommige modellen `logprobs` of `n` > 1 niet.
</Warning>

<Note>
  Gebruik voor OpenAI Pro-modellen, reasoning-modellen van o-series en Codex-modellen in plaats daarvan het [Responses](/nl/api/text/responses) -endpoint. Deze modelfamilies hebben uitgebreidere ondersteuning in de Responses API.
</Note>

***

## Berichtrollen

| Rol         | Beschrijving                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------------- |
| `system`    | Bepaalt het gedrag en de persoonlijkheid van de assistant. Wordt aan het begin van het gesprek geplaatst.                 |
| `developer` | Vervangt `system` voor nieuwere modellen (o1+). Geeft instructies die het model moet volgen, ongeacht gebruikersinvoer.   |
| `user`      | Berichten van de eindgebruiker.                                                                                           |
| `assistant` | Eerdere modelantwoorden, gebruikt om de gesprekshistorie te behouden.                                                     |
| `tool`      | Resultaten van tool/function-aanroepen. Moet `tool_call_id` bevatten dat overeenkomt met de oorspronkelijke tool-aanroep. |

<Tip>
  Gebruik voor nieuwere modellen (GPT-4.1, GPT-5-serie, o-series) bij voorkeur `developer` in plaats van `system` voor instructieberichten. Beide werken, maar `developer` biedt sterkere opvolging van instructies.
</Tip>

***

## Multimodale invoer verzenden

Veel modellen ondersteunen afbeeldingen en audio naast tekst. Gebruik de arrayindeling voor `content` om multimodale berichten te verzenden:

```json theme={null}
{
  "role": "user",
  "content": [
    {"type": "text", "text": "Describe this image"},
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.png",
        "detail": "high"
      }
    }
  ]
}
```

De parameter `detail` bepaalt de diepgang van afbeeldingsanalyse:

* `low` — sneller, gebruikt minder tokens (vaste kosten)
* `high` — gedetailleerde analyse, meer tokens verbruikt
* `auto` — het model beslist (standaard)

***

## Antwoorden streamen

Stel `stream` in op `true` om incrementele uitvoer te ontvangen. Het antwoord wordt geleverd als **Server-Sent Events (SSE)**, waarbij elk event een object `chat.completion.chunk` bevat:

```
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]
```

<Tip>
  Stel `stream_options.include_usage` in op `true` om statistieken over tokengebruik in streaming-antwoorden op te nemen. De gebruiksgegevens verschijnen in het laatste chunk vóór `[DONE]`.
</Tip>

***

## Gestructureerde uitvoer aanvragen

Gebruik `response_format` om het model te dwingen geldige JSON terug te geven die overeenkomt met een specifiek schema:

<CodeGroup>
  ```json JSON Schema Mode theme={null}
  {
    "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 JSON Object Mode theme={null}
  {
    "response_format": {"type": "json_object"}
  }
  ```
</CodeGroup>

<Note>
  De JSON Schema-modus (`json_schema`) garandeert dat de uitvoer exact overeenkomt met je schema. De JSON Object-modus (`json_object`) garandeert alleen geldige JSON — de structuur wordt niet afgedwongen.
</Note>

***

## Tools en functies aanroepen

Geef tooldefinities op om het model externe functies te laten aanroepen:

```json theme={null}
{
  "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"
}
```

Wanneer het model besluit een tool aan te roepen, bevat het antwoord `finish_reason: "tool_calls"` en bevat de array `message.tool_calls` de functienaam en argumenten. Vervolgens voer je de functie uit en stuur je het resultaat terug als een bericht `tool` met de overeenkomende `tool_call_id`.

***

## Opmerkingen over providers

<AccordionGroup>
  <Accordion title="Parameterondersteuning bij providers">
    | Parameter          | OpenAI GPT         | Claude (via compat) | Gemini (via compat)                       |
    | ------------------ | ------------------ | ------------------- | ----------------------------------------- |
    | `temperature`      | 0–2                | 0–1                 | 0–2                                       |
    | `top_p`            | 0–1                | 0–1                 | 0–1                                       |
    | `n`                | 1–128              | alleen 1            | 1–8                                       |
    | `stop`             | Maximaal 4         | Maximaal 4          | Maximaal 5                                |
    | `tools`            | ✅                  | ✅                   | ✅                                         |
    | `response_format`  | ✅                  | ✅ (json\_schema)    | ✅                                         |
    | `logprobs`         | ✅                  | ❌                   | ❌                                         |
    | `reasoning_effort` | o-series, GPT-5.1+ | ❌                   | ❌ (gebruik `thinking` voor native Gemini) |
  </Accordion>

  <Accordion title="max_tokens versus max_completion_tokens">
    * **`max_tokens`** — De verouderde parameter. Werkt met de meeste modellen, maar is verouderd voor nieuwere OpenAI-modellen.
    * **`max_completion_tokens`** — De aanbevolen parameter voor modellen van GPT-4.1, de GPT-5-serie en o-series. Vereist voor reasoning-modellen, omdat deze zowel uitvoertokens als reasoning-tokens omvat.

    CometAPI verwerkt de toewijzing automatisch bij routering naar verschillende providers.
  </Accordion>

  <Accordion title="system versus developer-rol">
    * **`system`** — De traditionele instructierol. Werkt met alle modellen.
    * **`developer`** — Geïntroduceerd met modellen van o1. Biedt sterkere opvolging van instructies voor nieuwere modellen. Valt bij oudere modellen terug op het gedrag van `system`.

    Gebruik `developer` voor nieuwe projecten die gericht zijn op modellen van GPT-4.1+ of o-series.
  </Accordion>
</AccordionGroup>

***

## Veelgestelde vragen

### Hoe ga je om met rate limits?

Implementeer exponential backoff wanneer je `429 Too Many Requests` tegenkomt:

```python theme={null}
import os
import time
import random
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.cometapi.com/v1",
    api_key=os.environ["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.6-sol",
                messages=messages,
            )
        except RateLimitError:
            if i < max_retries - 1:
                wait_time = (2 ** i) + random.random()
                time.sleep(wait_time)
            else:
                raise
```

### Hoe behoud je gesprekscontext?

Neem de volledige gesprekshistorie op in de array `messages`:

```python theme={null}
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?"},
]
```

### Wat betekent `finish_reason`?

| Waarde           | Betekenis                                                       |
| ---------------- | --------------------------------------------------------------- |
| `stop`           | Natuurlijke voltooiing of een stopsequentie bereikt.            |
| `length`         | Limiet voor `max_tokens` of `max_completion_tokens` bereikt.    |
| `tool_calls`     | Het model heeft een of meer tool/function-aanroepen uitgevoerd. |
| `content_filter` | De uitvoer is gefilterd vanwege het contentbeleid.              |

### Hoe beheers je kosten?

1. Gebruik `max_completion_tokens` om de uitvoerlengte te beperken.
2. Gebruik `gpt-5.6-terra` voor een balans tussen intelligentie en kosten, of `gpt-5.6-luna` voor efficiënte workloads met hoge volumes.
3. Houd Prompts beknopt — vermijd overbodige context.
4. Controleer het tokengebruik in het antwoordveld `usage`.


## OpenAPI

````yaml api/openapi/text/post-chat.openapi.json POST /v1/chat/completions
openapi: 3.1.0
info:
  title: Chat Completions API
  version: 1.0.0
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /v1/chat/completions:
    post:
      summary: Chat Completions
      description: >-
        Routes chat requests across multiple model providers. Request parameters
        and response fields can vary significantly by provider, so check the
        official documentation for the provider behind the model you use when
        you need provider-specific parameters or behavior details.
      operationId: chat_completions
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - messages
              properties:
                model:
                  type: string
                  description: >-
                    Model ID to use for this request. See the [Models
                    page](/overview/models) for current options.
                  example: gpt-4.1
                  default: gpt-5.6-sol
                messages:
                  type: array
                  description: >-
                    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).
                  items:
                    type: object
                    properties:
                      role:
                        type: string
                        enum:
                          - system
                          - user
                          - assistant
                          - tool
                          - developer
                        description: >-
                          The role of the message author. Common values:
                          `system` (recommended for system-level instructions),
                          `user`, `assistant`, `tool`. Newer OpenAI models may
                          also accept `developer` instead of `system`.
                      content:
                        type: string
                        description: >-
                          The message content. Can be a text string or an array
                          of content objects for multimodal input (text +
                          images).
                  default:
                    - role: system
                      content: You are a helpful assistant.
                    - role: user
                      content: Hello!
                stream:
                  type: boolean
                  description: >-
                    If `true`, partial response tokens are delivered
                    incrementally via server-sent events (SSE). The stream ends
                    with a `data: [DONE]` message.
                temperature:
                  type: number
                  description: >-
                    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.
                  minimum: 0
                  maximum: 2
                  default: 1
                top_p:
                  type: number
                  description: >-
                    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.
                  minimum: 0
                  maximum: 1
                  default: 1
                'n':
                  type: integer
                  description: >-
                    Number of completion choices to generate for each input
                    message. Defaults to 1.
                  default: 1
                stop:
                  type: string
                  description: >-
                    Up to 4 sequences where the API will stop generating further
                    tokens. Can be a string or an array of strings.
                max_tokens:
                  type: integer
                  description: >-
                    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:
                  type: number
                  description: >-
                    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.
                  minimum: -2
                  maximum: 2
                  default: 0
                frequency_penalty:
                  type: number
                  description: >-
                    Number between -2.0 and 2.0. Positive values penalize tokens
                    proportionally to how often they have appeared, reducing
                    verbatim repetition.
                  minimum: -2
                  maximum: 2
                  default: 0
                logit_bias:
                  type: object
                  description: >-
                    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:
                  type: string
                  description: >-
                    A unique identifier for your end-user. Helps with abuse
                    detection and monitoring.
                max_completion_tokens:
                  type: integer
                  description: >-
                    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:
                  type: object
                  description: >-
                    Specifies the output format. Use `{"type": "json_object"}`
                    for JSON mode, or `{"type": "json_schema", "json_schema":
                    {...}}` for strict structured output.
                  properties:
                    type:
                      type: string
                      enum:
                        - text
                        - json_object
                        - json_schema
                      description: >-
                        Output format type: `text` (default), `json_object`, or
                        `json_schema`.
                    json_schema:
                      type: object
                      description: The JSON Schema definition.
                tools:
                  type: array
                  description: >-
                    A list of tools the model may call. Currently supports
                    `function` type tools.
                  items:
                    type: object
                    properties:
                      type:
                        type: string
                        enum:
                          - function
                        description: Tool type. Use `function`.
                      function:
                        type: object
                        properties:
                          name:
                            type: string
                            description: >-
                              Function name. The model repeats it inside
                              `tool_calls` when it calls the tool.
                          description:
                            type: string
                            description: >-
                              What the function does. The model uses this text
                              to decide when to call it.
                          parameters:
                            type: object
                            description: >-
                              JSON Schema object that describes the function
                              arguments.
                          strict:
                            type: boolean
                            description: >-
                              If `true`, the model must produce arguments that
                              exactly match the JSON Schema.
                        description: The function definition the model may call.
                tool_choice:
                  type:
                    - string
                    - object
                  description: >-
                    Controls how the model selects tools. `auto` (default):
                    model decides. `none`: no tools. `required`: must call a
                    tool.
                  default: auto
                logprobs:
                  type: boolean
                  description: Whether to return log probabilities of the output tokens.
                  default: false
                top_logprobs:
                  type: integer
                  description: >-
                    Number of most likely tokens to return at each position
                    (0-20). Requires `logprobs` to be `true`.
                  minimum: 0
                  maximum: 20
                reasoning_effort:
                  type: string
                  description: >-
                    Controls the reasoning effort for o-series and GPT-5.1+
                    models.
                  enum:
                    - low
                    - medium
                    - high
                stream_options:
                  type: object
                  description: Options for streaming. Only valid when `stream` is `true`.
                  properties:
                    include_usage:
                      type: boolean
                      description: >-
                        If true, includes usage stats in the final streaming
                        chunk.
                service_tier:
                  type: string
                  description: Specifies the processing tier.
                  enum:
                    - auto
                    - default
                    - flex
                    - priority
              default:
                model: gpt-5.6-sol
                messages:
                  - role: system
                    content: You are a helpful assistant.
                  - role: user
                    content: Hello!
            examples:
              Default:
                summary: Default
                value:
                  model: gpt-5.6-sol
                  messages:
                    - role: system
                      content: You are a helpful assistant.
                    - role: user
                      content: Hello!
              Image Input:
                summary: Image Input
                value:
                  model: gpt-4.1
                  messages:
                    - role: user
                      content:
                        - type: text
                          text: What is in this image?
                        - type: image_url
                          image_url:
                            url: https://picsum.photos/1920/1080
                  max_tokens: 300
              Streaming:
                summary: Streaming
                value:
                  model: gpt-5.6-sol
                  messages:
                    - role: system
                      content: You are a helpful assistant.
                    - role: user
                      content: Hello!
                  stream: true
              Function Calling:
                summary: Function Calling
                value:
                  model: gpt-5.4
                  messages:
                    - role: user
                      content: What is the weather like in Boston today?
                  tools:
                    - type: function
                      function:
                        name: get_current_weather
                        description: Get the current weather in a given location
                        parameters:
                          type: object
                          properties:
                            location:
                              type: string
                              description: The city and state, e.g. San Francisco, CA
                            unit:
                              type: string
                              enum:
                                - celsius
                                - fahrenheit
                              description: Temperature unit.
                          required:
                            - location
                  tool_choice: auto
      responses:
        '200':
          description: Successful chat completion response.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: Unique completion identifier.
                    example: chatcmpl-abc123
                  object:
                    type: string
                    enum:
                      - chat.completion
                    example: chat.completion
                    description: >-
                      Object type. Non-streaming responses use
                      `chat.completion`.
                  created:
                    type: integer
                    description: Unix timestamp of creation.
                    example: 1774412483
                  model:
                    type: string
                    description: The model used (may include version suffix).
                    example: gpt-5.4-2026-03-05
                  choices:
                    type: array
                    description: Array of completion choices.
                    items:
                      type: object
                      properties:
                        index:
                          type: integer
                          description: Index of this choice in the `choices` array.
                        message:
                          type: object
                          properties:
                            role:
                              type: string
                              enum:
                                - assistant
                              description: Role of the generated message, `assistant`.
                            content:
                              type:
                                - string
                                - 'null'
                              description: >-
                                The generated text. null when the model calls
                                tools.
                            refusal:
                              type:
                                - string
                                - 'null'
                              description: Refusal message if the model refused.
                            tool_calls:
                              type: array
                              description: Tool calls the model wants to make.
                              items:
                                type: object
                                properties:
                                  id:
                                    type: string
                                    description: >-
                                      Unique ID of the tool call. Send it back
                                      as `tool_call_id` with the tool result
                                      message.
                                  type:
                                    type: string
                                    enum:
                                      - function
                                    description: Tool call type, `function`.
                                  function:
                                    type: object
                                    properties:
                                      name:
                                        type: string
                                        description: Name of the function to call.
                                      arguments:
                                        type: string
                                        description: >-
                                          Function arguments as a JSON-encoded
                                          string. Parse before use; the model can
                                          produce invalid JSON.
                                    description: The function the model wants to call.
                            annotations:
                              type: array
                              items:
                                type: object
                              description: >-
                                Annotations attached to the message content,
                                such as URL citations, when the provider returns
                                them.
                          description: The assistant message generated by the model.
                        logprobs:
                          type:
                            - object
                            - 'null'
                          description: >-
                            Log probability details when the request sets
                            `logprobs`; otherwise `null`.
                        finish_reason:
                          type: string
                          enum:
                            - stop
                            - length
                            - tool_calls
                            - content_filter
                          description: >-
                            Why generation stopped: `stop`, `length`,
                            `tool_calls`, or `content_filter`.
                  usage:
                    type: object
                    properties:
                      prompt_tokens:
                        type: integer
                        example: 29
                        description: Tokens in the input messages.
                      completion_tokens:
                        type: integer
                        example: 2
                        description: >-
                          Tokens generated in the completion, including
                          reasoning tokens for reasoning models.
                      total_tokens:
                        type: integer
                        example: 31
                        description: Sum of prompt and completion tokens.
                      prompt_tokens_details:
                        type: object
                        properties:
                          cached_tokens:
                            type: integer
                            example: 0
                            description: >-
                              Prompt tokens served from the provider prompt
                              cache.
                          audio_tokens:
                            type: integer
                            example: 0
                            description: Prompt tokens that came from audio input.
                        description: Breakdown of prompt token sources.
                      completion_tokens_details:
                        type: object
                        properties:
                          reasoning_tokens:
                            type: integer
                            example: 0
                            description: >-
                              Tokens the model spent on internal reasoning.
                              Billed as output tokens.
                          audio_tokens:
                            type: integer
                            example: 0
                            description: Completion tokens used for audio output.
                          accepted_prediction_tokens:
                            type: integer
                            example: 0
                            description: >-
                              Predicted-output tokens that matched the final
                              output and were accepted.
                          rejected_prediction_tokens:
                            type: integer
                            example: 0
                            description: >-
                              Predicted-output tokens that did not match the
                              final output and were discarded.
                        description: Breakdown of completion token usage.
                    description: >-
                      Token accounting for this request. Billing uses these
                      counts.
                  service_tier:
                    type: string
                    example: default
                    description: >-
                      Service tier that processed the request, when the provider
                      reports one.
                  system_fingerprint:
                    type:
                      - string
                      - 'null'
                    example: fp_490a4ad033
                    description: >-
                      Provider backend configuration fingerprint, when the
                      provider reports one.
              example:
                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
        '400':
          description: >-
            Request validation failed before the request could be processed
            normally.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: ''
                  message: 'model name is required (request id: <request_id>)'
                  type: comet_api_error
        '401':
          description: API key is missing, malformed, or invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: ''
                  message: 'invalid token (request id: <request_id>)'
                  type: comet_api_error
        '500':
          description: >-
            Internal failure or a request-shape error surfaced as a
            server-status response.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  message: 'field messages is required (request id: <request_id>)'
                  type: comet_api_error
                  param: ''
                  code: invalid_request
      x-codeSamples:
        - lang: Python
          label: Default
          source: |
            import os
            from openai import OpenAI
            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            completion = client.chat.completions.create(
                model="gpt-5.6-sol",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "Hello!"},
                ],
            )

            print(completion.choices[0].message)
        - lang: Python
          label: Image Input
          source: |
            import os
            from openai import OpenAI
            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            completion = client.chat.completions.create(
                model="gpt-4.1",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": "What is in this image?"},
                            {
                                "type": "image_url",
                                "image_url": {"url": "https://picsum.photos/1920/1080"},
                            },
                        ],
                    }
                ],
                max_tokens=300,
            )

            print(completion.choices[0].message)
        - lang: Python
          label: Streaming
          source: |
            import os
            from openai import OpenAI
            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            stream = client.chat.completions.create(
                model="gpt-5.4",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "Hello!"},
                ],
                stream=True,
            )

            for chunk in stream:
                if chunk.choices[0].delta.content is not None:
                    print(chunk.choices[0].delta.content, end="")
        - lang: Python
          label: Functions
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            completion = client.chat.completions.create(
                model="gpt-4.1",
                messages=[
                    {"role": "user", "content": "What is the weather like in Boston today?"}
                ],
                tools=[
                    {
                        "type": "function",
                        "function": {
                            "name": "get_current_weather",
                            "description": "Get the current weather in a given location",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "location": {
                                        "type": "string",
                                        "description": "The city and state, e.g. San Francisco, CA",
                                    },
                                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                                },
                                "required": ["location"],
                            },
                        },
                    }
                ],
                tool_choice="auto",
            )

            print(completion.choices[0].message)
        - lang: Python
          label: Logprobs
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            completion = client.chat.completions.create(
                model="gpt-5.4",
                messages=[
                    {"role": "user", "content": "Hello!"}
                ],
                logprobs=True,
                top_logprobs=2,
            )

            print(completion.choices[0].logprobs)
        - lang: JavaScript
          label: Default
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const completion = await client.chat.completions.create({
                model: "gpt-5.6-sol",
                messages: [
                    { role: "system", content: "You are a helpful assistant." },
                    { role: "user", content: "Hello!" },
                ],
            });

            console.log(completion.choices[0].message);
        - lang: JavaScript
          label: Image Input
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const completion = await client.chat.completions.create({
                model: "gpt-4.1",
                messages: [
                    {
                        role: "user",
                        content: [
                            { type: "text", text: "What is in this image?" },
                            {
                                type: "image_url",
                                image_url: { url: "https://picsum.photos/1920/1080" },
                            },
                        ],
                    },
                ],
                max_tokens: 300,
            });

            console.log(completion.choices[0].message);
        - lang: JavaScript
          label: Streaming
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const stream = await client.chat.completions.create({
                model: "gpt-5.6-sol",
                messages: [
                    { role: "system", content: "You are a helpful assistant." },
                    { role: "user", content: "Hello!" },
                ],
                stream: true,
            });

            for await (const chunk of stream) {
                process.stdout.write(chunk.choices[0]?.delta?.content || "");
            }
        - lang: JavaScript
          label: Functions
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const completion = await client.chat.completions.create({
                model: "gpt-4.1",
                messages: [
                    { role: "user", content: "What is the weather like in Boston today?" },
                ],
                tools: [
                    {
                        type: "function",
                        function: {
                            name: "get_current_weather",
                            description: "Get the current weather in a given location",
                            parameters: {
                                type: "object",
                                properties: {
                                    location: { type: "string", description: "The city and state" },
                                    unit: { type: "string", enum: ["celsius", "fahrenheit"] },
                                },
                                required: ["location"],
                            },
                        },
                    },
                ],
                tool_choice: "auto",
            });

            console.log(completion.choices[0].message);
        - lang: JavaScript
          label: Logprobs
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const completion = await client.chat.completions.create({
                model: "gpt-5.4",
                messages: [
                    { role: "user", content: "Hello!" },
                ],
                logprobs: true,
                top_logprobs: 2,
            });

            console.log(completion.choices[0].logprobs);
        - lang: Shell
          label: Default
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "gpt-5.6-sol",
                "messages": [
                  {"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": "Hello!"}
                ]
              }'
        - lang: Shell
          label: Image Input
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "gpt-4.1",
                "messages": [
                  {
                    "role": "user",
                    "content": [
                      {"type": "text", "text": "What is in this image?"},
                      {"type": "image_url", "image_url": {"url": "https://picsum.photos/1920/1080"}}
                    ]
                  }
                ],
                "max_tokens": 300
              }'
        - lang: Shell
          label: Streaming
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "gpt-5.6-sol",
                "messages": [
                  {"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": "Hello!"}
                ],
                "stream": true
              }'
        - lang: Shell
          label: Functions
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "gpt-4.1",
                "messages": [
                  {"role": "user", "content": "What is the weather like in Boston today?"}
                ],
                "tools": [
                  {
                    "type": "function",
                    "function": {
                      "name": "get_current_weather",
                      "description": "Get the current weather in a given location",
                      "parameters": {
                        "type": "object",
                        "properties": {
                          "location": {"type": "string", "description": "The city and state"},
                          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                        },
                        "required": ["location"]
                      }
                    }
                  }
                ],
                "tool_choice": "auto"
              }'
        - lang: Shell
          label: Logprobs
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "gpt-5.4",
                "messages": [
                  {"role": "user", "content": "Hello!"}
                ],
                "logprobs": true,
                "top_logprobs": 2
              }'
components:
  schemas:
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - message
            - type
          properties:
            message:
              type: string
              description: Human-readable error message. It often includes a request id.
            type:
              type: string
              description: CometAPI error type, such as `comet_api_error`.
            param:
              type:
                - string
                - 'null'
              description: Related parameter when the platform provides one.
            code:
              type:
                - string
                - 'null'
              description: Error code. Request-shape errors may use `invalid_request`.
          description: Error envelope returned for failed requests.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer token authentication. Use your CometAPI key.

````