🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: Optimize Gemini error message display & Filter empty messages (#8489)
sxjeru5b409ccfa28b
diff --git a/src/libs/model-runtime/google/index.ts b/src/libs/model-runtime/google/index.tsindex 86c5a3eb919..05e2d043381 100644--- a/src/libs/model-runtime/google/index.ts+++ b/src/libs/model-runtime/google/index.ts@@ -14,7 +14,7 @@ import { imageUrlToBase64 } from '@/utils/imageToBase64';import { safeParseJSON } from '@/utils/safeParseJSON';import { LobeRuntimeAI } from '../BaseAI';-import { AgentRuntimeErrorType, ILobeAgentRuntimeErrorType } from '../error';+import { AgentRuntimeErrorType } from '../error';import {ChatCompletionTool,ChatMethodOptions,@@ -25,6 +25,7 @@ import {import { CreateImagePayload, CreateImageResponse } from '../types/image';import { AgentRuntimeError } from '../utils/createError';import { debugStream } from '../utils/debugStream';+import { parseGoogleErrorMessage } from '../utils/googleErrorParser';import { StreamingResponse } from '../utils/response';import { GoogleGenerativeAIStream, VertexAIStream } from '../utils/streams';import { parseDataUri } from '../utils/uriParser';@@ -249,7 +250,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {}console.log(err);- const { errorType, error } = this.parseErrorMessage(err.message);+ const { errorType, error } = parseGoogleErrorMessage(err.message);throw AgentRuntimeError.chat({ error, errorType, provider: this.provider });}@@ -292,7 +293,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {const err = error as Error;console.error('Google AI image generation error:', err);- const { errorType, error: parsedError } = this.parseErrorMessage(err.message);+ const { errorType, error: parsedError } = parseGoogleErrorMessage(err.message);throw AgentRuntimeError.createImage({error: parsedError,errorType,@@ -509,59 +510,12 @@ export class LobeGoogleAI implements LobeRuntimeAI {.filter((message) => message.role !== 'function').map(async (msg) => await this.convertOAIMessagesToGoogleMessage(msg, toolCallNameMap));- return Promise.all(pools);+ const contents = await Promise.all(pools);++ // 筛除空消息: contents.parts must not be empty.+ return contents.filter((content: Content) => content.parts && content.parts.length > 0);};- private parseErrorMessage(message: string): {- error: any;- errorType: ILobeAgentRuntimeErrorType;- } {- const defaultError = {- error: { message },- errorType: AgentRuntimeErrorType.ProviderBizError,- };-- if (message.includes('location is not supported'))- return { error: { message }, errorType: AgentRuntimeErrorType.LocationNotSupportError };-- const startIndex = message.lastIndexOf('[');- if (startIndex === -1) {- return defaultError;- }-- try {- // 从开始位置截取字符串到最后- const jsonString = message.slice(startIndex);-- // 尝试解析 JSON 字符串- const json: GoogleChatErrors = JSON.parse(jsonString);-- const bizError = json[0];-- switch (bizError.reason) {- case 'API_KEY_INVALID': {- return { ...defaultError, errorType: AgentRuntimeErrorType.InvalidProviderAPIKey };- }-- default: {- return { error: json, errorType: AgentRuntimeErrorType.ProviderBizError };- }- }- } catch {- //- }-- const errorObj = this.extractErrorObjectFromError(message);-- const { errorDetails } = errorObj;-- if (errorDetails) {- return { error: errorDetails, errorType: AgentRuntimeErrorType.ProviderBizError };- }-- return defaultError;- }-private buildGoogleTools(tools: ChatCompletionTool[] | undefined,payload?: ChatStreamPayload,@@ -610,50 +564,6 @@ export class LobeGoogleAI implements LobeRuntimeAI {};};- private extractErrorObjectFromError(message: string) {- // 使用正则表达式匹配状态码部分 [数字 描述文本]- const regex = /^(.*?)(\[\d+ [^\]]+])(.*)$/;- const match = message.match(regex);-- if (match) {- const prefix = match[1].trim();- const statusCodeWithBrackets = match[2].trim();- const message = match[3].trim();-- // 提取状态码数字- const statusCodeMatch = statusCodeWithBrackets.match(/\[(\d+)/);- const statusCode = statusCodeMatch ? parseInt(statusCodeMatch[1]) : null;-- // 创建包含状态码和消息的JSON- const resultJson = {- message: message,- statusCode: statusCode,- statusCodeText: statusCodeWithBrackets,- };-- return {- errorDetails: resultJson,- prefix: prefix,- };- }-- // 如果无法匹配,返回原始消息- return {- errorDetails: null,- prefix: message,- };- }}export default LobeGoogleAI;--type GoogleChatErrors = GoogleChatError[];--interface GoogleChatError {- '@type': string;- 'domain': string;- 'metadata': {- service: string;- };- 'reason': string;-}diff --git a/src/libs/model-runtime/utils/googleErrorParser.test.ts b/src/libs/model-runtime/utils/googleErrorParser.test.tsnew file mode 100644index 00000000000..e879bd0c748--- /dev/null+++ b/src/libs/model-runtime/utils/googleErrorParser.test.ts@@ -0,0 +1,228 @@+import { describe, expect, it } from 'vitest';++import { AgentRuntimeErrorType } from '../error';++import {+ cleanErrorMessage,+ extractStatusCodeFromError,+ parseGoogleErrorMessage,+} from './googleErrorParser';++describe('googleErrorParser', () => {+ describe('cleanErrorMessage', () => {+ it('should remove leading asterisk and spaces', () => {+ const input = '* API key not valid. Please check your credentials.';+ const expected = 'API key not valid. Please check your credentials.';+ expect(cleanErrorMessage(input)).toBe(expected);+ });++ it('should convert escaped newlines to actual newlines', () => {+ const input = 'Error occurred\\nPlease try again';+ const expected = 'Error occurred Please try again';+ expect(cleanErrorMessage(input)).toBe(expected);+ });++ it('should replace multiple newlines with single space', () => {+ const input = 'Line 1\n\n\nLine 2\nLine 3';+ const expected = 'Line 1 Line 2 Line 3';+ expect(cleanErrorMessage(input)).toBe(expected);+ });++ it('should trim whitespace', () => {+ const input = ' \t Error message \t ';+ const expected = 'Error message';+ expect(cleanErrorMessage(input)).toBe(expected);+ });++ it('should handle combined formatting issues', () => {+ const input = '* API key not valid.\\nPlease check your credentials.\\n\\nContact support if needed. ';+ const expected = 'API key not valid. Please check your credentials. Contact support if needed.';+ expect(cleanErrorMessage(input)).toBe(expected);+ });+ });++ describe('extractStatusCodeFromError', () => {+ it('should extract status code and message correctly', () => {+ const input = 'Connection failed [503 Service Unavailable] Please try again later';+ const result = extractStatusCodeFromError(input);++ expect(result.errorDetails).toEqual({+ message: 'Please try again later',+ statusCode: 503,+ statusCodeText: '[503 Service Unavailable]',+ });+ expect(result.prefix).toBe('Connection failed');+ });++ it('should handle different status codes', () => {+ const input = 'Request failed [401 Unauthorized] Invalid credentials';+ const result = extractStatusCodeFromError(input);++ expect(result.errorDetails).toEqual({+ message: 'Invalid credentials',+ statusCode: 401,+ statusCodeText: '[401 Unauthorized]',+ });+ expect(result.prefix).toBe('Request failed');+ });++ it('should return null for messages without status codes', () => {+ const input = 'Simple error message without status code';+ const result = extractStatusCodeFromError(input);++ expect(result.errorDetails).toBeNull();+ expect(result.prefix).toBe('Simple error message without status code');+ });++ it('should handle empty message after status code', () => {+ const input = 'Error [404 Not Found]';+ const result = extractStatusCodeFromError(input);++ expect(result.errorDetails).toEqual({+ message: '',+ statusCode: 404,+ statusCodeText: '[404 Not Found]',+ });+ expect(result.prefix).toBe('Error');+ });+ });++ describe('parseGoogleErrorMessage', () => {+ it('should handle location not supported error', () => {+ const input = 'This location is not supported for Google AI services';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.LocationNotSupportError);+ expect(result.error.message).toBe(input);+ });++ it('should handle status JSON format', () => {+ const input = 'got status: UNAVAILABLE. {"error":{"code":503,"message":"Service temporarily unavailable","status":"UNAVAILABLE"}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toEqual({+ code: 503,+ message: 'Service temporarily unavailable',+ status: 'UNAVAILABLE',+ });+ });++ it('should handle direct JSON parsing', () => {+ const input = '{"error":{"code":400,"message":"* API key not valid. Please pass a valid API key.","status":"INVALID_ARGUMENT"}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);+ expect(result.error).toEqual({+ code: 400,+ message: 'API key not valid. Please pass a valid API key.',+ status: 'INVALID_ARGUMENT',+ });+ });++ it('should handle quota limit error', () => {+ const input = '{"error":{"code":429,"message":"Quota limit reached","status":"RESOURCE_EXHAUSTED"}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.QuotaLimitReached);+ expect(result.error).toEqual({+ code: 429,+ message: 'Quota limit reached',+ status: 'RESOURCE_EXHAUSTED',+ });+ });++ it('should handle nested JSON format', () => {+ const input = '{"error":{"message":"{\\"error\\":{\\"code\\":400,\\"message\\":\\"Invalid request\\"}}"}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toEqual({+ code: 400,+ message: 'Invalid request',+ status: '',+ });+ });++ it('should handle array format with API_KEY_INVALID', () => {+ const input = 'Request failed [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "API_KEY_INVALID", "domain": "googleapis.com"}]';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);+ });++ it('should handle array format with other errors', () => {+ const input = 'Request failed [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "QUOTA_EXCEEDED", "domain": "googleapis.com"}]';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toEqual([{+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",+ "reason": "QUOTA_EXCEEDED",+ "domain": "googleapis.com"+ }]);+ });++ it('should handle status code extraction fallback', () => {+ const input = 'Connection failed [503 Service Unavailable] Please try again later';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toEqual({+ message: 'Please try again later',+ statusCode: 503,+ statusCodeText: '[503 Service Unavailable]',+ });+ });++ it('should handle complex nested JSON with message cleaning', () => {+ const input = '{"error":{"code":400,"message":"* Request contains invalid parameters\\nPlease check the documentation\\n\\nContact support for help"}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error.message).toBe('Request contains invalid parameters Please check the documentation Contact support for help');+ });++ it('should return default error for unparseable messages', () => {+ const input = 'Some random error message that cannot be parsed';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error.message).toBe(input);+ });++ it('should handle malformed JSON gracefully', () => {+ const input = '{"error":{"code":400,"message":"Invalid JSON{incomplete';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error.message).toBe(input);+ });++ it('should handle empty error object in JSON', () => {+ const input = '{"error":{}}';+ const result = parseGoogleErrorMessage(input);++ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toEqual({+ code: null,+ message: input,+ status: '',+ });+ });++ it('should handle recursion depth limit', () => {+ // Create a deeply nested JSON that exceeds the recursion limit+ let deeplyNested = '{"error":{"code":400,"message":"Deep error"}}';+ for (let i = 0; i < 6; i++) {+ deeplyNested = `{"error":{"message":"${deeplyNested.replaceAll('"', '\\"')}"}}`;+ }++ const result = parseGoogleErrorMessage(deeplyNested);++ // Should still return a valid result, but might not reach the deepest level+ expect(result.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);+ expect(result.error).toBeDefined();+ });+ });+});diff --git a/src/libs/model-runtime/utils/googleErrorParser.ts b/src/libs/model-runtime/utils/googleErrorParser.tsnew file mode 100644index 00000000000..26dac1129cb--- /dev/null+++ b/src/libs/model-runtime/utils/googleErrorParser.ts@@ -0,0 +1,228 @@+import { AgentRuntimeErrorType, ILobeAgentRuntimeErrorType } from '../error';++export interface ParsedError {+ error: any;+ errorType: ILobeAgentRuntimeErrorType;+}++export interface GoogleChatError {+ '@type': string;+ 'domain': string;+ 'metadata': {+ service: string;+ };+ 'reason': string;+}++export type GoogleChatErrors = GoogleChatError[];++/**+ * 清理错误消息,移除格式化字符和多余的空格+ * @param message - 原始错误消息+ * @returns 清理后的错误消息+ */+export function cleanErrorMessage(message: string): string {+ return message+ .replaceAll(/^\*\s*/g, '') // 移除开头的星号和空格+ .replaceAll('\\n', '\n') // 转换转义的换行符+ .replaceAll(/\n+/g, ' ') // 将多个换行符替换为单个空格+ .trim(); // 去除首尾空格+}++/**+ * 从错误消息中提取状态码信息+ * @param message - 错误消息+ * @returns 提取的错误详情和前缀+ */+export function extractStatusCodeFromError(message: string): {+ errorDetails: any;+ prefix: string;+} {+ // 使用正则表达式匹配状态码部分 [数字 描述文本]+ const regex = /^(.*?)(\[\d+ [^\]]+])(.*)$/;+ const match = message.match(regex);++ if (match) {+ const prefix = match[1].trim();+ const statusCodeWithBrackets = match[2].trim();+ const messageContent = match[3].trim();++ // 提取状态码数字+ const statusCodeMatch = statusCodeWithBrackets.match(/\[(\d+)/);+ const statusCode = statusCodeMatch ? parseInt(statusCodeMatch[1]) : null;++ // 创建包含状态码和消息的JSON+ const resultJson = {+ message: messageContent,+ statusCode: statusCode,+ statusCodeText: statusCodeWithBrackets,+ };++ return {+ errorDetails: resultJson,+ prefix: prefix,+ };+ }++ // 如果无法匹配,返回原始消息+ return {+ errorDetails: null,+ prefix: message,+ };+}++/**+ * 解析Google AI API返回的错误消息+ * @param message - 原始错误消息+ * @returns 解析后的错误对象和错误类型+ */+export function parseGoogleErrorMessage(message: string): ParsedError {+ const defaultError = {+ error: { message },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ };++ // 快速识别特殊错误+ if (message.includes('location is not supported')) {+ return { error: { message }, errorType: AgentRuntimeErrorType.LocationNotSupportError };+ }++ // 统一的错误类型判断函数+ const getErrorType = (code: number | null, message: string): ILobeAgentRuntimeErrorType => {+ if (code === 400 && message.includes('API key not valid')) {+ return AgentRuntimeErrorType.InvalidProviderAPIKey;+ } else if (code === 429) {+ return AgentRuntimeErrorType.QuotaLimitReached;+ }+ return AgentRuntimeErrorType.ProviderBizError;+ };++ // 递归解析JSON,处理嵌套的JSON字符串+ const parseJsonRecursively = (str: string, maxDepth: number = 5): any => {+ if (maxDepth <= 0) return null;++ try {+ const parsed = JSON.parse(str);++ // 如果解析出的对象包含error字段+ if (parsed && typeof parsed === 'object' && parsed.error) {+ const errorInfo = parsed.error;++ // 清理错误消息+ if (typeof errorInfo.message === 'string') {+ errorInfo.message = cleanErrorMessage(errorInfo.message);++ // 如果error.message还是一个JSON字符串,继续递归解析+ try {+ const nestedResult = parseJsonRecursively(errorInfo.message, maxDepth - 1);+ // 只有当深层结果包含带有 code 的 error 对象时,才优先返回深层结果+ if (nestedResult && nestedResult.error && nestedResult.error.code) {+ return nestedResult;+ }+ } catch {+ // 如果嵌套解析失败,使用当前层的信息+ }+ }++ return parsed;+ }++ return parsed;+ } catch {+ return null;+ }+ };++ // 1. 处理 "got status: UNAVAILABLE. {JSON}" 格式+ const statusJsonMatch = message.match(/got status: (\w+)\.\s*({.*})$/);+ if (statusJsonMatch) {+ const statusFromMessage = statusJsonMatch[1];+ const jsonPart = statusJsonMatch[2];++ const parsedError = parseJsonRecursively(jsonPart);+ if (parsedError && parsedError.error) {+ const errorInfo = parsedError.error;+ const finalMessage = errorInfo.message || message;+ const finalCode = errorInfo.code || null;+ const finalStatus = errorInfo.status || statusFromMessage;++ return {+ error: {+ code: finalCode,+ message: finalMessage,+ status: finalStatus,+ },+ errorType: getErrorType(finalCode, finalMessage),+ };+ }+ }++ // 2. 尝试直接解析整个消息作为JSON+ const directParsed = parseJsonRecursively(message);+ if (directParsed && directParsed.error) {+ const errorInfo = directParsed.error;+ const finalMessage = errorInfo.message || message;+ const finalCode = errorInfo.code || null;+ const finalStatus = errorInfo.status || '';++ return {+ error: {+ code: finalCode,+ message: finalMessage,+ status: finalStatus,+ },+ errorType: getErrorType(finalCode, finalMessage),+ };+ }++ // 3. 处理嵌套JSON格式,特别是message字段包含JSON的情况+ try {+ const firstLevelParsed = JSON.parse(message);+ if (firstLevelParsed && firstLevelParsed.error && firstLevelParsed.error.message) {+ const nestedParsed = parseJsonRecursively(firstLevelParsed.error.message);+ if (nestedParsed && nestedParsed.error) {+ const errorInfo = nestedParsed.error;+ const finalMessage = errorInfo.message || message;+ const finalCode = errorInfo.code || null;+ const finalStatus = errorInfo.status || '';++ return {+ error: {+ code: finalCode,+ message: finalMessage,+ status: finalStatus,+ },+ errorType: getErrorType(finalCode, finalMessage),+ };+ }+ }+ } catch {+ // 继续其他解析方式+ }++ // 4. 原有的数组格式解析逻辑+ const startIndex = message.lastIndexOf('[');+ if (startIndex !== -1) {+ try {+ const jsonString = message.slice(startIndex);+ const json: GoogleChatErrors = JSON.parse(jsonString);+ const bizError = json[0];++ if (bizError?.reason === 'API_KEY_INVALID') {+ return { ...defaultError, errorType: AgentRuntimeErrorType.InvalidProviderAPIKey };+ }++ return { error: json, errorType: AgentRuntimeErrorType.ProviderBizError };+ } catch {+ // 忽略解析错误+ }+ }++ // 5. 使用状态码提取逻辑作为最后的后备方案+ const errorObj = extractStatusCodeFromError(message);+ if (errorObj.errorDetails) {+ return { error: errorObj.errorDetails, errorType: AgentRuntimeErrorType.ProviderBizError };+ }++ return defaultError;+}