Skip to main content

OpenAI Python SDK

The OpenAI Python SDK is the openai package that most Python apps use to call a model. Pointed at the Spanway gateway, the same code reaches any model the gateway serves, OpenAI or not, while your admin decides which models the app may use, how much it may spend and how fast it may call. The app keeps one key, the gateway's virtual key, and never holds a provider key.

A real-world scenario​

A support team runs a Python service that drafts replies with client.chat.completions.create. Finance wants a monthly cap on its spend and security wants the OpenAI key out of the service. The admin creates a virtual key named support-drafts with a 300 USD monthly budget and the two models the service uses. The team sets OPENAI_BASE_URL and OPENAI_API_KEY in the service's environment and redeploys without touching the code. From then on every draft shows on the Logs page under support-drafts, and when the budget runs out the service gets a clear UnprocessableEntityError instead of a surprise invoice.

Prerequisites​

  • A running gateway and its address, written here as https://gateway.example.com. On your own machine it is usually http://localhost:4000.
  • At least one model registered on the gateway under a public name, for example gpt-6.1-sol. An admin does this in Models + Endpoints.
  • Python 3.10 or later and the SDK, installed with pip install --upgrade openai. Recent versions are built on httpx2. Everything on this page also works on the 1.x releases unless a step says otherwise.

Make a key for this app​

Give the app its own key so its spend, errors and limits stay separate from every other tool.

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Under Key Details, set Key Name to a name that says which app it is, such as support-drafts. Leave Key Type on AI APIs, so the key can call models but cannot change the gateway.
  3. In Models, pick every public model name the app calls. Include the small model the app uses for cheap background jobs, such as summaries or classification, for example claude-haiku-5-5, or those calls fail with 403 while the main calls work.
  4. Open Optional Settings. Set Max Budget (USD) and Reset Budget, for example 300 USD monthly, and a Requests per minute Limit (RPM) that fits the app, for example 120. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.

The same key from the API, with the master key or a proxy admin's key:

curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "support-drafts", "key_type": "llm_api", "models": ["gpt-6.1-sol", "claude-haiku-5-5"], "max_budget": 300, "budget_duration": "30d", "rpm_limit": 120}'

The answer carries the new key in key. More options are described in make a key for a tool.

Steps​

  1. Check the key and the model names from a terminal before you change the app.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  2. Set the two environment variables the SDK reads when it creates a client. OPENAI_BASE_URL is the gateway address with /v1 at the end, because the SDK adds /chat/completions, /responses and the other routes directly after it.

    export OPENAI_BASE_URL="https://gateway.example.com/v1"
    export OPENAI_API_KEY="sk-...your virtual key..."
  3. Leave the client construction as it is, client = OpenAI(), or pass the same two values in code as base_url and api_key. Values passed in code win over the environment.

  4. Use a public model name from step 1 as model. Names are case sensitive.

  5. Run the app once and open Logs (/ui/logs) to see the request, as described under expected result.

The gateway also answers the OpenAI routes without /v1, so https://gateway.example.com works too. A base URL that ends in /v1/v1, or that has any other path after the host, fails with 404. See the /v1 rule.

Configuration​

A complete script you can paste and run. It reads the key from the environment and sends one gateway tag with the request.

import os

from openai import OpenAI

client = OpenAI(
base_url=os.environ.get("OPENAI_BASE_URL", "https://gateway.example.com/v1"),
api_key=os.environ["OPENAI_API_KEY"],
)

completion = client.chat.completions.create(
model="gpt-6.1-sol",
messages=[{"role": "user", "content": "Explain a model group in one sentence."}],
extra_headers={"x-spanway-tags": "app:support-drafts"},
)
print(completion.choices[0].message.content)

The Responses API works the same way with client.responses.create(model="gpt-6.1-sol", input="..."), see Responses API. The async client is AsyncOpenAI with the same arguments.

