sgl-project/sglang · error · IndexError

Image index {index} out of range

Error message

Image index {index} out of range

What it means

IndexError from decode_image_from_response: 'data' exists but the requested index is beyond its length. The caller asked for image N in a response that returned fewer images.

Source

Thrown at python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion/core/server_api.py:436

    def decode_image_from_response(
        self, response_data: Dict[str, Any], index: int = 0
    ) -> Image.Image:
        """
        Decode base64 image from API response.

        Args:
            response_data: API response dictionary
            index: Index of the image in the response (default: 0)

        Returns:
            PIL Image object
        """
        if "data" not in response_data or not response_data["data"]:
            raise ValueError("No image data in response")

        if index >= len(response_data["data"]):
            raise IndexError(f"Image index {index} out of range")

        image_data = response_data["data"][index]
        if "b64_json" not in image_data or not image_data["b64_json"]:
            raise ValueError("No base64 image data found")

        image_bytes = base64.b64decode(image_data["b64_json"])
        image = Image.open(io.BytesIO(image_bytes))

        # Convert to RGB if needed
        if image.mode != "RGB":
            image = image.convert("RGB")

        return image

    def set_lora(
        self,
        lora_nickname: str,
        lora_path: Optional[str] = None,

View on GitHub (pinned to 0132848349)

Solutions

  1. Use index within range: 0 <= index < len(response['data']).
  2. Iterate with enumerate(response['data']) instead of hardcoded indices.
  3. Verify the requested n matches how many images you try to decode.
  4. Log the data length when the error occurs.

Example fix

// before
img = decode_image_from_response(response, index=2)
// after
idx = min(2, len(response["data"]) - 1)
img = decode_image_from_response(response, index=idx)
Defensive patterns

Strategy: type-guard

Validate before calling

n = len(response['data']); assert 0 <= index < n, f'index {index} >= {n}'

Type guard

def valid_index(r: dict, i: int) -> bool:
    return 0 <= i < len(r.get('data') or [])

Prevention

When it happens

Trigger: Calling decode_image_from_response(response, index=2) when only 1-2 images were returned; n smaller than the index used; negative indices also bypass the >= check and fail oddly.

Common situations: Hardcoding an index in a loop over multiple responses; server returning fewer images than requested n; off-by-one when iterating.

Related errors


AI-assisted analysis of sgl-project/sglang@0132848349 (2026-08-28). Data as JSON: /api/errors/adbe26db36bc9427. Report an issue: GitHub.