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

# Opprett en chat completion

> Bruk CometAPI POST /v1/chat/completions til å sende samtaler med flere meldinger til chatmodeller med Streaming, strukturert utdata og verktøykall.

Send samtaler via det OpenAI-kompatible Chat Completions API-et. Konfigurer SDK-en med `base_url="https://api.cometapi.com/v1"` og CometAPI API-nøkkelen din.

Eksemplene for grunnleggende bruk, bilder, Streaming og strukturert utdata bruker `gpt-6-astra`. Function Calling-eksempelet bruker `gpt-5.6-sol`, og eksempelet med loggsannsynlighet bruker `gpt-4.1`.

<Note>
  Bruk [OpenAI Chat Completions-referansen](https://developers.openai.com/api/reference/typescript/resources/chat/subresources/completions/methods/create) for parameterdefinisjoner. For GPT-6 Astra-verktøykall bruker du [Responses](/api/text/responses), og følger [OpenAIs modellveiledning](https://developers.openai.com/api/docs/guides/latest-model).
</Note>

***

## Meldingsroller

| Rolle       | Beskrivelse                                                                                                          |
| ----------- | -------------------------------------------------------------------------------------------------------------------- |
| `system`    | Angir assistentens atferd og personlighet. Plasseres i starten av samtalen.                                          |
| `developer` | Inneholder applikasjonsinstruksjoner. Eksemplene for GPT-6 Astra bruker denne rollen.                                |
| `user`      | Meldinger fra sluttbrukeren.                                                                                         |
| `assistant` | Tidligere modellsvar, brukt for å opprettholde samtalehistorikken.                                                   |
| `tool`      | Resultater fra verktøy-/funksjonskall. Må inneholde `tool_call_id` som samsvarer med det opprinnelige verktøykallet. |

<Tip>
  Plasser applikasjonsinstruksjoner i en `developer`-melding før brukermeldinger når du bruker eksemplene for GPT-6 Astra.
</Tip>

***

## Send Multimodal-inndata

Bruk en matrise med innholdsdeler for å sende et bilde med tekst:

```json theme={null}
{
  "model": "gpt-6-astra",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Describe the road and surrounding landscape in this image."
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200",
            "detail": "high"
          }
        }
      ]
    }
  ],
  "reasoning_effort": "low",
  "max_completion_tokens": 4096
}
```

Bruk `image_url.detail` for å velge detaljnivå for bildebehandling. Dette eksempelet bruker `high`.

***

## Strøm responser

For å motta trinnvis utdata setter du `stream` til `true`. Responsen leveres som **Server-Sent Events (SSE)**. Teksten kommer i `chat.completion.chunk`-objekter; dette forkortede eksemplet inkluderer den endelige bruksblokken:

```text theme={null}
data: {"choices":[{"delta":{"content":"","refusal":null,"role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"}

data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null,"index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"}

: Additional text deltas omitted

data: {"choices":[{"delta":{},"finish_reason":"stop","index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"}

data: {"choices":[],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk","usage":{"completion_tokens":12,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens":18,"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0},"total_tokens":30}}

data: [DONE]
```

<Tip>
  For å inkludere token-bruksstatistikk i strømmende responser setter du `stream_options.include_usage` til `true`. Bruksdataene vises i en siste del før `[DONE]`. Deler kan ha en tom `choices`-matrise; kontroller den før du åpner `choices[0]`.
</Tip>

***

## Be om strukturert utdata

Bruk `response_format` for å be om strukturert utdata:

<CodeGroup>
  ```json JSON Schema theme={null}
  {
    "model": "gpt-6-astra",
    "messages": [
      {
        "role": "user",
        "content": "What is the capital of France? Return the answer and your confidence as a number from 0 to 1."
      }
    ],
    "reasoning_effort": "low",
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "result",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "answer": {
              "type": "string",
              "description": "The answer to the question."
            },
            "confidence": {
              "type": "number",
              "description": "Confidence between zero and one."
            }
          },
          "required": [
            "answer",
            "confidence"
          ],
          "additionalProperties": false
        }
      }
    }
  }
  ```

  ```json JSON Object theme={null}
  {
    "model": "gpt-6-astra",
    "messages": [
      {
        "role": "user",
        "content": "Return a JSON object with the key answer and the capital of France as its value."
      }
    ],
    "reasoning_effort": "low",
    "response_format": {
      "type": "json_object"
    }
  }
  ```
</CodeGroup>

JSON Schema-modus angir den nødvendige strukturen. JSON Object-modus ber om gyldig JSON uten å håndheve skjemaet ditt. Se etter et avslag eller en lengdebegrenset respons før du bruker resultatet.

***

## Kall verktøy og funksjoner

Bruk `gpt-5.6-sol` med en funksjonsdefinisjon:

```json theme={null}
{
  "model": "gpt-5.6-sol",
  "messages": [
    {
      "role": "user",
      "content": "What is the weather in Boston, MA, in celsius? Use the weather tool."
    }
  ],
  "reasoning_effort": "none",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City and state, for example Boston, MA."
            },
            "unit": {
              "type": "string",
              "enum": [
                "celsius",
                "fahrenheit"
              ],
              "description": "Temperature unit."
            }
          },
          "required": [
            "location",
            "unit"
          ],
          "additionalProperties": false
        },
        "strict": true
      }
    }
  ],
  "tool_choice": "auto"
}
```

Et funksjonskall returnerer `finish_reason: "tool_calls"` og en `message.tool_calls`-array. Analyser funksjonens JSON-kodede `arguments`, kjør funksjonen, og legg deretter til assistentmeldingen og en resultatmelding av typen `tool` med tilhørende `tool_call_id`.

***

## Velg forespørselsparametere

<AccordionGroup>
  <Accordion title="Modellspesifikke parametere">
    Bruk `reasoning_effort` og `max_completion_tokens` med GPT-6 Astra. Eksemplene for Functions og Logprobs viser forespørselsalternativene for henholdsvis `gpt-5.6-sol` og `gpt-4.1`.

    For Claude- eller Gemini-spesifikke forespørselsformater, se [Anthropic Messages](/api/text/anthropic-messages) og [Gemini Generate content](/api/text/gemini-generating-content).
  </Accordion>

  <Accordion title="max_tokens og max_completion_tokens">
    Bruk `max_completion_tokens` for å begrense genererte Tokens for eksemplene med GPT-6 Astra. Dette inkluderer resonnering og synlig utdata, så sørg for plass til begge deler. `max_tokens` er en eldre parameter.
  </Accordion>

  <Accordion title="Instruksjonsroller">
    Bruk `developer` for applikasjonsinstruksjoner i eksemplene med GPT-6 Astra. Behold sluttbrukerinnhold i `user`-meldinger, og ta vare på tidligere assistentsvar når du fortsetter en samtale.
  </Accordion>
</AccordionGroup>

***

## Vanlige spørsmål

### Hvordan håndterer du hastighetsgrenser?

Når du støter på `429 Too Many Requests`, implementerer du eksponentiell tilbakegang:

```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-6-astra",
                messages=messages,
                reasoning_effort="low",
            )
        except RateLimitError:
            if i < max_retries - 1:
                wait_time = (2 ** i) + random.random()
                time.sleep(wait_time)
            else:
                raise
```

### Hvordan opprettholder du samtalekontekst?

Inkluder hele samtalehistorikken i `messages`-arrayet:

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

### Hva betyr `finish_reason` ?

| Verdi            | Betydning                                                     |
| ---------------- | ------------------------------------------------------------- |
| `stop`           | Naturlig avslutning eller traff en stoppsekvens.              |
| `length`         | Nådde grensen for `max_tokens` eller `max_completion_tokens`. |
| `tool_calls`     | Modellen utførte ett eller flere verktøy-/funksjonskall.      |
| `content_filter` | Utdata ble filtrert på grunn av innholdspolicyen.             |

### Hvordan kontrollerer du kostnader?

1. Bruk `max_completion_tokens` for å begrense utdatalengden.
2. Sammenlign modellpriser og velg en modell som oppfyller kravene til arbeidsbelastningen din.
3. Hold prompts konsise — unngå overflødig kontekst.
4. Overvåk Token-bruken i პასუხsfeltet `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: >-
        Send conversation messages through the OpenAI-compatible Chat
        Completions API.
      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-6-astra
                  default: gpt-6-astra
                messages:
                  type: array
                  description: >-
                    Conversation messages, including instructions, user input,
                    assistant replies, and tool results.
                  items:
                    type: object
                    properties:
                      role:
                        type: string
                        enum:
                          - system
                          - user
                          - assistant
                          - tool
                          - developer
                        description: >-
                          Message role. The GPT-6 Astra examples use developer
                          for instructions, user for input, assistant for
                          replies, and tool for function results.
                      content:
                        description: >-
                          Message text, multimodal content parts, or null for an
                          assistant message containing tool calls.
                        oneOf:
                          - type: string
                          - type: array
                            items:
                              type: object
                          - type: 'null'
                      tool_call_id:
                        type: string
                        description: >-
                          For a tool result message, the ID of the assistant
                          tool call being answered.
                      tool_calls:
                        type: array
                        items:
                          type: object
                        description: >-
                          Tool calls from a previous assistant response.
                          Preserve these when adding tool results to the
                          conversation.
                  default:
                    - role: developer
                      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. Omit this field for GPT-6 Astra.
                  minimum: 0
                  maximum: 2
                top_p:
                  type: number
                  description: >-
                    Nucleus sampling threshold. Omit this field for GPT-6 Astra.
                    For sampling overrides, adjust either top_p or temperature.
                  minimum: 0
                  maximum: 1
                'n':
                  type: integer
                  description: >-
                    Number of completion choices to generate for each input
                    message. Defaults to 1.
                stop:
                  description: >-
                    Stop string or list of up to four strings, for models that
                    support stop sequences.
                  oneOf:
                    - type: string
                    - type: array
                      items:
                        type: string
                      maxItems: 4
                max_tokens:
                  type: integer
                  description: >-
                    Legacy output-token limit. Use max_completion_tokens for the
                    GPT-6 Astra examples.
                  deprecated: true
                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
                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
                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: >-
                    Maximum generated tokens, including visible output and
                    reasoning. Leave enough room for both, as in the image-input
                    example.
                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: >-
                    Function definitions for a model that supports tool calling
                    on Chat Completions. The function example uses GPT-5.6 Sol;
                    use Responses for GPT-6 Astra tool calls.
                  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.
                logprobs:
                  type: boolean
                  description: >-
                    Return token log probabilities. Use gpt-4.1 as shown in the
                    Logprobs example.
                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: >-
                    Reasoning effort supported by the selected model. The GPT-6
                    Astra examples use low; the GPT-5.6 Sol function example
                    uses none. See the model reference for other supported
                    levels.
                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-6-astra
                messages:
                  - role: developer
                    content: You are a helpful assistant.
                  - role: user
                    content: Hello!
                reasoning_effort: low
            examples:
              Default:
                summary: Default
                value:
                  model: gpt-6-astra
                  messages:
                    - role: developer
                      content: You are a helpful assistant.
                    - role: user
                      content: Hello!
                  reasoning_effort: low
              Image Input:
                summary: Image Input
                value:
                  model: gpt-6-astra
                  messages:
                    - role: user
                      content:
                        - type: text
                          text: >-
                            Describe the road and surrounding landscape in this
                            image.
                        - type: image_url
                          image_url:
                            url: >-
                              https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200
                            detail: high
                  reasoning_effort: low
                  max_completion_tokens: 4096
              Streaming:
                summary: Streaming
                value:
                  model: gpt-6-astra
                  messages:
                    - role: developer
                      content: You are a helpful assistant.
                    - role: user
                      content: Hello!
                  reasoning_effort: low
                  stream: true
                  stream_options:
                    include_usage: true
              Functions:
                summary: Functions
                value:
                  model: gpt-5.6-sol
                  messages:
                    - role: user
                      content: >-
                        What is the weather in Boston, MA, in celsius? Use the
                        weather tool.
                  reasoning_effort: none
                  tools:
                    - type: function
                      function:
                        name: get_current_weather
                        description: Get the current weather for a city.
                        parameters:
                          type: object
                          properties:
                            location:
                              type: string
                              description: City and state, for example Boston, MA.
                            unit:
                              type: string
                              enum:
                                - celsius
                                - fahrenheit
                              description: Temperature unit.
                          required:
                            - location
                            - unit
                          additionalProperties: false
                        strict: true
                  tool_choice: auto
              Logprobs:
                summary: Logprobs
                value:
                  model: gpt-4.1
                  messages:
                    - role: user
                      content: Hello!
                  logprobs: true
                  top_logprobs: 2
              JSON Schema:
                summary: JSON Schema
                value:
                  model: gpt-6-astra
                  messages:
                    - role: user
                      content: >-
                        What is the capital of France? Return the answer and
                        your confidence as a number from 0 to 1.
                  reasoning_effort: low
                  response_format:
                    type: json_schema
                    json_schema:
                      name: result
                      strict: true
                      schema:
                        type: object
                        properties:
                          answer:
                            type: string
                            description: The answer to the question.
                          confidence:
                            type: number
                            description: Confidence between zero and one.
                        required:
                          - answer
                          - confidence
                        additionalProperties: false
              JSON Object:
                summary: JSON Object
                value:
                  model: gpt-6-astra
                  messages:
                    - role: user
                      content: >-
                        Return a JSON object with the key answer and the capital
                        of France as its value.
                  reasoning_effort: low
                  response_format:
                    type: json_object
      responses:
        '200':
          description: Successful chat completion response.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: Unique completion identifier.
                    example: chatcmpl_example
                  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: 1788763703
                  model:
                    type: string
                    description: The model used (may include version suffix).
                    example: gpt-6-astra
                  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 returned.
                          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: 18
                        description: Tokens in the input messages.
                      completion_tokens:
                        type: integer
                        example: 12
                        description: >-
                          Tokens generated in the completion, including
                          reasoning tokens for reasoning models.
                      total_tokens:
                        type: integer
                        example: 30
                        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 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
                    description: Service tier that processed the request, when returned.
                  system_fingerprint:
                    type:
                      - string
                      - 'null'
                    description: Model configuration fingerprint, when returned.
              example:
                choices:
                  - finish_reason: stop
                    index: 0
                    logprobs: null
                    message:
                      annotations: []
                      content: Hi! How can I help you today?
                      refusal: null
                      role: assistant
                created: 1788763703
                id: chatcmpl_example
                model: gpt-6-astra
                object: chat.completion
                usage:
                  completion_tokens: 12
                  completion_tokens_details:
                    accepted_prediction_tokens: 0
                    audio_tokens: 0
                    reasoning_tokens: 0
                    rejected_prediction_tokens: 0
                  prompt_tokens: 18
                  prompt_tokens_details:
                    audio_tokens: 0
                    cache_write_tokens: 0
                    cached_tokens: 0
                  total_tokens: 30
        '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-6-astra",
                messages=[
                    {
                        "role": "developer",
                        "content": "You are a helpful assistant.",
                    },
                    {
                        "role": "user",
                        "content": "Hello!",
                    },
                ],
                reasoning_effort="low",
            )

            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-6-astra",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": "Describe the road and surrounding landscape in this image.",
                            },
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200",
                                    "detail": "high",
                                },
                            },
                        ],
                    },
                ],
                reasoning_effort="low",
                max_completion_tokens=4096,
            )

            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-6-astra",
                messages=[
                    {
                        "role": "developer",
                        "content": "You are a helpful assistant.",
                    },
                    {
                        "role": "user",
                        "content": "Hello!",
                    },
                ],
                reasoning_effort="low",
                stream=True,
                stream_options={
                    "include_usage": True,
                },
            )

            for chunk in stream:
                if chunk.choices and chunk.choices[0].delta.content:
                    print(chunk.choices[0].delta.content, end="")
                if chunk.usage:
                    print("\nUsage:", chunk.usage)
        - 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-5.6-sol",
                messages=[
                    {
                        "role": "user",
                        "content": "What is the weather in Boston, MA, in celsius? Use the weather tool.",
                    },
                ],
                reasoning_effort="none",
                tools=[
                    {
                        "type": "function",
                        "function": {
                            "name": "get_current_weather",
                            "description": "Get the current weather for a city.",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "location": {
                                        "type": "string",
                                        "description": "City and state, for example Boston, MA.",
                                    },
                                    "unit": {
                                        "type": "string",
                                        "enum": [
                                            "celsius",
                                            "fahrenheit",
                                        ],
                                        "description": "Temperature unit.",
                                    },
                                },
                                "required": [
                                    "location",
                                    "unit",
                                ],
                                "additionalProperties": False,
                            },
                            "strict": True,
                        },
                    },
                ],
                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-4.1",
                messages=[
                    {
                        "role": "user",
                        "content": "Hello!",
                    },
                ],
                logprobs=True,
                top_logprobs=2,
            )

            print(completion.choices[0].logprobs)
        - lang: Python
          label: JSON Schema
          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-6-astra",
                messages=[
                    {
                        "role": "user",
                        "content": "What is the capital of France? Return the answer and your confidence as a number from 0 to 1.",
                    },
                ],
                reasoning_effort="low",
                response_format={
                    "type": "json_schema",
                    "json_schema": {
                        "name": "result",
                        "strict": True,
                        "schema": {
                            "type": "object",
                            "properties": {
                                "answer": {
                                    "type": "string",
                                    "description": "The answer to the question.",
                                },
                                "confidence": {
                                    "type": "number",
                                    "description": "Confidence between zero and one.",
                                },
                            },
                            "required": [
                                "answer",
                                "confidence",
                            ],
                            "additionalProperties": False,
                        },
                    },
                },
            )

            print(completion.choices[0].message)
        - lang: Python
          label: JSON Object
          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-6-astra",
                messages=[
                    {
                        "role": "user",
                        "content": "Return a JSON object with the key answer and the capital of France as its value.",
                    },
                ],
                reasoning_effort="low",
                response_format={
                    "type": "json_object",
                },
            )

            print(completion.choices[0].message)
        - 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-6-astra",
                "messages": [
                    {
                        "role": "developer",
                        "content": "You are a helpful assistant."
                    },
                    {
                        "role": "user",
                        "content": "Hello!"
                    }
                ],
                "reasoning_effort": "low"
            });

            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-6-astra",
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": "Describe the road and surrounding landscape in this image."
                            },
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200",
                                    "detail": "high"
                                }
                            }
                        ]
                    }
                ],
                "reasoning_effort": "low",
                "max_completion_tokens": 4096
            });

            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-6-astra",
                "messages": [
                    {
                        "role": "developer",
                        "content": "You are a helpful assistant."
                    },
                    {
                        "role": "user",
                        "content": "Hello!"
                    }
                ],
                "reasoning_effort": "low",
                "stream": true,
                "stream_options": {
                    "include_usage": true
                }
            });

            for await (const chunk of stream) {
                process.stdout.write(chunk.choices[0]?.delta?.content || "");
                if (chunk.usage) console.log("\nUsage:", chunk.usage);
            }
        - 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-5.6-sol",
                "messages": [
                    {
                        "role": "user",
                        "content": "What is the weather in Boston, MA, in celsius? Use the weather tool."
                    }
                ],
                "reasoning_effort": "none",
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_current_weather",
                            "description": "Get the current weather for a city.",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "location": {
                                        "type": "string",
                                        "description": "City and state, for example Boston, MA."
                                    },
                                    "unit": {
                                        "type": "string",
                                        "enum": [
                                            "celsius",
                                            "fahrenheit"
                                        ],
                                        "description": "Temperature unit."
                                    }
                                },
                                "required": [
                                    "location",
                                    "unit"
                                ],
                                "additionalProperties": false
                            },
                            "strict": true
                        }
                    }
                ],
                "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-4.1",
                "messages": [
                    {
                        "role": "user",
                        "content": "Hello!"
                    }
                ],
                "logprobs": true,
                "top_logprobs": 2
            });

            console.log(completion.choices[0].logprobs);
        - lang: JavaScript
          label: JSON Schema
          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-6-astra",
                "messages": [
                    {
                        "role": "user",
                        "content": "What is the capital of France? Return the answer and your confidence as a number from 0 to 1."
                    }
                ],
                "reasoning_effort": "low",
                "response_format": {
                    "type": "json_schema",
                    "json_schema": {
                        "name": "result",
                        "strict": true,
                        "schema": {
                            "type": "object",
                            "properties": {
                                "answer": {
                                    "type": "string",
                                    "description": "The answer to the question."
                                },
                                "confidence": {
                                    "type": "number",
                                    "description": "Confidence between zero and one."
                                }
                            },
                            "required": [
                                "answer",
                                "confidence"
                            ],
                            "additionalProperties": false
                        }
                    }
                }
            });

            console.log(completion.choices[0].message);
        - lang: JavaScript
          label: JSON Object
          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-6-astra",
                "messages": [
                    {
                        "role": "user",
                        "content": "Return a JSON object with the key answer and the capital of France as its value."
                    }
                ],
                "reasoning_effort": "low",
                "response_format": {
                    "type": "json_object"
                }
            });

            console.log(completion.choices[0].message);
        - 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-6-astra",
              "messages": [
                {
                  "role": "developer",
                  "content": "You are a helpful assistant."
                },
                {
                  "role": "user",
                  "content": "Hello!"
                }
              ],
              "reasoning_effort": "low"
            }'
        - 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-6-astra",
              "messages": [
                {
                  "role": "user",
                  "content": [
                    {
                      "type": "text",
                      "text": "Describe the road and surrounding landscape in this image."
                    },
                    {
                      "type": "image_url",
                      "image_url": {
                        "url": "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200",
                        "detail": "high"
                      }
                    }
                  ]
                }
              ],
              "reasoning_effort": "low",
              "max_completion_tokens": 4096
            }'
        - lang: Shell
          label: Streaming
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              --no-buffer \
              -d '{
              "model": "gpt-6-astra",
              "messages": [
                {
                  "role": "developer",
                  "content": "You are a helpful assistant."
                },
                {
                  "role": "user",
                  "content": "Hello!"
                }
              ],
              "reasoning_effort": "low",
              "stream": true,
              "stream_options": {
                "include_usage": 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-5.6-sol",
              "messages": [
                {
                  "role": "user",
                  "content": "What is the weather in Boston, MA, in celsius? Use the weather tool."
                }
              ],
              "reasoning_effort": "none",
              "tools": [
                {
                  "type": "function",
                  "function": {
                    "name": "get_current_weather",
                    "description": "Get the current weather for a city.",
                    "parameters": {
                      "type": "object",
                      "properties": {
                        "location": {
                          "type": "string",
                          "description": "City and state, for example Boston, MA."
                        },
                        "unit": {
                          "type": "string",
                          "enum": [
                            "celsius",
                            "fahrenheit"
                          ],
                          "description": "Temperature unit."
                        }
                      },
                      "required": [
                        "location",
                        "unit"
                      ],
                      "additionalProperties": false
                    },
                    "strict": true
                  }
                }
              ],
              "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-4.1",
              "messages": [
                {
                  "role": "user",
                  "content": "Hello!"
                }
              ],
              "logprobs": true,
              "top_logprobs": 2
            }'
        - lang: Shell
          label: JSON Schema
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
              "model": "gpt-6-astra",
              "messages": [
                {
                  "role": "user",
                  "content": "What is the capital of France? Return the answer and your confidence as a number from 0 to 1."
                }
              ],
              "reasoning_effort": "low",
              "response_format": {
                "type": "json_schema",
                "json_schema": {
                  "name": "result",
                  "strict": true,
                  "schema": {
                    "type": "object",
                    "properties": {
                      "answer": {
                        "type": "string",
                        "description": "The answer to the question."
                      },
                      "confidence": {
                        "type": "number",
                        "description": "Confidence between zero and one."
                      }
                    },
                    "required": [
                      "answer",
                      "confidence"
                    ],
                    "additionalProperties": false
                  }
                }
              }
            }'
        - lang: Shell
          label: JSON Object
          source: |
            curl https://api.cometapi.com/v1/chat/completions \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
              "model": "gpt-6-astra",
              "messages": [
                {
                  "role": "user",
                  "content": "Return a JSON object with the key answer and the capital of France as its value."
                }
              ],
              "reasoning_effort": "low",
              "response_format": {
                "type": "json_object"
              }
            }'
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.

````