GPT Image 2 批量生图实战:网页验证与无限并发异步 API

本文给出一套适合跨境电商多 SKU 的图片生产流程:先在网页"自由绘图"验证商品一致性提示词,再通过 POST /v1/images/generations 异步提交批量任务,以 GET /v1/tasks/{task_id} 查询状态并下载 result_urls。同一方法也可用于短剧、广告、游戏、文旅、出版和 POD 等稳定的批量生图任务。

体验入口:https://www.maizimarket.com/

1. 先在网页验证输入和提示词

真实导航为"创意中心---快速创作---自由绘图"。已有商品原图时选择"批量图生图"。

上传清晰、完整的商品图后,使用下面的商品一致性提示词:

text 复制代码
Use the uploaded product image as the only source of truth.

Create a premium lifestyle product photograph for a cross-border ecommerce listing.

Keep the exact product shape, proportions, colors, materials, buttons, logo and packaging details.
Use realistic commercial lighting, physically accurate reflections and shadows, a clean square composition, and clear product focus.

Do not add or remove product parts.
Do not invent accessories, functions, certifications or claims.
No promotional text, price, discount badge, watermark, extra logo or duplicated product.

模型选择 GPT Image 2,商品主图先测试 1:1、1K、1 张。点击"立即生成",完成后核对形状、颜色、材质、Logo、包装文字、按钮、配件和商品数量。通过就下载;不通过则调整提示词后重新生成。

下面是站内帮助区的内置商品输入与场景结果示例,并非本文新执行的生成批次。

2. API 契约

基础地址:https://www.maizitech.xyz

动作 接口 关键结果
提交图片任务 POST /v1/images/generations data[0].task_id
查询任务 GET /v1/tasks/{task_id} statusresult_urlserror_msg

认证头为 Authorization: Bearer sk-...。Key 必须放在环境变量或密钥管理服务,不要硬编码。

任务状态包括 queuedpendingprocessingcompletedfailedviolation。建议图片任务每 5--10 秒查询一次;完成 URL 只保留有限时间,应及时下载到自己的对象存储。

3. 可运行的 asyncio + httpx 示例

先安装依赖并设置 Key:

bash 复制代码
pip install httpx
export MAIZIAI_API_KEY="sk-..."
python 复制代码
import asyncio
import os
from pathlib import Path

import httpx

BASE_URL = "https://www.maizitech.xyz"
API_KEY = os.environ["MAIZIAI_API_KEY"]
TERMINAL = {"completed", "failed", "violation"}
PROMPT = 'Use the uploaded product image as the only source of truth.\n\nCreate a premium lifestyle product photograph for a cross-border ecommerce listing.\n\nKeep the exact product shape, proportions, colors, materials, buttons, logo and packaging details.\nUse realistic commercial lighting, physically accurate reflections and shadows, a clean square composition, and clear product focus.\n\nDo not add or remove product parts.\nDo not invent accessories, functions, certifications or claims.\nNo promotional text, price, discount badge, watermark, extra logo or duplicated product.'


async def submit(client, item):
    response = await client.post(
        "/v1/images/generations",
        json={
            "model": "gpt-image-2",
            "prompt": PROMPT,
            "images": [item["image_url"]],
            "size": "1:1",
            "image_size": "1K",
            "n": 1,
        },
    )
    response.raise_for_status()
    return response.json()["data"][0]["task_id"]


async def wait_result(client, task_id, timeout_seconds=600):
    deadline = asyncio.get_running_loop().time() + timeout_seconds
    while asyncio.get_running_loop().time() < deadline:
        response = await client.get(f"/v1/tasks/{task_id}")
        response.raise_for_status()
        task = response.json()
        if task["status"] in TERMINAL:
            if task["status"] != "completed":
                raise RuntimeError(task.get("error_msg") or task["status"])
            return task["result_urls"]
        await asyncio.sleep(5)
    raise TimeoutError(f"task {task_id} timed out")


async def generate_one(client, semaphore, item):
    async with semaphore:
        task_id = await submit(client, item)
        urls = await wait_result(client, task_id)
        output = Path("downloads") / f'{item["sku"]}.png'
        output.parent.mkdir(exist_ok=True)
        image = await client.get(urls[0])
        image.raise_for_status()
        output.write_bytes(image.content)
        return item["sku"], task_id, output


