SDKs
クライアントライブラリ
Python の標準ライブラリと Node.js の fetch を使う接続例です。認証情報を安全に保管できるサーバー側で実行してください。追加のパッケージは不要です。
Python
インストール
Python 3.9 以上を使用します。
python3 --version認証情報を設定する
export ORCHESTOR_API_KEY="YOUR_API_KEY"送信して完了を待つ
同期の例を creative_client.py として保存します。HTTP エラーは HTTPError、通信障害は URLError として呼び出し元へ返します。自動再送は行いません。
import json
import os
import time
import uuid
from urllib.request import Request, urlopen
from urllib.parse import quote
BASE_URL = "https://api.orchestor.io"
def request(path, payload=None, key=None, timeout=30):
headers = {"Authorization": f"Bearer {os.environ['ORCHESTOR_API_KEY']}"}
data = None
if payload is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(payload).encode()
if key:
headers["Idempotency-Key"] = key
req = Request(BASE_URL + path, data=data, headers=headers)
with urlopen(req, timeout=timeout) as response:
return json.load(response)["data"]
def generate():
key = str(uuid.uuid4()) # 受付が不明な場合の再送に備えて保存します。
submitted = request("/v1/creative/image-router/generate", {
"model": "gpt-image-2", "prompt": "海辺の空を飛ぶ赤い凧", "mode": "async",
}, key=key)
job_id = quote(submitted["job"]["id"], safe="")
deadline = time.monotonic() + 600
state = submitted
while not state.get("terminal", False):
delay = max(1, state.get("next_poll_after_seconds") or 2)
if time.monotonic() + delay >= deadline:
raise TimeoutError(f"待機時間を超えました。job={job_id}, key={key}")
time.sleep(delay)
state = request(f"/v1/creative/jobs/{job_id}/status",
timeout=max(0.001, min(30, deadline - time.monotonic())))
if not state.get("result_ready"):
raise RuntimeError(f"ジョブが成功せず終了しました: {state.get('status')}")
return request(f"/v1/creative/jobs/{job_id}/result")["result"]
if __name__ == "__main__":
print(generate()["artifacts"])ライフサイクルを個別に制御するときは、返されたジョブ ID を保存して状態取得・取消を行います。入力メディアはファイルのアップロードで準備します。
Node.js and TypeScript
インストール
Node.js 24 以上を使用します。
node --version認証情報を設定する
export ORCHESTOR_API_KEY="YOUR_API_KEY"送信して完了を待つ
次の例を .mjs ファイルに保存して実行します。HTTP エラーを呼び出し元へ返し、最大10分間ポーリングします。
const baseURL = 'https://api.orchestor.io';
const headers = {
Authorization: `Bearer ${process.env.ORCHESTOR_API_KEY}`,
'Content-Type': 'application/json',
};
const idempotencyKey = crypto.randomUUID();
const maxPollTime = 600_000;
async function readData(response) {
const body = await response.json();
if (!response.ok) {
const error = new Error(body.error?.message ?? `HTTP ${response.status}`);
error.status = response.status;
error.apiError = body.error;
throw error;
}
return body.data;
}
const submitted = await readData(await fetch(
`${baseURL}/v1/creative/image-router/generate`,
{
method: 'POST',
headers: { ...headers, 'Idempotency-Key': idempotencyKey },
body: JSON.stringify({
model: 'gpt-image-2',
prompt: '海辺の空を飛ぶ赤い凧',
aspect_ratio: '1:1',
mode: 'async',
}),
signal: AbortSignal.timeout(30_000),
},
));
const jobId = encodeURIComponent(submitted.job.id);
const deadline = Date.now() + maxPollTime;
let state = submitted;
while (!state.terminal) {
const delay = Math.max(1, state.next_poll_after_seconds ?? 2) * 1000;
const remaining = deadline - Date.now();
if (remaining <= delay) {
throw new Error(`待機時間を超えました。job=${jobId}, key=${idempotencyKey}`);
}
await new Promise(resolve => setTimeout(resolve, delay));
state = await readData(await fetch(
`${baseURL}/v1/creative/jobs/${jobId}/status`,
{
headers,
signal: AbortSignal.timeout(Math.max(1, Math.min(30_000, deadline - Date.now()))),
},
));
}
if (state.next_action !== 'fetch_result' || !state.result_ready) {
throw new Error(`ジョブが成功せず終了しました: ${state.status ?? state.job?.status}`);
}
const result = await readData(await fetch(
`${baseURL}/v1/creative/jobs/${jobId}/result`,
{ headers, signal: AbortSignal.timeout(30_000) },
));
console.log(result.result.artifacts);ブラウザーに API キーを渡さず、サーバー側で実行してください。
待機終了は取消ではありません
クライアントがタイムアウトしてもジョブは継続します。ジョブ ID で状態確認を再開してください。受付結果が不明な場合は、同じ入力と冪等性キーで再送します。
連携方法を選ぶ
| 用途 | 方法 |
|---|---|
| スクリプト・プロトタイプ | 上記の送信・待機例を使用します。 |
| ワーカーで状態を個別に管理 | mode: "async" で送信し、ジョブ ID を永続化します。 |
| ジョブ ID を取得済み | status・result・cancel を呼び出します。 |
| 本番のイベント駆動処理 | mode: "webhook" と webhook_url を指定し、通知欠落時はポーリングします。 |
入力と応答の仕様は API リファレンスで確認してください。