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.

💄 style: enhance handling of blocked content on Gemini (#13270)

sxjeru48b5927024f0
diff --git a/packages/model-runtime/src/core/streams/google/const.ts b/packages/model-runtime/src/core/streams/google/const.ts
index adaa3fb3d58..69edaac3350 100644
--- a/packages/model-runtime/src/core/streams/google/const.ts
+++ b/packages/model-runtime/src/core/streams/google/const.ts
@@ -1,17 +1,13 @@
export const GOOGLE_AI_BLOCK_REASON = {
- BLOCKLIST:
- 'Your content contains prohibited terms. Please review and modify your input, then try again.',
+ BLOCKLIST: 'The content includes blocked terms. Please rephrase and try again.',
IMAGE_SAFETY:
- 'The generated image was blocked for safety reasons. Please try modifying your image request.',
- LANGUAGE:
- 'The language you are using is not supported. Please try again in English or another supported language.',
- OTHER: 'The content was blocked for an unknown reason. Please try rephrasing your request.',
- PROHIBITED_CONTENT:
- 'Your request may contain prohibited content. Please adjust your request to comply with the usage guidelines.',
+ 'The generated image was blocked for safety reasons. Please try modifying your request.',
+ LANGUAGE: "The requested language isn't supported. Please try again in a supported language.",
+ OTHER: 'The content was blocked for an unknown reason. Please rephrase and try again.',
+ PROHIBITED_CONTENT: 'The content may contain prohibited content. Please adjust it and try again.',
RECITATION:
- 'Your content was blocked due to potential copyright concerns. Please try using original content or rephrase your request.',
- SAFETY:
- 'Your content was blocked for safety policy reasons. Please adjust your request to avoid potentially harmful or inappropriate content.',
- SPII: 'Your content may contain sensitive personally identifiable information (PII). To protect privacy, please remove any sensitive details and try again.',
- default: 'Content blocked: {{blockReason}}. Please adjust your request and try again.',
+ 'The content was blocked due to recitation risk. Please use more original wording and try again.',
+ SAFETY: 'The content was blocked for safety reasons. Please adjust it and try again.',
+ SPII: 'The content may include sensitive personal information (SPII). Please remove sensitive details and try again.',
+ default: 'The content was blocked ({{blockReason}}). Please adjust it and try again.',
} as const;
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 90a4e9978de..3b4aff0572f 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -1646,7 +1646,49 @@ describe('GoogleGenerativeAIStream', () => {
expect(chunks).toEqual([
'id: chat_1\n',
'event: error\n',
- `data: {"body":{"context":{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"}},"message":"Your request may contain prohibited content. Please adjust your request to comply with the usage guidelines.","provider":"google"},"type":"ProviderBizError"}\n\n`,
+ `data: {"body":{"context":{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"}},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderBizError"}\n\n`,
+ ]);
+ });
+
+ it('should handle blocked candidate finishReason (PROHIBITED_CONTENT)', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = {
+ candidates: [
+ {
+ content: {},
+ finishMessage:
+ 'The model output could not be generated. This output contains sensitive words that violate policies.',
+ finishReason: 'PROHIBITED_CONTENT',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 2,
+ promptTokenCount: 10,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ totalTokenCount: 12,
+ },
+ modelVersion: 'gemini-3.1-flash-lite-preview',
+ };
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(data);
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const chunks = await decodeStreamChunks(protocolStream);
+
+ expect(chunks).toEqual([
+ 'id: chat_1\n',
+ 'event: usage\n',
+ `data: {"inputTextTokens":10,"outputImageTokens":0,"outputTextTokens":2,"totalInputTokens":10,"totalOutputTokens":2,"totalTokens":12}\n\n`,
+ 'id: chat_1\n',
+ 'event: error\n',
+ `data: {"body":{"context":{"finishMessage":"The model output could not be generated. This output contains sensitive words that violate policies.","finishReason":"PROHIBITED_CONTENT"},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderBizError"}\n\n`,
]);
});
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index 67697be3c1a..4f042e93fe1 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -30,6 +30,18 @@ const getBlockReasonMessage = (blockReason: string): string => {
);
};
+const getCandidateBlockedReason = (
+ candidate: NonNullable<GenerateContentResponse['candidates']>[number] | undefined,
+) => {
+ const finishReason = candidate?.finishReason;
+
+ if (!finishReason || typeof finishReason !== 'string') return undefined;
+
+ if (finishReason in GOOGLE_AI_BLOCK_REASON) return finishReason;
+
+ return undefined;
+};
+
const transformGoogleGenerativeAIStream = (
chunk: GenerateContentResponse,
context: StreamContext,
@@ -67,6 +79,37 @@ const transformGoogleGenerativeAIStream = (
// maybe need another structure to add support for multiple choices
const candidate = chunk.candidates?.[0];
const { usageMetadata } = chunk;
+
+ // Handle blocked terminal candidate finishReason (e.g., PROHIBITED_CONTENT, SAFETY)
+ const blockedReason = getCandidateBlockedReason(candidate);
+ if (blockedReason) {
+ const convertedUsage = usageMetadata
+ ? convertGoogleAIUsage(usageMetadata, payload?.pricing)
+ : undefined;
+ const humanFriendlyMessage = getBlockReasonMessage(blockedReason);
+
+ return [
+ ...(convertedUsage
+ ? [{ data: convertedUsage, id: context?.id, type: 'usage' as const }]
+ : []),
+ {
+ data: {
+ body: {
+ context: {
+ finishMessage: (candidate as any)?.finishMessage,
+ finishReason: blockedReason,
+ },
+ message: humanFriendlyMessage,
+ provider: 'google',
+ },
+ type: 'ProviderBizError',
+ },
+ id: context?.id || 'error',
+ type: 'error' as const,
+ },
+ ];
+ }
+
const usageChunks: StreamProtocolChunk[] = [];
if (candidate?.finishReason && usageMetadata) {
usageChunks.push({ data: candidate.finishReason, id: context?.id, type: 'stop' });
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index 0ca157d8c9e..fb22daa4f8e 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -61,6 +61,14 @@ const AssistantMessage = memo<AssistantMessageProps>(({ id, index, disableEditin
const errorContent = useErrorContent(error);
+ const shouldForceShowError =
+ error?.type === 'ProviderBizError' &&
+ (error?.body as any)?.provider === 'google' &&
+ !!(
+ (error?.body as any)?.context?.promptFeedback?.blockReason ||
+ (error?.body as any)?.context?.finishReason
+ );
+
// remove line breaks in artifact tag to make the ast transform easier
const message = !editing ? normalizeThinkTags(processWithArtifact(content)) : content;
@@ -103,7 +111,9 @@ const AssistantMessage = memo<AssistantMessageProps>(({ id, index, disableEditin
</>
}
error={
- errorContent && error && (message === LOADING_FLAT || !message) ? errorContent : undefined
+ errorContent && error && (message === LOADING_FLAT || !message || shouldForceShowError)
+ ? errorContent
+ : undefined
}
messageExtra={
<AssistantMessageExtra
diff --git a/src/locales/default/error.ts b/src/locales/default/error.ts
index ed6e74cd1ed..b3e59c6e88e 100644
--- a/src/locales/default/error.ts
+++ b/src/locales/default/error.ts
@@ -125,23 +125,23 @@ export default {
'response.InsufficientBudgetForModel':
'Your remaining credits are insufficient for this model. Please top up credits, upgrade your plan, or try a less expensive model.',
'response.GoogleAIBlockReason.BLOCKLIST':
- 'Your content contains prohibited terms. Please review and modify your input, then try again.',
+ 'The content includes blocked terms. Please rephrase and try again.',
'response.GoogleAIBlockReason.IMAGE_SAFETY':
- 'The generated image was blocked for safety reasons. Please try modifying your image request.',
+ 'The generated image was blocked for safety reasons. Please try modifying your request.',
'response.GoogleAIBlockReason.LANGUAGE':
- 'The language you are using is not supported. Please try again in English or another supported language.',
+ "The requested language isn't supported. Please try again in a supported language.",
'response.GoogleAIBlockReason.OTHER':
- 'The content was blocked for an unknown reason. Please try rephrasing your request.',
+ 'The content was blocked for an unknown reason. Please rephrase and try again.',
'response.GoogleAIBlockReason.PROHIBITED_CONTENT':
- 'Your request may contain prohibited content. Please adjust your request to comply with the usage guidelines.',
+ 'The content may contain prohibited content. Please adjust it and try again.',
'response.GoogleAIBlockReason.RECITATION':
- 'Your content was blocked due to potential copyright concerns. Please try using original content or rephrase your request.',
+ 'The content was blocked due to recitation risk. Please use more original wording and try again.',
'response.GoogleAIBlockReason.SAFETY':
- 'Your content was blocked for safety policy reasons. Please adjust your request to avoid potentially harmful or inappropriate content.',
+ 'The content was blocked for safety reasons. Please adjust it and try again.',
'response.GoogleAIBlockReason.SPII':
- 'Your content may contain sensitive personally identifiable information (PII). To protect privacy, please remove any sensitive details and try again.',
+ 'The content may include sensitive personal information (SPII). Please remove sensitive details and try again.',
'response.GoogleAIBlockReason.default':
- 'Content blocked: {{blockReason}}. Please adjust your request and try again.',
+ 'The content was blocked ({{blockReason}}). Please adjust it and try again.',
'response.InsufficientQuota':
"Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.",
'response.InvalidAccessCode':
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
index 29f9b2535c4..55cc4532efa 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
@@ -1672,4 +1672,59 @@ describe('call_llm executor', () => {
expect(mockStore.optimisticCreateMessage).toHaveBeenCalled();
});
});
+
+ describe('Google blocked stream errors', () => {
+ it('should keep normal content and update message error state', async () => {
+ // Given
+ const mockStore = createMockStore();
+ const context = createTestContext();
+ const instruction = createCallLLMInstruction();
+ const state = createInitialState();
+
+ mockStore.dbMessagesMap[context.messageKey] = [];
+
+ vi.mocked(chatService.createAssistantMessageStream).mockImplementation(
+ async (params: any) => {
+ if (params.onMessageHandle) {
+ await params.onMessageHandle({ text: 'Partial output', type: 'text' });
+ }
+
+ if (params.onErrorHandle) {
+ params.onErrorHandle({
+ body: {
+ context: {
+ finishReason: 'PROHIBITED_CONTENT',
+ },
+ provider: 'google',
+ },
+ message:
+ 'Your request may contain prohibited content. Please adjust your request to comply with the usage guidelines.',
+ type: 'ProviderBizError',
+ });
+ }
+
+ if (params.onFinish) {
+ await params.onFinish('Partial output', { type: 'error' });
+ }
+ },
+ );
+
+ // When
+ await executeWithMockContext({
+ executor: 'call_llm',
+ instruction,
+ state,
+ mockStore,
+ context,
+ });
+
+ // Then
+ expect(mockStore.optimisticUpdateMessageError).toHaveBeenCalled();
+
+ const contentCall = vi.mocked(mockStore.optimisticUpdateMessageContent).mock.calls.at(-1);
+ const finalContent = contentCall?.[1] as string;
+
+ expect(finalContent).toBe('Partial output');
+ });
+ });
});
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 8520721999e..5ef7c40d412 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -23,6 +23,7 @@ import { isDesktop } from '@lobechat/const';
import type { ToolsEngine } from '@lobechat/context-engine';
import { chainCompressContext } from '@lobechat/prompts';
import {
+ type ChatMessageError,
type ChatToolPayload,
type ConversationContext,
type CreateMessageParams,
@@ -32,6 +33,7 @@ import {
} from '@lobechat/types';
import { dedupeBy } from '@lobechat/utils';
import debug from 'debug';
+import { t } from 'i18next';
import pMap from 'p-map';
import { LOADING_FLAT } from '@/const/message';
@@ -68,6 +70,69 @@ const isAbortError = (error: unknown, abortController?: AbortController) =>
const createAbortError = () =>
Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });
+const getGoogleBlockedReason = (error: ChatMessageError): string | undefined => {
+ const body = error.body as
+ | {
+ context?: {
+ finishReason?: unknown;
+ promptFeedback?: {
+ blockReason?: unknown;
+ };
+ };
+ provider?: unknown;
+ }
+ | undefined;
+
+ if (body?.provider !== 'google') return undefined;
+
+ const promptFeedbackReason = body.context?.promptFeedback?.blockReason;
+ if (typeof promptFeedbackReason === 'string') return promptFeedbackReason;
+
+ const finishReason = body.context?.finishReason;
+ if (typeof finishReason === 'string') return finishReason;
+
+ return undefined;
+};
+
+const localizeGoogleBlockedError = (error: ChatMessageError): ChatMessageError => {
+ const blockReason = getGoogleBlockedReason(error);
+ if (!blockReason) return error;
+
+ const translationKey = `response.GoogleAIBlockReason.${blockReason}`;
+ const localized = t(translationKey as any, {
+ defaultValue: error.message ?? '',
+ ns: 'error',
+ }).trim();
+
+ if (!localized || localized === translationKey) return error;
+
+ const normalizedBody =
+ error.body && typeof error.body === 'object' ? (error.body as Record<string, any>) : {};
+
+ return {
+ ...error,
+ body: {
+ ...normalizedBody,
+ message: localized,
+ },
+ message: localized,
+ };
+};
+
+const localizeError = (error: ChatMessageError): ChatMessageError => {
+ const body = error.body as
+ | {
+ provider?: unknown;
+ }
+ | undefined;
+
+ if (body?.provider === 'google') {
+ return localizeGoogleBlockedError(error);
+ }
+
+ return error;
+};
+
/**
* Creates custom executors for the Chat Agent Runtime
* These executors wrap existing chat store methods to integrate with agent-runtime
@@ -247,7 +312,7 @@ export const createAgentExecutors = (context: {
const fetchContext = { ...operation.context, agentId };
- const { agentConfig: agentConfigData, chatConfig } = context.agentConfig;
+ const { agentConfig: agentConfigData } = context.agentConfig;
let finalUsage: ModelUsage | undefined;
let finalToolCalls: MessageToolCall[] | undefined;
@@ -411,7 +476,9 @@ export const createAgentExecutors = (context: {
traceName: TraceNameMap.Conversation,
},
onErrorHandle: async (error) => {
- await context.get().optimisticUpdateMessageError(assistantMessageId, error, {
+ const localizedError = localizeError(error);
+
+ await context.get().optimisticUpdateMessageError(assistantMessageId, localizedError, {
operationId: context.operationId,
});
},