Gateway features that have no SDK argument go in extra_headers for request headers and extra_body for body fields. Useful ones are x-spanway-tags for tags, x-spanway-session-id to group a conversation, x-spanway-trace-id to link your own tracing, x-spanway-timeout for a per-request timeout in seconds, and the cache body field described under caching. Every request header is listed on calling the gateway.

Expected result​

The script prints the model's answer. A request to the gateway answers in the same shape as OpenAI, with model, choices and usage.

To see what the gateway did, read the response headers with with_raw_response:

raw = client.chat.completions.with_raw_response.create(
model="gpt-6.1-sol",
messages=[{"role": "user", "content": "Hello"}],
)
print(raw.headers.get("x-spanway-call-id"), raw.headers.get("x-spanway-model-group"), raw.headers.get("x-spanway-routing-reason"))
completion = raw.parse()

A run against a test gateway printed this.

3af12a24-7f82-40a5-9e1f-df8236ff8b62 gpt-6.1-sol strategy=simple-shuffle

The headers worth logging in your app are these.

HeaderWhat it tells you
x-spanway-call-idThe id of this request. Search for it on Logs or send it to support.
x-spanway-model-group, x-spanway-model-idThe public model name and the deployment that answered.
x-spanway-routing-reason, x-spanway-attemptsWhy the gateway picked that deployment and how many provider calls it took. See routing decision headers.
x-spanway-response-cost, x-spanway-key-spendWhat this request cost and what the key has spent so far.
x-spanway-cache-keyPresent when the gateway's response cache was used.

On Logs (/ui/logs), click Filters, pick Key Alias = support-drafts and click Apply Filters. The row shows the model, the tokens, the cost and the status, and opening it shows the request, the answer and the deployment that served it.

Streaming, tools, images, caching and reasoning​

