APIs and capabilities

API Scripting Guide

Copy Python and Node.js examples for Responses, Chat Completions, Messages, image generation and editing, and video APIs.

These examples cover text, vision, image and video APIs. Replace YOUR_API_KEY with your API key before running them.

OpenAI Responses: text and vision

The OpenAI Responses API for text conversations, image understanding and streaming output.

POST /v1/responses
1import json
2import urllib.request
3 
4API_URL = "https://api.zhenapi.ai/v1/responses"
5API_KEY = "YOUR_API_KEY"
6 
7body = {
8 "model": "gpt-6.1-sol",
9 "stream": True,
10 "input": "Briefly introduce ZhenAPI in English.",
11}
12 
13def iter_sse(response):
14 buffer = ""
15 while chunk := response.read(4096):
16 buffer += chunk.decode("utf-8", errors="replace")
17 frames = buffer.split("\n\n")
18 buffer = frames.pop()
19 for frame in frames:
20 payload = [line[5:].strip() for line in frame.splitlines() if line.startswith("data:")]
21 data = "\n".join(payload).strip()
22 if data and data != "[DONE]":
23 yield data
24 
25request = urllib.request.Request(
26 API_URL,
27 data=json.dumps(body).encode("utf-8"),
28 method="POST",
29 headers={
30 "Authorization": "Bearer " + API_KEY,
31 "Content-Type": "application/json",
32 "Accept": "text/event-stream",
33 },
34)
35 
36with urllib.request.urlopen(request, timeout=900) as response:
37 for data in iter_sse(response):
38 event = json.loads(data)
39 if event.get("type") == "response.output_text.delta":
40 print(event.get("delta", ""), end="", flush=True)
41 if event.get("type") in ("response.completed", "response.done"):
42 break
43print()

OpenAI Chat Completions: text and vision

Compatible with the traditional OpenAI Chat format for migrating existing clients.

POST /v1/chat/completions
1import json
2import urllib.request
3 
4API_URL = "https://api.zhenapi.ai/v1/chat/completions"
5API_KEY = "YOUR_API_KEY"
6 
7body = {
8 "model": "gpt-6.1-sol",
9 "stream": True,
10 "messages": [{"role": "user", "content": "Briefly introduce ZhenAPI in English."}],
11}
12 
13def iter_sse(response):
14 buffer = ""
15 while chunk := response.read(4096):
16 buffer += chunk.decode("utf-8", errors="replace")
17 frames = buffer.split("\n\n")
18 buffer = frames.pop()
19 for frame in frames:
20 payload = [line[5:].strip() for line in frame.splitlines() if line.startswith("data:")]
21 data = "\n".join(payload).strip()
22 if data and data != "[DONE]":
23 yield data
24 
25request = urllib.request.Request(
26 API_URL,
27 data=json.dumps(body).encode("utf-8"),
28 method="POST",
29 headers={
30 "Authorization": "Bearer " + API_KEY,
31 "Content-Type": "application/json",
32 "Accept": "text/event-stream",
33 },
34)
35 
36with urllib.request.urlopen(request, timeout=900) as response:
37 for data in iter_sse(response):
38 chunk = json.loads(data)
39 for choice in chunk.get("choices") or []:
40 print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
41print()

Anthropic Messages: text and vision

Claude / Anthropic Messages format. Image mode encodes the image as Base64 before sending it.

POST /v1/messages
1import json
2import urllib.request
3 
4API_URL = "https://api.zhenapi.ai/v1/messages"
5API_KEY = "YOUR_API_KEY"
6 
7body = {
8 "model": "claude-opus-5-5",
9 "max_tokens": 64000,
10 "stream": True,
11 "messages": [{"role": "user", "content": "Briefly introduce ZhenAPI in English."}],
12}
13 
14def iter_sse(response):
15 buffer = ""
16 while chunk := response.read(4096):
17 buffer += chunk.decode("utf-8", errors="replace")
18 frames = buffer.split("\n\n")
19 buffer = frames.pop()
20 for frame in frames:
21 payload = [line[5:].strip() for line in frame.splitlines() if line.startswith("data:")]
22 data = "\n".join(payload).strip()
23 if data and data != "[DONE]":
24 yield data
25 
26request = urllib.request.Request(
27 API_URL,
28 data=json.dumps(body).encode("utf-8"),
29 method="POST",
30 headers={
31 "Authorization": "Bearer " + API_KEY,
32 "Content-Type": "application/json",
33 "Accept": "text/event-stream",
34 },
35)
36 
37with urllib.request.urlopen(request, timeout=900) as response:
38 for data in iter_sse(response):
39 event = json.loads(data)
40 if event.get("type") == "content_block_delta":
41 print((event.get("delta") or {}).get("text", ""), end="", flush=True)
42 if event.get("type") == "message_stop":
43 break
44print()

