# Start with your first image

English translation. Model names, API fields and executable examples retain their original text, including prompts and comments.

This tutorial uses the group **\#128【YYY】Grok Imagine 2K** with model `grok-imagine-image-2.0` to complete an image edit through four steps: prepare → request → inspect → debug.

> **Important**
>
> **Check your group first.** Use the key for \#128【YYY】Grok Imagine 2K. Parameters and prices may differ for same-name models in other groups. This guide does not ask you to enter your key into the webpage.

## 1. Prepare your key and a reference

Prepare Python 3, a terminal and a `reference.png` image in a new folder. Start with one ordinary PNG; leave complex multi-image layouts until the baseline request succeeds.

| Item | Recommended first value | Reason |
|----|----|----|
| Model | `grok-imagine-image-2.0` | The model currently recommended throughout this guide |
| Reference images | One PNG | Confirm that reference content appears in the result |
| Aspect ratio / tier | `1:1` / `1k` | Makes dimensions and content easy to inspect |
| Quality / output count | `low` / `1` | One output is easier to debug; low had a lower upstream billing metric |
| Response format | `b64_json` | Avoids a separate image-URL download step |

> **Description**
>
> **Use your site bill as the source of truth.** A lower upstream billing metric for low does not guarantee a lower site charge. Each generation may be billed; do not repeatedly submit the same failing request.

## 2. Build the request file

Save the following as `make_request.py`. Comments belong in the Python script; the generated `request.json` is strict JSON without comments.

``` python
import base64
import json
from pathlib import Path

image = Path("reference.png").read_bytes()  # 与脚本放在同一文件夹
payload = {
    "model": "grok-imagine-image-2.0",
    "prompt": "保留参考图中的主体和主要颜色，改成简洁白色背景",
    "images": [{
        "image_url": "data:image/png;base64," + base64.b64encode(image).decode()
    }],
    "aspect_ratio": "1:1",      # 调试时先固定画幅
    "resolution": "1k",        # 必须使用小写 1k / 2k
    "quality": "low",          # 正式编辑可调整到 medium
    "n": 1,                    # 输出张数，不是参考图数量
    "response_format": "b64_json"
}
Path("request.json").write_text(
    json.dumps(payload, ensure_ascii=False), encoding="utf-8"
)
print("request.json 已生成")
```

In your terminal, run `python make_request.py`. You should see `request.json 已生成` and find the request file in the current folder.

> **Tip**
>
> **Change the prefix when changing image format.** For JPEG use `data:image/jpeg;base64,`, and for WebP use `data:image/webp;base64,`. Do not paste bare Base64 or rename the field to `images[].url`.

## 3. Send one request

Replace the example key with your own. Run the block for your terminal; you do not need to run both.

### Bash / WSL / macOS

``` bash
export YM2API_KEY="YOUR_GROUP_128_API_KEY"
python make_request.py
curl --fail-with-body --max-time 300 \
  "https://yyds.seqnode.com/v1/images/edits" \
  -A "YM2API/1.0" \
  -H "Authorization: Bearer $YM2API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @request.json \
  -D response.headers \
  -o response.json
```

### Windows PowerShell

``` powershell
$env:YM2API_KEY = "YOUR_GROUP_128_API_KEY"
python make_request.py
curl.exe --fail-with-body --max-time 300 "https://yyds.seqnode.com/v1/images/edits" -A "YM2API/1.0" -H "Authorization: Bearer $env:YM2API_KEY" -H "Content-Type: application/json" --data-binary "@request.json" -D response.headers -o response.json
```

**Checkpoint:** Creates `response.headers` and `response.json`. The response headers should contain HTTP 200, and the JSON should contain a nonempty `data` array. If you see `error`, follow section 6 before resubmitting.

> **Watch out**
>
> **Distinguish generation failures from download failures.** The default Python User-Agent triggered upstream 403 / Cloudflare 1010 during testing. These examples set `YM2API/1.0`. URL responses require a separate download. A download failure does not mean generation failed or that no charge occurred.

## 4. Save and inspect the image

Save the following as `save_images.py` and run `python save_images.py`. This processes only the local response file and does not create a new generation request.

