Skip to content
IQ

OpenAI · Python

The OpenAI Python SDK accepts a base_url argument on the client constructor. Point it at the gateway and every chat completion routes to a model from your connected providers without changing the call sites in your application code. This recipe ships a short script that you can drop into a fresh virtualenv, install one package, and run against your own org.

Drop-in switch

Two lines change in your existing client construction.

client = OpenAI(
    base_url="https://gateway.iq-routing.com/v1",
    api_key="gw_live_xxxxxxxx",
)

See Authentication for how to generate a gw_live_... key and where to store it. The base_url swap routes the request through the gateway. Everything below the client (calls to client.chat.completions.create and client.models.list) hits the gateway, which forwards to the upstream provider the gateway picks. The gateway serves the chat, models, and Responses paths; it does not implement /v1/embeddings, so leave embedding calls pointed at your provider.

Verify it routes

import json
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://gateway.iq-routing.com/v1",
    api_key=os.environ["IQ_API_KEY"],
)

response = client.chat.completions.with_raw_response.create(
    model="auto",
    messages=[{"role": "user", "content": "Summarise: routing-aware gateway."}],
    max_tokens=64,
)

print("X-Request-Id:", response.headers.get("x-request-id"))
print("Model:", response.headers.get("x-iq-model"))
telemetry = json.loads(response.headers.get("x-iq-routing", "{}"))
print("Provider:", telemetry.get("chosen_provider"))
print("Cache hit:", telemetry.get("cache_hit"))
print(response.parse().choices[0].message.content)

Set IQ_API_KEY in your environment, run the script. X-Request-Id is the correlation handle. When present, x-iq-model identifies the model IQ dispatched, or the model recorded for a cache hit. When routing telemetry is enabled, a non-streaming reply like this one can also include x-iq-routing with JSON fields such as chosen_model, chosen_provider and cache_hit. Without that header, the provider and cache-hit lines print None. Open /requests/<uuid> with the X-Request-Id value to see the recorded model, provider, token counts and cost. If your code sets its own X-Request-Id, IQ records the call under an ID it generates instead.

Use model="auto" for routing, or pass a model ID to keep the request within that model's family. Find the request in Requests by its X-Request-Id to see the model IQ recorded.

Using capability aliases

Pass cap:<name> in the model field to request a capability; check the x-iq-model response header for the dispatched or recorded model and manage your workspace's overrides at /settings/capabilities.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://gateway.iq-routing.com/v1",
    api_key=os.environ["IQ_API_KEY"],
)

completion = client.chat.completions.create(
    model="cap:reason-heavy",
    messages=[{"role": "user", "content": "Plan the migration in three phases."}],
)

Use with_raw_response to read the response headers, as in the Verify it routes example. When routing telemetry is enabled, non-streaming replies can also include x-iq-routing with JSON fields such as chosen_model, chosen_provider and cache_hit. Decode it with json.loads(response.headers.get("x-iq-routing", "{}")). See the capability aliases docs for the full list of default mappings and how to override them. A workspace owner or admin can override the default capability mapping in the editor at /settings/capabilities.

Common gotchas

A missing or invalid API key returns 401 before the request reaches routing -- no provider call is made and nothing is billed. See the API reference for the full set of status codes and error body shapes.

The gateway allows up to 600 seconds per provider attempt and 1800 seconds across the fallback loop; streaming limits cover upstream stream readiness rather than the full token stream, so set an explicit client timeout if you need a shorter limit.

client = OpenAI(
    base_url="https://gateway.iq-routing.com/v1",
    api_key=os.environ["IQ_API_KEY"],
    timeout=60.0,
)

When the fallback chain runs out because providers are overloaded or returning server errors, the gateway returns 503 with type: "service_unavailable" and code: "overloaded" in the error body. Use your own backoff schedule for this response.

The SDK's default retry behaviour catches 429 and retries with exponential backoff up to two times. IQ's own rate-limit and daily-budget 429s carry a Retry-After hint; monthly-budget and spend-ceiling 429s do not. SDK-side retries on top of that just burn calls inside the same cooldown window. Disable SDK retries when you call through the gateway:

client = OpenAI(
    base_url="https://gateway.iq-routing.com/v1",
    api_key=os.environ["IQ_API_KEY"],
    timeout=60.0,
    max_retries=0,
)

Streaming works as you would expect against /v1/chat/completions. The gateway forwards the SSE stream chunk-by-chunk; X-Request-Id arrives on the response headers before the first chunk, so you can log the correlation handle even on a streamed response.

Try this in the playground

Run this snippet against your gateway key →