DOC 08APIs and capabilities
API Scripting Guide
Copy-ready Python and Node.js examples for Responses, Chat Completions, Messages, image generation and editing, and video.
These examples cover text, vision, image and video APIs. Replace YOUR_API_KEY with your key and run them: the Python examples use only the standard library (Python 3.8+), save one as demo.py and run python3 demo.py; save a Node.js example as demo.mjs and run node demo.mjs (Node.js 18+).
| API | Example model | Groups |
|---|---|---|
| Responses / Chat Completions | gpt-6.1-sol | GPT Economy, GPT General or GPT Official API |
| Anthropic Messages | claude-opus-5-5 | Claude Economy, Claude General or Claude Official API |
| Image generation and editing | gpt-image-2 | GPT General, GPT Economy or GPT Images |
| Seedream image generation | seedream-5-5 | Seedream Images |
| Video generation | grok-imagine-video | Grok General |
OpenAI Responses: text and vision
The OpenAI Responses API for text conversations, image understanding and streaming output. POST /v1/responses
import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/responses"
API_KEY = "YOUR_API_KEY"
body = {
"model": "gpt-6.1-sol",
"stream": True,
"input": "Briefly introduce yourself in English.",
}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
if event.get("type") == "response.output_text.delta":
print(event.get("delta", ""), end="", flush=True)
if event.get("type") in ("response.completed", "response.done"):
break
print()const API_URL = "https://api.spiderai.fun/v1/responses";
const API_KEY = "YOUR_API_KEY";
const body = {
model: "gpt-6.1-sol",
stream: true,
input: "Briefly introduce yourself in English.",
};
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
if (event.type === "response.output_text.delta") process.stdout.write(event.delta || "");
if (event.type === "response.completed" || event.type === "response.done") break;
}
process.stdout.write("\n");import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/responses"
API_KEY = "YOUR_API_KEY"
body = {
"model": "gpt-6.1-sol",
"stream": True,
"input": [{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image? Briefly describe it in English."},
{"type": "input_image", "image_url": "https://spiderai.fun/logo.png"},
],
}],
}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
if event.get("type") == "response.output_text.delta":
print(event.get("delta", ""), end="", flush=True)
if event.get("type") in ("response.completed", "response.done"):
break
print()const API_URL = "https://api.spiderai.fun/v1/responses";
const API_KEY = "YOUR_API_KEY";
const body = {
model: "gpt-6.1-sol",
stream: true,
input: [{
role: "user",
content: [
{ type: "input_text", text: "What is in this image? Briefly describe it in English." },
{ type: "input_image", image_url: "https://spiderai.fun/logo.png" },
],
}],
};
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
if (event.type === "response.output_text.delta") process.stdout.write(event.delta || "");
if (event.type === "response.completed" || event.type === "response.done") break;
}
process.stdout.write("\n");OpenAI Chat Completions: text and vision
Compatible with the traditional OpenAI Chat format for migrating existing clients. POST /v1/chat/completions
import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/chat/completions"
API_KEY = "YOUR_API_KEY"
body = {
"model": "gpt-6.1-sol",
"stream": True,
"messages": [{"role": "user", "content": "Briefly introduce yourself in English."}],
}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
chunk = json.loads(data)
for choice in chunk.get("choices") or []:
print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
print()const API_URL = "https://api.spiderai.fun/v1/chat/completions";
const API_KEY = "YOUR_API_KEY";
const body = {
model: "gpt-6.1-sol",
stream: true,
messages: [{ role: "user", content: "Briefly introduce yourself in English." }],
};
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const chunk = JSON.parse(data);
for (const choice of chunk.choices || []) process.stdout.write(choice.delta?.content || "");
}
process.stdout.write("\n");import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/chat/completions"
API_KEY = "YOUR_API_KEY"
body = {
"model": "gpt-6.1-sol",
"stream": True,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image? Briefly describe it in English."},
{"type": "image_url", "image_url": {"url": "https://spiderai.fun/logo.png"}},
],
}],
}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
chunk = json.loads(data)
for choice in chunk.get("choices") or []:
print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
print()const API_URL = "https://api.spiderai.fun/v1/chat/completions";
const API_KEY = "YOUR_API_KEY";
const body = {
model: "gpt-6.1-sol",
stream: true,
messages: [{
role: "user",
content: [
{ type: "text", text: "What is in this image? Briefly describe it in English." },
{ type: "image_url", image_url: { url: "https://spiderai.fun/logo.png" } },
],
}],
};
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const chunk = JSON.parse(data);
for (const choice of chunk.choices || []) process.stdout.write(choice.delta?.content || "");
}
process.stdout.write("\n");Anthropic Messages: text and vision
Claude / Anthropic Messages format. Image mode encodes the image as Base64 before sending it. POST /v1/messages
import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/messages"
API_KEY = "YOUR_API_KEY"
body = {
"model": "claude-opus-5-5",
"max_tokens": 64000,
"stream": True,
"messages": [{"role": "user", "content": "Briefly introduce yourself in English."}],
}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
if event.get("type") == "content_block_delta":
print((event.get("delta") or {}).get("text", ""), end="", flush=True)
if event.get("type") == "message_stop":
break
print()const API_URL = "https://api.spiderai.fun/v1/messages";
const API_KEY = "YOUR_API_KEY";
const body = {
model: "claude-opus-5-5",
max_tokens: 64000,
stream: true,
messages: [{ role: "user", content: "Briefly introduce yourself in English." }],
};
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
if (event.type === "content_block_delta") process.stdout.write(event.delta?.text || "");
if (event.type === "message_stop") break;
}
process.stdout.write("\n");import base64
import codecs
import json
import re
import urllib.request
API_URL = "https://api.spiderai.fun/v1/messages"
API_KEY = "YOUR_API_KEY"
IMAGE_HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "image/*,*/*;q=0.8"}
def image_as_base64(url):
request = urllib.request.Request(url, headers=IMAGE_HEADERS)
with urllib.request.urlopen(request, timeout=60) as response:
media_type = response.headers.get("content-type", "image/png").split(";")[0]
data = base64.b64encode(response.read()).decode("ascii")
return media_type, data
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
media_type, image_data = image_as_base64("https://spiderai.fun/logo.png")
body = {
"model": "claude-opus-5-5",
"max_tokens": 64000,
"stream": True,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image? Briefly describe it in English."},
{"type": "image", "source": {"type": "base64", "media_type": media_type, "data": image_data}},
],
}],
}
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
if event.get("type") == "content_block_delta":
print((event.get("delta") or {}).get("text", ""), end="", flush=True)
if event.get("type") == "message_stop":
break
print()const API_URL = "https://api.spiderai.fun/v1/messages";
const API_KEY = "YOUR_API_KEY";
async function imageAsBase64(url) {
const response = await fetch(url);
const mediaType = response.headers.get("content-type")?.split(";")[0] || "image/png";
const data = Buffer.from(await response.arrayBuffer()).toString("base64");
return { mediaType, data };
}
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
const image = await imageAsBase64("https://spiderai.fun/logo.png");
const body = {
model: "claude-opus-5-5",
max_tokens: 64000,
stream: true,
messages: [{
role: "user",
content: [
{ type: "text", text: "What is in this image? Briefly describe it in English." },
{ type: "image", source: { type: "base64", media_type: image.mediaType, data: image.data } },
],
}],
};
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
if (event.type === "content_block_delta") process.stdout.write(event.delta?.text || "");
if (event.type === "message_stop") break;
}
process.stdout.write("\n");GPT image generation and editing
Use /v1/images/generations for text-to-image and /v1/images/edits for reference images or editing. Edits accept local files as multipart, several reference images, or JSON images[].image_url with an image URL or data URL. The image-to-image example reads a.png and b.png from the working directory (one is enough). Gemini image models use the native Gemini generateContent API and are not available here. POST /v1/images/generations
import base64
import codecs
import json
import re
import urllib.request
from pathlib import Path
API_URL = "https://api.spiderai.fun/v1/images/generations"
API_KEY = "YOUR_API_KEY"
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
body = {
"model": "gpt-image-2",
"prompt": "Generate an image of a cat in space",
"n": 1,
"size": "1024x1024",
"stream": True,
"response_format": "b64_json",
}
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
if event.get("type") == "image_generation.partial_image":
print(".", end="", flush=True)
if event.get("type") == "image_generation.completed":
image = event.get("b64_json") or (event.get("data") or [{}])[0].get("b64_json")
Path("generated-image.png").write_bytes(base64.b64decode(image))
print("\nImage saved: generated-image.png")
breakimport { writeFile } from "node:fs/promises";
const API_URL = "https://api.spiderai.fun/v1/images/generations";
const API_KEY = "YOUR_API_KEY";
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
async function main() {
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify({
model: "gpt-image-2",
prompt: "Generate an image of a cat in space",
n: 1,
size: "1024x1024",
stream: true,
response_format: "b64_json",
}),
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
if (event.type === "image_generation.partial_image") process.stdout.write(".");
if (event.type === "image_generation.completed") {
const image = event.b64_json || event.data?.[0]?.b64_json;
await writeFile("generated-image.png", Buffer.from(image, "base64"));
console.log("\nImage saved: generated-image.png");
break;
}
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});import base64
import json
import mimetypes
import urllib.request
import uuid
from pathlib import Path
API_URL = "https://api.spiderai.fun/v1/images/edits"
API_KEY = "YOUR_API_KEY"
IMAGE_PATHS = [Path("a.png"), Path("b.png")] # You can keep just one image
boundary = "----spiderai-" + uuid.uuid4().hex
fields = {"model": "gpt-image-2", "prompt": "Combine the reference images while preserving the subjects.", "n": "1", "size": "1024x1024", "quality": "auto", "stream": "true", "response_format": "b64_json"}
body = bytearray()
for name, value in fields.items():
body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n".encode())
for image_path in IMAGE_PATHS:
data = image_path.read_bytes()
content_type = mimetypes.guess_type(image_path.name)[0] or "image/png"
body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{image_path.name}\"\r\nContent-Type: {content_type}\r\n\r\n".encode())
body.extend(data)
body.extend(b"\r\n")
body.extend(f"--{boundary}--\r\n".encode())
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
request = urllib.request.Request(API_URL, data=bytes(body), method="POST", headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": "multipart/form-data; boundary=" + boundary,
"Accept": "text/event-stream",
})
with urllib.request.urlopen(request, timeout=900) as response:
payload = response.read().decode("utf-8", errors="replace")
if response.headers.get("content-type", "").startswith("application/json"):
event = json.loads(payload)
image = event.get("b64_json") or (event.get("data") or [{}])[0].get("b64_json")
else:
image = None
for frame in payload.replace("\r\n", "\n").split("\n\n"):
data = sse_data(frame)
if data and data != "[DONE]":
event = json.loads(data)
image = event.get("b64_json") or (event.get("data") or [{}])[0].get("b64_json")
if image:
break
if not image:
raise RuntimeError("The API returned no image")
Path("generated-image.png").write_bytes(base64.b64decode(image))
print("Image saved: generated-image.png")import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
const API_URL = "https://api.spiderai.fun/v1/images/edits";
const API_KEY = "YOUR_API_KEY";
const MIME_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
const IMAGE_PATHS = ["a.png", "b.png"]; // You can keep just one image
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function main() {
const form = new FormData();
form.append("model", "gpt-image-2");
form.append("prompt", "Combine the reference images while preserving the subjects.");
form.append("n", "1");
form.append("size", "1024x1024");
form.append("quality", "auto");
form.append("stream", "true");
form.append("response_format", "b64_json");
for (const imagePath of IMAGE_PATHS) {
const type = MIME_TYPES[path.extname(imagePath).toLowerCase()] || "image/png";
form.append("image", new Blob([await readFile(imagePath)], { type }), path.basename(imagePath));
}
const response = await fetch(API_URL, {
method: "POST",
headers: { Authorization: "Bearer " + API_KEY, Accept: "text/event-stream" },
body: form,
});
if (!response.ok) throw new Error(await response.text());
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
const event = await response.json();
const image = event.data?.[0]?.b64_json || event.b64_json;
await writeFile("generated-image.png", Buffer.from(image, "base64"));
console.log("Image saved: generated-image.png");
return;
}
const raw = await response.text();
for (const frame of raw.replace(/\r\n/g, "\n").split("\n\n")) {
const data = sseData(frame);
if (!data || data === "[DONE]") continue;
const event = JSON.parse(data);
const image = event.b64_json || event.data?.[0]?.b64_json || event.item?.result;
if (image) {
await writeFile("generated-image.png", Buffer.from(image, "base64"));
console.log("Image saved: generated-image.png");
return;
}
}
throw new Error("The API returned no image");
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});gpt-image-2 image editing (multipart)
Upload an image, edit it according to the prompt, and save the result from streaming events. POST /v1/images/edits
import base64
import codecs
import json
import mimetypes
import re
import urllib.request
import uuid
from pathlib import Path
API_URL = "https://api.spiderai.fun/v1/images/edits"
API_KEY = "YOUR_API_KEY"
IMAGE_HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "image/*,*/*;q=0.8"}
def sse_data(frame):
# Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
lines, in_data = [], False
for line in frame.splitlines():
if line.startswith("data:"):
lines.append(line[5:].strip())
in_data = True
elif in_data and line and not line.startswith(("event:", "id:", "retry:", ":")):
lines.append(line)
else:
in_data = False
return "\n".join(lines).strip()
def iter_sse(response):
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
buffer = ""
while chunk := response.read1(65536):
buffer += decoder.decode(chunk)
frames = re.split(r"\r?\n\r?\n", buffer)
buffer = frames.pop()
for frame in frames:
data = sse_data(frame)
if data and data != "[DONE]":
yield data
def multipart(fields, file_data, file_type):
boundary = "----spiderai-" + uuid.uuid4().hex
body = bytearray()
for name, value in fields.items():
body.extend(
f"--{boundary}\r\n"
f"Content-Disposition: form-data; name=\"{name}\"\r\n\r\n"
f"{value}\r\n".encode()
)
body.extend(
f"--{boundary}\r\n"
f"Content-Disposition: form-data; name=\"image\"; filename=\"source.png\"\r\n"
f"Content-Type: {file_type}\r\n\r\n".encode()
)
body.extend(file_data)
body.extend(f"\r\n--{boundary}--\r\n".encode())
return bytes(body), "multipart/form-data; boundary=" + boundary
image_request = urllib.request.Request("https://spiderai.fun/logo.png", headers=IMAGE_HEADERS)
with urllib.request.urlopen(image_request, timeout=60) as image_response:
header_type = image_response.headers.get("content-type", "").split(";")[0]
image_type = header_type or mimetypes.guess_type("source.png")[0] or "image/png"
image_data = image_response.read()
fields = {
"prompt": "Change the overall color palette of the image to blue.",
"model": "gpt-image-2",
"n": "1",
"quality": "auto",
"size": "1024x1024",
"stream": "true",
"response_format": "b64_json",
}
body, content_type = multipart(fields, image_data, image_type)
request = urllib.request.Request(
API_URL,
data=body,
method="POST",
headers={
"Authorization": "Bearer " + API_KEY,
"Content-Type": content_type,
"Accept": "text/event-stream",
},
)
with urllib.request.urlopen(request, timeout=900) as response:
for data in iter_sse(response):
event = json.loads(data)
image = (
event.get("b64_json")
or ((event.get("data") or [{}])[0]).get("b64_json")
or (event.get("item") or {}).get("result")
)
if event.get("type") == "image_generation.partial_image":
print(".", end="", flush=True)
if image:
Path("edited-image.png").write_bytes(base64.b64decode(image))
print("\nImage saved: edited-image.png")
breakimport { writeFile } from "node:fs/promises";
const API_URL = "https://api.spiderai.fun/v1/images/edits";
const API_KEY = "YOUR_API_KEY";
// Collect the data of one SSE event; some endpoints split the JSON over several lines, so keep the continuation lines
function sseData(frame) {
const lines = [];
let inData = false;
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith("data:")) {
lines.push(line.slice(5).trim());
inData = true;
} else if (inData && line && !/^(event:|id:|retry:|:)/.test(line)) {
lines.push(line);
} else {
inData = false;
}
}
return lines.join("\n").trim();
}
async function* readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || "";
for (const frame of frames) {
const data = sseData(frame);
if (data && data !== "[DONE]") yield data;
}
}
}
async function main() {
const source = await fetch("https://spiderai.fun/logo.png");
const sourceType = source.headers.get("content-type") || "image/png";
const sourceFile = new File([await source.arrayBuffer()], "source.png", { type: sourceType });
const form = new FormData();
form.append("image", sourceFile);
form.append("prompt", "Change the overall color palette of the image to blue.");
form.append("model", "gpt-image-2");
form.append("n", "1");
form.append("quality", "auto");
form.append("size", "1024x1024");
form.append("stream", "true");
form.append("response_format", "b64_json");
const response = await fetch(API_URL, {
method: "POST",
headers: {
Authorization: "Bearer " + API_KEY,
Accept: "text/event-stream",
},
body: form,
});
if (!response.ok) throw new Error(await response.text());
for await (const data of readSse(response)) {
const event = JSON.parse(data);
const image = event.b64_json || event.data?.[0]?.b64_json || event.item?.result;
if (event.type === "image_generation.partial_image") process.stdout.write(".");
if (image) {
await writeFile("edited-image.png", Buffer.from(image, "base64"));
console.log("\nImage saved: edited-image.png");
break;
}
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});Seedream 5.5 image generation
An image model billed per image; use a key from the Seedream Images group. The size can be exact pixels or a ratio; for reference images, transparent backgrounds and layer splitting see the Seedream 5.5 Image Guide. POST /v1/images/generations
import json, urllib.request
API_KEY = "YOUR_API_KEY"
body = {
"model": "seedream-5-5",
"prompt": "An orange cat sunbathing on a windowsill, film grain, warm tones",
"size": "1920x1080",
}
req = urllib.request.Request(
"https://api.spiderai.fun/v1/images/generations",
data=json.dumps(body).encode("utf-8"),
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=180) as resp:
result = json.load(resp)
image = result["data"][0]
print(image["size"], result["usage"])
urllib.request.urlretrieve(image["url"], "seedream.png") # the link is temporary: save the file right away
print("saved seedream.png")import { writeFile } from "node:fs/promises";
const API_KEY = "YOUR_API_KEY";
const res = await fetch("https://api.spiderai.fun/v1/images/generations", {
method: "POST",
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
model: "seedream-5-5",
prompt: "An orange cat sunbathing on a windowsill, film grain, warm tones",
size: "1920x1080",
}),
signal: AbortSignal.timeout(180_000),
});
const result = await res.json();
if (!res.ok) throw new Error(JSON.stringify(result));
const image = result.data[0];
console.log(image.size, result.usage);
// the link is temporary: save the file right away
await writeFile("seedream.png", Buffer.from(await (await fetch(image.url)).arrayBuffer()));
console.log("saved seedream.png");grok-imagine-video video generation
Asynchronous video generation: submit a task to obtain a request_id, poll until completion, then download the video file. POST /v1/videos/generations
import json
import time
import urllib.request
from pathlib import Path
API_BASE = "https://api.spiderai.fun/v1"
API_KEY = "YOUR_API_KEY"
AUTH_HEADERS = {
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
}
body = {
"model": "grok-imagine-video",
"prompt": "A corgi running along the beach, with sunlit waves and a cinematic camera shot.",
"resolution": "720p",
"duration": 8,
}
def post_json(path, payload):
request = urllib.request.Request(
API_BASE + path,
data=json.dumps(payload).encode("utf-8"),
method="POST",
headers=AUTH_HEADERS,
)
with urllib.request.urlopen(request, timeout=300) as response:
return json.loads(response.read())
def get_json(path):
request = urllib.request.Request(API_BASE + path, headers=AUTH_HEADERS)
with urllib.request.urlopen(request, timeout=300) as response:
return json.loads(response.read())
# 1. Submit the generation task and obtain request_id
task = post_json("/videos/generations", body)
request_id = task.get("request_id") or task.get("id")
print("Task submitted:", request_id)
# 2. Poll until completion (video generation usually takes tens of seconds)
for _ in range(120):
status = get_json("/videos/" + request_id)
state = status.get("status", "")
print("Current status:", state)
if state in ("completed", "done", "succeeded"):
break
if state in ("failed", "error", "cancelled"):
raise RuntimeError(json.dumps(status, ensure_ascii=False))
time.sleep(5)
else:
raise TimeoutError("Video generation timed out; query the task later using request_id")
# 3. Download the video, or use the temporary URL in status["video"]["url"]
content_request = urllib.request.Request(
API_BASE + "/videos/" + request_id + "/content",
headers={"Authorization": "Bearer " + API_KEY},
)
with urllib.request.urlopen(content_request, timeout=600) as response:
Path("grok-video.mp4").write_bytes(response.read())
print("Video saved: grok-video.mp4")import { writeFile } from "node:fs/promises";
const API_BASE = "https://api.spiderai.fun/v1";
const API_KEY = "YOUR_API_KEY";
const AUTH_HEADERS = {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
};
const body = {
model: "grok-imagine-video",
prompt: "A corgi running along the beach, with sunlit waves and a cinematic camera shot.",
resolution: "720p",
duration: 8,
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function callApi(path, init = {}) {
const response = await fetch(API_BASE + path, { headers: AUTH_HEADERS, ...init });
if (!response.ok) throw new Error(await response.text());
return response;
}
async function main() {
// 1. Submit the generation task and obtain request_id
const created = await callApi("/videos/generations", {
method: "POST",
headers: AUTH_HEADERS,
body: JSON.stringify(body),
});
const task = await created.json();
const requestId = task.request_id || task.id;
console.log("Task submitted:", requestId);
// 2. Poll until completion (video generation usually takes tens of seconds)
let status = null;
let finished = false;
for (let i = 0; i < 120; i += 1) {
status = await (await callApi("/videos/" + requestId)).json();
console.log("Current status:", status.status);
if (["completed", "done", "succeeded"].includes(status.status)) {
finished = true;
break;
}
if (["failed", "error", "cancelled"].includes(status.status)) {
throw new Error(JSON.stringify(status));
}
await sleep(5000);
}
if (!finished) throw new Error("Video generation timed out; query the task later using request_id");
// 3. Download the video, or use the temporary URL in status.video.url
const content = await callApi("/videos/" + requestId + "/content");
const buffer = Buffer.from(await content.arrayBuffer());
await writeFile("grok-video.mp4", buffer);
console.log("Video saved: grok-video.mp4");
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});import json
import time
import urllib.request
from pathlib import Path
API_BASE = "https://api.spiderai.fun/v1"
API_KEY = "YOUR_API_KEY"
IMAGE_URL = "https://spiderai.fun/logo.png"
AUTH_HEADERS = {
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json",
}
body = {
"model": "grok-imagine-video",
"prompt": "Slowly move the camera closer as the lighting transitions from dark to bright.",
"resolution": "720p",
"duration": 8,
# ✅ image must be an object: {"url": "https://..."}
# ❌ Using "image": "https://..." causes an error
# image: invalid type: string "...", expected struct ImageUrl
"image": {"url": IMAGE_URL},
}
def post_json(path, payload):
request = urllib.request.Request(
API_BASE + path,
data=json.dumps(payload).encode("utf-8"),
method="POST",
headers=AUTH_HEADERS,
)
with urllib.request.urlopen(request, timeout=300) as response:
return json.loads(response.read())
def get_json(path):
request = urllib.request.Request(API_BASE + path, headers=AUTH_HEADERS)
with urllib.request.urlopen(request, timeout=300) as response:
return json.loads(response.read())
# 1. Submit the generation task and obtain request_id
task = post_json("/videos/generations", body)
request_id = task.get("request_id") or task.get("id")
print("Task submitted:", request_id)
# 2. Poll the task until completion
for _ in range(120):
status = get_json("/videos/" + request_id)
state = status.get("status", "")
print("Current status:", state)
if state in ("completed", "done", "succeeded"):
break
if state in ("failed", "error", "cancelled"):
raise RuntimeError(json.dumps(status, ensure_ascii=False))
time.sleep(5)
else:
raise TimeoutError("Video generation timed out; query the task later using request_id")
# 3. Download the video file
content_request = urllib.request.Request(
API_BASE + "/videos/" + request_id + "/content",
headers={"Authorization": "Bearer " + API_KEY},
)
with urllib.request.urlopen(content_request, timeout=600) as response:
Path("grok-video.mp4").write_bytes(response.read())
print("Video saved: grok-video.mp4")import { writeFile } from "node:fs/promises";
const API_BASE = "https://api.spiderai.fun/v1";
const API_KEY = "YOUR_API_KEY";
const IMAGE_URL = "https://spiderai.fun/logo.png";
const AUTH_HEADERS = {
Authorization: "Bearer " + API_KEY,
"Content-Type": "application/json",
};
const body = {
model: "grok-imagine-video",
prompt: "Slowly move the camera closer as the lighting transitions from dark to bright.",
resolution: "720p",
duration: 8,
// ✅ image must be an object: { url: "https://..." }
// ❌ Using image: "https://..." causes an error
// image: invalid type: string "...", expected struct ImageUrl
image: { url: IMAGE_URL },
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function callApi(path, init = {}) {
const response = await fetch(API_BASE + path, { headers: AUTH_HEADERS, ...init });
if (!response.ok) throw new Error(await response.text());
return response;
}
async function main() {
// 1. Submit the generation task and obtain request_id
const created = await callApi("/videos/generations", {
method: "POST",
headers: AUTH_HEADERS,
body: JSON.stringify(body),
});
const task = await created.json();
const requestId = task.request_id || task.id;
console.log("Task submitted:", requestId);
// 2. Poll the task until completion
let status = null;
let finished = false;
for (let i = 0; i < 120; i += 1) {
status = await (await callApi("/videos/" + requestId)).json();
console.log("Current status:", status.status);
if (["completed", "done", "succeeded"].includes(status.status)) {
finished = true;
break;
}
if (["failed", "error", "cancelled"].includes(status.status)) {
throw new Error(JSON.stringify(status));
}
await sleep(5000);
}
if (!finished) throw new Error("Video generation timed out; query the task later using request_id");
// 3. Download the video file
const content = await callApi("/videos/" + requestId + "/content");
const buffer = Buffer.from(await content.arrayBuffer());
await writeFile("grok-video.mp4", buffer);
console.log("Video saved: grok-video.mp4");
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});image field was sent as a string. Send { "url": "https://..." } instead.resolution supports 480p / 720p; duration defaults to 8 seconds and accepts 1–15 seconds, billed per second. See Pricing for rates.