# Use Chat Completions

Source: https://provod.ai/en/docs/chat-completions

## Send the smallest successful request

Choose an available chat model from `GET /v1/models`, then send a non-streaming request first:

```bash
export PROVOD_API_KEY="sk_..."

curl --fail-with-body --silent --show-error https://api.provod.ai/v1/chat/completions \
  -H "Authorization: Bearer $PROVOD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.4",
    "messages": [
      { "role": "user", "content": "Reply with ok" }
    ]
  }'
```

A representative successful response is:

```json
{
  "id": "chatcmpl_example",
  "object": "chat.completion",
  "created": 1786651200,
  "model": "openai/gpt-5.4",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "ok" },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 8,
    "completion_tokens": 1,
    "total_tokens": 9
  }
}
```

Read the assistant text from `choices[0].message.content`. Check `finish_reason` before assuming the answer is complete, and use the returned `usage` when the selected model reports it.

*A chat message is submitted and streamed back as incremental output.*

*OpenAI-compatible chat at `/v1/chat/completions`.*

## Set an output limit only when needed

The shipped request contract accepts either `max_completion_tokens` or the legacy spelling `max_tokens` as a positive integer. Send only one. The selected model's capabilities determine whether and how the limit can be used, so check its `supported_parameters` instead of treating either spelling as a universal workaround.

If you omit both fields, the service uses its current default when preparing and reserving the request. That default is not a promise about every model's maximum output. For a deliberate cap, send one field supported by the chosen model and inspect `finish_reason` in the result.

## Add streaming after the first request works

**Streaming** delivers an answer incrementally instead of waiting for the complete JSON response. Chat Completions uses &#x2A;*Server-Sent Events (SSE)**, a text format in which each event is carried in a `data:` record.

```bash
export PROVOD_API_KEY="sk_..."

curl --no-buffer --fail-with-body --silent --show-error https://api.provod.ai/v1/chat/completions \
  -H "Authorization: Bearer $PROVOD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.4",
    "messages": [
      { "role": "user", "content": "Reply with ok" }
    ],
    "stream": true
  }'
```

Each JSON event contributes a `choices[0].delta`; a successful stream ends with the literal marker `[DONE]`:

```text
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}

data: {"id":"chatcmpl_example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}

data: {"id":"chatcmpl_example","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

Handle three terminal cases: a non-2xx JSON error before SSE starts, an SSE payload containing an error, and a connection that closes before `[DONE]`. A **public error code** is the client-facing `error.code` value in an error payload; use it for diagnostics and retry decisions.

**Do not blindly retry delivered output**


Retry with bounded backoff only when no output has been delivered. After any text arrives, keep the partial result and ask the user or application to decide whether to continue: an automatic retry can duplicate work and cost, and confirmed usage from an interrupted stream may be billed.


## Get JSON matching a schema

Requires Bash, `curl` and `jq`. Set `AI_API_KEY` and `MODEL_ID` to a model whose catalog and contract confirm `response_format` with JSON Schema and strict mode. Catalog availability alone does not establish this support. The example makes one paid request; the expected result is an object with one boolean field, `ready`. The application must still check refusals, completion and the returned JSON.

```bash
set -euo pipefail
: "${AI_API_KEY:?Set the API key for your workspace}"
: "${MODEL_ID:?Choose a model supporting strict JSON Schema}"
API_BASE="${API_BASE:-https://api.provod.ai}"

REQUEST_JSON="$(jq -n --arg model "$MODEL_ID" '{
  model: $model,
  messages: [{role: "user", content: "Return ready as true."}],
  response_format: {
    type: "json_schema",
    json_schema: {
      name: "readiness", strict: true,
      schema: {type: "object", properties: {ready: {type: "boolean"}},
               required: ["ready"], additionalProperties: false}
    }
  }
}')"
RESPONSE_JSON="$(curl --fail-with-body --silent --show-error "$API_BASE/v1/chat/completions" \
  -H "Authorization: Bearer $AI_API_KEY" \
  -H "Content-Type: application/json" --data-binary "$REQUEST_JSON")"

jq -e '
  .choices[0]
  | if .finish_reason == "stop" and (.message.content | type) == "string"
    then .message.content | fromjson
    else error("No completed text response; inspect the response") end
  | if keys == ["ready"] and (.ready | type) == "boolean"
    then . else error("Unexpected response shape") end
' <<<"$RESPONSE_JSON"
```

## Key management and exact spending

Use ordinary API keys for model calls. A separate [management key](/en/docs/management-keys) controls keys, limits and analytics within its workspace. Chat Completions and Responses return the actual charge in `usage.cost` with `usage.currency`; `provod.billing.total_charge` preserves the exact decimal string. After a disconnect, use the saved `x-generation-id` and [generation lookup](/en/docs/generation-metadata), rather than repeating inference.

## Troubleshooting


**A request parameter is rejected**


Compare the body with this minimal example and the selected model's `supported_parameters`. Remove the unsupported known option or choose a model that publishes it; do not assume changing field case or switching token-limit spellings fixes every model.


**The stream closes without [DONE]**


Treat the response as incomplete. Record whether any output arrived, the HTTP status or terminal error payload, model ID, time, and request identifier if present. Do not automatically replay a request that already produced output.


**The request times out**


For long responses, enable streaming so output can arrive incrementally. If the timeout happens before any response output or SSE data arrives, a bounded retry with exponential backoff and jitter is allowed. If stream output has started, keep the partial result and do not retry automatically because that can duplicate work and cost. Timeout behavior depends on the request stage and current service configuration; do not assume a fixed 120-second limit.


**The answer is shorter than expected**


Inspect `finish_reason` and the one explicit output-limit field you sent. Compare that value with the current model limits; an internal reservation default is not a universal output limit.


**The model appears to forget earlier messages**


Every request must include the conversation history it needs. The public API does not automatically attach messages from a previous request, so inspect the submitted `messages` array and request-level input usage.
