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

# Eine Chat Completion erstellen

> Verwenden Sie CometAPI POST /v1/chat/completions, um Unterhaltungen mit mehreren Nachrichten an Chat-Modelle mit Steuerung für Streaming, temperature und max_tokens zu senden.

CometAPI leitet Chat Completions über eine einzige OpenAI-kompatible Schnittstelle an mehrere Anbieter weiter, darunter OpenAI, Claude und Gemini. Wechseln Sie zwischen Modellen, indem Sie den Parameter `model` ändern; die meisten OpenAI-kompatiblen SDKs funktionieren, wenn `base_url` auf `https://api.cometapi.com/v1` gesetzt wird.

<Warning>
  Anfrageparameter und Antwortfelder können sich je nach Modellanbieter erheblich unterscheiden. Prüfen Sie die offizielle Dokumentation des Anbieters hinter dem verwendeten Modell, wenn Sie die vollständige Parameterliste oder anbieterspezifisches Verhalten benötigen. Beispielsweise gilt `reasoning_effort` nur für Reasoning-Modelle (o-series, GPT-5.1+), und einige Modelle unterstützen `logprobs` oder `n` > 1 nicht.
</Warning>

<Note>
  Verwenden Sie für OpenAI-Pro-Modelle, o-series Reasoning-Modelle und Codex-Modelle stattdessen den [Responses](/de/api/text/responses) Endpunkt. Diese Modellfamilien werden von der Responses API umfassender unterstützt.
</Note>

***

## Nachrichtenrollen

| Rolle       | Beschreibung                                                                                                                     |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `system`    | Legt das Verhalten und die Persönlichkeit des Assistenten fest. Wird an den Anfang der Unterhaltung gestellt.                    |
| `developer` | Ersetzt `system` für neuere Modelle (o1+). Enthält Anweisungen, denen das Modell unabhängig von der Benutzereingabe folgen soll. |
| `user`      | Nachrichten des Endbenutzers.                                                                                                    |
| `assistant` | Frühere Modellantworten, die zur Aufrechterhaltung des Unterhaltungsverlaufs verwendet werden.                                   |
| `tool`      | Ergebnisse von Tool-/Funktionsaufrufen. Muss `tool_call_id` enthalten, das mit dem ursprünglichen Tool-Aufruf übereinstimmt.     |

<Tip>
  Bei neueren Modellen (GPT-4.1, GPT-5-Serie, o-series) sollten Sie für Anweisungsnachrichten `developer` gegenüber `system` bevorzugen. Beide funktionieren, aber `developer` sorgt für eine stärkere Befolgung von Anweisungen.
</Tip>

***

## Multimodal-Eingaben senden

Viele Modelle unterstützen neben Text auch Bilder und Audio. Verwenden Sie zum Senden von Multimodal-Nachrichten das Array-Format für `content`:

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

Der Parameter `detail` steuert die Analysetiefe für Bilder:

* `low` — schneller, verwendet weniger Tokens (feste Kosten)
* `high` — detaillierte Analyse, verbraucht mehr Tokens
* `auto` — das Modell entscheidet (Standard)

***

## Antworten streamen

Um inkrementelle Ausgaben zu erhalten, setzen Sie `stream` auf `true`. Die Antwort wird als **Server-Sent Events (SSE)**, wobei jedes Ereignis ein `chat.completion.chunk`-Objekt enthält:

