<style>#docs-navigation{display:block!important}.docs-article [style*="display:none"],.docs-article [style*="display: none"]{display:block!important}</style>
跳到文档正文

接口与能力

API 脚本接入教程

可复制的 Python 和 Node.js 示例,覆盖 Responses、Chat Completions、Messages、图片生成编辑和视频接口。

本页目录

下面示例覆盖文本、视觉、图片和视频接口。复制后把 YOUR_API_KEY 替换为你的密钥即可运行。

OpenAI Responses 文本+视觉

新一代 OpenAI 接口,适合文本对话、图片理解和流式输出。

POST /v1/responses
1import json
2import urllib.request
3 
4API_URL = "https://api.apikey.fan/v1/responses"
5API_KEY = "YOUR_API_KEY"
6 
7body = {
8 "model": "gpt-6.1-sol",
9 "stream": True,
10 "input": "用中文简单介绍一下 APIKEY.FAN。",
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 文本+视觉

兼容传统 OpenAI Chat 格式,适合已有客户端平滑迁移。

POST /v1/chat/completions
1import json
2import urllib.request
3 
4API_URL = "https://api.apikey.fan/v1/chat/completions"
5API_KEY = "YOUR_API_KEY"
6 
7body = {
8 "model": "gpt-6.1-sol",
9 "stream": True,
10 "messages": [{"role": "user", "content": "用中文简单介绍一下 APIKEY.FAN。"}],
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 文本+视觉

Claude / Anthropic Messages 格式;图片模式会先转 base64 再提交。

POST /v1/messages
1import json
2import urllib.request
3 
4API_URL = "https://api.apikey.fan/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": "用中文简单介绍一下 APIKEY.FAN。"}],
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 图片生成与编辑

文生图走 /v1/images/generations;图生图和图片编辑走 /v1/images/edits,支持 multipart 本地文件、多张参考图,以及 JSON 的 images[].image_url(图片链接或 data URL)。Gemini(官方直连)分组可直接将示例 model 换成图片生成 使用教程中列出的 Gemini 图片模型 ID,保留 stream=true、n=1、response_format=b64_json。Gemini 返回 usage 和 usageMetadata,图片格式见 mime_type;size 会转换为比例与 1K/2K/4K 档位,实际像素由模型决定,2.5 系列仅支持 1K。Gemini 暂不支持 mask、批量 n>1、强制 output_format 和非 auto 的 quality/background 等参数。

POST /v1/images/generations
1import base64
2import json
3import urllib.request
4from pathlib import Path
5 
6API_URL = "https://api.apikey.fan/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": "生成一只太空猫",
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("\n图片已保存:generated-image.png")
50 break

gpt-image-2 图片编辑(multipart)

上传图片并按提示修改,通过流式事件保存编辑结果。

POST /v1/images/edits
1import base64
2import json
3import mimetypes
4import urllib.request
5import uuid
6from pathlib import Path
7 
8API_URL = "https://api.apikey.fan/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 = "----apikeyfun-" + 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://api.apikey.fan/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": "把图片整体颜色更改为蓝色。",
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("\n图片已保存:edited-image.png")
83 break

grok-imagine-video 视频生成

异步视频生成:提交任务拿到 request_id,轮询状态直到完成,再下载视频文件。

POST /v1/videos/generations
1import json
2import time
3import urllib.request
4from pathlib import Path
5 
6API_BASE = "https://api.apikey.fan/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": "一只柯基在海边奔跑,浪花被阳光照亮,电影质感镜头。",
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. 提交生成任务,取回 request_id
36task = post_json("/videos/generations", body)
37request_id = task.get("request_id") or task.get("id")
38print("任务已提交:", request_id)
39 
40# 2. 轮询任务状态,直到完成(视频生成通常需要几十秒)
41for _ in range(120):
42 status = get_json("/videos/" + request_id)
43 state = status.get("status", "")
44 print("当前状态:", 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("视频生成超时,请稍后凭 request_id 重新查询")
52 
53# 3. 下载视频;也可直接使用 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("视频已保存:grok-video.mp4")

常见报错:expected struct ImageUrl

若返回 “Failed to deserialize the JSON body into the target type: image: invalid type: string "https://...", expected struct ImageUrl”,说明 image 字段被直接写成了字符串。 正确写法:{"image": {"url": "https://example.com/a.png"}};同时兼容 {"image": {"image_url": "https://example.com/a.png"}}。 错误写法:{"image": "https://example.com/a.png"}。 传本地图片时把 url 换成 data URL,例如 "data:image/png;base64,<BASE64>"。

参数与计费说明

resolution 支持 480p / 720p,duration 默认 8 秒、可选 1–15 秒,按秒计费。 生成为异步任务:/v1/videos/generations 返回 request_id,轮询 GET /v1/videos/{request_id} 得到 status 与 video.url,再用 GET /v1/videos/{request_id}/content 下载视频字节流。 video.url 为临时签名直链,请及时下载保存。