OpenAI Python SDK with AIXHUB
Create an isolated Python environment, call AIXHUB Responses, inspect the full object, stream safely, and manage SDK upgrades.
The OpenAI Python SDK can call AIXHUB through the versioned Base URL https://api.aixhub.org/v1. This guide passes the AIXHUB key and Base URL explicitly so an existing official OpenAI environment cannot silently win.
Prerequisites
- A Python 3 installation supported by the current
openaipackage. Check withpy -3 --versionon Windows orpython3 --versionon macOS/Linux. - A dedicated AIXHUB API key for this application.
- An exact Responses-compatible model ID from Model routes. Examples use
panel-openai-model-idas a visible stand-in. - A disposable project directory that does not already contain a different virtual environment or a file named
openai.py.
AIXHUB_API_KEY and AIXHUB_MODEL are conventions used by this documentation. The SDK does not automatically read them; the script passes them to OpenAI(...) and responses.create(...) explicitly.
Steps
Create and activate a virtual environment
Windows PowerShell:
py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install openai
python -m pip show openaiIf activation is blocked by local policy, do not weaken the machine-wide policy. Run .\.venv\Scripts\python.exe -m pip ... and .\.venv\Scripts\python.exe aixhub_openai.py directly.
macOS or Linux:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install openai
python -m pip show openaiRecord the installed version before troubleshooting or upgrading. Do not use sudo pip or install into the system interpreter.
Set temporary credentials without storing the key in history
Open a disposable shell where AIXHUB_API_KEY and AIXHUB_MODEL are not already set. This prevents the test from overwriting another workflow's values.
Bash:
read -rsp "AIXHUB API key: " AIXHUB_API_KEY && echo
export AIXHUB_API_KEY
export AIXHUB_MODEL="panel-openai-model-id"PowerShell:
$secureKey = Read-Host "AIXHUB API key" -AsSecureString
$env:AIXHUB_API_KEY = [System.Net.NetworkCredential]::new("", $secureKey).Password
$env:AIXHUB_MODEL = "panel-openai-model-id"Replace the model stand-in with the complete ID copied from the panel. In production, inject the key from an approved server-side secret store instead of an interactive shell.
Create the complete non-streaming script
Create aixhub_openai.py:
import os
import sys
import openai
from openai import OpenAI
def main() -> None:
client = OpenAI(
api_key=os.environ["AIXHUB_API_KEY"],
base_url="https://api.aixhub.org/v1",
max_retries=0,
timeout=60.0,
)
try:
response = client.responses.create(
model=os.environ["AIXHUB_MODEL"],
input="Reply with OK only.",
)
print(response.output_text)
print(response.model_dump_json(indent=2))
request_id = getattr(response, "_request_id", None)
if request_id:
print(f"request_id={request_id}")
if response.status != "completed":
raise RuntimeError(f"response ended with status={response.status}")
except openai.APIStatusError as exc:
print(f"status_code={exc.status_code}", file=sys.stderr)
if exc.request_id:
print(f"request_id={exc.request_id}", file=sys.stderr)
raise
finally:
client.close()
if __name__ == "__main__":
main()The official SDK's output_text convenience property combines text output. model_dump_json() keeps the complete typed response visible for field inspection. Do not assume output[0] is a text message when processing the raw object.
Run the script with the Python from the active virtual environment:
python aixhub_openai.pyStream text and require a terminal event
Create aixhub_openai_stream.py:
import os
import sys
import openai
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIXHUB_API_KEY"],
base_url="https://api.aixhub.org/v1",
max_retries=0,
timeout=60.0,
)
final_response = None
try:
with client.responses.with_streaming_response.create(
model=os.environ["AIXHUB_MODEL"],
input="Reply with OK only.",
stream=True,
) as raw_response:
if raw_response.request_id:
print(f"request_id={raw_response.request_id}", file=sys.stderr)
events = raw_response.parse()
for event in events:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif event.type == "response.completed":
final_response = event.response
elif event.type in {"response.failed", "response.incomplete", "error"}:
raise RuntimeError(f"stream ended with {event.type}")
print()
if final_response is None:
raise RuntimeError("stream closed without a terminal response.completed event")
print(final_response.model_dump_json(indent=2))
except openai.APIStatusError as exc:
print(f"status_code={exc.status_code}", file=sys.stderr)
if exc.request_id:
print(f"request_id={exc.request_id}", file=sys.stderr)
raise
finally:
client.close()Run it with python aixhub_openai_stream.py. Partial text and HTTP 200 are not enough; only response.completed is success. Check Usage before replaying a failed, incomplete, timed-out, or disconnected generation.
Verification
The first line from the non-streaming script, and the accumulated streaming text, should be:
OKAlso verify:
- The full response reports
statusascompletedand contains the expected model ID. - A request ID is recorded only when the SDK exposes one; do not synthesize it.
- AIXHUB Usage contains a request at the same time with the selected model and successful status.
- The stream reached
response.completed, not merely a connection close after partial text.
Troubleshooting
ModuleNotFoundErroror noresponsesattribute: Confirmpython -m pip show openaipoints into the active.venv; rename any localopenai.py, then upgrade the package in that environment.- 401 /
AuthenticationError: Confirm the script receivesAIXHUB_API_KEYand thatbase_urlis AIXHUB. Do not substitute an official OpenAI account token. - 403 /
PermissionDeniedError: Check key group, subscription, and balance.INSUFFICIENT_BALANCEis a 403 condition. - 404 /
NotFoundError: Keepbase_url="https://api.aixhub.org/v1"; the SDK appends/responses. Recopy the model and confirm it supports Responses. - 429 /
RateLimitError: Honor an actualRetry-After, reduce concurrency, and use a bounded retry budget. APIConnectionErroror timeout: Check proxy, TLS, DNS, and network state. The result is ambiguous; inspect Usage before sending another billable generation.APIStatusError: Recordstatus_codeandrequest_idwhen present. Redact the response body before sharing it, because it can contain application data.- Empty
output_text: Inspect the complete object and iterate output items bytype; a response can contain reasoning, tool calls, or non-text content before a message.
The verification scripts set max_retries=0 so one command produces one observable SDK attempt. In production, choose exactly one retry owner: either enable SDK retries and do not wrap the call in an application retry loop, or keep max_retries=0 and let the application own retries. Cap all layers together at three total attempts including the original request. For example, SDK max_retries=2 already consumes that complete budget. Check Usage before replaying an ambiguous timeout, 5xx, failed stream, incomplete stream, or disconnect, and never replay unless the application accepts duplicate output and charges. See Error code reference.
Next step
Compare the generated object with the raw OpenAI Responses reference, or review Authentication and Base URL before moving this code into a service.
Upgrade and restore
Before upgrading, record the working package set:
python -m pip freeze > requirements.before-aixhub-sdk.txt
python -m pip show openaiUpgrade only inside the virtual environment, then rerun both scripts and Usage verification:
python -m pip install --upgrade openai
python -m pip check
python aixhub_openai.pyIf an upgrade breaks a previously verified integration, reinstall the recorded version in the same virtual environment and test again:
python -m pip install "openai==<recorded-version>"To stop using the package in this environment:
python -m pip uninstall openai
deactivateDelete the virtual environment or sample scripts only when they were created solely for this guide and contain no work that must be retained. Revoke the dedicated AIXHUB key after confirming no deployed service uses it.
Security
-
Keep the key out of source files,
.envfiles committed to Git, tracebacks, notebooks, telemetry, and full HTTP logs. -
AIXHUB_API_KEYis plain text in the current process environment after input. Limit child processes and use a real secret store for deployed services. -
The full response can contain prompts, generated content, tool arguments, and metadata. Redact it before logging or sharing.
-
Set retry, timeout, and duplicate-handling policies explicitly for billable generation.
-
In the disposable shell opened for this guide, clear temporary state after testing:
unset AIXHUB_API_KEY AIXHUB_MODELRemove-Item Env:AIXHUB_API_KEY, Env:AIXHUB_MODEL -ErrorAction SilentlyContinue Remove-Variable secureKey -ErrorAction SilentlyContinueIf either environment variable existed before this guide, do not run the cleanup commands in that shell. Use a separate terminal for the test, or restore the prior value from its authorized secret source.
Official sources
Last verified: 2026-07-14