FeatureHow to use it through the gatewayNotes
Streamingstream=True, and stream_options={"include_usage": True} to get token counts in the last chunk.Works for every model behind the name. Keep include_usage on so your own usage numbers match the gateway's.
Toolstools=[...] and tool_choice exactly as for OpenAI.Translated for other providers. Parallel tool calls depend on the model that answers.
Images{"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}} content parts.The model behind the name must accept images. A text-only model rejects the request with 400.
Response cacheextra_body={"cache": {"no-cache": True}} skips the gateway cache for one call, {"ttl": 300} stores the answer for 300 seconds.Only when an admin turned on caching. A key can be limited to some of these controls.
Provider prompt cachingNothing to change. Repeated long prefixes are cached by the provider.Cached tokens show in usage.prompt_tokens_details.cached_tokens. See prompt caching.
Reasoningreasoning_effort="low", "medium" or "high".Mapped to the reasoning setting of other providers where they have one.
Parameters a provider lacksSent as usual.The gateway answers 400 does not support parameters unless the admin set drop_params: true, see drop params.

The SDK retries connection errors, 408, 409, 429 and 5xx answers twice by default, and the gateway has its own retries and fallbacks. One slow request can therefore turn into several provider attempts. Set max_retries=0 on the client when the gateway's retries should be the only ones. The default timeout is 10 minutes, set with timeout= on the client.

Errors​

Every error from the gateway arrives as a subclass of openai.APIStatusError with status_code, response and body. Printed, it reads Error code: <status> - {'error': {'message': '...', 'type': '...', 'param': None, 'code': '<status>'}}. Catch the class, log e.status_code, e.body and e.response.headers.get("x-spanway-call-id"), and look the call id up on Logs.

CaseExceptionText the gateway sendsCause and fix
No key on the requestAuthenticationError (401)Authentication Error, No api key passed in.The SDK always sends a key, so this comes from a proxy in between that strips Authorization. Check that hop.
Wrong or deleted keyAuthenticationError (401)Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db.Copy the key again from where the app reads it, or create a new key.
Blocked keyAuthenticationError (401)Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin.Ask the admin to open the key in Virtual Keys and click Unblock Key.
Expired keyAuthenticationError (401)Authentication Error - Expired Key. Key Expiry time <time> and current time <time>Ask the admin to extend the key or issue a new one.
The key may not use the modelPermissionDeniedError (403)The requested model '<model>' is not available for this API key, or the model name is invalid.Add the model to the key in Virtual Keys, or use a name from GET /v1/models.
The model name is unknownBadRequestError (400)Invalid model name passed in model=<name>No deployment has that public name. Use a name from client.models.list(), typed exactly.
A parameter the provider does not takeBadRequestError (400)does not support parameters: <names>, for model=<model>Remove the parameter or ask the admin for drop_params: true.
The budget is spentUnprocessableEntityError (422)Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max>Wait for Reset Budget or ask the admin to raise Max Budget (USD). With budget_exceeded_status_code: 429 the gateway answers 429 and the SDK raises RateLimitError.
The key or team is over its rate limitRateLimitError (429)Rate limit exceeded for <scope>: <value>. Limit type: <type>.The SDK already retried twice. Slow down, or ask for a higher RPM or TPM limit. The retry-after and x-spanway-rate-limited-by headers say how long to wait and which limit fired.
Wrong path, often a doubled /v1NotFoundError (404)Not FoundSet OPENAI_BASE_URL to the address with exactly one /v1.
The provider failed and no fallback helpedInternalServerError (500 to 503)The provider's own message, followed by the model group that failedRetry later, and ask the admin for a fallback deployment.
Nothing listens at the addressAPIConnectionErrorNone, the gateway never answered. The SDK prints Connection error.Check the address and port, and that the gateway runs with curl https://gateway.example.com/health/liveliness. Inside Docker, localhost is the container itself, so use host.docker.internal.
TLS certificate not trustedAPIConnectionErrorNone. e.__cause__ holds CERTIFICATE_VERIFY_FAILEDThe gateway's certificate comes from a company or private authority. See TLS below.
The answer took too longAPITimeoutErrorNone. The SDK prints Request timed out.Raise timeout= on the client, or use streaming for long answers.
OPENAI_API_KEY is not setOpenAIErrorNone, raised before any requestExport OPENAI_API_KEY or pass api_key=.

The client error reference has the same cases for every SDK.

Troubleshooting​

  1. Copy x-spanway-call-id from the failing response, with e.response.headers in an except openai.APIStatusError as e block or with with_raw_response.

  2. Open Logs (/ui/logs), filter by Key Alias or paste the call id into the search box, and open the row. It shows the status, the error, the deployment the gateway picked and the provider's own answer.

  3. If the request is not on Logs, it never reached the gateway. Turn on the SDK's own logging with export OPENAI_LOG=debug and run again. The log shows the full URL the SDK called, which shows a doubled /v1 or a wrong host at once.

  4. For a TLS error, the SDK trusts the operating system's certificate store since it moved to httpx2, so installing the company root certificate on the machine fixes it. You can also point SSL_CERT_FILE at a PEM bundle, or pass the bundle in code.

    import ssl

    from openai import DefaultHttpx2Client, OpenAI

    client = OpenAI(http_client=DefaultHttpx2Client(verify=ssl.create_default_context(cafile="/etc/ssl/company-root.pem")))

    Releases before httpx2 call the same class DefaultHttpxClient. Never turn certificate checks off outside a test machine.

  5. Compare what you send with the routing headers. x-spanway-routing-reason and x-spanway-attempts show retries and fallbacks, and routing decision headers explains each part.

More symptoms are in troubleshooting.

Rotation and removal​

To rotate, open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h so the old key keeps working while you deploy, and put the new key in OPENAI_API_KEY. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}. Regeneration needs an Enterprise license. Without one, create a new key, move the app to it and delete the old one.

To stop the app at once while you investigate, use Block Key in the key's actions menu, or POST /key/block with {"key": "<key>"}. Unblock Key undoes it. To remove the key for good, delete it in Virtual Keys or call POST /key/delete with {"keys": ["<key>"]}. Its spend history stays for audit, and every later request with it fails with 401.

To take the app off the gateway, unset OPENAI_BASE_URL and put a provider key back in OPENAI_API_KEY. No other code change is needed.