Developer Tutorials
How to call the AIx API with Python and no SDK dependency
Build a server-side Python HTTP client with explicit timeouts, status handling and environment-based credentials. Includes the limits of mock verification.
An AI API request is an authenticated HTTP call that sends a model identifier and input to an inference endpoint. For a first AIx integration, keep the key on your server, choose an exact identifier from the catalog, send a small non-streaming request, and handle HTTP and connection failures separately.
This guide uses Python’s standard library rather than claiming a dedicated AIx SDK. The program below has been checked against a mocked response and the inspected request contract. Authenticated inference has not been live-tested.
Prerequisites and model selection
Use Python 3.10 or later and an AIx account with a permitted API key and sufficient credits. Create keys in the key dashboard. Do not paste a real key into source control, a browser bundle, a screenshot or an issue report.
Check the model catalog before choosing AIX_MODEL. The catalog’s billing listing establishes an identifier and configured rate. It is not proof that every upstream route is healthy or that every optional model feature works. Start with a text chat model and the simplest request before adding tools or images.
Set AIX_KEY and AIX_MODEL in your process environment using your deployment’s secret manager. The client reads these values without embedding them in the program. Do not put secrets into shell history on a shared machine.
Complete Python program
Save this program as chat.py and run python3 chat.py after configuring the environment. There is no package installation step.
"""Python 3.10+ standard-library HTTP integration, not an AIx SDK.
Mock-tested request shape; authenticated inference has not been live-tested.
Run: AIX_KEY=... AIX_MODEL=... python3 examples/chat.py
"""
import json
import os
import urllib.error
import urllib.request
def chat(key, model, opener=urllib.request.urlopen):
request = urllib.request.Request(
'https://api.aix.theaimart.co/v1/chat/completions',
data=json.dumps({'model': model, 'messages': [
{'role': 'user', 'content': 'Explain an HTTP timeout in one sentence.'}
], 'max_tokens': 128, 'stream': False}).encode(),
headers={'Authorization': f'Bearer {key}', 'Content-Type': 'application/json'},
method='POST',
)
try:
with opener(request, timeout=30) as response:
result = json.load(response)
return result['choices'][0]['message']['content']
except urllib.error.HTTPError as error:
# Do not print request headers, credentials or provider error bodies.
status = error.code
error.close()
raise RuntimeError(f'AIx returned HTTP {status}; inspect status-specific guidance.') from None
except (urllib.error.URLError, TimeoutError):
raise RuntimeError('Connection failed or timed out; completion and billing may be uncertain.') from None
except (ValueError, KeyError, IndexError, TypeError):
raise RuntimeError('Unexpected response shape; inspect the API contract.') from None
if __name__ == '__main__':
key = os.environ.get('AIX_KEY')
model = os.environ.get('AIX_MODEL')
if not key or not model:
raise SystemExit('Set AIX_KEY and AIX_MODEL in the server environment.')
try:
print(chat(key, model))
except RuntimeError as error:
raise SystemExit(str(error)) from None
How the request works
The endpoint is /v1/chat/completions, with the production inference origin rather than the public website origin. The Authorization header carries the key as a bearer credential. Content-Type describes the JSON body; it is not a replacement for authentication.
messages contains one user turn. max_tokens bounds the requested output length rather than making the call free. stream: false asks for a JSON response. The code checks the first text message and deliberately rejects malformed or unexpected response shapes. A tool-calling response needs a different handling loop; do not treat this text-only client as an agent framework.
The timeout passed to urlopen applies to blocking operations; it is not a guaranteed end-to-end wall-clock deadline including every possible DNS behavior. Set an application deadline separately when your service has a strict response budget.
Diagnose failures before retrying
| Outcome | First action |
|---|---|
| 400 | Check the model identifier, required fields and parameter support. |
| 401 or 403 | Check key validity and scope without printing the key. |
| 402 | Check credit balance and spend policies. Repetition cannot fix a funding problem. |
| 429 | Reduce concurrency and use a bounded retry policy. |
| 5xx | Record a sanitized failure and check status before another attempt. |
| Timeout | Treat completion and billing as uncertain; do not assume the server cancelled. |
Blind retries after a timeout can create duplicate work. Read error handling before adding automation. A small application should first surface a clear failure rather than enter an unbounded loop.
Safe production adaptation
Put the client behind your own authenticated backend endpoint. Apply per-user request limits, keep a server-side usage budget, and log status and duration without recording credentials or private prompts. Escape model output before rendering it into HTML, and validate generated data before using it in another system.
For application tests, inject a fake opener to exercise success, malformed responses and HTTP errors without spending credits. Then perform an explicitly permitted live smoke test with a small prompt, record the model and date, and inspect actual usage. Keep those live results distinct from unit test results.
The same request can be made from Node.js with native fetch; use the SDK and integration overview to choose an integration style. OpenAI-compatible request shapes do not imply that every SDK feature or every provider-specific parameter is supported.
References and verification
- Python urllib.request reference — checked
- AIx public billing catalog — checked
Reviewed 2026-10-21: Repository contract inspection and editorial review; executable examples use controlled mocks. No authenticated inference, billing benchmark or independent upstream verification.