API 协议

当前项目接入流程

预览指南

粘贴给 AI,帮助理解文档并完成接入。 仅包含文档与示例,不包含真实密钥。

预览指南

当前项目接入流程

直接答案按当前项目实现与成功样本选择接入方式,包含 MJ U1 按钮放大的完整示例。

更新 · 审核信息

范围与选择

本页按当前项目路由、请求结构和转发实现整理接入流程。外部文档仅作对照。只将已有成功样本的具体调用方式纳入本页;型号可见、路由存在或 HTTP 200 都不能单独作为功能成功的依据。

下表列出已有成功样本的调用方式。U1 按钮放大使用独立的 action 契约;旧 change 路径的调用说明暂未发布,两条路径不能混用。

需求本页接入方式边界
放大 MJ 四宫格第一张图片U1 按钮放大源任务成功、提供真实 U1 按钮,源渠道支持 action
MJ 强变化或平移强变化、平移复制对应真实按钮,使用自己的源任务
查询 MJ 多个任务批量查询返回当前账号任务;检查每项状态
生成音乐旧 Suno music使用渠道支持的参数;歌词示例待验收后恢复
查询旧 Suno 结果单查、批查、feed GET、feed POST本站任务信封,不是上游歌曲数组
兼容旧 Key 用量查询按 Key 查询路径 Key 加所属账号 ID;避免将完整 URL 写入日志

MJ 按钮放大的完整流程

先通过 MJ 绘图 取得自己的成功源任务。下方示例只使用普通 /mj 路径和 U1;源任务、令牌模式及渠道须兼容。它不会创建源图,也不会自动替换不支持的按钮。没有唯一 U1 按钮时停止,而不是猜 customId 或改走旧 change 路径。

  1. 使用同一账号的模型调用 Key 查询源任务,确认 status=SUCCESS。
  2. 从源任务 buttons 选择真实 U1,将完整 customId 与 taskId 提交到 /mj/submit/action。请求无需 model、action、index。
  3. 立即保存返回的任务 ID,有限轮询到终态。只有 SUCCESS、action=UPSCALE、有效 imageUrl 同时满足,才读取图片。
  4. 下载图片时不附带本站 API Key。最终使用前确认响应确实是可解码图片,而不是 JSON 错误或过期链接。

可运行 Python 示例

使用 Python 3 标准库,无需安装第三方包。将下面代码保存为 midjourney_button_upscale.py。运行前在本机环境设置 GATEWAY_ORIGIN(本站 HTTPS 域名,不带 /v1)、API_KEY 和 SOURCE_TASK_ID,再执行 python3 midjourney_button_upscale.py。

程序受理后立即输出 RESUME_TASK_ID。查询中断时设置该变量再次运行,只查询已受理任务。若提交阶段超时且未取得任务 ID,应先查任务/调用记录;不要直接重复创建。此示例的轮询预算为 10 分钟,每次 HTTP 请求另有 120 秒超时。

"""Gateway MJ U1 workflow. Set GATEWAY_ORIGIN, API_KEY and SOURCE_TASK_ID.

Set RESUME_TASK_ID instead of SOURCE_TASK_ID to query an accepted job without
submitting again. A timed-out POST must be investigated before any retry.
"""

