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 usuallyhttp://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 onhttpx2. 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.
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - 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. - 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. - 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. - 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
-
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" -
Set the two environment variables the SDK reads when it creates a client.
OPENAI_BASE_URLis the gateway address with/v1at the end, because the SDK adds/chat/completions,/responsesand the other routes directly after it.export OPENAI_BASE_URL="https://gateway.example.com/v1"export OPENAI_API_KEY="sk-...your virtual key..." -
Leave the client construction as it is,
client = OpenAI(), or pass the same two values in code asbase_urlandapi_key. Values passed in code win over the environment. -
Use a public model name from step 1 as
model. Names are case sensitive. -
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.
| Header | What it tells you |
|---|---|
x-spanway-call-id | The id of this request. Search for it on Logs or send it to support. |
x-spanway-model-group, x-spanway-model-id | The public model name and the deployment that answered. |
x-spanway-routing-reason, x-spanway-attempts | Why the gateway picked that deployment and how many provider calls it took. See routing decision headers. |
x-spanway-response-cost, x-spanway-key-spend | What this request cost and what the key has spent so far. |
x-spanway-cache-key | Present 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
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | stream=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. |
| Tools | tools=[...] 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 cache | extra_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 caching | Nothing to change. Repeated long prefixes are cached by the provider. | Cached tokens show in usage.prompt_tokens_details.cached_tokens. See prompt caching. |
| Reasoning | reasoning_effort="low", "medium" or "high". | Mapped to the reasoning setting of other providers where they have one. |
| Parameters a provider lacks | Sent 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.
| Case | Exception | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | AuthenticationError (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 key | AuthenticationError (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 key | AuthenticationError (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 key | AuthenticationError (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 model | PermissionDeniedError (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 unknown | BadRequestError (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 take | BadRequestError (400) | does not support parameters: <names>, for model=<model> | Remove the parameter or ask the admin for drop_params: true. |
| The budget is spent | UnprocessableEntityError (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 limit | RateLimitError (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 /v1 | NotFoundError (404) | Not Found | Set OPENAI_BASE_URL to the address with exactly one /v1. |
| The provider failed and no fallback helped | InternalServerError (500 to 503) | The provider's own message, followed by the model group that failed | Retry later, and ask the admin for a fallback deployment. |
| Nothing listens at the address | APIConnectionError | None, 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 trusted | APIConnectionError | None. e.__cause__ holds CERTIFICATE_VERIFY_FAILED | The gateway's certificate comes from a company or private authority. See TLS below. |
| The answer took too long | APITimeoutError | None. The SDK prints Request timed out. | Raise timeout= on the client, or use streaming for long answers. |
OPENAI_API_KEY is not set | OpenAIError | None, raised before any request | Export OPENAI_API_KEY or pass api_key=. |
The client error reference has the same cases for every SDK.
Troubleshooting
-
Copy
x-spanway-call-idfrom the failing response, withe.response.headersin anexcept openai.APIStatusError as eblock or withwith_raw_response. -
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. -
If the request is not on Logs, it never reached the gateway. Turn on the SDK's own logging with
export OPENAI_LOG=debugand run again. The log shows the full URL the SDK called, which shows a doubled/v1or a wrong host at once. -
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 pointSSL_CERT_FILEat a PEM bundle, or pass the bundle in code.import sslfrom openai import DefaultHttpx2Client, OpenAIclient = OpenAI(http_client=DefaultHttpx2Client(verify=ssl.create_default_context(cafile="/etc/ssl/company-root.pem")))Releases before
httpx2call the same classDefaultHttpxClient. Never turn certificate checks off outside a test machine. -
Compare what you send with the routing headers.
x-spanway-routing-reasonandx-spanway-attemptsshow 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.
Related
- OpenAI Node SDK for the same steps in JavaScript and TypeScript.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error and the exception each SDK raises.
- Chat completions and Responses API for every request field.
- Calling the gateway for every request and response header.
- Make a key for a tool for the admin side.