async def main():
    items = [
        {"sku": "SKU-001", "image_url": "https://example.com/sku-001.png"},
        {"sku": "SKU-002", "image_url": "https://example.com/sku-002.png"},
    ]
    headers = {"Authorization": f"Bearer {API_KEY}"}
    timeout = httpx.Timeout(30, read=60)
    semaphore = asyncio.Semaphore(5)
    async with httpx.AsyncClient(
        base_url=BASE_URL, headers=headers, timeout=timeout, follow_redirects=True
    ) as client:
        results = await asyncio.gather(
            *(generate_one(client, semaphore, item) for item in items),
            return_exceptions=True,
        )
        for result in results:
            print(result)


asyncio.run(main())

接口支持无限并发调用,另一台服务器的批量测试成功率为 99%。示例为了控制单个客户端资源占用,将本地并发设为 5;单请求与总轮询都有超时,失败/违规会保留为异常,完成后从 result_urls 下载。正式系统还应将 SKU、task_id、状态、重试次数和目标文件地址持久化。

4. 行业与任务映射

行业 输入 输出 建议工作流
跨境电商 SKU 原图、包装、品牌规范 主图、场景图、A+ 图、尺寸变体 网页验一款,API 批量 SKU
短剧/网文 角色参考、剧本、场景设定 海报、定妆图、分镜气氛图 网页锁角色,API 按集生产
广告营销 品牌资产、产品图、Brief KV、广告变体、社媒素材 网页确认创意,API 跑渠道版
游戏 角色、道具、世界观设定 概念图、道具图、场景图 网页迭代核心设定,API 补资产
建筑/室内 模型截图、线稿、材质参考 外立面、室内、夜景表达 网页逐张结构校核
文旅 景点照片、文化元素、路线 海报、路线视觉、文创方向 网页定方向,API 多尺寸输出
内容出版 文章、脚本、栏目模板 封面、插图、轮播、缩略图 模板稳定后用 API
POD/服装 版型、印花主题、尺寸 花型、印花图、展示图 网页查版式版权,API 批量

5. 结果检查与重试边界

电商图片应核对商品事实、品牌文字和平台规范;短剧与游戏应核对角色和道具一致性;建筑应核对体量与结构;广告、文旅和 POD 还要核对商标、版权、文化表达与可印刷性。

网络错误、HTTP 429/5xx 可以有限重试;failedviolation 应先读 error_msg,修改输入后再创建新任务。不要因任务处于 queued 就重复提交,否则会产生重复订单。

相关推荐
进阶的小名1 小时前
Spring AI 2.0 探索:多 OpenAI-Compatible 模型接入,以及下一代 Session 记忆管理
java·人工智能·后端·gpt·spring·ai·chatgpt
捣鼓软件3 小时前
告别“玄学咒语“:这个 GitHub 项目把 GPT-Image2 的提示词变成了“可复用代码“!
gpt·github
AI模型调用笔记4 小时前
GPT-5.4 8月31日退出 Codex?先分清 ChatGPT 登录与 API Key,再迁移 Terra/Luna
人工智能·gpt·chatgpt·ai编程
yingyuecom9 小时前
映悦AI × Joverse全球发布:四大重磅更新,AI创作进入工业化时代
人工智能·gpt·chatgpt·prompt·aigc
小弥儿10 小时前
GPT Image 2 提示词库,把散落的生图提示词变成工程资产
开发语言·javascript·gpt·学习
小女孩真可爱12 小时前
GPT(1)----------从零实现 GPT 模型以生成文本
人工智能·python·gpt·nlp
小女孩真可爱13 小时前
GPT(3)----------------GQA分组查询注意力机制提速
人工智能·pytorch·gpt·深度学习·大模型
薛定猫AI1 天前
【深度解析】多编程代理协同开发:用共享上下文构建 Claude Code 与 Codex 编排工作流
人工智能·gpt
Lee_jerome1 天前
python神经网络编程入门(四十二)——GPT:自回归生成式预训练
gpt·生成式·decoder·topk·自回归·temperature·下一个词预测