``` python
import base64
import json
from pathlib import Path

response = json.loads(Path("response.json").read_text(encoding="utf-8"))
if response.get("error"):
    raise SystemExit(json.dumps(response["error"], ensure_ascii=False))
items = response.get("data", [])
if not items:
    raise SystemExit("没有图片数据，请检查响应和用量记录")
for i, item in enumerate(items, 1):
    if not item.get("b64_json"):
        raise SystemExit("没有 b64_json；请先检查 response_format 与原始响应")
    raw = base64.b64decode(item["b64_json"], validate=True)
    if raw.startswith(b"\x89PNG\r\n\x1a\n"):
        ext = "png"
    elif raw.startswith(b"\xff\xd8"):
        ext = "jpg"
    elif raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
        ext = "webp"
    else:
        raise SystemExit("返回内容不是已识别的图片编码")
    path = Path(f"result-{i}.{ext}")
    if path.exists():
        raise SystemExit(f"{path} 已存在，请先改名保存，避免覆盖")
    path.write_bytes(raw)
    print(f"已保存 {path}，{len(raw)} 字节")
```

**Checkpoint:** Open the result and check the reference subject, orientation, actual dimensions and image count. Grok's `1:1 + 1k` produced a 1024×1024 JPEG in tests. For other ratios, see the [Grok ratio table](grok-imagine-image-api.en.html#3-比例与实际尺寸).

## 5. Change one parameter at a time

After each change to `make_request.py`, regenerate `request.json` and submit once. Record the single change you made.

| Step | Change | Keep unchanged | Inspect |
|----|----|----|----|
| A | `quality` from low to medium | One reference, 1k, n=1 | Edit quality, response and bill |
| B | `resolution` to 2k | medium, n=1, same prompt | 1:1 became 2048×2048 PNG in tests |
| C | `aspect_ratio` to 16:9 | 2k、medium、n=1 | 2816×1584 PNG in tests |
| D | Increase from 1 to 2/3 references | Keep n=1 initially | Whether each reference contributes the intended content |
| E | Change n to 2 only if needed | Same references and other parameters | Two returned images; check usage |

> **Important**
>
> **Stable Grok configuration:** `aspect_ratio` controls the aspect ratio, and `resolution` controls the 1k/2k tier. Do not rely on `size` for exact pixel dimensions. high, uppercase 2K and 4k did not pass. The site currently allows up to 3 references and n up to 10.

Specify multi-image layouts explicitly, for example: “Arrange the three references in one row, each appearing once.” The three-reference test retained all three numbers but added an empty cell, so inspect the layout manually.

### Switching to the Adobe group

**\#127【YYY】4k Image 2.0 (Med) 4K image2.5 flare / sunburst** Start with `gpt-image-2`, `size="1536x864"`, `quality="medium"`, `n=1`. Its size parameters differ from Grok's. Switch to the group's key and follow the full request in the [Adobe API guide](adobe-group127-api.en.html) rather than carrying Grok parameters across unchanged.

## 6. Debug by failure stage

| Symptom | Check first | Next step |
|----|----|----|
| 400 | images objects, Base64 prefix, prompt and n type | Correct the parameters before submitting again |
| 401 / 403 | Key, group and response body | Confirm the correct key; check User-Agent for upstream 1010 |
| 422 | quality, resolution and ratio enum values and casing | Restore the low/medium, 1k/2k, 1:1 baseline |
| API 200, download 403 | The failure occurs while downloading the image URL | Set an application User-Agent for downloads; do not send your site key to the image host |
| Timeout / 502 / 503 | Usage records and channel status | Check for completed generation / charges first; retry one image after recovery |
| 200 with unexpected dimensions or encoding | Actual file header, dimensions and parameter effects | Consult the model's test table; do not repeatedly adjust ineffective parameters |

Keep these details for troubleshooting: **group name, model, time, HTTP status, error body, parameters and actual dimensions**. Remove keys, Authorization headers and private image content before sharing logs.

## 7. Further reading

- [\#128【YYY】Grok Imagine 2K](grok-imagine-image-api.en.html): parameters, all ratios and a report covering 93 requests.
- [\#127 Adobe image group](adobe-group127-api.en.html): 10/6-reference boundaries, 4K tests and model differences.
- [\#75 Upscaling / \#77 Integration](gpt-image-2-api.en.html): dimensions and proxy behavior for these groups.

> **Description**
>
> The request structures are based on earlier live tests. This documentation update did not send additional paid generation requests. Code examples passed syntax and local-sample checks.
