API Documentation
Last updated: November 2026
Start with your first request, then explore API examples and troubleshooting.
On this page
- Register and verify your email, or sign in with Google. Before calling Auto, check your available Auto tokens or enable wallet billing with sufficient funds. The Free promotion has ended and Qwen3.8-27B is retired.
- Create a key that allows Auto and save the secret shown once.Open API Keys
- Choose Bash (cURL and Python 3), Python 3, or JavaScript (Node.js 18+). Replace your-api-key with your key. Bash saves response.json locally.
export ITERACOMPUTE_API_KEY="your-api-key"
curl --fail-with-body --max-time 180 https://api.iteracompute.com/v1/chat/completions \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"Auto","messages":[{"role":"user","content":"Reply with exactly: Hello!"}],"max_tokens":512,"reasoning_effort":"low"}' \
-o response.json && python3 -c 'import json; r=json.load(open("response.json")); text=r["choices"][0]["message"]["content"]; assert text and text.strip(), "Empty model reply: activation is incomplete"; print(text)'import json
from urllib.request import Request, urlopen
api_key = "your-api-key"
payload = {
"model": "Auto",
"messages": [{"role": "user", "content": "Reply with exactly: Hello!"}],
"max_tokens": 512,
"reasoning_effort": "low",
}
request = Request(
"https://api.iteracompute.com/v1/chat/completions",
data=json.dumps(payload).encode(),
headers={"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"},
method="POST",
)
with urlopen(request, timeout=180) as response:
result = json.load(response)
text = result["choices"][0]["message"]["content"]
if not text or not text.strip():
raise RuntimeError("Empty model reply: activation is incomplete")
print(text)const apiKey = "your-api-key";
const response = await fetch(
"https://api.iteracompute.com/v1/chat/completions",
{
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
"model": "Auto",
"messages": [{"role": "user", "content": "Reply with exactly: Hello!"}],
"max_tokens": 512,
"reasoning_effort": "low",
}),
signal: AbortSignal.timeout(180000),
},
);
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
const text = result.choices[0].message.content;
if (!text?.trim()) throw new Error("Empty model reply: activation is incomplete");
console.log(text);Success means a non-empty choices[0].message.content. Each example prints the reply and fails on an empty response. Expected output: Hello! (wording may vary).
For 401/403, check the key and model permission. For 429, follow the recovery steps below.
The IteraCompute API is OpenAI-compatible: if your application already talks to the OpenAI API, migrating is a change of base_url and API key. Chat completions, Responses, streaming and tool calling follow compatible formats where the selected model supports them.
API requests go to https://api.iteracompute.com/v1. Chat Completions and Responses requests authenticate with your API key in the Authorization header.
export ITERACOMPUTE_API_KEY="your-api-key"
curl --fail-with-body --max-time 180 https://api.iteracompute.com/v1/chat/completions \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek/deepseek-v4.1-flash-1017","messages":[{"role":"user","content":"Reply with exactly: Hello!"}],"temperature":0,"max_tokens":128}'Use the exact provider/model ID returned by the Models endpoint; do not add an iteracompute/ prefix. List the models currently published by the gateway:
curl --fail-with-body https://api.iteracompute.com/v1/modelsThe Models endpoint is public and returns the current gateway catalog. Use its id values exactly as returned. Commercial access to a model is still controlled by your API key and agreement.
Model support and costs
The Chat Completions, Responses, streaming and tool calling examples use paid DeepSeek V4.1 Flash 1017 and deduct usage from your API balance. Check current input, cached-input and output prices on the Models page. Model IDs and reasoning parameters are not interchangeable. Confirm the selected model supports each endpoint and option before adapting an example.
All three language tabs call the same HTTP endpoint. Set ITERACOMPUTE_API_KEY in your environment before running an example. JavaScript examples use Node.js 18+.
These examples disable automatic retries. For 429, inspect the error body and Retry-After. Stop when the monthly allowance is exhausted. After a timeout, disconnect or 5xx, save the request ID and confirm the outcome before sending another billable request.
All published conversation models support OpenAI Chat Completions and Anthropic Messages. Responses support and model features follow each model's documented limits.
4. Chat Completions
POST /v1/chat/completions follows the OpenAI request and response format:
POSThttps://api.iteracompute.com/v1/chat/completions
curl --fail-with-body --max-time 180 https://api.iteracompute.com/v1/chat/completions \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek/deepseek-v4.1-flash-1017","messages":[{"role":"user","content":"Reply with exactly: Hello!"}],"temperature":0,"max_tokens":128}'# Install once: python -m pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.iteracompute.com/v1",
api_key=os.environ["ITERACOMPUTE_API_KEY"],
max_retries=0,
timeout=180.0,
)
resp = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash-1017",
messages=[{"role": "user", "content": "Reply with exactly: Hello!"}],
temperature=0,
max_tokens=128,
)
print(resp.choices[0].message.content)
print(resp.usage) # prompt_tokens / completion_tokens / total_tokensconst response = await fetch("https://api.iteracompute.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "deepseek/deepseek-v4.1-flash-1017",
messages: [{role: "user", content: "Reply with exactly: Hello!"}],
temperature: 0,
max_tokens: 128,
}),
signal: AbortSignal.timeout(180000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
console.log(result.choices[0].message.content);Anthropic Messages
This example uses DeepSeek V4.1 Flash 1017. You can select any published conversation model allowed by your key. The Python example uses only the standard library. Messages uses native Anthropic responses and errors; its streams end with message_stop instead of [DONE].
POSThttps://api.iteracompute.com/v1/messages
curl --fail-with-body --max-time 180 https://api.iteracompute.com/v1/messages \
-H "x-api-key: $ITERACOMPUTE_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d @- <<JSON
{
"model": "deepseek/deepseek-v4.1-flash-1017",
"max_tokens": 128,
"messages": [{"role": "user", "content": "Hello!"}]
}
JSONimport json
import os
from urllib.request import Request, urlopen
request = Request(
"https://api.iteracompute.com/v1/messages",
data=json.dumps({
"model": "deepseek/deepseek-v4.1-flash-1017",
"max_tokens": 128,
"messages": [{"role": "user", "content": "Hello!"}],
}).encode(),
headers={
"x-api-key": os.environ["ITERACOMPUTE_API_KEY"],
"anthropic-version": "2023-06-01",
"Content-Type": "application/json",
},
method="POST",
)
with urlopen(request, timeout=180) as response:
result = json.load(response)
print("".join(block["text"] for block in result["content"] if block["type"] == "text"))const response = await fetch("https://api.iteracompute.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": process.env.ITERACOMPUTE_API_KEY,
"anthropic-version": "2023-06-01",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "deepseek/deepseek-v4.1-flash-1017",
max_tokens: 128,
messages: [{role: "user", content: "Hello!"}],
}),
signal: AbortSignal.timeout(180000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
console.log(result.content.filter(block => block.type === "text").map(block => block.text).join(""));5. Responses API
POST /v1/responses supports the OpenAI Responses API used by clients such as Codex:
POSThttps://api.iteracompute.com/v1/responses
curl --fail-with-body --max-time 180 https://api.iteracompute.com/v1/responses \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek/deepseek-v4.1-flash-1017","input":"Reply with exactly: Hello!","max_output_tokens":128}'# Install once: python -m pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.iteracompute.com/v1",
api_key=os.environ["ITERACOMPUTE_API_KEY"],
max_retries=0,
timeout=180.0,
)
response = client.responses.create(
model="deepseek/deepseek-v4.1-flash-1017",
input="Reply with exactly: Hello!",
max_output_tokens=128,
)
print(response.output_text)const response = await fetch("https://api.iteracompute.com/v1/responses", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "deepseek/deepseek-v4.1-flash-1017",
input: "Reply with exactly: Hello!",
max_output_tokens: 128,
}),
signal: AbortSignal.timeout(180000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
console.log(result.output.filter(item => item.type === "message").flatMap(item => item.content || [])
.filter(block => block.type === "output_text").map(block => block.text).join(""));Use the Images API with a published image model and an authorized API key. Confirm current availability in the model catalog before calling.
Generate images with a model ID and a prompt or native contents. Use only the fields supported by the selected model. Authenticate with your API key and save the base64 image locally.
POSThttps://api.iteracompute.com/v1/images/generations
These paid examples create one image and save it locally. Set ITERACOMPUTE_API_KEY first. cURL examples require Bash and Python 3; Python uses httpx; JavaScript uses Node.js 18+.
| Model ID | Generation | Reference editing |
|---|---|---|
openai/gpt-image-2.6-flare | /v1/images/generations | /v1/images/edits · multipart |
openai/gpt-image-2.6-sunburst | /v1/images/generations | /v1/images/edits · multipart |
gemini/gemini-nano-banana-2.1 | /v1/images/generations | /v1/images/generations · contents |
OpenAI Image 2.6
Flare and Sunburst use the same fields. To use Sunburst, replace the model ID with openai/gpt-image-2.6-sunburst. The examples request low quality at 1024x1024.
POSThttps://api.iteracompute.com/v1/images/generations
set -e
curl --fail-with-body --max-time 1800 https://api.iteracompute.com/v1/images/generations \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"openai/gpt-image-2.6-flare","prompt":"A blue ceramic cup on a white background. No text, no people.","n":1,"size":"1024x1024","quality":"low","output_format":"png"}' \
-o generation-response.json && python3 - <<'PY'
import base64, json
from pathlib import Path
result = json.loads(Path("generation-response.json").read_text())
Path("generated.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])
PY# Install once: python -m pip install httpx
import base64
import os
from pathlib import Path
import httpx
payload = {'model': 'openai/gpt-image-2.6-flare',
'prompt': 'A blue ceramic cup on a white background. No text, no people.',
'n': 1,
'size': '1024x1024',
'quality': 'low',
'output_format': 'png'}
headers = {"Authorization": f"Bearer {os.environ['ITERACOMPUTE_API_KEY']}"}
with httpx.Client(timeout=1800.0, transport=httpx.HTTPTransport(retries=0)) as client:
response = client.post("https://api.iteracompute.com/v1/images/generations", headers=headers, json=payload)
response.raise_for_status()
result = response.json()
Path("generated.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])import { writeFile } from "node:fs/promises";
const payload = {
"model": "openai/gpt-image-2.6-flare",
"prompt": "A blue ceramic cup on a white background. No text, no people.",
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
};
const response = await fetch("https://api.iteracompute.com/v1/images/generations", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(1800000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
await writeFile("generated.png", Buffer.from(result.data[0].b64_json, "base64"));
console.log(result.usage);Gemini Nano Banana 2.1
Gemini uses contents and generationConfig instead of OpenAI size and quality fields. These examples request a square 1K PNG with a 3000-token output limit.
set -e
curl --fail-with-body --max-time 1800 https://api.iteracompute.com/v1/images/generations \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"gemini/gemini-nano-banana-2.1","contents":[{"role":"user","parts":[{"text":"A blue ceramic cup on a white background. No text, no people."}]}],"generationConfig":{"maxOutputTokens":3000,"thinkingConfig":{"thinkingLevel":"MINIMAL","includeThoughts":false},"imageConfig":{"imageSize":"1K","aspectRatio":"1:1"}}}' \
-o generation-response.json && python3 - <<'PY'
import base64, json
from pathlib import Path
result = json.loads(Path("generation-response.json").read_text())
Path("generated.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])
PY# Install once: python -m pip install httpx
import base64
import os
from pathlib import Path
import httpx
payload = {'model': 'gemini/gemini-nano-banana-2.1',
'contents': [{'role': 'user',
'parts': [{'text': 'A blue ceramic cup on a white background. '
'No text, no people.'}]}],
'generationConfig': {'maxOutputTokens': 3000,
'thinkingConfig': {'thinkingLevel': 'MINIMAL',
'includeThoughts': False},
'imageConfig': {'imageSize': '1K',
'aspectRatio': '1:1'}}}
headers = {"Authorization": f"Bearer {os.environ['ITERACOMPUTE_API_KEY']}"}
with httpx.Client(timeout=1800.0, transport=httpx.HTTPTransport(retries=0)) as client:
response = client.post("https://api.iteracompute.com/v1/images/generations", headers=headers, json=payload)
response.raise_for_status()
result = response.json()
Path("generated.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])import { writeFile } from "node:fs/promises";
const payload = {
"model": "gemini/gemini-nano-banana-2.1",
"contents": [
{
"role": "user",
"parts": [
{
"text": "A blue ceramic cup on a white background. No text, no people."
}
]
}
],
"generationConfig": {
"maxOutputTokens": 3000,
"thinkingConfig": {
"thinkingLevel": "MINIMAL",
"includeThoughts": false
},
"imageConfig": {
"imageSize": "1K",
"aspectRatio": "1:1"
}
}
};
const response = await fetch("https://api.iteracompute.com/v1/images/generations", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(1800000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
await writeFile("generated.png", Buffer.from(result.data[0].b64_json, "base64"));
console.log(result.usage);Save a PNG reference as reference.png before running an edit example. The image and prompt are both billable input. The edited output is saved as edited.png.
Use the editing format declared by the model: multipart files at /v1/images/edits, or base64 inlineData references at /v1/images/generations. The file MIME type must match its contents.
OpenAI Image 2.6
Upload files with multipart form data. Let your HTTP client set Content-Type with its boundary. Edits accept low, medium or high quality and an optional PNG mask.
POSThttps://api.iteracompute.com/v1/images/edits
set -e
curl --fail-with-body --max-time 1800 https://api.iteracompute.com/v1/images/edits \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-F 'model=openai/gpt-image-2.6-flare' \
-F 'prompt=Change the cup to matte green. Keep its silhouette and white background.' \
-F 'n=1' \
-F 'size=1024x1024' \
-F 'quality=low' \
-F 'output_format=png' \
-F 'image[]=@reference.png;type=image/png' \
-o edit-response.json && python3 - <<'PY'
import base64, json
from pathlib import Path
result = json.loads(Path("edit-response.json").read_text())
Path("edited.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])
PY# Install once: python -m pip install httpx
import base64
import os
from pathlib import Path
import httpx
payload = {'model': 'openai/gpt-image-2.6-flare',
'prompt': 'Change the cup to matte green. Keep its silhouette and white '
'background.',
'n': 1,
'size': '1024x1024',
'quality': 'low',
'output_format': 'png'}
headers = {"Authorization": f"Bearer {os.environ['ITERACOMPUTE_API_KEY']}"}
with httpx.Client(timeout=1800.0, transport=httpx.HTTPTransport(retries=0)) as client:
with open("reference.png", "rb") as image:
response = client.post("https://api.iteracompute.com/v1/images/edits", headers=headers,
data=payload, files=[("image[]", ("reference.png", image, "image/png"))])
response.raise_for_status()
result = response.json()
Path("edited.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])import { readFile, writeFile } from "node:fs/promises";
const payload = {
"model": "openai/gpt-image-2.6-flare",
"prompt": "Change the cup to matte green. Keep its silhouette and white background.",
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
};
const form = new FormData();
for (const [key, value] of Object.entries(payload)) form.append(key, String(value));
form.append("image[]", new Blob([await readFile("reference.png")], { type: "image/png" }), "reference.png");
const response = await fetch("https://api.iteracompute.com/v1/images/edits", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
},
body: form,
signal: AbortSignal.timeout(1800000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
await writeFile("edited.png", Buffer.from(result.data[0].b64_json, "base64"));
console.log(result.usage);Gemini Nano Banana 2.1
Gemini edits use the generation endpoint with inlineData references inside contents. Set mimeType to match the file; keep the reference bytes base64-encoded.
POSThttps://api.iteracompute.com/v1/images/generations
set -e
python3 - <<'PY'
import base64, json
from pathlib import Path
payload = {'model': 'gemini/gemini-nano-banana-2.1',
'contents': [{'role': 'user',
'parts': [{'inlineData': {'mimeType': 'image/png',
'data': 'REFERENCE_BASE64'}},
{'text': 'Change the cup to matte green. Keep its '
'silhouette and white background.'}]}],
'generationConfig': {'maxOutputTokens': 3000,
'thinkingConfig': {'thinkingLevel': 'MINIMAL',
'includeThoughts': False},
'imageConfig': {'imageSize': '1K',
'aspectRatio': '1:1'}}}
payload["contents"][0]["parts"][0]["inlineData"]["data"] = base64.b64encode(Path("reference.png").read_bytes()).decode()
Path("image-request.json").write_text(json.dumps(payload))
PY
curl --fail-with-body --max-time 1800 https://api.iteracompute.com/v1/images/generations \
-H "Authorization: Bearer $ITERACOMPUTE_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @image-request.json \
-o edit-response.json && python3 - <<'PY'
import base64, json
from pathlib import Path
result = json.loads(Path("edit-response.json").read_text())
Path("edited.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])
PY# Install once: python -m pip install httpx
import base64
import os
from pathlib import Path
import httpx
payload = {'model': 'gemini/gemini-nano-banana-2.1',
'contents': [{'role': 'user',
'parts': [{'inlineData': {'mimeType': 'image/png',
'data': 'REFERENCE_BASE64'}},
{'text': 'Change the cup to matte green. Keep its '
'silhouette and white background.'}]}],
'generationConfig': {'maxOutputTokens': 3000,
'thinkingConfig': {'thinkingLevel': 'MINIMAL',
'includeThoughts': False},
'imageConfig': {'imageSize': '1K',
'aspectRatio': '1:1'}}}
payload["contents"][0]["parts"][0]["inlineData"]["data"] = base64.b64encode(Path("reference.png").read_bytes()).decode()
headers = {"Authorization": f"Bearer {os.environ['ITERACOMPUTE_API_KEY']}"}
with httpx.Client(timeout=1800.0, transport=httpx.HTTPTransport(retries=0)) as client:
response = client.post("https://api.iteracompute.com/v1/images/generations", headers=headers, json=payload)
response.raise_for_status()
result = response.json()
Path("edited.png").write_bytes(base64.b64decode(result["data"][0]["b64_json"]))
print(result["usage"])import { readFile, writeFile } from "node:fs/promises";
const payload = {
"model": "gemini/gemini-nano-banana-2.1",
"contents": [
{
"role": "user",
"parts": [
{
"inlineData": {
"mimeType": "image/png",
"data": "REFERENCE_BASE64"
}
},
{
"text": "Change the cup to matte green. Keep its silhouette and white background."
}
]
}
],
"generationConfig": {
"maxOutputTokens": 3000,
"thinkingConfig": {
"thinkingLevel": "MINIMAL",
"includeThoughts": false
},
"imageConfig": {
"imageSize": "1K",
"aspectRatio": "1:1"
}
}
};
payload.contents[0].parts[0].inlineData.data = (await readFile("reference.png")).toString("base64");
const response = await fetch("https://api.iteracompute.com/v1/images/generations", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ITERACOMPUTE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(1800000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
await writeFile("edited.png", Buffer.from(result.data[0].b64_json, "base64"));
console.log(result.usage);Responses include data[].b64_json, mime_type and usage.cost in USD. The examples decode the image rather than treating the base64 value as a URL. Actual text, image and reasoning token usage determines the fee at the current model prices.
- Each image is admitted and billed separately; fees are rounded up to USD micros. Check current prices in Models.
- Use n=1 to start; requests accept 1–4 images. References accept PNG, JPEG or WebP, up to four files and 8 MiB decoded in total including a mask. The full request limit is 12 MiB.
- Image 2.6 uses explicit pixel dimensions and does not stream. Gemini accepts 1K, 2K or 4K and aspectRatio in imageConfig; its optional SSE events differ from chat streaming. These examples are non-streaming.
A price estimate does not generate an image. OpenAI reservation_cost_micros is a conservative balance reservation, not an upstream output cap or a final fee. Gemini maximum_cost_micros uses the request output limit. Settlement uses actual usage.
POSThttps://api.iteracompute.com/v1/images/price-estimate
curl --fail-with-body https://api.iteracompute.com/v1/images/price-estimate \
-H "Content-Type: application/json" \
-d '{"model":"openai/gpt-image-2.6-flare","prompt":"A blue ceramic cup","n":1,"size":"1024x1024","quality":"low"}'On HTTP 207, inspect each result and keep completed images: earlier images may already be billed. HTTP 422 can carry billable usage even when no completed image is delivered. Missing usage or a timeout does not prove the request was free. Save the request ID and confirm the outcome before sending another paid request.
6. Streaming (SSE)
Set "stream": true to receive server-sent events. Chunks arrive as generated; token usage is included in the final chunk that carries usage, before the terminal [DONE] event. Treat the stream as one logical request: once tokens have been emitted, the request is not retried transparently.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.iteracompute.com/v1",
api_key=os.environ["ITERACOMPUTE_API_KEY"],
max_retries=0,
timeout=180.0,
)
stream = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash-1017",
messages=[{"role": "user", "content": "Reply with exactly: Hello!"}],
stream=True,
stream_options={"include_usage": True},
temperature=0,
max_tokens=128,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
if chunk.usage: # final chunk: token usage
print("\n", chunk.usage)7. Tool Calling
Tool results are sent in a new request and also count toward the key rate and concurrency limits. On 429, inspect Retry-After and stop this attempt; do not launch parallel copies.
Tools are declared in the tools parameter, following the OpenAI function-calling format. When the model decides to call a tool, the response contains tool_calls; send tool results back with role "tool" to continue the conversation.
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.iteracompute.com/v1",
api_key=os.environ["ITERACOMPUTE_API_KEY"],
max_retries=0,
timeout=180.0,
)
messages = [{"role": "user", "content": "What is the weather in Singapore?"}]
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
resp = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash-1017",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}},
max_tokens=512,
)
assistant_message = resp.choices[0].message
messages.append(assistant_message)
for call in assistant_message.tool_calls or []:
arguments = json.loads(call.function.arguments)
result = {"city": arguments["city"], "temperature_c": 29}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash-1017",
messages=messages,
tools=tools,
max_tokens=512,
)
print(final.choices[0].message.content)8. Error Codes
Chat Completions and Responses errors use the OpenAI error format with a JSON body of {"error": {"message", "type", "code"}}:
| Status | Meaning |
|---|---|
| 400 | Invalid request - malformed JSON or missing required parameters |
| 401 | Authentication failed - missing or invalid API key |
| 403 | Key not permitted for this model or action. For a model-restricted key, add the new Model ID to its allowed-model list in the Console, save, then retry. |
| 404 | Unknown model or endpoint |
| 429 | Rate or capacity limit - check error.code and the recovery steps below |
| 500 | Internal error - save the request ID; confirm the outcome before retrying |
| 503 | Model temporarily unavailable - retry with backoff |
Retained monthly Auto allowances, plan tokens and promotional rewards are tracked separately. Check your available tokens in Billing.
Recover from 429
Check your available Auto allowance in Billing. Wallet charges require you to enable pay-as-you-go.
- Monthly allowance used or reserved
free_model_monthly_limit Check the available and reserved tokens in Billing. Retry when the allowance covers the request, or enable wallet billing to use your balance.
- Provider capacity
provider_rate_limit Follow Retry-After and use exponential backoff. Stop at your application deadline. If the error persists, contact support with the request ID.
View allowance, reservations and request limits · Contact support
Auto FAQ
How does Auto select a model?
Auto matches each request with spare capacity across our listed models, using current demand and cost to select a model.
What context length is available?
The Auto model details show the current context window and maximum output. Input and requested output share the context window.
How are Auto allowances applied?
Retained monthly Auto allowances, plan tokens and promotional rewards are tracked separately. Check your available tokens in Billing.
Integration questions: support@iteracompute.com