{"record":{"id":"370459b9d7f56375","repo":"microsoft/semantic-kernel","slug":"failed-to-edit-image-ex","errorCode":null,"errorMessage":"Failed to edit image: {ex}","messagePattern":"Failed to edit image: (.+?)","errorType":"exception","errorClass":"ServiceResponseException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py","lineNumber":159,"sourceCode":"\n        Args:\n            image: List of image files to edit. Accepts file paths or bytes.\n            settings: Image edit execution settings.\n            mask: Optional mask image. Accepts file path or bytes.\n\n        Returns:\n            ImagesResponse: The response from the image edit API.\n        \"\"\"\n        try:\n            response: ImagesResponse = await self.client.images.edit(\n                image=image,\n                mask=mask,  # type: ignore\n                **settings.prepare_settings_dict(),\n            )\n            self.store_usage(response)\n            return response\n        except Exception as ex:\n            raise ServiceResponseException(f\"Failed to edit image: {ex}\") from ex\n\n    async def _send_audio_to_text_request(self, settings: OpenAIAudioToTextExecutionSettings) -> Transcription:\n        \"\"\"Send a request to the OpenAI audio to text endpoint.\"\"\"\n        if not settings.filename:\n            raise ServiceInvalidRequestError(\"Audio file is required for audio to text service\")\n\n        try:\n            with open(settings.filename, \"rb\") as audio_file:\n                return await self.client.audio.transcriptions.create(\n                    file=audio_file,\n                    **settings.prepare_settings_dict(),\n                )\n        except Exception as ex:\n            raise ServiceResponseException(\n                f\"{type(self)} service failed to transcribe audio\",\n                ex,\n            ) from ex\n","sourceCodeStart":141,"sourceCodeEnd":177,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/ai/open_ai/services/open_ai_handler.py#L141-L177","documentation":"Raised as ServiceResponseException in _send_image_edit_request when any exception occurs during client.images.edit. This endpoint accepts image files (and optionally a mask) plus generation settings; failures include invalid file formats, file-size limits, content-filter rejections, or API/network errors.","triggerScenarios":"Calling image edit with invalid image files (wrong format, too large, corrupt), missing or invalid mask, unsupported parameters for the edit endpoint, or network/quota failures during client.images.edit.","commonSituations":"Passing PNG when a different format is required; file exceeding the 4MB limit; mask not matching the image dimensions; using dall-e-2-specific parameters with an unsupported model; content filter on the edit prompt.","solutions":["Inspect the interpolated exception message for the specific API error reason","Verify image files are valid PNG and within size limits (max 4MB per OpenAI spec)","Ensure the mask, if provided, has the same dimensions as the image and uses alpha channel transparency","For content-filter rejections, rephrase the editing prompt"],"exampleFix":"# before\nresponse = await service._send_image_edit_request(image=[b'corrupt_data'], settings=settings)\n# after — validate file before sending\nfrom pathlib import Path\nimg_bytes = Path('input.png').read_bytes()\nif len(img_bytes) > 4 * 1024 * 1024:\n    raise ValueError('Image exceeds 4MB limit')\nresponse = await service._send_image_edit_request(image=[img_bytes], settings=settings)","handlingStrategy":"validation","validationCode":"MAX_FILE_SIZE = 4 * 1024 * 1024  # 4MB\nfor f in image_files:\n    data = f if isinstance(f, bytes) else Path(f).read_bytes()\n    if len(data) > MAX_FILE_SIZE:\n        raise ValueError(f'Image file exceeds {MAX_FILE_SIZE} bytes')\n    if not data[:8].startswith(b'\\\\x89PNG'):\n        logger.warning('Image may not be a valid PNG')","typeGuard":null,"tryCatchPattern":"from semantic_kernel.exceptions import ServiceResponseException\n\ntry:\n    response = await service._send_image_edit_request(image=img, settings=settings, mask=mask)\nexcept ServiceResponseException as e:\n    logger.error('Image edit failed: %s', e)\n    raise","preventionTips":["Validate image format (PNG), dimensions, and file size before calling the edit endpoint","If using a mask, confirm its dimensions match the source image exactly"],"tags":["openai","image-edit","dall-e","file-validation","catch-all"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}