К основному содержанию
скилл CX Codex

adobe-firefly-image — скилл для Claude Code: установка

Скилл adobe-firefly-image для Claude Code управляет генерацией и обработкой изображений через Adobe Firefly Services. Включается для асинхронных REST-запросов.

MIT 137 установок ★ 252 обновлён 2026-07-14

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add calesthio/generative-media-skills --skill adobe-firefly-image -a claude-code
Открыть на GitHub

Что делает adobe-firefly-image

Скилл adobe-firefly-image помогает выбирать операции Firefly для генерации, редактирования, расширения, заливки, сопоставления, композитинга и увеличения still images. Он разбирает различия между Image 5, Image 3/4 и custom models, а также работу со style и structure references.

Внутри описаны текущие асинхронные REST-маршруты, включая generate-async, fill-async, expand-async, generate-object-composite-async, precise-composite, adaptive-composite и upscale. Для загрузки изображения или маски используется POST /v2/storage/image; upload ID действует семь дней. Без entitlement к Firefly Services, OAuth Server-to-Server credentials, Adobe IMS bearer token и Client ID в x-api-key запросы не заработают; client secret и access token нельзя помещать в браузерный код, логи, промпты или артефакты.

Какие задачи решает

  • выбрать endpoint и модель для генерации изображения
  • собрать асинхронный workflow с авторизацией Adobe
  • обработать изображение через маску или расширение холста
  • создать product composite с существующим фоном или без него
  • увеличить изображение через precise_upsampler_v1

Примеры запросов агенту

  • Выбери между Image 5 и Image 3/4 для этой задачи и опиши нужный REST-запрос.
  • Собери серверный асинхронный workflow Firefly с OAuth Server-to-Server, x-api-key и обновлением токена.
  • Подскажи, какой endpoint использовать для product composite с объектом, маской и существующим фоном.

Как установить adobe-firefly-image

1Через Skills CLI (Vercel)

npx skills add calesthio/generative-media-skills --skill adobe-firefly-image -a claude-code

2Вручную: положить файлы

~/.claude/skills/adobe-firefly-image/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/adobe-firefly-image/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об adobe-firefly-image

Как установить adobe-firefly-image в Claude Code?

Выполни npx skills add calesthio/generative-media-skills --skill adobe-firefly-image -a claude-code, затем проверь файл ~/.claude/skills/adobe-firefly-image/SKILL.md.

Что делает adobe-firefly-image?

Скилл помогает работать с Adobe Firefly Services для генерации, редактирования, расширения, заливки, сопоставления, композитинга и увеличения изображений через асинхронные REST API.

Что нужно для работы adobe-firefly-image?

Нужны entitlement к Firefly Services, OAuth Server-to-Server credentials, Adobe IMS bearer token и Client ID, передаваемый в x-api-key. Для custom model нужны provisioned custom model и его доступность приложению.

Исходный текст

SKILL.md · MIT
---
name: adobe-firefly-image
description: Use Adobe Firefly Services to generate, edit, expand, fill, match, composite, and upscale still images through the current REST APIs. Apply when selecting Firefly Image 5 versus Image 3/4 or custom models, implementing authenticated asynchronous image workflows, using style or structure references, building product composites, handling provenance and enterprise rights, or diagnosing Firefly image jobs in production. Exclude Firefly video, audio, and unrelated Creative Cloud APIs.
---

# Adobe Firefly Image

Treat this as a still-image production and integration skill. Keep video, audio, and unrelated Photoshop, Lightroom, Express, or Creative Production operations out of scope unless the user explicitly asks to combine systems.

## Evidence discipline

Use these labels consistently:

- **Documented** means the current Adobe API reference, changelog, product terms, or security material states the claim.
- **Inference** means the conclusion follows from documented fields or behavior but Adobe does not state it directly.
- **Production heuristic** means practical guidance to test in the target account and workflow.