GPT / Gemini 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, multiple reference images, or JSON images[].image_url containing an image URL or data URL. For the Gemini (Official Direct) group, replace model with a Gemini image model listed in the Image Generation Guide, keeping stream=true, n=1 and response_format=b64_json. Gemini returns usage and usageMetadata; mime_type identifies the image format. size maps to an aspect ratio and a 1K/2K/4K tier; actual dimensions depend on the model, and the 2.5 series only supports 1K. Gemini currently does not support mask, n greater than 1, forced output_format, or quality/background values other than auto.

POST /v1/images/generations
1import base64
2import json
3import urllib.request
4from pathlib import Path
5 
6API_URL = "https://api.zhenapi.ai/v1/images/generations"
7API_KEY = "YOUR_API_KEY"
8 
9def iter_sse(response):
10 buffer = ""
11 while chunk := response.read(4096):
12 buffer += chunk.decode("utf-8", errors="replace")
13 frames = buffer.split("\n\n")
14 buffer = frames.pop()
15 for frame in frames:
16 payload = [line[5:].strip() for line in frame.splitlines() if line.startswith("data:")]
17 data = "\n".join(payload).strip()
18 if data and data != "[DONE]":
19 yield data
20 
21body = {
22 "model": "gpt-image-2",
23 "prompt": "Generate an image of a cat in space",
24 "n": 1,
25 "size": "1024x1024",
26 "stream": True,
27 "response_format": "b64_json",
28}
29 
30request = urllib.request.Request(
31 API_URL,
32 data=json.dumps(body).encode("utf-8"),
33 method="POST",
34 headers={
35 "Authorization": "Bearer " + API_KEY,
36 "Content-Type": "application/json",
37 "Accept": "text/event-stream",
38 },
39)
40 
41with urllib.request.urlopen(request, timeout=900) as response:
42 for data in iter_sse(response):
43 event = json.loads(data)
44 if event.get("type") == "image_generation.partial_image":
45 print(".", end="", flush=True)
46 if event.get("type") == "image_generation.completed":
47 image = event.get("b64_json") or (event.get("data") or [{}])[0].get("b64_json")
48 Path("generated-image.png").write_bytes(base64.b64decode(image))
49 print("\nImage saved:generated-image.png")
50 break

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
1import base64
2import json
3import mimetypes
4import urllib.request
5import uuid
6from pathlib import Path
7 
8API_URL = "https://api.zhenapi.ai/v1/images/edits"
9API_KEY = "YOUR_API_KEY"
10IMAGE_HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "image/*,*/*;q=0.8"}
11 
12def iter_sse(response):
13 buffer = ""
14 while chunk := response.read(4096):
15 buffer += chunk.decode("utf-8", errors="replace")
16 frames = buffer.split("\n\n")
17 buffer = frames.pop()
18 for frame in frames:
19 payload = [line[5:].strip() for line in frame.splitlines() if line.startswith("data:")]
20 data = "\n".join(payload).strip()
21 if data and data != "[DONE]":
22 yield data
23 
24def multipart(fields, file_data, file_type):
25 boundary = "----zhenapi-" + uuid.uuid4().hex
26 body = bytearray()
27 for name, value in fields.items():
28 body.extend(
29 f"--{boundary}\r\n"
30 f"Content-Disposition: form-data; name=\"{name}\"\r\n\r\n"
31 f"{value}\r\n".encode()
32 )
33 body.extend(
34 f"--{boundary}\r\n"
35 f"Content-Disposition: form-data; name=\"image\"; filename=\"source.png\"\r\n"
36 f"Content-Type: {file_type}\r\n\r\n".encode()
37 )
38 body.extend(file_data)
39 body.extend(f"\r\n--{boundary}--\r\n".encode())
40 return bytes(body), "multipart/form-data; boundary=" + boundary
41 
42image_request = urllib.request.Request("https://zhenapi.ai/landing/logo.png", headers=IMAGE_HEADERS)
43with urllib.request.urlopen(image_request, timeout=60) as image_response:
44 header_type = image_response.headers.get("content-type", "").split(";")[0]
45 image_type = header_type or mimetypes.guess_type("source.png")[0] or "image/png"
46 image_data = image_response.read()
47 
48fields = {
49 "prompt": "Change the overall color palette of the image to blue.",
50 "model": "gpt-image-2",
51 "n": "1",
52 "quality": "auto",
53 "size": "1024x1024",
54 "stream": "true",
55 "response_format": "b64_json",
56}
57body, content_type = multipart(fields, image_data, image_type)
58 
59request = urllib.request.Request(
60 API_URL,
61 data=body,
62 method="POST",
63 headers={
64 "Authorization": "Bearer " + API_KEY,
65 "Content-Type": content_type,
66 "Accept": "text/event-stream",
67 },
68)
69 
70with urllib.request.urlopen(request, timeout=900) as response:
71 for data in iter_sse(response):
72 event = json.loads(data)
73 image = (
74 event.get("b64_json")
75 or ((event.get("data") or [{}])[0]).get("b64_json")
76 or (event.get("item") or {}).get("result")
77 )
78 if event.get("type") == "image_generation.partial_image":
79 print(".", end="", flush=True)
80 if image:
81 Path("edited-image.png").write_bytes(base64.b64decode(image))
82 print("\nImage saved:edited-image.png")
83 break

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
1import json
2import time
3import urllib.request
4from pathlib import Path
5 
6API_BASE = "https://api.zhenapi.ai/v1"
7API_KEY = "YOUR_API_KEY"
8AUTH_HEADERS = {
9 "Authorization": "Bearer " + API_KEY,
10 "Content-Type": "application/json",
11}
12 
13body = {
14 "model": "grok-imagine-video",
15 "prompt": "A corgi running along the beach, with sunlit waves and a cinematic camera shot.",
16 "resolution": "720p",
17 "duration": 8,
18}
19 
20def post_json(path, payload):
21 request = urllib.request.Request(
22 API_BASE + path,
23 data=json.dumps(payload).encode("utf-8"),
24 method="POST",
25 headers=AUTH_HEADERS,
26 )
27 with urllib.request.urlopen(request, timeout=300) as response:
28 return json.loads(response.read())
29 
30def get_json(path):
31 request = urllib.request.Request(API_BASE + path, headers=AUTH_HEADERS)
32 with urllib.request.urlopen(request, timeout=300) as response:
33 return json.loads(response.read())
34 
35# 1. Submit the generation task and obtain request_id
36task = post_json("/videos/generations", body)
37request_id = task.get("request_id") or task.get("id")
38print("Task submitted:", request_id)
39 
40# 2. Poll until completion (video generation usually takes tens of seconds)
41for _ in range(120):
42 status = get_json("/videos/" + request_id)
43 state = status.get("status", "")
44 print("Current status:", state)
45 if state in ("completed", "done", "succeeded"):
46 break
47 if state in ("failed", "error", "cancelled"):
48 raise RuntimeError(json.dumps(status, ensure_ascii=False))
49 time.sleep(5)
50else:
51 raise TimeoutError("Video generation timed out; query the task later using request_id")
52 
53# 3. Download the video, or use the temporary URL in status["video"]["url"]
54content_request = urllib.request.Request(
55 API_BASE + "/videos/" + request_id + "/content",
56 headers={"Authorization": "Bearer " + API_KEY},
57)
58with urllib.request.urlopen(content_request, timeout=600) as response:
59 Path("grok-video.mp4").write_bytes(response.read())
60print("Video saved:grok-video.mp4")

Common error: expected struct ImageUrl

If the response says "Failed to deserialize the JSON body into the target type: image: invalid type: string https://..., expected struct ImageUrl", the image field was supplied as a string instead of an object. Correct: {"image": {"url": "https://example.com/a.png"}}. The format {"image": {"image_url": "https://example.com/a.png"}} is also accepted. Incorrect: {"image": "https://example.com/a.png"}. For local images, replace url with a data URL, such as "data:image/png;base64,<BASE64>".

Parameters and billing

resolution supports 480p / 720p. duration defaults to 8 seconds and accepts 1–15 seconds. Billing is per second. Generation is asynchronous: /v1/videos/generations returns request_id; poll GET /v1/videos/{request_id} for status and video.url, then download the video bytes with GET /v1/videos/{request_id}/content. video.url is a temporary signed download URL. Download and save the file promptly.