{"record":{"id":"a9fb9a737b8506f8","repo":"LykosAI/StabilityMatrix","slug":"image-generation-failed","errorCode":null,"errorMessage":"Image generation failed","messagePattern":"Image generation failed","errorType":"exception","errorClass":"ImageGenerationException","httpStatus":null,"severity":"error","filePath":"StabilityMatrix.Core/Services/ImageGeneration/ImageGenerationChatService.cs","lineNumber":711,"sourceCode":"        );\n\n        var response = await provider.GenerateAsync(request, cancellationToken).ConfigureAwait(false);\n\n        if (!response.IsSuccess)\n        {\n            logger.LogError(\"Image generation failed: {ErrorMessage}\", response.ErrorMessage);\n\n            // Don't save error messages to the database - let the caller handle the error via UI\n            // Update conversation timestamp and provider\n            var errorUpdatedConversation = conversation with\n            {\n                ProviderId = providerId,\n                UpdatedAt = DateTime.UtcNow,\n            };\n            await database.Conversations.UpdateAsync(errorUpdatedConversation).ConfigureAwait(false);\n\n            // Throw exception so caller can handle it appropriately (show notification, etc.)\n            throw new ImageGenerationException(response.ErrorMessage ?? \"Image generation failed\")\n            {\n                DetailJson = response.ErrorDetailJson,\n                ErrorCode = response.ErrorCode,\n            };\n        }\n\n        // Save generated images\n        List<string>? savedImagePaths = null;\n        if (response.Images?.Count > 0)\n        {\n            progress?.Report(\n                new ImageGenerationProgress(\n                    ProviderId: providerId,\n                    PromptId: null,\n                    Value: null,\n                    Maximum: null,\n                    RunningNode: null,\n                    Stage: \"Saving image(s)...\"","sourceCodeStart":693,"sourceCodeEnd":729,"githubUrl":"https://github.com/LykosAI/StabilityMatrix/blob/af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002/StabilityMatrix.Core/Services/ImageGeneration/ImageGenerationChatService.cs#L693-L729","documentation":"When the provider's GenerateAsync call returns a response with IsSuccess == false, the service persists the (failed-generation-updated) conversation and throws ImageGenerationException carrying the provider's ErrorMessage (defaulting to 'Image generation failed' when the provider gave none), plus DetailJson and ErrorCode from the response. It means the backend image generation itself failed — not a local argument problem — and the exception is intended for the caller/UI to surface.","triggerScenarios":"Calling SendMessageAsync (or RetryGenerationAsync) where provider.GenerateAsync returns an unsuccessful response: provider-side errors such as invalid API key, safety/content policy rejection, model unavailable, rate limiting, malformed provider options, or empty prompt with no images — with response.ErrorMessage null so the fallback message is thrown.","commonSituations":"Expired or missing API key; prompt rejected by safety filters; provider outage or rate limit; providerOptions dict containing invalid keys/values for the chosen provider; model deprecation on the backend.","solutions":["Inspect the thrown ImageGenerationException.ErrorCode and DetailJson — they contain the provider's actual error code and detail payload.","Check the provider API key / login status and renew it if expired (many errors here are auth failures).","Retry after a delay if ErrorCode indicates rate limiting or a transient provider outage.","Validate prompt and attached images against the provider's content policy; remove or rephrase rejected content.","Review providerOptions — remove or correct options unsupported by this provider."],"exampleFix":"// before\ntry\n{\n    await chatService.SendMessageAsync(convId, providerId, prompt);\n}\ncatch (ImageGenerationException) { } // swallowed, no diagnosis\n// after\ntry\n{\n    await chatService.SendMessageAsync(convId, providerId, prompt);\n}\ncatch (ImageGenerationException ex)\n{\n    logger.LogError(ex, \"Generation failed: code={Code} detail={Detail}\", ex.ErrorCode, ex.DetailJson);\n    if (IsTransient(ex.ErrorCode))\n    {\n        await Task.Delay(TimeSpan.FromSeconds(5));\n        await chatService.RetryGenerationAsync(convId, providerId);\n    }\n}","handlingStrategy":"try-catch","validationCode":"// Validate inputs before calling the provider\nif (string.IsNullOrWhiteSpace(textPrompt) && (imagePaths is null || imagePaths.Count == 0))\n    throw new ArgumentException(\"Provide a text prompt and/or at least one image\");\n// Ensure an API key / login is configured for the provider\nif (!providerService.IsApiKeyConfigured(providerId))\n    throw new InvalidOperationException($\"No API key configured for provider {providerId}\");","typeGuard":"bool GenerationSucceeded(ImageGenerationResponse r) => r is { IsSuccess: true, Images.Count: > 0 };","tryCatchPattern":"try\n{\n    await chatService.SendMessageAsync(conversationId, providerId, prompt, imagePaths);\n}\ncatch (ImageGenerationException ex)\n{\n    switch (ex.ErrorCode)\n    {\n        case \"rate_limited\": await Task.Delay(TimeSpan.FromSeconds(10)); goto retry;\n        case \"auth_failed\": await promptForReloginAsync(); break;\n        default: ui.ShowNotification($\"Generation failed: {ex.Message}\\n{ex.DetailJson}\"); break;\n    }\n}","preventionTips":["Keep provider API keys valid and refreshed","Pre-validate prompts/images against provider content policies","Only pass providerOptions keys documented for the chosen provider","Inspect ErrorCode/DetailJson on every failure to classify transient vs permanent errors","Back off and retry on rate-limit style error codes"],"tags":["api","image-generation","provider","unhandled"],"backgroundTag":"api-error-response","analyzedSha":"af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002","analyzedAt":"2026-09-12T19:02:43.389Z","contentChangedAt":"2026-09-12T19:02:43.389Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}