Python
The OpenAI Python SDK accepts a custom base_url, so existing chat-completions code only needs the NexoAI versioned base and issued key.
Install the SDK
Use a virtual environment in application projects, then install openai:
bash
python -m pip install openaiMake a request
python
import os
from openai import OpenAI
gateway = os.environ.get("OPENAI_BASE_URL", "https://api.nexoai.ma")
client = OpenAI(
api_key=os.environ["OPENAI_API_KEY"],
base_url=f"{gateway.rstrip('/')}/v1",
)
completion = client.chat.completions.create(
model="gpt-5.4",
messages=[
{
"role": "user",
"content": "Explain idempotency in two concise sentences.",
}
],
)
print(completion.choices[0].message.content)Run it with the variables already set:
bash
python example.pyrstrip('/') makes the code tolerate either form of the root variable without producing a double slash. The SDK base still resolves consistently to https://api.nexoai.ma/v1.
Stream output
For interactive tools, stream deltas as the model produces them:
python
stream = client.chat.completions.create(
model="gpt-5.4",
messages=[{"role": "user", "content": "List three uses for a queue."}],
stream=True,
)
for chunk in stream:
text = chunk.choices[0].delta.content
if text:
print(text, end="", flush=True)
print()Streaming changes delivery, not billing: input and generated output tokens are still counted against the key and wallet.
Handle API failures
python
import openai
try:
completion = client.chat.completions.create(
model="gpt-5.4",
messages=[{"role": "user", "content": "ping"}],
)
except openai.AuthenticationError:
print("Check the NexoAI key and base URL.")
except openai.RateLimitError:
print("Check RPM, TPM, key budget, and wallet balance.")In production, log the error type and request correlation metadata, but do not log the authorization header or complete prompt content by default.
Switch models, not clients
To try deepseek-v4-flash or qwen3-coder-next, change the model value. The OpenAI client, gateway base, and key stay the same.
