SynapseX API cookbooks and recipes
Each recipe here is a complete, runnable pattern for something the SynapseX gateway actually serves — no capability is promised that the API does not forward. Copy one, change the model id and the key, and it runs.
All examples assume:
export SYNAPSEX_API_KEY=sk-synapsex-YOUR-API-KEYand the base URL https://platform.synapsex.ai/api/v1.
Recipe 1 — Stream tokens so the first word arrives immediately
Without streaming, the user waits for the entire completion. With stream: true
the gateway returns text/event-stream and you render deltas as they arrive.
from openai import OpenAI
client = OpenAI(
api_key="sk-synapsex-YOUR-API-KEY",
base_url="https://platform.synapsex.ai/api/v1",
)
stream = client.chat.completions.create(
model="synapsex-forge-code-14b-v1",
messages=[{"role": "user", "content": "Write a bash one-liner that finds large files."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)The wire format is standard OpenAI SSE: data: lines carrying
chat.completion.chunk objects, terminated by data: [DONE]. Full details,
including the raw curl form, are on
Chat completions and streaming.
A streamed response can still fail after the first byte, because the HTTP status was already sent as 200. Always handle a stream that ends early — do not assume a 200 means a complete answer.
Recipe 2 — Migrate an existing OpenAI app without a rewrite
Keep the client library you already ship. Change two values:
base_url = https://platform.synapsex.ai/api/v1
api_key = sk-synapsex-YOUR-API-KEYThat is the whole migration for Python, Node, Go and any tool that accepts a custom OpenAI base URL. What carries over and what does not — including the fields the gateway drops — is listed on OpenAI compatibility.
Recipe 3 — Route by per-token price
Most traffic does not need your most expensive model. Send the cheap path to a compact model and escalate only when a request needs it. Atlas is $0.10/$0.40 per 1M tokens; Quasar is $3.50/$14.00 — a 35× difference on input.
from openai import OpenAI
client = OpenAI(
api_key="sk-synapsex-YOUR-API-KEY",
base_url="https://platform.synapsex.ai/api/v1",
)
CHEAP = "synapsex-atlas-7b-v1"
STRONG = "synapsex-oracle-v1"
def needs_reasoning(prompt: str) -> bool:
"""Your own routing rule — length, task type, a classifier, or a user tier."""
return len(prompt) > 4000 or "prove" in prompt.lower()
def complete(prompt: str) -> str:
model = STRONG if needs_reasoning(prompt) else CHEAP
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=800, # cap the expensive half of the bill
)
return response.choices[0].message.contentTwo things make this cheaper than it looks: max_tokens bounds output, which is
billed at the higher rate, and the API is stateless, so switching models is just
changing one field on the next call. Current rates are on
Models and pricing.
Verify your ids at startup rather than hard-coding them blindly — see the catalog-check snippet on Models on the API.
Recipe 4 — Run a workspace agent over HTTP
A deployed agent is callable with the same key, the same wallet and the same usage records as a model call:
POST https://platform.synapsex.ai/api/v1/agents/{slug}/runcurl -sS https://platform.synapsex.ai/api/v1/agents/YOUR-AGENT-SLUG/run \
-H "Authorization: Bearer $SYNAPSEX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"input": "Summarise the attached incident timeline in five bullets."}'| Field | Required | Notes |
|---|---|---|
input | Yes | A string, or any JSON value — objects are serialised before the agent sees them. |
model | No | Overrides the agent’s default model for this run. |
The response is an agent.run object, with the text answer lifted out for you
and the underlying completion kept under raw:
{
"id": "…",
"object": "agent.run",
"status": "completed",
"agent_slug": "your-agent-slug",
"model": "synapsex-forge-code-14b-v1",
"output": { "text": "…" },
"raw": { "…": "the full chat completion" }
}Two preconditions decide whether this works, and both return HTTP 403:
- the key must carry the
chat:writescope, and - the agent must be deployed for your workspace. An agent that exists in the
catalog but is not deployed for your team is refused with
"Agent is not deployed for this workspace".
An unknown or inactive slug returns HTTP 404. Agent runs are not streamed.
Recipe 5 — Fail closed on credits and back off on bursts
Billing is prepaid, so a zero balance is not a soft warning — it is an HTTP 402 returned before any model runs. Treat it as an operational alert, not a retry:
import time
from openai import OpenAI, APIStatusError
client = OpenAI(
api_key="sk-synapsex-YOUR-API-KEY",
base_url="https://platform.synapsex.ai/api/v1",
)
def complete_with_backoff(prompt: str, attempts: int = 4) -> str:
for attempt in range(attempts):
try:
response = client.chat.completions.create(
model="synapsex-atlas-7b-v1",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
except APIStatusError as error:
if error.status_code == 402:
raise RuntimeError("SynapseX workspace is out of credits — top up") from error
if error.status_code == 429 and attempt < attempts - 1:
time.sleep(2**attempt) # no Retry-After header is sent; back off yourself
continue
raise
raise RuntimeError("exhausted retries")Retrying a 402 will never succeed and only burns latency. Retrying a 429 with exponential backoff will. Every status code and the correct response to it is on API errors.