Text-to-Image API in Production: Size Mapping and Error Code Troubleshooting

    A practical, production-focused guide to integrating text-to-image APIs. It explains how to unify requests and responses across native and compatibility protocols, how to model the core parameters (model, prompt, n, size), and why size is the most common trigger of 400 errors. You will learn how to map business size presets to model-supported dimensions, how to reliably parse and persist returned images (whether URLs or base64), how to handle the download stage, and how to diagnose failures by layer with a disciplined retry strategy. The article includes Python examples and a pre-launch checklist for building text-to-image integrations that are deployable, operable, and cost-accountable.

    Many teams hit the same wall when they integrate text-to-image capabilities. After tuning prompts through a hundred iterations and finally getting stable results, they go live and run straight into 400 parameter errors, 403s on download, and “fake success” responses that return empty images. This shows that generation quality is only one piece of the puzzle. To ship reliably, the real problems to solve are four: protocol adaptation, parameter mapping, reliable file persistence, and fault observability.

    This article focuses on production practices for text-to-image endpoints across four areas: how a compatibility protocol unifies requests and responses, how model sizes are mapped, how returned images are reliably written to disk, and how error codes are diagnosed by layer. Code examples are given in Python for illustration; the exact parameters and response formats should follow the latest API documentation of the platform you choose.

    1. Protocol Fragmentation: The Real Difficulty in Text-to-Image Integration

    From a caller’s perspective, text-to-image endpoints usually come in two forms:

    • Native form: The vendor defines its own request body, authentication scheme, and response structure. Images are typically returned as inline binary data that the client must decode and save itself.
    • Compatibility form: The vendor or an aggregation service puts a compatibility layer on top of the underlying models. It follows the widely adopted chat and image-generation conventions: with a single key and a single auth header, you can call models from different vendors. For the business side, this is similar to using one unified adapter layer to talk to multiple capability providers.

    Each form has its place. The native form stays close to the model’s capabilities; the value of the compatibility form is a unified contract—you maintain only one request wrapper, one error parser, and one key-management scheme, so switching models requires minimal change. For example, the OpenAI-compatible interface offered by Baidu AI Cloud belongs to the latter category, letting you call the various models on the platform using a familiar interface shape. Weigh the options with the table below.

    Dimension Native interface Compatibility interface
    Number of protocols Different capabilities may each have their own Text, image, and file capabilities share one base convention
    Key management Apply for and rotate keys per vendor One key calls multiple authorized models
    Response shape Mostly inline image data that you must decode May return an image URL or an image-content field; shape depends on the model
    Extension parameters Track upstream model updates quickly Depend on compatibility-layer mapping; some new parameters may not pass through yet
    Long-running requests You handle timeouts yourself Depends on the gateway’s timeout policy; verify empirically
    Billing Reconcile per-vendor invoices Reconcile against the chosen platform’s invoice and usage details

    Whichever form you choose, production code needs three capabilities:

    1. Adapter layer: Translate business requests into the interface contract, and normalize interface responses into internal data structures.
    2. State machine: Treat “generate” and “fetch the image file” as two independently managed stages.
    3. Retry policy: Distinguish retryable errors from non-retryable ones.

    2. Request Contract: An Engineering View of model, prompt, n, and size

    2.1 Responsibilities of the four core parameters

    The image-generation path of a compatibility interface is usually POST /v1/images/generations, with four core parameters:

    • model: Determines output quality, style, and billing tier. In practice, it helps to establish model tiers of “lightweight / balanced / flagship”:

      • Lightweight models have low latency and low cost, suited to thumbnails, drafts, and large-scale batch scenarios;
      • Balanced models fit most mainstream business scenarios;
      • Flagship models are used for covers and posters with high quality demands.

      It is best to keep model identifiers in a configuration center rather than scattered across business code.

    • prompt: Has the greatest impact on the result. A structured three-layer approach is recommended:

      1. Subject: What to draw, plus quantity and spatial relationships;
      2. Scene and style: Background, lighting, color tone, camera, art style;
      3. Technical constraints: Composition, negative space, aspect ratio, and explicitly stated prohibitions.

      Structured descriptions improve output stability and make templating and A/B testing easier later.

    • n: The number of images generated in one request. Output images are usually billed per image, so online interactive scenarios should default to n=1; only increase it when you need to offer users a “pick from several” experience.
    • size: The parameter most likely to trigger 400 errors and the most easily overlooked. Section 3 covers it in detail.

    Additionally, some compatibility implementations support the following parameters:

    • Output format (e.g., png, jpeg, webp): PNG suits illustrations and assets that need transparent backgrounds; JPEG suits photographic images;
    • Quality tier;
    • Background mode (transparent or a specified background color);
    • Output size set to auto, letting the model decide.

    When using transparent backgrounds, note that if the pipeline includes format conversion or re-compression, the alpha channel may be dropped.

    2.2 Minimal runnable example

    1. import json
    2. import os
    3. import urllib.request
    4. BASE = os.environ["GEN_API_BASE"].rstrip("/") # Base URL of the compatibility endpoint
    5. KEY = os.environ["GEN_API_KEY"] # Server-side key; never expose it to the frontend
    6. def generate_image(prompt: str, model: str, size: str, n: int = 1,
    7. timeout: float = 180.0) -> dict:
    8. body = json.dumps({
    9. "model": model,
    10. "prompt": prompt,
    11. "n": n,
    12. "size": size,
    13. }).encode("utf-8")
    14. req = urllib.request.Request(
    15. f"{BASE}/images/generations", data=body, method="POST",
    16. headers={"Authorization": f"Bearer {KEY}",
    17. "Content-Type": "application/json"})
    18. # Image generation takes far longer than text completion; the timeout
    19. # must cover at least the endpoint's P99 latency
    20. with urllib.request.urlopen(req, timeout=timeout) as resp:
    21. return json.load(resp)

    A few notes:

    • Timeout setting: Set it based on the P99 latency observed in monitoring, with some headroom. A timeout that is too short will misclassify requests that are “still generating” as failures.
    • Retry and billing: Whether a failed request is billed depends on the chosen platform’s billing rules. Before retrying, confirm whether the target platform provides idempotency or request de-duplication; if it does not, retrying a failed generation may incur extra charges.
    • Key protection: Keep keys only in server-side environment variables or a secret-management service. If the platform supports it, create separate keys per business line and restrict which models each can use, making it easier to audit usage by business and cut off problems quickly.

    2.3 Prompt and parameter coordination constraints

    • Negative space determines crop safety: If the result will later be cropped to a different aspect ratio, ask for the subject to be centered with safe margins on all sides.
    • Do not rely on the model for in-image text: Poster copy, price figures, and the like should be composited programmatically to avoid distorted or garbled text.
    • Complex prompts pair better with low randomness: When generating repeatedly from the same prompt, fix the random seed (if the interface supports it) or reuse the previous successful prompt template, to avoid “the same sentence, but a different art style every time.”

    3. Size Mapping: The Key to Avoiding 400 Parameter Errors

    3.1 The nature of the problem

    Business needs for size are usually expressed in one of three ways:

    • Absolute pixels: e.g., a design spec requires 1080×1920;
    • Aspect ratio: e.g., a feed cover at 16:9, an avatar at 1:1;
    • auto: let the model decide.

    The interface’s size parameter only accepts a limited set of enum values (in string form, such as 1024x1024), and the set of supported sizes often differs across models. Passing business sizes straight through to the interface is the most common source of text-to-image 400 errors.

    3.2 Build a “business preset → model tier” mapping table

    Maintaining the mapping as a configuration table is easier to maintain than writing if-else branches in code:

    1. # Business presets: scene -> target aspect ratio and pixel budget
    2. PRESETS = {
    3. "avatar": {"ratio": 1.0, "area": 1024 * 1024},
    4. "cover": {"ratio": 16 / 9, "area": 1536 * 1024},
    5. "poster": {"ratio": 3 / 4, "area": 1536 * 1024},
    6. }
    7. # Model capability matrix: model -> set of sizes supported by the interface
    8. MODEL_SIZES = {
    9. "image-light": [(1024, 1024)],
    10. "image-balanced": [(1024, 1024), (1536, 1024), (1024, 1536)],
    11. "image-pro": [(1024, 1024), (1536, 1024), (1024, 1536), (2048, 2048)],
    12. }
    13. def pick_size(model: str, scene: str) -> str:
    14. """Among the model's supported sizes, pick the one with the aspect
    15. ratio and pixel count closest to the preset"""
    16. preset = PRESETS[scene]
    17. candidates = MODEL_SIZES[model]
    18. best = min(
    19. candidates,
    20. key=lambda s: (abs(s[0] / s[1] - preset["ratio"]),
    21. abs(s[0] * s[1] - preset["area"])),
    22. )
    23. return f"{best[0]}x{best[1]}"

    The sort key uses a two-level strategy—aspect ratio first, then pixel count:

    • Aspect ratio governs visual composition and should be guaranteed first;
    • Pixel count governs sharpness and cost, and serves as a secondary factor.

    3.3 Three engineering constraints

    1. Model capability is a whitelist, not a guess: Only ever send sizes the chosen model actually supports. The capability matrix should come from official documentation or a one-time probe script, and be regression-tested after version upgrades.
    2. Decouple generation size from export size: What the model produces is a “tier size,” which may differ from the aspect ratio the business needs. The correct approach is to generate at a tier and then let the program scale or crop (center the subject when cropping, and fill the sides with a blurred background if needed), rather than asking the model to output arbitrary dimensions.
    3. Stay consistent within a single business request: Multiple generations for the same scene must land on the same size tier, or the frontend waterfall and card layouts will show height jitter. When switching models, update the capability matrix at the same time, or batch jobs will produce “the same batch, mismatched sizes.”
    Symptom Typical root cause Remedy
    400, size reported as invalid Sent a size the model does not support Filter through the capability matrix before sending
    Returned aspect ratio differs from expected Treated the “generation size” as the “final delivery size” Crop to the target ratio programmatically after generation
    The same model works sometimes and fails sometimes Multiple models share one business entry point without per-model mapping Maintain a separate mapping table per model
    Large-size request times out High-resolution tiers take noticeably longer Drop to a lower tier, or switch to an async task with polling

    4. Response Parsing and Image Persistence

    Compatibility interfaces usually return a uniform envelope structure:

    1. {
    2. "created": 1730000000,
    3. "data": [
    4. {"url": "https://.../image.png"},
    5. {"b64_json": "iVBORw0KGgo..."}
    6. ]
    7. }

    Field shapes vary by model and platform: some return an image URL, some return image content directly (base64-encoded), and the same field can mean different things in different scenarios. The parsing layer must therefore provide dual-channel compatibility and perform strict validation.

    4.1 Dual-channel parsing and persistence

    1. import base64
    2. import hashlib
    3. import os
    4. import tempfile
    5. MAX_BYTES = 20 * 1024 * 1024 # Per-image cap to prevent abnormal responses from exhausting memory
    6. MAGIC = {b"\x89PNG": ".png", b"\xff\xd8\xff": ".jpg",
    7. b"RIFF": ".webp", b"GIF8": ".gif"}
    8. def sniff_ext(head: bytes) -> str:
    9. for magic, ext in MAGIC.items():
    10. if head.startswith(magic):
    11. return ext
    12. return ".bin"
    13. def atomic_write(raw: bytes, obj_key: str) -> str:
    14. """Write to a temp file first, then atomically replace, so a partial
    15. file is never read"""
    16. local = os.path.join(tempfile.gettempdir(), hashlib.sha1(obj_key.encode()).hexdigest())
    17. with open(local + ".tmp", "wb") as f:
    18. f.write(raw)
    19. f.flush()
    20. os.fsync(f.fileno()) # Ensure the data is actually flushed to disk
    21. os.replace(local + ".tmp", local) # Atomic rename
    22. return local
    23. def persist(item: dict, req_id: str, index: int) -> str:
    24. if item.get("b64_json"):
    25. data = item["b64_json"]
    26. if data.startswith("data:"): # Strip the data URI prefix
    27. data = data.split(",", 1)[1]
    28. raw = base64.b64decode(data, validate=True)
    29. elif item.get("url"):
    30. raw = download(item["url"]) # See 4.2
    31. else:
    32. raise ValueError(f"Response has no usable image field: {item.keys()}")
    33. ext = sniff_ext(raw[:8])
    34. key = f"images/{req_id}/{index}{ext}"
    35. return atomic_write(raw, key) + f" # Object storage key to upload to: {key}"

    Two details are worth emphasizing:

    • File-header validation: It is not enough to check only “can it be decoded”—you must confirm the real format via the file header, so an error page or placeholder image returned by the interface is not saved as an image;
    • Idempotency: Include the request identifier and sequence number in the persistence key, so retries do not create duplicate objects, making traceability and de-duplication easier.

    4.2 Four points for the image-download stage

    If a URL is returned, the download itself is a separate pipeline that can also fail:

    1. The URL may be time-limited: Signed URLs usually have a validity window, so complete the download within a reasonable time; do not cache the URL in the database long-term and use it much later.
    2. Consistent authentication: Some platforms require the same key when downloading protected files, or they return 401/403. It is best to wrap “generation” and “download” in the same client with unified authentication.
    3. Streaming download + size cap + timeout: Read chunk by chunk while accumulating the byte count, and abort immediately if the cap is exceeded, so an abnormal response cannot consume large amounts of memory.
    4. Retry download failures: A download failure caused by network jitter differs in nature from a generation failure. Use a separate backoff retry, and do not re-trigger a billable generation request just because the download failed.

    4.3 Storage-layer design suggestions

    • Use the local temp directory only as a relay; write the final result to object storage (such as Baidu AI Cloud object storage). Set the bucket to private, and generate time-limited signed URLs when distributing externally.
    • Name objects with the convention “business line / request identifier / sequence + extension,” making full-chain tracing by request easy.
    • Record metadata alongside the image: model, the actual size used, a prompt summary (or hash), n, generation latency, error code, and whether it was retried. This data is the foundation for later cost analysis and incident retrospectives.
    • Apply content-addressed caching to results: use a hash of “model + prompt + size + parameters” as the key, and reuse on a hit—saving money and reducing latency.

    5. Error Code Troubleshooting: Layered Diagnosis and Retry Strategy

    5.1 Diagnose by layer, not just by status code

    On the text-to-image pipeline, errors can come from five different layers. Rule them out in this order, layer by layer:

    1. Network and timeout: Connection failures, read timeouts;
    2. Authentication: Invalid key, no permission for the model;
    3. Parameters: Invalid model name, size, or count;
    4. Business constraints: Content moderation rejection, exhausted quota;
    5. Server side: Upstream model busy, gateway internal error;
    6. Download and persistence: Expired URL, file too large, write failure.
    Status code / case Common cause Retry? Suggested handling
    400 Invalid parameter (size, model, n) No Validate against the parameter whitelist, then fix the request
    401 Missing, wrong, or expired key No Check key configuration and rotation status
    403 No permission for the model, quota limit No Verify the model’s authorization scope and account status
    404 Wrong path, model not found No Double-check the path and model identifier
    408 / 504 Request timeout, gateway timeout Yes (carefully) Measure P99 first, then raise the timeout; consider going async
    429 Rate limit or quota cap hit Yes Exponential backoff + jitter, plus client-side rate limiting
    500 / 502 / 503 Server-side or upstream model error Yes Back off and retry; circuit-break and degrade after consecutive failures
    Image URL 403 Expired URL or missing auth header No Regenerate, or switch to a supported auth method
    Persistence failure Disk full, insufficient permissions Yes Decouple from generation and compensate separately

    5.2 Key points of the retry implementation

    1. import random
    2. import time
    3. import urllib.error
    4. RETRYABLE = {408, 429, 500, 502, 503, 504}
    5. def call_with_retry(fn, max_attempts: int = 3):
    6. for attempt in range(1, max_attempts + 1):
    7. try:
    8. return fn()
    9. except urllib.error.HTTPError as e:
    10. if e.code not in RETRYABLE or attempt == max_attempts:
    11. raise
    12. # Exponential backoff with random jitter to avoid a retry storm
    13. time.sleep(min(2 ** attempt, 8) + random.random())
    • Declare the retryable set explicitly: Retrying 4xx parameter, authentication, or permission errors is pointless and only amplifies the failure;
    • Jitter is not optional: Many instances retrying at once turns a transient fault into a sustained avalanche;
    • Distinguish “retry” from “compensate”: For a request where generation succeeded but persistence failed, replay only “download + persist,” not regeneration;
    • Circuit breaking and degradation: When a model’s consecutive failures reach a threshold, automatically switch to a backup model or degrade to a lightweight tier, and mark the degraded status in the response so the frontend can inform users.

    5.3 Observability: Make every failure reviewable

    • Structured logs: Record request_id, model, size, latency, status code, error type, retry count, and whether it was degraded. Do not log keys or full image content; mask prompts according to policy.
    • Core metrics: Success rate, P50/P95/P99 latency, retry rate, degradation rate, average cost per image, and rate-limit hit count.
    • Alerting rules: Spikes in error rate, rising P95 latency, an increasing share of 429s, and quota usage approaching its threshold.
    • Reconciliation: Periodically compare “images successfully generated” against the platform’s usage details; when a discrepancy appears, first investigate the retry logic and any missing idempotency.

    6. Production Readiness Checklist

    Confirm each item before launch:

    • The model and size capability matrix is documented, and parameters are validated against the whitelist before sending;
    • Timeouts cover measured P99, with backoff retry and circuit-break/degradation configured;
    • Response parsing supports both URL and image-content forms and validates file headers;
    • Download and persistence are independently retryable, with private object storage and signed-URL distribution;
    • Keys are used only on the server, isolated per business, and can be rotated quickly;
    • Structured logs, core metrics, and alerting are in place, with full-chain tracing by request identifier;
    • The “failed requests are not billed” assumption has been verified against the invoice, and retries are guaranteed idempotent.

    The stability of a text-to-image capability does not depend on how well the prompt is written, but on how rigorous the engineering pipeline is: whether parameter mapping is accurate, whether images persist reliably, and whether errors can be located quickly. Treat the compatibility protocol as a unified contract, size mapping as configuration governance, persistence as an independent state machine, and error codes as layered diagnostics—only then does a text-to-image interface truly move from “it runs” to “deployable, operable, and accountable.”