Volatile API facts below were verified on **2026-07-09**. Re-check the [API reference](https://developer.adobe.com/firefly-services/docs/firefly-api/api/), [changelog](https://developer.adobe.com/firefly-services/docs/firefly-api/getting-started/changelog/), and [usage notes](https://developer.adobe.com/firefly-services/docs/firefly-api/getting-started/usage-notes/) immediately before shipping. Adobe has several prose pages whose examples conflict with the endpoint reference. When they disagree, prefer the operation schema in the API reference plus a later explicit changelog entry; do not merge fields from incompatible versions.

## Start with the production contract

Before generating anything:

1. Confirm that the organization is entitled to Firefly Services and that the project has OAuth Server-to-Server credentials.
2. Record the deliverable, aspect ratio or dimensions, acceptable alteration of supplied assets, rights/consent status, locale, accessibility needs, and review owner.
3. Choose the operation from the matrix below. Do not select a model only because it is newest.
4. Quote the endpoint, model header, variation count, and cost unit before a paid batch.
5. Run one representative sample, download it immediately, and perform visual and provenance QA before scaling.

## Current API and model map

**Documented, verified 2026-07-09:**

| Need | Endpoint | Model selection | Key boundary |
|---|---|---|---|
| New Image 5 generation | `POST /v4/images/generate-async` | Header `x-model-version: image5`; body `modelId: firefly_image` | One variation per request; up to one reference image |
| Image 5 natural-language edit | Same v4 endpoint | Same header/body | A non-empty `referenceBlobs` array switches the operation to instruct edit |
| Image 3/4 generation and explicit controls | `POST /v3/images/generate-async` | `image3`, `image4_standard`, or `image4_ultra` | Up to four variations; style/structure controls live here |
| Custom-model generation | Same v3 endpoint | `image3_custom` or `image4_custom` plus `customModelId` | Custom model must be provisioned and shared with the app |
| Similar image | `POST /v3/images/generate-similar-async` | `image3`, `image4_standard`, or `image4_ultra` | Source image required |
| Masked replacement | `POST /v3/images/fill-async` | Operation schema, not Image 5 instruct-edit schema | Source and mask required |
| Canvas expansion/outpainting | `POST /v3/images/expand-async` | Operation schema | Source required; mask and placement are mutually constrained |
| Prompt-generated background around an object | `POST /v3/images/generate-object-composite-async` | Operation schema | Use when no background exists |
| Preserve an object precisely in an existing background | `POST /v3/images/precise-composite` | Precise composite pipeline | Existing background and placement mask required |
| Adapt an object into an existing background | `POST /v3/images/adaptive-composite` | Adaptive composite pipeline | May regenerate/adapt the object for realism |
| Fidelity-oriented upscale | `POST /v3/images/upscale` | `x-model-version: precise_upsampler_v1` | Factors 2, 3, 4, or 6; asynchronous |
| Upload input image or mask | `POST /v2/storage/image` | None | Returns an upload ID valid for seven days |

Image 5 is the latest documented image model and exposes 1 MP, 2.4 MP, and 4 MP resolution levels. The v3 model values remain present in the current API schema; do not call them removed merely because Image 5 exists. Adobe removed the deprecated synchronous v3 references on 2025-10-03 and removed Generate Images v2, Expand v1, and Fill v1 on 2025-09-10. Build only against current asynchronous routes. See the [changelog](https://developer.adobe.com/firefly-services/docs/firefly-api/getting-started/changelog/).

### Resolve documentation conflicts deliberately

**Documented conflict, verified 2026-07-09:** the Image 5 API reference defines `aspectRatio`, `resolutionLevel`, `modelId`, `modelSpecificPayload`, and `referenceBlobs` for `/v4/images/generate-async`. The [Image 5 migration page](https://developer.adobe.com/firefly-services/docs/firefly-api/guides/how-tos/cm-generate-image/breaking-changes) simultaneously describes some of those fields as removed and presents a payload resembling the v3 custom-model schema. Do not use that migration table as executable schema without reconciling it against the API reference.

Likewise, a prose upscale guide still names `/v1/images/upsample-async`, while the current API reference and 2026-04-24 changelog identify `POST /v3/images/upscale` and `precise_upsampler_v1`. Use the latter. `creative_upsampler_v1` is rejected with 422. This is a source-quality decision, not a claim that every Adobe prose page is obsolete.

## Authenticate from a server

**Documented:** Firefly requests require both an Adobe IMS bearer token and the Client ID as `x-api-key`. Use OAuth Server-to-Server. Never expose the client secret or access token in browser code, logs, prompts, or generated artifacts. Adobe documents 24-hour access-token validity; refresh proactively and retry once after a 401 only after obtaining a fresh token. See [Authentication](https://developer.adobe.com/firefly-services/docs/firefly-api/getting-started/) and [credentials setup](https://developer.adobe.com/firefly-services/docs/guides/get-started).

Token request:

```http
POST https://ims-na1.adobelogin.com/ims/token/v3
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=...&client_secret=...&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis
```

Every Firefly API call then includes:

```http
Authorization: Bearer <access-token>
x-api-key: <client-id>
Content-Type: application/json
Accept: application/json
```

Use the scopes and product profiles actually provisioned in the Developer Console; do not broaden scopes speculatively. A 403 after successful token exchange usually points to entitlement, product-profile, organization, custom-model sharing, policy, or regional access rather than malformed OAuth.

## Understand request and response contracts

### Image 5: v4 generate and instruct edit

**Documented v4 fields:**

- `prompt`: required, 1–1500 characters.
- `aspectRatio`: `1:1`, `4:3`, `3:4`, `16:9`, `9:16`, or `auto`.
- `resolutionLevel`: `1MP`, `2.4MP` (default), or `4MP`.
- `modelId`: `firefly_image`.
- `numVariations`: maximum 1.
- `seeds`: maximum one integer; its count must match `numVariations` when both appear.
- `modelSpecificPayload.localeCode`: locale control used by Image 5.
- `modelSpecificPayload.prompt_reasoner`: `speed` (default) or `quality`; Adobe says `quality` populates `altText`, while `speed` returns it empty.
- `referenceBlobs`: maximum one. Empty means text-to-image; non-empty with `usage: general` means instruct edit. When present, omit `aspectRatio` or set it to `auto`.

Do not send v3-only `style`, `structure`, `contentClass`, `visualIntensity`, or `customModelId` fields to v4. The v4 operation schema does not document a negative-prompt field or arbitrary output-format selector. Validate the actual response asset `Content-Type` rather than assuming JPEG or PNG.

The v4 submission returns HTTP 200 with a `links.result.href`, `links.cancel.href`, and progress value. It is still asynchronous. Poll the returned result link with the same authorization headers until a terminal state, then download the image URL promptly.

### Image 3/4: v3 generate

**Documented v3 fields:**

- `prompt`: required, 1–1024 characters.
- `negativePrompt`: up to 1024 characters; not supported for Image 3 or Image 4 custom models.
- `contentClass`: `photo` or `art`.
- `numVariations`: 1–4. If seeds are supplied, seed count must equal variation count.
- `promptBiasingLocaleCode`: BCP-47-like language-region value such as `en-US`.
- `style.presets`: documented snake_case presets; combine deliberately.
- `style.strength`: 1–100, default 50; may accompany a style reference.
- `structure.strength`: 1–100, default 50; controls outline/depth resemblance to the structure reference.
- `visualIntensity`: 2–10; not supported by `image4_custom`.
- `upsamplerType`: only for `image4_custom`; `default` or `low_creativity`.

Supported generation sizes:

| Model | Exact documented sizes |
|---|---|
| Image 4 | `2048×2048`, `2304×1792`, `1792×2304`, `2688×1536`, `1440×2560` |
| Image 3 | `2048×2048`, `1024×1024`, `2304×1792`, `1792×2304`, `2688×1536`, `2688×1512`, `1344×768`, `1344×756`, `1152×896`, `896×1152` |

Do not round to a convenient aspect-equivalent size. The service validates exact pairs.

The v3 submission returns HTTP 202 with `jobId`, `statusUrl`, and `cancelUrl`. Poll `statusUrl`. A running response includes `status: running`; success includes `status: succeeded` and `result.outputs[]`, each with a seed and image URL. Treat `failed`, `cancelled`, HTTP terminal errors, and a local timeout as terminal outcomes; capture the response body and request ID for support.

### Uploads, masks, and source URLs

The upload API accepts binary image data. The current API reference lists PNG, JPEG, WebP, TIFF, and JXL with a 15 MB maximum, while an older upload guide lists only JPEG, PNG, and WebP. **Production heuristic:** use PNG for masks/transparency and JPEG or PNG for ordinary inputs unless the target account has been tested with the broader formats.

An upload response is shaped as `{"images":[{"id":"..."}]}`. The API contract says the ID is valid for seven days. Adobe's Firefly Services security sheet separately says uploaded reference content is cached for 24 hours; do not equate cache retention with ID validity.

For v3 source URLs, the operation reference commonly allow-lists `amazonaws.com`, `windows.net`, `dropboxusercontent.com`, and `storage.googleapis.com`. The Image 5 usage notes add `frontdoor.prod.azure.cxp.adobe.com`. Requirements vary by operation. Use short-lived HTTPS pre-signed URLs, restrict object permissions, and confirm the exact operation's allow-list. Never pass an arbitrary public URL and assume Firefly will fetch it.

Masks are production assets, not annotations. Inspect dimensions, alpha/gray semantics, inversion, feathering, and alignment before a paid call. `expand-async` forbids using `placement` for a source when a mask is also applied. Its output can be up to 3999×3999. Use Fill for a localized masked replacement; use Expand for a larger canvas; use Image 5 instruct edit for a natural-language whole-image refinement where one reference is sufficient.

## Choose references and composites by what must remain fixed

### Style and structure

Use v3 `style.imageReference` to transfer visual language such as palette, medium, lighting, or mood. Use `structure.imageReference` to guide outline and depth. Strength 1–100 changes adherence; default 50. These controls can coexist, but competing high strengths can reduce prompt compliance.

**Production heuristic:** sweep one control at a time—such as 30, 60, 90—using the same prompt and seed, then select by a written rubric. A seed is a reproducibility aid, not an archival guarantee across model, endpoint, or service updates. Adobe's seed guide says identical settings reproduce an image; still record the model header, endpoint, payload, and source hashes because lifecycle changes can invalidate cross-version assumptions.

Use only documented preset values from the [style preset catalog](https://developer.adobe.com/firefly-services/docs/firefly-api/guides/concepts/style-presets/). Do not invent UI labels as API enum values. A few useful documented examples are `product_photo`, `studio_light`, `golden_hour`, `flat_design`, `watercolor`, `cinematic`, `bw`, and `shallow_depth_of_field`; this is not the complete catalog.

### Composite selection

- Use **Generate Object Composite** when the object exists but the background should be generated from a prompt. The request must provide an input that can be composited: a larger requested canvas, transparency, or a mask.
- Use **Precise Composite** when the supplied object's pixels or packaging details must remain exact. It uses background image + fill-area mask + object image. `blend` ranges 0–1; 0 is fully harmonized and 1 preserves the original object appearance. Up to three variations.
- Use **Adaptive Composite** when realism in an existing background is more important than pixel-exact object preservation. `harmonization` and `shadowIntensity` range 0–1; `preserveBackground` retains original background pixels while modifying the object region. Up to three variations.

All three are asynchronous. Do not promise that “precise” removes the need for a pixel-diff and label-legibility review. Do not use Adaptive Composite for regulated packaging or product claims unless alteration is acceptable and reviewed.

### Upscale

Use current `POST /v3/images/upscale` with `x-model-version: precise_upsampler_v1`, an input image source, one to four seeds, and `upscaleFactor` 2, 3, 4, or 6. Poll the returned `links.result.href`. The API reference describes output dimensions as input dimensions multiplied by the factor. Validate service limits and the actual result; a prose guide states a 6k maximum while the endpoint schema focuses on factors, so preflight large inputs instead of assuming every factor is accepted.

## Direct the image before writing prose

**Production heuristic:** express a prompt as a compact art-direction brief, not a pile of adjectives. Specify:

1. subject and action;
2. environment and era;
3. framing, viewpoint, lens language, or layout;
4. lighting and color relationships;
5. material and surface cues;
6. text that must be visible, quoted exactly, only when essential;
7. exclusions through the API's documented negative-prompt field when available.

Do not imitate a living artist or use third-party marks, faces, copyrighted characters, or reference assets without rights. For localization, set the API locale field and have a native reviewer check cultural details; locale bias is not translation or legal clearance.

For exact typography, logos, pack copy, QR codes, and compliance marks, generate a clean visual base and composite approved vector/raster artwork afterward. Treat model-rendered text as draft content. For a product, request negative space and camera geometry that accommodate the later overlay.

## Example 1 — complete Image 5 generation client

**Example, not a mandatory formula.** This Python 3.11+ standard-library program obtains a token, submits one Image 5 job, polls the returned result URL with bounded exponential backoff, downloads the first image, and records response metadata. Set `FIREFLY_SERVICES_CLIENT_ID` and `FIREFLY_SERVICES_CLIENT_SECRET` in a secure server environment.

```python
import json
import os
import random
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path

CLIENT_ID = os.environ["FIREFLY_SERVICES_CLIENT_ID"]
CLIENT_SECRET = os.environ["FIREFLY_SERVICES_CLIENT_SECRET"]
TOKEN_URL = "https://ims-na1.adobelogin.com/ims/token/v3"
GENERATE_URL = "https://firefly-api.adobe.io/v4/images/generate-async"
SCOPES = "openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis"
MIN_API_INTERVAL = 15.0  # Default 4-RPM org entitlement; use a distributed limiter at scale.
_last_api_request = 0.0


def wait_for_org_quota():
    global _last_api_request
    delay = MIN_API_INTERVAL - (time.monotonic() - _last_api_request)
    if delay > 0:
        time.sleep(delay)
    _last_api_request = time.monotonic()


def retry_after_seconds(value, fallback):
    if not value:
        return fallback
    try:
        return max(0.0, float(value))
    except ValueError:
        when = parsedate_to_datetime(value)
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
        return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())


def request_json(url, *, method="GET", headers=None, body=None, attempts=5):
    data = None if body is None else json.dumps(body).encode("utf-8")
    for attempt in range(attempts):
        req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
        wait_for_org_quota()
        try:
            with urllib.request.urlopen(req, timeout=60) as response:
                return response.status, dict(response.headers), json.load(response)
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode("utf-8", "replace")
            retryable = exc.code == 429 or 500 <= exc.code < 600
            if not retryable or attempt == attempts - 1:
                raise RuntimeError(f"HTTP {exc.code} from {url}: {detail}") from exc
            fallback = min(30, 2 ** attempt + random.random())
            time.sleep(max(MIN_API_INTERVAL, retry_after_seconds(exc.headers.get("Retry-After"), fallback)))
        except (urllib.error.URLError, TimeoutError) as exc:
            if attempt == attempts - 1:
                raise RuntimeError(f"Network failure from {url}: {exc}") from exc
            time.sleep(max(MIN_API_INTERVAL, min(30, 2 ** attempt + random.random())))


def get_token():
    form = urllib.parse.urlencode({
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": SCOPES,
    }).encode("utf-8")
    req = urllib.request.Request(
        TOKEN_URL,
        data=form,
        method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    with urllib.request.urlopen(req, timeout=30) as response:
        return json.load(response)["access_token"]


def find_first_image_url(value):
    if isinstance(value, dict):
        image = value.get("image")
        if isinstance(image, dict) and isinstance(image.get("url"), str):
            return image["url"]
        for child in value.values():
            found = find_first_image_url(child)
            if found:
                return found
    elif isinstance(value, list):
        for child in value:
            found = find_first_image_url(child)
            if found:
                return found
    return None


def main():
    token = get_token()
    headers = {
        "Authorization": f"Bearer {token}",
        "x-api-key": CLIENT_ID,
        "Content-Type": "application/json",
        "Accept": "application/json",
        "x-model-version": "image5",
    }
    payload = {
        "prompt": (
            "Editorial product photograph of a matte cobalt reusable bottle on pale limestone, "
            "three-quarter view, soft north-window light, restrained blue and warm-gray palette, "
            "clean negative space at upper left, realistic condensation, no logo or lettering"
        ),
        "aspectRatio": "4:3",
        "resolutionLevel": "4MP",
        "modelId": "firefly_image",
        "numVariations": 1,
        "seeds": [42345],
        "referenceBlobs": [],
        "modelSpecificPayload": {"localeCode": "en-US", "prompt_reasoner": "quality"},
    }
    status, response_headers, accepted = request_json(
        GENERATE_URL, method="POST", headers=headers, body=payload
    )
    result_url = accepted["links"]["result"]["href"]
    cancel_url = accepted["links"]["cancel"]["href"]
    deadline = time.monotonic() + 300
    final = accepted
    result_headers = {}
    while time.monotonic() < deadline:
        _, result_headers, final = request_json(result_url, headers=headers)
        state = str(final.get("status", "")).lower()
        if state in {"succeeded", "failed", "cancelled", "canceled"}:
            break
        if find_first_image_url(final):
            break
    else:
        cancel_result = None
        try:
            cancel_status, _, cancel_body = request_json(cancel_url, method="PUT", headers=headers)
            cancel_result = {"status": cancel_status, "body": cancel_body}
        except Exception as exc:
            cancel_result = {"error": str(exc)}
        Path("firefly-response.json").write_text(
            json.dumps({
                "request": payload,
                "accept_status": status,
                "accept_headers": response_headers,
                "accepted": accepted,
                "cancel_attempt": cancel_result,
            }, indent=2),
            encoding="utf-8",
        )
        raise TimeoutError("Firefly job did not finish within 300 seconds")

    if str(final.get("status", "")).lower() in {"failed", "cancelled", "canceled"}:
        raise RuntimeError(f"Firefly job ended unsuccessfully: {json.dumps(final)}")
    image_url = find_first_image_url(final)
    if not image_url:
        raise RuntimeError(f"No image URL in terminal response: {json.dumps(final)}")
    with urllib.request.urlopen(image_url, timeout=120) as image_response:
        content_type = image_response.headers.get_content_type()
        suffix = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}.get(
            content_type, ".bin"
        )
        Path("firefly-output" + suffix).write_bytes(image_response.read())
    Path("firefly-response.json").write_text(
        json.dumps({
            "request": payload,
            "accept_status": status,
            "accept_headers": response_headers,
            "accepted": accepted,
            "result_headers": result_headers,
            "result": final,
        }, indent=2),
        encoding="utf-8",
    )


if __name__ == "__main__":
    main()
```

Expected result: one 4:3 Image 5 asset, locally downloaded with its real media-type extension, plus an audit JSON. Likely failures: missing entitlement (403), a field from the v3 schema accidentally sent to v4 (422), organization throttling (429), expired token (401), or the output URL expiring before download.

Meaningful variations: switch `prompt_reasoner` to `speed` for latency testing; use `resolutionLevel: 1MP` for cheap preflight if the account rate card favors it; or supply one allowed `referenceBlobs` item, remove/auto the aspect ratio, and phrase the prompt as an edit instruction.

## Example 2 — upload and masked fill

**Example, not a mandatory formula.** This Python 3 program uploads a PNG source and mask, submits four seeded v3 fill variations, then polls the returned status URL. It assumes the source and mask share dimensions and the mask semantics have been verified visually.

```python
import json
import os
import random
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path

CLIENT_ID = os.environ["FIREFLY_SERVICES_CLIENT_ID"]
TOKEN = os.environ["FIREFLY_SERVICES_ACCESS_TOKEN"]
BASE = "https://firefly-api.adobe.io"
AUTH = {"Authorization": f"Bearer {TOKEN}", "x-api-key": CLIENT_ID}
MIN_API_INTERVAL = 15.0  # Default 4-RPM org entitlement; replace with shared storage at scale.
_last_api_request = 0.0


def wait_for_org_quota():
    global _last_api_request
    delay = MIN_API_INTERVAL - (time.monotonic() - _last_api_request)
    if delay > 0:
        time.sleep(delay)
    _last_api_request = time.monotonic()


def retry_after_seconds(value, fallback):
    if not value:
        return fallback
    try:
        return max(0.0, float(value))
    except ValueError:
        when = parsedate_to_datetime(value)
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
        return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())


def open_bytes(req, *, attempts=5):
    for attempt in range(attempts):
        wait_for_org_quota()
        try:
            with urllib.request.urlopen(req, timeout=60) as response:
                return response.status, dict(response.headers), response.read()
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode("utf-8", "replace")
            retryable = exc.code == 429 or 500 <= exc.code < 600
            if not retryable or attempt == attempts - 1:
                raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
            fallback = min(30, 2 ** attempt + random.random())
            time.sleep(max(MIN_API_INTERVAL, retry_after_seconds(exc.headers.get("Retry-After"), fallback)))
        except (urllib.error.URLError, TimeoutError) as exc:
            if attempt == attempts - 1:
                raise RuntimeError(f"Network failure: {exc}") from exc
            time.sleep(max(MIN_API_INTERVAL, min(30, 2 ** attempt + random.random())))
    raise AssertionError("unreachable")


def upload_png(path):
    req = urllib.request.Request(
        f"{BASE}/v2/storage/image",
        data=Path(path).read_bytes(),
        method="POST",
        headers={**AUTH, "Content-Type": "image/png", "Accept": "application/json"},
    )
    _, _, raw = open_bytes(req)
    return json.loads(raw)["images"][0]["id"]


def json_request(url, *, method="GET", payload=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        url,
        data=data,
        method=method,
        headers={**AUTH, "Content-Type": "application/json", "Accept": "application/json"},
    )
    _, _, raw = open_bytes(req)
    return json.loads(raw)


source_id = upload_png("source.png")
mask_id = upload_png("mask.png")
job = json_request(
    f"{BASE}/v3/images/fill-async",
    method="POST",
    payload={
        "image": {"source": {"uploadId": source_id}},
        "mask": {"source": {"uploadId": mask_id}, "invert": False},
        "prompt": (
            "replace only the masked vase with a handmade cobalt ceramic vase, "
            "preserve table and shadows"
        ),
        "negativePrompt": "lettering, logo, extra objects",
        "promptBiasingLocaleCode": "en-US",
        "numVariations": 4,
        "seeds": [101, 202, 303, 404],
        "size": {"width": 2048, "height": 2048},
    },
)
Path("fill-accepted.json").write_text(json.dumps(job, indent=2), encoding="utf-8")

deadline = time.monotonic() + 300
while time.monotonic() < deadline:
    result = json_request(job["statusUrl"])
    state = result.get("status", "")
    if state == "succeeded":
        Path("fill-result.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
        break
    if state in {"failed", "cancelled", "canceled"}:
        raise RuntimeError(json.dumps(result))
else:
    cancel_result = None
    try:
        cancel_result = json_request(job["cancelUrl"], method="PUT")
    except Exception as exc:
        cancel_result = {"error": str(exc)}
    Path("fill-accepted.json").write_text(
        json.dumps({"accepted": job, "cancel_attempt": cancel_result}, indent=2),
        encoding="utf-8",
    )
    raise TimeoutError("Fill job did not finish within 300 seconds")

outputs = result.get("result", {}).get("outputs", [])
if len(outputs) != 4:
    raise RuntimeError(f"Expected four outputs, received {len(outputs)}")
suffixes = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
for index, output in enumerate(outputs, start=1):
    with urllib.request.urlopen(output["image"]["url"], timeout=120) as response:
        content_type = response.headers.get_content_type()
        suffix = suffixes.get(content_type)
        if suffix is None:
            raise RuntimeError(f"Unexpected output Content-Type: {content_type}")
        Path(f"fill-output-{index}{suffix}").write_bytes(response.read())
```

Expected result: four URLs and their seeds in `fill-result.json`, plus four locally downloaded image files. Likely failures: a source/mask dimension mismatch, inverted mask intent, unsupported size, seed-count mismatch, an unexpected delivery media type, or a prompt asking the fill endpoint to change unmasked pixels.

## Operate asynchronous jobs safely

1. Persist the submission response before polling.
2. Follow the returned `statusUrl` or `links.result.href`; do not reconstruct hostnames from a job ID.
3. Route uploads, submissions, and polls through one organization-wide limiter. At the default 4 RPM entitlement, average at least 15 seconds between all Firefly API requests across workers; use adaptive polling, honor `Retry-After`, and only poll faster when the organization's contracted limit supports it. Older one-second examples do not override the current usage notes.
4. Set a local deadline and expose cancellation. Current job cancellation is `PUT` to the returned cancel link.
5. Retry 429 and transient 5xx with jittered exponential backoff. Do not retry 400/403/413/415/422 unchanged.
6. Treat 401 as token refresh, then retry once. Repeated 401 is configuration failure.
7. Download outputs immediately to controlled storage; pre-signed URLs are delivery mechanisms, not...

© calesthio · MIT · calesthio/generative-media-skills

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
gpt-image-v2 eachlabs Скилл gpt-image-v2 для Claude Code создаёт и редактирует изображения через EachLabs с моделями GPT Image v2. CX Codex +1 169установок ai-image-generation prime-skills Скилл ai-image-generation создаёт изображения по тексту и редактирует их через RunComfy CLI. Он выбирает модель по задаче: например, для точного текста на постере или фотореалистичного портрета. CX Codex +1 393 900установок scenario-image scenario-labs Скилл scenario-image для Claude Code запускает генерацию и редактирование изображений через Scenario MCP. Работает с моделями, референсами, масками и точными размерами. CX Codex +1 1 100установок scenario-mai-image scenario-labs Скилл scenario-mai-image для Claude Code создаёт изображения моделями Microsoft MAI Image и редактирует их по текстовой инструкции. Создаёт постеры, упаковку и обложки с надписями внутри изображения. CX Codex +1 837установок linkfox-multimodal-generate-image linkfox-ai Скилл linkfox-multimodal-generate-image для Claude Code создаёт и редактирует изображения товаров по описанию и референсам. Меняет фон, предметы, стиль, сцену или модель. CX Codex +1 405установок qwen-image-2 101-skills Скилл qwen-image-2 для Claude Code создаёт и редактирует изображения через модели Alibaba Qwen-Image-2.0. Запускается по запросам о Qwen Image и генерации картинок. CX Codex +1 240установок

Из того же набора149

Весь набор →
sync-labs-lipsync Скилл sync-labs-lipsync для Claude Code создаёт липсинк и дубляж видео через Sync Labs. Он запускается для переозвучки, перевода или синхронизации речи. CX Codex +1 139установок stable-audio Скилл stable-audio для Claude Code помогает настраивать генерацию музыки и звуковых эффектов через Stability AI. Запускается при выборе моделей, сборке промптов и разметке аудио. CX Codex +1 139установок alibaba-image-models Скилл alibaba-image-models для Claude Code настраивает вызовы моделей Wan 2.7, Qwen-Image 2.0 и Z-Image Turbo через Model Studio API. Запускается при генерации картинок и планировании запросов к DashScope. CX Codex +1 138установок audiobook-production Скилл audiobook-production для Claude Code превращает рукописи и длинный текст в многочасовую аудиокнигу с помощью генеративных голосовых инструментов. CX Codex +1 138установок lottie-animation-delivery Скилл lottie-animation-delivery для Claude Code координирует передачу векторных анимаций Lottie и dotLottie в приложения. Он отслеживает совместимость рендеринга и требования к целевым платформам. CX Codex +1 137установок livestream-event-production Скилл livestream-event-production для Claude Code планирует и ведёт live- и hybrid-трансляции: от run of show до аварийного плана. Подключается к репетиции, эфиру и разбору сбоев. CX Codex +1 137установок gemini-live-audio Скилл gemini-live-audio для Claude Code помогает проектировать голосовые сессии реального времени через Google Gemini Live API. Запускается при настройке WebSocket-сессий, barge-in и вызова инструментов. CX Codex +1 137установок ideogram-image Скилл ideogram-image для Claude Code подключает Ideogram Developer API для генерации и редактирования изображений. Включается при работе с V4, V3 и API-пайплайнами. CX Codex +1 137установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой