Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: improve Google image error handling (#15285)

YuTengjing403de538d690
diff --git a/locales/en-US/image.json b/locales/en-US/image.json
index 1dd1b3227de..4c1106f4efe 100644
--- a/locales/en-US/image.json
+++ b/locales/en-US/image.json
@@ -48,7 +48,7 @@
"generation.actions.seedCopied": "Seed Copied to Clipboard",
"generation.actions.seedCopyFailed": "Failed to Copy Seed",
"generation.metadata.count": "{{count}} Images",
- "generation.status.failed": "Generation Failed",
+ "generation.status.failed": "Generation hit a problem. Adjust the prompt and try again",
"generation.status.generating": "Generating...",
"notSupportGuide.desc": "The current deployment mode does not support AI image generation. Switch to the <1>server database deployment mode</1>, or use <3>LobeHub Cloud</3>.",
"notSupportGuide.features.fileIntegration.desc": "Deep integration with the file management system; generated images are automatically saved to the file system for unified management and organization.",
diff --git a/locales/zh-CN/image.json b/locales/zh-CN/image.json
index 2af2d0f2dd8..805d731366c 100644
--- a/locales/zh-CN/image.json
+++ b/locales/zh-CN/image.json
@@ -48,7 +48,7 @@
"generation.actions.seedCopied": "种子已复制到剪贴板",
"generation.actions.seedCopyFailed": "复制遇到了问题。你可以再试一次",
"generation.metadata.count": "{{count}} 张图片",
- "generation.status.failed": "生成遇到了问题。你可以重试,或调整描述后再试",
+ "generation.status.failed": "生成遇到了问题,建议调整描述后重试",
"generation.status.generating": "生成中…",
"notSupportGuide.desc": "当前部署模式不支持 AI 图像生成功能。请切换到<1>服务端数据库部署模式</1>,或直接使用 <3>LobeHub Cloud</3>",
"notSupportGuide.features.fileIntegration.desc": "与文件管理深度整合。生成的图片自动保存到文件系统,统一管理和组织",
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index 3ab79e1ca40..030c3caaedf 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -510,6 +510,17 @@ export const ERROR_CODE_SPECS: SpecMap = {
countAsFailure: false,
description: 'ComfyUI model load / inference failed.',
},
+ [AgentRuntimeErrorType.ProviderContentPolicyViolation]: {
+ code: AgentRuntimeErrorType.ProviderContentPolicyViolation,
+ numericId: 8010,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 471,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Image-generation provider blocked the request due to content policy.',
+ },
// ─── 9xxx Config ──────────────────────────────────────────────────────
[AgentRuntimeErrorType.InvalidOllamaArgs]: {
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index d0888e96490..a3e2c9d5637 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -42,7 +42,7 @@ export { LobeCometAPIAI } from './providers/cometapi';
export { LobeComfyUI } from './providers/comfyui';
export { LobeDeepSeekAI } from './providers/deepseek';
export { LobeGLMCodingPlanAI } from './providers/glmCodingPlan';
-export { GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE, LobeGoogleAI } from './providers/google';
+export { LobeGoogleAI } from './providers/google';
export { LobeGroq } from './providers/groq';
export { LobeKimiCodingPlanAI } from './providers/kimiCodingPlan';
export { LobeHubAI } from './providers/lobehub';
diff --git a/packages/model-runtime/src/providers/google/createImage.test.ts b/packages/model-runtime/src/providers/google/createImage.test.ts
index 0241e071f7b..107dac83b1a 100644
--- a/packages/model-runtime/src/providers/google/createImage.test.ts
+++ b/packages/model-runtime/src/providers/google/createImage.test.ts
@@ -5,13 +5,29 @@ import * as imageToBase64Module from '@lobechat/utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateImagePayload } from '../../types/image';
-import { createGoogleImage, GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE } from './createImage';
+import {
+ createGoogleImage,
+ GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
+ GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT,
+} from './createImage';
const provider = 'google';
const bizErrorType = 'ProviderBizError';
+const contentPolicyErrorType = 'ProviderContentPolicyViolation';
const noImageErrorType = 'ProviderNoImageGenerated';
const invalidErrorType = 'InvalidProviderAPIKey';
const getModelPricingMock = vi.hoisted(() => vi.fn());
+const expectGoogleImagePromptPart = (prompt: string) => ({
+ text: expect.stringContaining(
+ [
+ GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT,
+ '<user_request>',
+ prompt,
+ '</user_request>',
+ '</image_generation_request>',
+ ].join('\n'),
+ ),
+});
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -383,12 +399,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Create a beautiful sunset landscape' }],
+ parts: [expectGoogleImagePromptPart('Create a beautiful sunset landscape')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
},
});
expect(result).toEqual({
@@ -500,12 +517,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Create a beautiful sunset landscape' }],
+ parts: [expectGoogleImagePromptPart('Create a beautiful sunset landscape')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
},
});
});
@@ -551,12 +569,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Create a beautiful sunset landscape' }],
+ parts: [expectGoogleImagePromptPart('Create a beautiful sunset landscape')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
imageConfig: {
imageSize: '4K',
},
@@ -603,12 +622,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Cinematic widescreen shot' }],
+ parts: [expectGoogleImagePromptPart('Cinematic widescreen shot')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
imageConfig: {
aspectRatio: '16:9',
imageSize: '2K',
@@ -655,12 +675,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Portrait orientation' }],
+ parts: [expectGoogleImagePromptPart('Portrait orientation')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
imageConfig: {
aspectRatio: '9:16',
},
@@ -668,6 +689,67 @@ describe('createGoogleImage', () => {
});
});
+ it('should define image-only behavior in the image generation prompts', () => {
+ expect(GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT).toContain('<image_generation_contract>');
+ expect(GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT).toContain('Return an image whenever possible');
+ expect(GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT).toContain(
+ 'policy, moderation, or safety prevents generation',
+ );
+ expect(GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT).toContain(
+ 'Create a relevant visual interpretation',
+ );
+ expect(GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT).toContain('return text only: 1');
+ expect(GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT).toContain('<image_generation_request>');
+ expect(GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT).toContain(
+ 'Generate an image whenever possible',
+ );
+ });
+
+ it('should escape user prompts inside the XML request wrapper', async () => {
+ // Arrange
+ const realBase64ImageData =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
+ const mockContentResponse = {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: {
+ data: realBase64ImageData,
+ mimeType: 'image/png',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ };
+ vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
+
+ const payload: CreateImagePayload = {
+ model: 'gemini-2.5-flash-image:image',
+ params: {
+ prompt: 'Create <cat & dog>',
+ },
+ };
+
+ // Act
+ await createGoogleImage(mockClient, provider, payload);
+
+ // Assert
+ expect(mockClient.models.generateContent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ contents: [
+ {
+ role: 'user',
+ parts: [expectGoogleImagePromptPart('Create &lt;cat &amp; dog&gt;')],
+ },
+ ],
+ }),
+ );
+ });
+
it('should support image editing with base64 imageUrl', async () => {
// Arrange
const inputImageBase64 =
@@ -710,7 +792,7 @@ describe('createGoogleImage', () => {
{
role: 'user',
parts: [
- { text: 'Add a red rose to this image' },
+ expectGoogleImagePromptPart('Add a red rose to this image'),
{
inlineData: {
data: inputImageBase64,
@@ -723,6 +805,7 @@ describe('createGoogleImage', () => {
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
},
});
expect(result).toEqual({
@@ -781,7 +864,7 @@ describe('createGoogleImage', () => {
{
role: 'user',
parts: [
- { text: 'Change the background to blue sky' },
+ expectGoogleImagePromptPart('Change the background to blue sky'),
{
inlineData: {
data: inputImageBase64,
@@ -794,6 +877,7 @@ describe('createGoogleImage', () => {
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
},
});
expect(result).toEqual({
@@ -840,12 +924,13 @@ describe('createGoogleImage', () => {
contents: [
{
role: 'user',
- parts: [{ text: 'Generate a colorful abstract pattern' }],
+ parts: [expectGoogleImagePromptPart('Generate a colorful abstract pattern')],
},
],
model: 'gemini-2.5-flash-image',
config: {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
},
});
expect(result).toEqual({
@@ -881,12 +966,14 @@ describe('createGoogleImage', () => {
};
// Act & Assert
- await expect(createGoogleImage(mockClient, provider, payload)).rejects.toEqual(
- expect.objectContaining({
- errorType: noImageErrorType,
- provider,
- }),
- );
+ await expect(createGoogleImage(mockClient, provider, payload)).rejects.toMatchObject({
+ error: {
+ message: 'I cannot generate an image.',
+ reasonCode: 'google_image_text_only_response',
+ },
+ errorType: noImageErrorType,
+ provider,
+ });
});
it('should preserve Google no-image diagnostic context without serializing text parts', async () => {
@@ -951,7 +1038,7 @@ describe('createGoogleImage', () => {
expect(JSON.stringify(error)).not.toContain('I can describe the image');
});
- it('should explain text-only image responses as non-generation prompts', async () => {
+ it('should surface text-only image responses as provider no-image reasons', async () => {
// Arrange
const mockContentResponse = {
candidates: [
@@ -991,7 +1078,10 @@ describe('createGoogleImage', () => {
// Assert
expect(error).toMatchObject({
- error: { message: GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE },
+ error: {
+ message: 'The uploaded image shows a cartoon portrait.',
+ reasonCode: 'google_image_text_only_response',
+ },
errorType: noImageErrorType,
provider,
});
@@ -1003,10 +1093,10 @@ describe('createGoogleImage', () => {
],
responseId: 'text-only-response',
});
- expect(JSON.stringify(error)).not.toContain('cartoon portrait');
+ expect(JSON.stringify(error)).toContain('cartoon portrait');
});
- it('should keep text-only guidance safe for policy refusals', async () => {
+ it('should classify the text-only policy signal as a content policy violation', async () => {
// Arrange
const mockContentResponse = {
candidates: [
@@ -1014,14 +1104,14 @@ describe('createGoogleImage', () => {
content: {
parts: [
{
- text: "Sorry, I can't generate that image because it may violate safety policies.",
+ text: '1',
},
],
},
finishReason: 'STOP',
},
],
- responseId: 'text-refusal-response',
+ responseId: 'text-policy-signal-response',
};
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(
mockContentResponse as any,
@@ -1034,38 +1124,25 @@ describe('createGoogleImage', () => {
},
};
- // Act
- let error: any;
- try {
- await createGoogleImage(mockClient, provider, payload);
- } catch (e) {
- error = e;
- }
-
- // Assert
- expect(error).toMatchObject({
- error: { message: GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE },
- errorType: noImageErrorType,
+ // Act & Assert
+ await expect(createGoogleImage(mockClient, provider, payload)).rejects.toMatchObject({
+ error: {
+ providerReason: 'TEXT_POLICY_REFUSAL',
+ reasonCode: 'google_image_content_policy_violation',
+ responseId: 'text-policy-signal-response',
+ },
+ errorType: contentPolicyErrorType,
provider,
});
- expect(error.error.message).toContain('try a safer prompt');
- expect(error.providerResponse).toMatchObject({
- candidates: [
- {
- finishReason: 'STOP',
- },
- ],
- responseId: 'text-refusal-response',
- });
});
- it('should preserve Google image safety finish reasons without provider policy classification', async () => {
+ it('should classify Google image safety finish reasons as content policy violations', async () => {
// Arrange
const mockContentResponse = {
candidates: [
{
content: {},
- finishReason: 'IMAGE_SAFETY',
+ finishReason: 'IMAGE_PROHIBITED_CONTENT',
finishMessage: 'The generated image was blocked.',
},
],
@@ -1084,12 +1161,17 @@ describe('createGoogleImage', () => {
// Act & Assert
await expect(createGoogleImage(mockClient, provider, payload)).rejects.toMatchObject({
- errorType: noImageErrorType,
+ error: {
+ providerReason: 'IMAGE_PROHIBITED_CONTENT',
+ reasonCode: 'google_image_content_policy_violation',
+ responseId: 'safety-response',
+ },
+ errorType: contentPolicyErrorType,
provider,
providerResponse: {
candidates: [
{
- finishReason: 'IMAGE_SAFETY',
+ finishReason: 'IMAGE_PROHIBITED_CONTENT',
},
],
responseId: 'safety-response',
diff --git a/packages/model-runtime/src/providers/google/createImage.ts b/packages/model-runtime/src/providers/google/createImage.ts
index eee291ddcfd..0d94cfa4eac 100644
--- a/packages/model-runtime/src/providers/google/createImage.ts
+++ b/packages/model-runtime/src/providers/google/createImage.ts
@@ -8,6 +8,7 @@ import type {
import { imageUrlToBase64 } from '@lobechat/utils';
import { convertGoogleAIUsage } from '../../core/usageConverters/google-ai';
+import { AgentRuntimeErrorType } from '../../types/error';
import type { CreateImagePayload, CreateImageResponse } from '../../types/image';
import { AgentRuntimeError } from '../../utils/createError';
import { getModelPricing } from '../../utils/getModelPricing';
@@ -16,14 +17,70 @@ import { parseDataUri } from '../../utils/uriParser';
// Maximum number of images allowed for processing
const MAX_IMAGE_COUNT = 10;
-
-export const GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE = [
- 'The model returned text instead of an image.',
- 'Ask it to generate or edit an image, or try a safer prompt if the request may have been blocked.',
-].join(' ');
+const GOOGLE_IMAGE_CONTENT_POLICY_TEXT_SIGNAL = '1';
+
+export const GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT = [
+ '<image_generation_contract>',
+ 'You are an image generation API endpoint, not a conversational assistant.',
+ '',
+ 'Use the wrapped <user_request> as the image prompt.',
+ 'Return an image whenever possible. Do not answer conversationally.',
+ '',
+ 'If the user request is conversational, ambiguous, or not a direct image prompt:',
+ '- Do not answer the question in text.',
+ '- Create a relevant visual interpretation of the request instead.',
+ '- For model identity or capability questions, generate a simple visual metaphor for an AI image model.',
+ '',
+ 'If no image can be returned:',
+ '- If policy, moderation, or safety prevents generation, return text only: 1',
+ '- If another concrete reason prevents generation, return that reason as concise user-safe text.',
+ '',
+ 'Output rules:',
+ '- Return the image.',
+ '- If an image is returned, do not include captions or explanatory text.',
+ '- Do not explain, apologize, ask follow-up questions, or wrap anything in Markdown.',
+ '</image_generation_contract>',
+].join('\n');
+
+export const GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT = [
+ '<image_generation_request>',
+ '<instruction>Generate an image whenever possible. If policy or safety blocks generation, return text only: 1.</instruction>',
+].join('\n');
+
+// Google enum values from GenerateContentResponse.FinishReason and
+// PromptFeedback.BlockedReason that should be surfaced as provider moderation.
+// Reference: https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1beta1/GenerateContentResponse
+const GOOGLE_IMAGE_CONTENT_POLICY_FINISH_REASONS = new Set([
+ 'BLOCKLIST',
+ 'IMAGE_PROHIBITED_CONTENT',
+ 'IMAGE_RECITATION',
+ 'IMAGE_SAFETY',
+ 'MODEL_ARMOR',
+ 'PROHIBITED_CONTENT',
+ 'RECITATION',
+ 'SAFETY',
+ 'SPII',
+]);
+
+const GOOGLE_IMAGE_CONTENT_POLICY_BLOCK_REASONS = new Set([
+ 'BLOCKLIST',
+ 'IMAGE_SAFETY',
+ 'JAILBREAK',
+ 'MODEL_ARMOR',
+ 'PROHIBITED_CONTENT',
+ 'SAFETY',
+]);
interface ErrorWithRawProviderResponse extends Error {
+ isGoogleImageNoImageError?: boolean;
+ providerReason?: string;
providerResponse?: GenerateContentResponse;
+ reasonCode?: string;
+}
+
+interface GoogleImageErrorMetadata {
+ providerReason?: string;
+ reasonCode?: string;
}
// Keep raw provider responses available to upstream error handlers without
@@ -44,11 +101,35 @@ const attachNonSerializableProviderResponse = <T extends object>(
const createGoogleImageNoImageError = (
message: string,
response: GenerateContentResponse,
-): ErrorWithRawProviderResponse =>
- attachNonSerializableProviderResponse(
- new Error(message),
- response,
- ) as ErrorWithRawProviderResponse;
+ metadata?: GoogleImageErrorMetadata,
+): ErrorWithRawProviderResponse => {
+ const error = new Error(message) as ErrorWithRawProviderResponse;
+ error.isGoogleImageNoImageError = true;
+
+ if (metadata?.providerReason) {
+ error.providerReason = metadata.providerReason;
+ }
+ if (metadata?.reasonCode) {
+ error.reasonCode = metadata.reasonCode;
+ }
+
+ return attachNonSerializableProviderResponse(error, response) as ErrorWithRawProviderResponse;
+};
+
+const createGoogleImageContentPolicyError = (
+ response: GenerateContentResponse,
+ reason: string,
+ message = 'Google image generation was blocked by content policy.',
+ metadata?: Pick<GoogleImageErrorMetadata, 'reasonCode'>,
+): ErrorWithRawProviderResponse => {
+ const error = new Error(message) as ErrorWithRawProviderResponse;
+ error.providerReason = reason;
+ if (metadata?.reasonCode) {
+ error.reasonCode = metadata.reasonCode;
+ }
+
+ return attachNonSerializableProviderResponse(error, response) as ErrorWithRawProviderResponse;
+};
const getTextFromParts = (parts: Part[]) =>
parts
@@ -56,6 +137,40 @@ const getTextFromParts = (parts: Part[]) =>
.filter(Boolean)
.join('\n');
+const escapeGoogleImageXmlText = (value: string) =>
+ value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
+
+// Some image gateways ignore systemInstruction-only fallback guidance and answer
+// prompts like "can you generate images?" conversationally, so keep the API
+// contract in the user part as well.
+const buildGoogleImageUserPrompt = (prompt: string) =>
+ [
+ GOOGLE_IMAGE_GENERATION_USER_PROMPT_CONTRACT,
+ '<user_request>',
+ escapeGoogleImageXmlText(prompt),
+ '</user_request>',
+ '</image_generation_request>',
+ ].join('\n');
+
+const getGoogleImageContentPolicyReason = (response: GenerateContentResponse) => {
+ const candidate = response.candidates?.[0];
+ const finishReason = candidate?.finishReason;
+ const blockReason = response.promptFeedback?.blockReason;
+
+ if (
+ typeof finishReason === 'string' &&
+ GOOGLE_IMAGE_CONTENT_POLICY_FINISH_REASONS.has(finishReason)
+ ) {
+ return finishReason;
+ }
+ if (
+ typeof blockReason === 'string' &&
+ GOOGLE_IMAGE_CONTENT_POLICY_BLOCK_REASONS.has(blockReason)
+ ) {
+ return blockReason;
+ }
+};
+
/**
* Process a single image URL and convert it to Google AI Part format
*/
@@ -92,6 +207,11 @@ async function processImageForParts(imageUrl: string): Promise<Part> {
*/
function extractImageFromResponse(response: GenerateContentResponse): CreateImageResponse {
const candidate = response.candidates?.[0];
+ const contentPolicyReason = getGoogleImageContentPolicyReason(response);
+
+ if (contentPolicyReason) {
+ throw createGoogleImageContentPolicyError(response, contentPolicyReason);
+ }
if (candidate?.finishReason === 'NO_IMAGE') {
throw createGoogleImageNoImageError('No image generated', response);
@@ -108,8 +228,20 @@ function extractImageFromResponse(response: GenerateContentResponse): CreateImag
}
}
- if (candidate.finishReason === 'STOP' && getTextFromParts(candidate.content.parts)) {
- throw createGoogleImageNoImageError(GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE, response);
+ const textFromParts = getTextFromParts(candidate.content.parts);
+ if (textFromParts) {
+ if (textFromParts.trim() === GOOGLE_IMAGE_CONTENT_POLICY_TEXT_SIGNAL) {
+ throw createGoogleImageContentPolicyError(
+ response,
+ 'TEXT_POLICY_REFUSAL',
+ 'Google image generation was blocked by text policy refusal.',
+ { reasonCode: 'google_image_content_policy_violation' },
+ );
+ }
+
+ throw createGoogleImageNoImageError(textFromParts, response, {
+ reasonCode: 'google_image_text_only_response',
+ });
}
// Fallback when no inlineData is present (commonly moderation or policy blocks)
@@ -164,7 +296,7 @@ async function generateImageByChatModel(
}
// Build content parts
- const parts: Part[] = [{ text: params.prompt }];
+ const parts: Part[] = [{ text: buildGoogleImageUserPrompt(params.prompt) }];
// Add image for editing if provided
if (params.imageUrl && params.imageUrl !== null) {
@@ -205,6 +337,7 @@ async function generateImageByChatModel(
const config: GenerateContentConfig = {
responseModalities: ['TEXT', 'IMAGE'],
+ systemInstruction: GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
...(Object.keys(imageConfig).length > 0 ? { imageConfig } : {}),
};
@@ -250,9 +383,28 @@ export async function createGoogleImage(
const { errorType, error: parsedError } = parseGoogleErrorMessage(err.message);
const providerResponse = (err as ErrorWithRawProviderResponse).providerResponse;
+ const providerReason =
+ (err as ErrorWithRawProviderResponse).providerReason ??
+ (providerResponse ? getGoogleImageContentPolicyReason(providerResponse) : undefined);
+ const isContentPolicyViolation = Boolean(providerReason);
+ const isGoogleImageNoImageError = Boolean(
+ (err as ErrorWithRawProviderResponse).isGoogleImageNoImageError,
+ );
+ const reasonCode =
+ (err as ErrorWithRawProviderResponse).reasonCode ??
+ (isContentPolicyViolation ? 'google_image_content_policy_violation' : undefined);
const agentError = AgentRuntimeError.createImage({
- error: parsedError,
- errorType,
+ error: {
+ ...parsedError,
+ providerReason,
+ reasonCode,
+ responseId: providerResponse?.responseId,
+ },
+ errorType: isContentPolicyViolation
+ ? AgentRuntimeErrorType.ProviderContentPolicyViolation
+ : isGoogleImageNoImageError
+ ? AgentRuntimeErrorType.ProviderNoImageGenerated
+ : errorType,
provider,
});
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 2567bc394b8..3bf17c17b41 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -31,8 +31,6 @@ import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';
import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';
import { resolveGoogleThinkingConfig } from './thinkingResolver';
-export { GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE } from './createImage';
-
const log = debug('model-runtime:google');
const modelsOffSafetySettings = new Set(['gemini-2.0-flash-exp']);
diff --git a/packages/model-runtime/src/utils/errorResponse.test.ts b/packages/model-runtime/src/utils/errorResponse.test.ts
index cfbd3d8e5b7..f58353a3bde 100644
--- a/packages/model-runtime/src/utils/errorResponse.test.ts
+++ b/packages/model-runtime/src/utils/errorResponse.test.ts
@@ -49,6 +49,12 @@ describe('createErrorResponse', () => {
expect(response.status).toBe(471);
});
+ it('returns a 471 status for ProviderContentPolicyViolation error type', () => {
+ const errorType = AgentRuntimeErrorType.ProviderContentPolicyViolation;
+ const response = createErrorResponse(errorType);
+ expect(response.status).toBe(471);
+ });
+
it('returns a 470 status for AgentRuntimeError error type', () => {
const errorType = AgentRuntimeErrorType.AgentRuntimeError;
const response = createErrorResponse(errorType);
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
index 87a04369d52..e0d1ee296e6 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
@@ -13,6 +13,22 @@ describe('isNonRetryableRequestError', () => {
).toBe(true);
});
+ it('returns true for terminal image generation errors', () => {
+ expect(
+ isNonRetryableRequestError({
+ error: { message: 'Google image generation was blocked by content policy.' },
+ errorType: AgentRuntimeErrorType.ProviderContentPolicyViolation,
+ }),
+ ).toBe(true);
+
+ expect(
+ isNonRetryableRequestError({
+ error: { message: 'The provider did not return an image.' },
+ errorType: AgentRuntimeErrorType.ProviderNoImageGenerated,
+ }),
+ ).toBe(true);
+ });
+
it('returns true for invalid request payload errors', () => {
expect(
isNonRetryableRequestError({
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
index 7ffbda94672..cdc788e086b 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
@@ -2,7 +2,11 @@ import { toRecord } from '@lobechat/utils';
import { AgentRuntimeErrorType } from '../types/error';
-const NON_RETRYABLE_ERROR_TYPES = new Set<string>([AgentRuntimeErrorType.ExceededContextWindow]);
+const NON_RETRYABLE_ERROR_TYPES = new Set<string>([
+ AgentRuntimeErrorType.ExceededContextWindow,
+ AgentRuntimeErrorType.ProviderContentPolicyViolation,
+ AgentRuntimeErrorType.ProviderNoImageGenerated,
+]);
const RETRYABLE_STATUS_CODES = new Set([401, 403, 404, 408, 409, 423, 425, 429]);
const RETRYABLE_ERROR_CODES = new Set([
'accountdeactivated',
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 16ed628a340..81a02c6daa4 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -124,6 +124,7 @@ export const AgentRuntimeErrorType = {
ConnectionCheckFailed: 'ConnectionCheckFailed',
// ******* Image Generation Error ******* //
+ ProviderContentPolicyViolation: 'ProviderContentPolicyViolation',
ProviderNoImageGenerated: 'ProviderNoImageGenerated',
InvalidComfyUIArgs: 'InvalidComfyUIArgs',
diff --git a/src/locales/default/image.ts b/src/locales/default/image.ts
index 746ee87082c..f484660b2a4 100644
--- a/src/locales/default/image.ts
+++ b/src/locales/default/image.ts
@@ -49,7 +49,7 @@ export default {
'generation.actions.seedCopied': 'Seed Copied to Clipboard',
'generation.actions.seedCopyFailed': 'Failed to Copy Seed',
'generation.metadata.count': '{{count}} Images',
- 'generation.status.failed': 'Generation Failed',
+ 'generation.status.failed': 'Generation hit a problem. Adjust the prompt and try again',
'generation.status.generating': 'Generating...',
'notSupportGuide.desc':
'The current deployment mode does not support AI image generation. Switch to the <1>server database deployment mode</1>, or use <3>LobeHub Cloud</3>.',
diff --git a/src/server/routers/async/contentPolicyError.ts b/src/server/routers/async/contentPolicyError.ts
index 0b818ab0781..49f1c90f620 100644
--- a/src/server/routers/async/contentPolicyError.ts
+++ b/src/server/routers/async/contentPolicyError.ts
@@ -1,4 +1,4 @@
-const CONTENT_POLICY_ERROR_MESSAGE =
+export const CONTENT_POLICY_ERROR_MESSAGE =
'Content policy check failed. Revise your prompt and try again.';
const getErrorCode = (error: any) => error?.code || error?.error?.code;
diff --git a/src/server/routers/async/image.ts b/src/server/routers/async/image.ts
index 4f3f8226bb1..3b6a3200bd2 100644
--- a/src/server/routers/async/image.ts
+++ b/src/server/routers/async/image.ts
@@ -4,16 +4,7 @@ import {
buildMappedBusinessModelFields,
resolveBusinessModelMapping,
} from '@lobechat/business-model-runtime';
-import {
- AgentRuntimeErrorType,
- GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE,
-} from '@lobechat/model-runtime';
-import {
- AsyncTaskError,
- AsyncTaskErrorType,
- AsyncTaskStatus,
- RequestTrigger,
-} from '@lobechat/types';
+import { AsyncTaskError, AsyncTaskStatus, RequestTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { type RuntimeImageGenParams } from 'model-bank';
@@ -32,21 +23,11 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { GenerationService } from '@/server/services/generation';
import { sanitizeFileName } from '@/utils/sanitizeFileName';
-import { getContentPolicyErrorMessage } from './contentPolicyError';
+import { categorizeImageGenerationError } from './imageError';
const log = debug('lobe-image:async');
const IMAGE_URL_PREVIEW_LENGTH = 100;
-const IMAGE_EDITING_NO_IMAGE_MESSAGE = [
- 'The provider did not return an image.',
- 'This may be due to content review.',
- 'Try a safer source image or a milder prompt.',
-].join(' ');
-const IMAGE_GENERATION_NO_IMAGE_MESSAGE = [
- 'The provider did not return an image.',
- 'This may be due to content review.',
- 'Try a milder prompt or another model.',
-].join(' ');
const imageProcedure = asyncAuthedProcedure.use(async (opts) => {
const { ctx } = opts;
@@ -91,158 +72,6 @@ const checkAbortSignal = (signal: AbortSignal) => {
}
};
-/**
- * Categorizes errors into appropriate AsyncTaskErrorType
- * Returns the original error message if available, otherwise returns the error type as message
- * Client should handle localization based on errorType
- */
-const categorizeError = (
- error: any,
- isAborted: boolean,
- isEditingImage: boolean,
- providerContentPolicyMessage?: string,
-): { errorMessage: string; errorType: AsyncTaskErrorType } => {
- log('🔥🔥🔥 [ASYNC] categorizeError called:', {
- errorMessage: error?.message,
- errorName: error?.name,
- errorStatus: error?.status,
- errorType: error?.errorType,
- fullError: JSON.stringify(error, null, 2),
- isAborted,
- isEditingImage,
- });
- // Handle Comfy UI errors
- if (error.errorType === AgentRuntimeErrorType.ComfyUIServiceUnavailable) {
- return {
- errorMessage:
- error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIServiceUnavailable,
- errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ComfyUIBizError) {
- return {
- errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIBizError,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ComfyUIWorkflowError) {
- return {
- errorMessage:
- error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIWorkflowError,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ComfyUIModelError) {
- return {
- errorMessage:
- error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIModelError,
- errorType: AsyncTaskErrorType.ModelNotFound,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ConnectionCheckFailed) {
- return {
- errorMessage: error.message || AgentRuntimeErrorType.ConnectionCheckFailed,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.PermissionDenied) {
- return {
- errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.PermissionDenied,
- errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ModelNotFound) {
- return {
- errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.ModelNotFound,
- errorType: AsyncTaskErrorType.ModelNotFound,
- };
- }
-
- if (providerContentPolicyMessage) {
- return {
- errorMessage: providerContentPolicyMessage,
- errorType: AsyncTaskErrorType.ProviderContentModeration,
- };
- }
-
- if (error.errorType === AgentRuntimeErrorType.ProviderNoImageGenerated) {
- const providerErrorMessage = error.error?.message || error.message;
-
- if (
- typeof providerErrorMessage === 'string' &&
- providerErrorMessage.includes(GOOGLE_IMAGE_TEXT_ONLY_RESPONSE_MESSAGE)
- ) {
- return {
- errorMessage: providerErrorMessage,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- return {
- errorMessage: isEditingImage
- ? IMAGE_EDITING_NO_IMAGE_MESSAGE
- : IMAGE_GENERATION_NO_IMAGE_MESSAGE,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- // FIXME: 401 errors should be handled in agentRuntime for better practice
- if (error.errorType === AgentRuntimeErrorType.InvalidProviderAPIKey || error?.status === 401) {
- return {
- errorMessage:
- error.error?.message || error.message || AgentRuntimeErrorType.InvalidProviderAPIKey,
- errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
- };
- }
-
- const fallbackContentPolicyMessage = getContentPolicyErrorMessage(error);
- if (fallbackContentPolicyMessage) {
- return {
- errorMessage: fallbackContentPolicyMessage,
- errorType: AsyncTaskErrorType.ProviderContentModeration,
- };
- }
-
- if (error instanceof AsyncTaskError) {
- return {
- errorMessage: typeof error.body === 'string' ? error.body : error.body.detail,
- errorType: error.name as AsyncTaskErrorType,
- };
- }
-
- if (isAborted || error.message?.includes('aborted')) {
- return {
- errorMessage: AsyncTaskErrorType.Timeout,
- errorType: AsyncTaskErrorType.Timeout,
- };
- }
-
- if (error.message?.includes('timeout') || error.name === 'TimeoutError') {
- return {
- errorMessage: AsyncTaskErrorType.Timeout,
- errorType: AsyncTaskErrorType.Timeout,
- };
- }
-
- if (error.message?.includes('network') || error.name === 'NetworkError') {
- return {
- errorMessage: error.message || AsyncTaskErrorType.ServerError,
- errorType: AsyncTaskErrorType.ServerError,
- };
- }
-
- return {
- errorMessage: error.message || error.error?.message || AsyncTaskErrorType.ServerError,
- errorType: AsyncTaskErrorType.ServerError,
- };
-};
-
export const imageRouter = router({
createImage: imageProcedure
.use(createImageBusinessMiddleware)
@@ -480,12 +309,12 @@ export const imageRouter = router({
trigger: RequestTrigger.Image,
userId: ctx.userId,
});
- const { errorType, errorMessage } = categorizeError(
+ const { errorType, errorMessage } = categorizeImageGenerationError({
error,
- abortController.signal.aborted,
isEditingImage,
+ isAborted: abortController.signal.aborted,
providerContentPolicyMessage,
- );
+ });
await ctx.asyncTaskModel.update(taskId, {
error: new AsyncTaskError(errorType, errorMessage),
diff --git a/src/server/routers/async/imageError.test.ts b/src/server/routers/async/imageError.test.ts
new file mode 100644
index 00000000000..bddd5a38e1c
--- /dev/null
+++ b/src/server/routers/async/imageError.test.ts
@@ -0,0 +1,81 @@
+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { AsyncTaskErrorType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { CONTENT_POLICY_ERROR_MESSAGE } from './contentPolicyError';
+import { categorizeImageGenerationError } from './imageError';
+
+describe('categorizeImageGenerationError', () => {
+ it('should map runtime content policy violations to async content moderation errors', () => {
+ const result = categorizeImageGenerationError({
+ error: {
+ error: {
+ providerReason: 'IMAGE_PROHIBITED_CONTENT',
+ reasonCode: 'google_image_content_policy_violation',
+ },
+ errorType: AgentRuntimeErrorType.ProviderContentPolicyViolation,
+ },
+ isAborted: false,
+ isEditingImage: false,
+ });
+
+ expect(result).toEqual({
+ errorMessage: CONTENT_POLICY_ERROR_MESSAGE,
+ errorType: AsyncTaskErrorType.ProviderContentModeration,
+ });
+ });
+
+ it('should surface provider text-only image responses as server errors', () => {
+ const result = categorizeImageGenerationError({
+ error: {
+ error: {
+ message: "I'm just a language model and can't help with that.",
+ reasonCode: 'google_image_text_only_response',
+ },
+ errorType: AgentRuntimeErrorType.ProviderNoImageGenerated,
+ },
+ isAborted: false,
+ isEditingImage: false,
+ });
+
+ expect(result).toEqual({
+ errorMessage: "I'm just a language model and can't help with that.",
+ errorType: AsyncTaskErrorType.ServerError,
+ });
+ });
+
+ it('should surface provider text refusal reasons when the runtime classified an explicit refusal', () => {
+ const result = categorizeImageGenerationError({
+ error: {
+ error: {
+ message: 'No image generated: The requested output format is not supported.',
+ reasonCode: 'google_image_generation_refused',
+ },
+ errorType: AgentRuntimeErrorType.ProviderNoImageGenerated,
+ },
+ isAborted: false,
+ isEditingImage: false,
+ });
+
+ expect(result).toEqual({
+ errorMessage: 'No image generated: The requested output format is not supported.',
+ errorType: AsyncTaskErrorType.ServerError,
+ });
+ });
+
+ it('should keep generic no-image provider responses as server errors', () => {
+ const result = categorizeImageGenerationError({
+ error: {
+ errorType: AgentRuntimeErrorType.ProviderNoImageGenerated,
+ },
+ isAborted: false,
+ isEditingImage: false,
+ });
+
+ expect(result).toEqual({
+ errorMessage:
+ 'The provider did not return an image. This may be due to content review. Try a milder prompt or another model.',
+ errorType: AsyncTaskErrorType.ServerError,
+ });
+ });
+});
diff --git a/src/server/routers/async/imageError.ts b/src/server/routers/async/imageError.ts
new file mode 100644
index 00000000000..b3ed0fb23d8
--- /dev/null
+++ b/src/server/routers/async/imageError.ts
@@ -0,0 +1,187 @@
+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { AsyncTaskError, AsyncTaskErrorType } from '@lobechat/types';
+
+import { CONTENT_POLICY_ERROR_MESSAGE, getContentPolicyErrorMessage } from './contentPolicyError';
+
+const IMAGE_EDITING_NO_IMAGE_MESSAGE = [
+ 'The provider did not return an image.',
+ 'This may be due to content review.',
+ 'Try a safer source image or a milder prompt.',
+].join(' ');
+const IMAGE_GENERATION_NO_IMAGE_MESSAGE = [
+ 'The provider did not return an image.',
+ 'This may be due to content review.',
+ 'Try a milder prompt or another model.',
+].join(' ');
+
+interface CategorizeImageGenerationErrorOptions {
+ error: ImageGenerationErrorLike;
+ isAborted: boolean;
+ isEditingImage: boolean;
+ providerContentPolicyMessage?: string;
+}
+
+interface ImageGenerationErrorLike {
+ body?: string | { detail: string };
+ error?: {
+ message?: string;
+ providerReason?: string;
+ reasonCode?: string;
+ responseId?: string;
+ };
+ errorType?: string;
+ message?: string;
+ name?: string;
+ status?: number;
+}
+
+interface CategorizedImageGenerationError {
+ errorMessage: string;
+ errorType: AsyncTaskErrorType;
+}
+
+export const categorizeImageGenerationError = ({
+ error,
+ isAborted,
+ isEditingImage,
+ providerContentPolicyMessage,
+}: CategorizeImageGenerationErrorOptions): CategorizedImageGenerationError => {
+ // Handle Comfy UI errors
+ if (error.errorType === AgentRuntimeErrorType.ComfyUIServiceUnavailable) {
+ return {
+ errorMessage:
+ error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIServiceUnavailable,
+ errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ComfyUIBizError) {
+ return {
+ errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIBizError,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ComfyUIWorkflowError) {
+ return {
+ errorMessage:
+ error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIWorkflowError,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ComfyUIModelError) {
+ return {
+ errorMessage:
+ error.error?.message || error.message || AgentRuntimeErrorType.ComfyUIModelError,
+ errorType: AsyncTaskErrorType.ModelNotFound,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ConnectionCheckFailed) {
+ return {
+ errorMessage: error.message || AgentRuntimeErrorType.ConnectionCheckFailed,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.PermissionDenied) {
+ return {
+ errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.PermissionDenied,
+ errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ModelNotFound) {
+ return {
+ errorMessage: error.error?.message || error.message || AgentRuntimeErrorType.ModelNotFound,
+ errorType: AsyncTaskErrorType.ModelNotFound,
+ };
+ }
+
+ if (providerContentPolicyMessage) {
+ return {
+ errorMessage: providerContentPolicyMessage,
+ errorType: AsyncTaskErrorType.ProviderContentModeration,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ProviderContentPolicyViolation) {
+ return {
+ errorMessage: CONTENT_POLICY_ERROR_MESSAGE,
+ errorType: AsyncTaskErrorType.ProviderContentModeration,
+ };
+ }
+
+ if (error.errorType === AgentRuntimeErrorType.ProviderNoImageGenerated) {
+ const providerErrorMessage = error.error?.message || error.message;
+
+ if (
+ (error.error?.reasonCode === 'google_image_text_only_response' ||
+ error.error?.reasonCode === 'google_image_generation_refused') &&
+ typeof providerErrorMessage === 'string'
+ ) {
+ return {
+ errorMessage: providerErrorMessage,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ return {
+ errorMessage: isEditingImage
+ ? IMAGE_EDITING_NO_IMAGE_MESSAGE
+ : IMAGE_GENERATION_NO_IMAGE_MESSAGE,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ // FIXME: 401 errors should be handled in agentRuntime for better practice
+ if (error.errorType === AgentRuntimeErrorType.InvalidProviderAPIKey || error?.status === 401) {
+ return {
+ errorMessage:
+ error.error?.message || error.message || AgentRuntimeErrorType.InvalidProviderAPIKey,
+ errorType: AsyncTaskErrorType.InvalidProviderAPIKey,
+ };
+ }
+
+ const fallbackContentPolicyMessage = getContentPolicyErrorMessage(error);
+ if (fallbackContentPolicyMessage) {
+ return {
+ errorMessage: fallbackContentPolicyMessage,
+ errorType: AsyncTaskErrorType.ProviderContentModeration,
+ };
+ }
+
+ if (error instanceof AsyncTaskError) {
+ return {
+ errorMessage: typeof error.body === 'string' ? error.body : error.body.detail,
+ errorType: error.name as AsyncTaskErrorType,
+ };
+ }
+
+ if (isAborted || error.message?.includes('aborted')) {
+ return {
+ errorMessage: AsyncTaskErrorType.Timeout,
+ errorType: AsyncTaskErrorType.Timeout,
+ };
+ }
+
+ if (error.message?.includes('timeout') || error.name === 'TimeoutError') {
+ return {
+ errorMessage: AsyncTaskErrorType.Timeout,
+ errorType: AsyncTaskErrorType.Timeout,
+ };
+ }
+
+ if (error.message?.includes('network') || error.name === 'NetworkError') {
+ return {
+ errorMessage: error.message || AsyncTaskErrorType.ServerError,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
+ return {
+ errorMessage: error.message || error.error?.message || AsyncTaskErrorType.ServerError,
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+};
diff --git a/src/utils/errorResponse.test.ts b/src/utils/errorResponse.test.ts
index 3950b7880c5..7d41cafba16 100644
--- a/src/utils/errorResponse.test.ts
+++ b/src/utils/errorResponse.test.ts
@@ -74,6 +74,12 @@ describe('createErrorResponse', () => {
expect(response.status).toBe(471);
});
+ it('returns a 471 status for ProviderContentPolicyViolation error type', () => {
+ const errorType = AgentRuntimeErrorType.ProviderContentPolicyViolation;
+ const response = createErrorResponse(errorType);
+ expect(response.status).toBe(471);
+ });
+
it('returns a 470 status for AgentRuntimeError error type', () => {
const errorType = AgentRuntimeErrorType.AgentRuntimeError;
const response = createErrorResponse(errorType);
diff --git a/src/utils/errorResponse.ts b/src/utils/errorResponse.ts
index bc2604d6d95..3a3492a3ef1 100644
--- a/src/utils/errorResponse.ts
+++ b/src/utils/errorResponse.ts
@@ -58,7 +58,8 @@ const getStatus = (errorType: ILobeAgentRuntimeErrorType | ErrorType) => {
return 470;
}
- case AgentRuntimeErrorType.ProviderBizError: {
+ case AgentRuntimeErrorType.ProviderBizError:
+ case AgentRuntimeErrorType.ProviderContentPolicyViolation: {
return 471;
}