import json
import os
import time
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def run(base, key, source_id="", resume_id="", emit=print):
    base = base.rstrip("/")
    origin = urlsplit(base)
    if (origin.scheme not in ("http", "https") or not origin.netloc
            or origin.path or origin.query or origin.fragment
            or origin.username or origin.password):
        raise ValueError("GATEWAY_ORIGIN must be the gateway origin without a path")
    if origin.scheme != "https" and origin.hostname not in ("localhost", "127.0.0.1", "::1"):
        raise ValueError("Use HTTPS for a remote gateway")
    if not key or not (resume_id or source_id):
        raise ValueError("API_KEY and SOURCE_TASK_ID or RESUME_TASK_ID are required")
    opener = build_opener(NoRedirect())

    def request(path, payload=None):
        headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
        body = None if payload is None else json.dumps(payload).encode()
        # No redirects with credentials, and no automatic POST retries.
        with opener.open(Request(base + path, data=body, headers=headers), timeout=120) as response:
            value = json.load(response)
        if not isinstance(value, dict) or value.get("error"):
            raise RuntimeError("Gateway returned an invalid or error response")
        if "code" in value and str(value["code"]) not in ("1", "21", "22"):
            raise RuntimeError(value.get("description") or "MJ request failed")
        return value

    def query(task_id):
        task = request("/mj/task/" + quote(task_id, safe="") + "/fetch")
        if task.get("id") != task_id or not isinstance(task.get("status"), str):
            raise RuntimeError("Task response has a missing or mismatched ID/status")
        return task

    task_id = resume_id
    if not task_id:
        source = query(source_id)
        if source["status"] != "SUCCESS":
            raise RuntimeError("Source task must be SUCCESS before selecting its U1 button")
        buttons = source.get("buttons")
        if not isinstance(buttons, list):
            raise RuntimeError("Source task does not provide action buttons")
        matches = [button["customId"] for button in buttons
                   if isinstance(button, dict)
                   and button.get("label") == "U1"
                   and isinstance(button.get("customId"), str)
                   and button["customId"].startswith("MJ::JOB::upsample::1::")]
        if len(matches) != 1:
            raise RuntimeError("Source task must provide exactly one genuine U1 button")
        submitted = request("/mj/submit/action", {"taskId": source_id, "customId": matches[0]})
        task_id = submitted.get("result")
        if str(submitted.get("code")) not in ("1", "21", "22") or not isinstance(task_id, str) or not task_id:
            raise RuntimeError("Submission was not accepted with a valid task ID")
        emit("RESUME_TASK_ID=" + task_id, flush=True)

    deadline = time.monotonic() + 600
    delay = 2
    while time.monotonic() < deadline:
        task = query(task_id)
        if task["status"] == "FAILURE":
            raise RuntimeError(task.get("failReason") or "MJ task failed")
        if task["status"] == "SUCCESS":
            result = task.get("imageUrl")
            if task.get("action") != "UPSCALE" or not isinstance(result, str):
                raise RuntimeError("Task did not return an UPSCALE image result")
            image = urlsplit(result)
            if image.scheme not in ("http", "https") or not image.netloc:
                raise RuntimeError("Task returned an invalid image URL")
            # Retrieve this media separately; never forward the gateway API key.
            return {"task_id": task_id, "image_url": result}
        time.sleep(delay)
        delay = min(delay * 2, 15)
    raise TimeoutError("Polling timed out; resume with RESUME_TASK_ID=" + task_id)


if __name__ == "__main__":
    result = run(os.environ["GATEWAY_ORIGIN"], os.environ["API_KEY"],
                 os.environ.get("SOURCE_TASK_ID", ""), os.environ.get("RESUME_TASK_ID", ""))
    print(json.dumps(result, ensure_ascii=False))

暂未纳入的场景

传统 Completions、其他未通过的 MJ 动作、Seed 查询、Sora Remix、Qwen Omni、旧 Suno 拼接与音频 URL 上传仍需补齐各自的渠道或验收条件。没有将普通聊天当作 Omni、把 v2 当作旧 Suno 已通过,或把按钮放大的成功推广到其他动作。

验证边界

U1 路径的历史真实样本完成于 2026-11-08:提交成功、任务 SUCCESS、PNG 完整解码。新示例另做本地请求与异常流程验证。该证据不代表所有模型、账号、模式和渠道均可用。正式接入前,应对实际使用的账号和渠道完成一次提交、终态、产物及用量检查。

适用场景

  • 使用成功源任务的 U1 按钮放大
  • 中断后恢复查询并读取结果

API 协议

  • /mj/submit/action
  • /mj/task/{task_id}/fetch

常见问题

可以直接复制示例的 taskId 和 customId 吗?

不可以。必须查询当前账号自己的成功源任务,并完整复制其实际 U1 按钮;没有按钮时停止调用。

提交成功就表示图片可用了?

提交仅返回任务 ID。继续查询到 SUCCESS,确认 UPSCALE 和有效 imageUrl,再下载并验证图片。

提交或查询超时可以直接重跑吗?

已有任务 ID 时设置 RESUME_TASK_ID 只恢复查询;提交超时且未取得 ID 时先查任务与调用记录,避免重复创建。

按钮放大成功是否表示其他 MJ 动作也能调用?

不表示。U1 按钮放大有独立的请求契约和成功样本;其他动作需要对应的源任务、按钮及渠道能力,请按各自动作文档接入。

官方来源

  1. new-api · QuantumNous 官方