```
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>
  Um Token-Nutzungsstatistiken in Streaming-Antworten einzuschließen, setzen Sie `stream_options.include_usage` auf `true`. Die Nutzungsdaten erscheinen im letzten Chunk vor `[DONE]`.
</Tip>

***

## Strukturierte Ausgabe anfordern

Um das Modell dazu zu zwingen, gültiges JSON zurückzugeben, das einem bestimmten Schema entspricht, verwenden Sie `response_format`:

<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>
  Der JSON-Schema-Modus (`json_schema`) garantiert, dass die Ausgabe exakt Ihrem Schema entspricht. Der JSON-Object-Modus (`json_object`) garantiert nur gültiges JSON – die Struktur wird nicht erzwungen.
</Note>

***

## Tools und Funktionen aufrufen

Um dem Modell den Aufruf externer Funktionen zu ermöglichen, stellen Sie Tool-Definitionen bereit:

```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"
}
```

Wenn das Modell entscheidet, ein Tool aufzurufen, enthält die Antwort `finish_reason: "tool_calls"`, und das Array `message.tool_calls` enthält den Funktionsnamen und die Argumente. Führen Sie anschließend die Funktion aus und senden Sie das Ergebnis als `tool`-Nachricht mit dem passenden `tool_call_id` zurück.

***

## Hinweise anbieterübergreifend

<AccordionGroup>
  <Accordion title="Parameterunterstützung bei verschiedenen Anbietern">
    | Parameter          | OpenAI GPT         | Claude (über compat) | Gemini (über compat)                            |
    | ------------------ | ------------------ | -------------------- | ----------------------------------------------- |
    | `temperature`      | 0–2                | 0–1                  | 0–2                                             |
    | `top_p`            | 0–1                | 0–1                  | 0–1                                             |
    | `n`                | 1–128              | nur 1                | 1–8                                             |
    | `stop`             | Bis zu 4           | Bis zu 4             | Bis zu 5                                        |
    | `tools`            | ✅                  | ✅                    | ✅                                               |
    | `response_format`  | ✅                  | ✅ (json\_schema)     | ✅                                               |
    | `logprobs`         | ✅                  | ❌                    | ❌                                               |
    | `reasoning_effort` | o-series, GPT-5.1+ | ❌                    | ❌ (Verwenden Sie `thinking` für natives Gemini) |
  </Accordion>

  <Accordion title="max_tokens im Vergleich zu max_completion_tokens">
    * **`max_tokens`** — Der Legacy-Parameter. Funktioniert mit den meisten Modellen, ist aber für neuere OpenAI-Modelle veraltet.
    * **`max_completion_tokens`** — Der empfohlene Parameter für GPT-4.1, die GPT-5-Serie und o-series-Modelle. Für Reasoning-Modelle erforderlich, da er sowohl Ausgabe-Tokens als auch Reasoning-Tokens umfasst.

    CometAPI übernimmt beim Routing an verschiedene Anbieter automatisch die Zuordnung.
  </Accordion>

  <Accordion title="system- im Vergleich zur developer-Rolle">
    * **`system`** — Die traditionelle Anweisungsrolle. Funktioniert mit allen Modellen.
    * **`developer`** — Mit o1-Modellen eingeführt. Bietet für neuere Modelle eine stärkere Befolgung von Anweisungen. Fällt bei älteren Modellen auf das Verhalten von `system` zurück.

    Verwenden Sie `developer` für neue Projekte, die auf GPT-4.1+- oder o-series-Modelle ausgerichtet sind.
  </Accordion>
</AccordionGroup>

***

## FAQ

### Wie gehe ich mit Ratenlimits um?

Implementieren Sie bei Auftreten von `429 Too Many Requests` exponentielles Backoff:

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

### Wie kann der Unterhaltungskontext erhalten werden?

Fügen Sie den vollständigen Unterhaltungsverlauf in das Array `messages` ein:

```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?"},
]
```

### Was bedeutet `finish_reason`?

| Wert             | Bedeutung                                                               |
| ---------------- | ----------------------------------------------------------------------- |
| `stop`           | Natürlicher Abschluss oder Erreichen einer Stop-Sequenz.                |
| `length`         | Das Limit für `max_tokens` oder `max_completion_tokens` wurde erreicht. |
| `tool_calls`     | Das Modell hat einen oder mehrere Tool-/Funktionsaufrufe ausgelöst.     |
| `content_filter` | Die Ausgabe wurde aufgrund der Inhaltsrichtlinie gefiltert.             |

### Wie lassen sich Kosten kontrollieren?

1. Verwenden Sie `max_completion_tokens`, um die Ausgabelänge zu begrenzen.
2. Verwenden Sie `gpt-5.6-terra` für ein Gleichgewicht zwischen Leistungsfähigkeit und Kosten oder `gpt-5.6-luna` für effiziente Workloads mit hohem Volumen.
3. Halten Sie Prompts prägnant – vermeiden Sie redundanten Kontext.
4. Überwachen Sie die Token-Nutzung im Antwortfeld `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.

````