🤯 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(agent): stop retries for empty completions (#17418)
YuTengjing174b03976ce3
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 2fbbbf97012..cf03e756070 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -1105,63 +1105,50 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});});- it('retries empty completions on the branded provider then throws ModelEmptyError', async () => {- // A "gave up" turn: no onText / onThinking / onToolsCalling and ~0 output- // tokens — mirrors the empty completion repro (provider=lobehub, `out=1 token`).- // The branded provider has 0 general retries, but empty completions get a- // dedicated budget so the request is still re-issued before failing.- vi.useFakeTimers();- try {- const mockChat = vi.fn().mockImplementation(async (_payload, options) => {- await options?.callback?.onCompletion?.({- usage: { totalInputTokens: 100, totalOutputTokens: 1, totalTokens: 101 },- });- return new Response('done');+ it('stops immediately when the provider returns an empty completion with output usage', async () => {+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {+ await options?.callback?.onCompletion?.({+ usage: {+ cost: 5.980_015,+ totalInputTokens: 100,+ totalOutputTokens: 25_617,+ totalTokens: 25_717,+ },});- // initModelRuntimeFromDB resolves once before the retry loop; the same- // empty mockChat is then re-invoked on every attempt.- vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);-- const executors = createRuntimeExecutors(ctx);- const state = createMockState();+ return new Response('done');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);- const promise = executors.call_llm!(- {- payload: {- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-v4-pro',- provider: 'lobehub',- tools: [],- },- type: 'call_llm' as const,+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();+ const error = await executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-pro',+ provider: 'lobehub',+ tools: [],},- state,- );- // Drive the retry backoff sleeps to completion.- const rejection = promise.catch((error) => error);- await vi.runAllTimersAsync();- // Must throw (so the harness records a readable error state) instead of- // silently finalizing to a completion with a blank assistant message.- const error = await rejection;- expect(error).toBeInstanceOf(ModelEmptyError);- // EMPTY_COMPLETION_MAX_RETRIES (2) retries → 3 total attempts.- expect(mockChat).toHaveBeenCalledTimes(3);- expect(error.diagnostics).toMatchObject({- attempt: 3,- maxAttempts: 3,- model: 'deepseek-v4-pro',- outputTokens: 1,- provider: 'lobehub',- retryBudget: 2,- retryEvents: [- expect.objectContaining({ attempt: 2, delayMs: 1000, maxAttempts: 3 }),- expect.objectContaining({ attempt: 3, delayMs: 2000, maxAttempts: 3 }),- ],- toolCallCount: 0,- });- } finally {- vi.useRealTimers();- }+ type: 'call_llm' as const,+ },+ state,+ ).catch((cause) => cause);++ expect(error).toBeInstanceOf(ModelEmptyError);+ expect(mockChat).toHaveBeenCalledTimes(1);+ expect(error.diagnostics).toMatchObject({+ attempt: 1,+ cost: 5.980_015,+ maxAttempts: 1,+ model: 'deepseek-v4-pro',+ outputTokens: 25_617,+ provider: 'lobehub',+ toolCallCount: 0,+ });+ expect(mockStreamManager.publishStreamEvent).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ type: 'stream_retry' }),+ );});it('does NOT treat a content-bearing completion as empty', async () => {diff --git a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.tsindex 2ccff23eaf8..24d2840eaa4 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts@@ -72,6 +72,7 @@ describe('classifyLLMError', () => {['CapabilityNotSupported', 'The model is not a VLM'],['LocationNotSupportError', 'service unavailable in this region'],['ExceededToolLimit', 'tools array exceeds limit'],+ ['ModelEmptyCompletion', 'model returned an empty completion'],])('classifies %s as stop (no HTTP status)', (errorType, message) => {expect(classifyLLMError({ errorType, message }).kind).toBe('stop');});@@ -82,13 +83,12 @@ describe('classifyLLMError', () => {['ProviderServiceUnavailable', 'upstream temporarily overloaded'],['ProviderNetworkError', 'connection timed out'],['RateLimitExceeded', 'tokens per minute (TPM)'],- ['ModelEmptyCompletion', 'model returned an empty completion'],])('classifies %s as retry (no HTTP status)', (errorType, message) => {expect(classifyLLMError({ errorType, message }).kind).toBe('retry');});- it('classifies a thrown ModelEmptyError instance as retry', () => {- expect(classifyLLMError(new ModelEmptyError()).kind).toBe('retry');+ it('classifies a thrown ModelEmptyError instance as stop', () => {+ expect(classifyLLMError(new ModelEmptyError()).kind).toBe('stop');});});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex b7ada46d7a8..a20272320b7 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -17,7 +17,6 @@ import { BRANDING_PROVIDER } from '@lobechat/business-const';import {type ChatStreamPayload,consumeStreamUntilDone,- ModelEmptyError,type ModelRuntime,} from '@lobechat/model-runtime';import {@@ -51,7 +50,6 @@ const getErrorMessage = (error: unknown): string => {};const SERVER_LLM_RETRY_POLICY = {- isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,noRetryProviders: [BRANDING_PROVIDER],};@@ -66,14 +64,7 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {return resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);}- onError({ error, events, retryBudget }: LLMCallErrorInput) {- if (error instanceof ModelEmptyError && error.diagnostics) {- error.diagnostics.retryBudget = retryBudget;- error.diagnostics.retryEvents = events- .filter((event) => event.type === 'stream_retry')- .map((event) => event.data);- }-+ onError({ error }: LLMCallErrorInput) {console.error(`[StreamingLLMExecutor][${this.ctx.operationId}:${this.ctx.stepIndex}] LLM execution failed:`,error,@@ -92,8 +83,8 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {);}- resolveRetryBudget(provider: string, error: unknown) {- return resolveLLMRetryBudget(provider, error, SERVER_LLM_RETRY_POLICY);+ resolveRetryBudget(provider: string) {+ return resolveLLMRetryBudget(provider, SERVER_LLM_RETRY_POLICY);}async waitForRetry(delayMs: number): Promise<void> {diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex e4a795f109b..7df19e6a15b 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -286,7 +286,7 @@ export class ServerCallLlmAttempt {!(await isOperationInterrupted(this.ctx))) {log(- '[%s] Model returned an empty completion (attempt %d/%d) — throwing ModelEmptyError to retry',+ '[%s] Model returned an empty completion (attempt %d/%d) — throwing terminal ModelEmptyError',this.operationLogId,this.attempt,this.maxAttempts,@@ -294,6 +294,7 @@ export class ServerCallLlmAttempt {throw new ModelEmptyError(undefined, {attempt: this.attempt,contentLength: this.streamSink.content.length,+ cost: this.usage?.cost,finishReason: this.finishReason,imageCount: this.imageList.length,maxAttempts: this.maxAttempts,diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.tsindex 68e2946ed57..5d8bb3b25b0 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts@@ -82,13 +82,13 @@ describe('formatErrorForState', () => {});});- it('enriches a thrown ModelEmptyError into a readable retryable terminal error', () => {+ it('enriches a thrown ModelEmptyError into a readable non-retryable terminal error', () => {const result = formatErrorForState(new ModelEmptyError(undefined, {- attempt: 3,- maxAttempts: 3,- outputTokens: 1,- retryEvents: [{ attempt: 2, delayMs: 1000, maxAttempts: 3 }],+ attempt: 1,+ cost: 5.980_015,+ maxAttempts: 1,+ outputTokens: 25_617,}),);@@ -98,16 +98,16 @@ describe('formatErrorForState', () => {expect(result.type).toBe(AgentRuntimeErrorType.ModelEmptyCompletion);expect(result.category).toBe('provider');expect(result.attribution).toBe('provider');- expect(result.retryable).toBe(true);+ expect(result.retryable).toBe(false);expect(result.countAsFailure).toBe(true);expect(result.numericId).toBe(8014);expect(result.message).toContain('empty completion');expect(result.body).toMatchObject({diagnostics: {- attempt: 3,- maxAttempts: 3,- outputTokens: 1,- retryEvents: [expect.objectContaining({ attempt: 2 })],+ attempt: 1,+ cost: 5.980_015,+ maxAttempts: 1,+ outputTokens: 25_617,},});});diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.tsindex f6d8abffbd2..0834c24b15f 100644--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts@@ -307,17 +307,13 @@ describe('OperationTraceRecorder', () => {error: {body: {diagnostics: {- attempt: 3,- maxAttempts: 3,- outputTokens: 1,- retryEvents: [- { attempt: 2, delayMs: 1000, maxAttempts: 3, type: 'stream_retry' },- { attempt: 3, delayMs: 2000, maxAttempts: 3, type: 'stream_retry' },- ],+ attempt: 1,+ maxAttempts: 1,+ outputTokens: 25_617,},},message: 'Model returned an empty completion',- retryable: true,+ retryable: false,type: 'ModelEmptyCompletion',},failedStep: { startedAt: 5000, stepIndex: 1, stepType: 'call_llm' },@@ -331,18 +327,16 @@ describe('OperationTraceRecorder', () => {error: {body: {diagnostics: {- attempt: 3,- retryEvents: [- expect.objectContaining({ attempt: 2 }),- expect.objectContaining({ attempt: 3 }),- ],+ attempt: 1,+ maxAttempts: 1,+ outputTokens: 25_617,},},type: 'ModelEmptyCompletion',},type: 'error',});- expect(saved.error.body.diagnostics).toMatchObject({ attempt: 3, maxAttempts: 3 });+ expect(saved.error.body.diagnostics).toMatchObject({ attempt: 1, maxAttempts: 1 });});it('merges the error event into an existing step when stepIndex collides (success-path append landed before later failure)', async () => {diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex 5d670200b8e..82c8be4ac12 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -524,8 +524,11 @@ describe('replyTemplate', () => {expect(renderAgentError('RateLimitExceeded', undefined, 'op-1')).toContain('Too many requests',);- expect(renderAgentError('ModelEmptyCompletion', undefined, 'op-1')).toContain(- 'empty response',+ const emptyCompletion = renderAgentError('ModelEmptyCompletion', undefined, 'op-1');+ expect(emptyCompletion).toContain('empty response');+ expect(emptyCompletion).toContain('may still incur charges');+ expect(renderAgentError('ModelEmptyCompletion', undefined, 'op-1', 'zh-CN')).toContain(+ '仍可能产生费用',);});diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex 5778dac67f4..e9b9c7cf98a 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -306,7 +306,7 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {errorContentModeration:"**Blocked by the content-safety filter.**\nThe model provider's safety filter rejected the request or response. Please rephrase and try again.",errorEmptyCompletion:- "**The model returned an empty response.**\nThe model finished without producing any output. Please try again, or switch to a different model in the agent's settings.",+ "**The model provider returned an empty response.**\nEven without visible content, this request may still incur charges. You can retry, or switch models in the agent's settings and try again.",errorHarnessInternal:'**Something went wrong on our side.**\nThe agent run hit an internal error, which has been logged. Please try again — if it keeps happening, share the Operation ID below with support.',errorInsufficientCredits:@@ -383,7 +383,7 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {errorContentModeration:'**被内容安全策略拦截**\n模型 Provider 的安全策略拒绝了本次请求或回复。请调整内容后重试。',errorEmptyCompletion:- '**模型未返回任何内容**\n模型执行结束但没有产生输出。请重试,或在 Agent 设置中切换到其他模型。',+ '**模型供应商返回了空内容**\n即使没有可显示的内容,本次请求仍可能产生费用。你可以重试,或在 Agent 设置中切换模型后再试。',errorHarnessInternal:'**我们这边出了点问题**\nAgent 执行遇到内部错误,已记录。请重试;如果持续出现,请把下方 Operation ID 提供给支持人员。',errorInsufficientCredits:diff --git a/locales/ar/modelRuntime.json b/locales/ar/modelRuntime.jsonindex f151b179725..95aa9e82da4 100644--- a/locales/ar/modelRuntime.json+++ b/locales/ar/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "عذرًا، رفض المزود المصدر الطلب باعتباره غير صالح. يرجى التحقق من الإدخال أو تجربة نموذج مختلف.","InvalidVertexCredentials": "فشل التحقق من صحة Vertex. يرجى التحقق من بيانات الاعتماد وإعادة المحاولة.","LocationNotSupportError": "نأسف، موقعك الحالي لا يدعم خدمة هذا النموذج. قد يكون ذلك بسبب قيود إقليمية أو عدم توفر الخدمة. يرجى التأكد مما إذا كان الموقع الحالي يدعم استخدام هذه الخدمة، أو حاول استخدام موقع مختلف.",- "ModelEmptyCompletion": "أعاد النموذج استجابة فارغة. عادةً ما يتم حل هذه المشكلة عند المحاولة مرة أخرى؛ إذا استمرت، حاول تبسيط الطلب أو تغيير النموذج.",+ "ModelEmptyCompletion": "أعاد مزود النموذج استجابة فارغة. حتى بدون محتوى مرئي، قد تترتب تكاليف على هذا الطلب. يمكنك المحاولة مرة أخرى أو تغيير النموذج والمحاولة مجددًا.","ModelNotFound": "عذرًا، لم يتم العثور على النموذج المطلوب. قد لا يكون موجودًا أو قد لا تكون لديك الأذونات اللازمة للوصول إليه. يرجى إعادة المحاولة بعد تغيير مفتاح API أو تعديل أذونات الوصول.","NoAvailableChannel": "عذرًا، لا يحتوي الوكيل أو الموجه على قناة متاحة للنموذج المطلوب. يرجى تبديل إعدادات القناة/المفتاح أو إعادة المحاولة لاحقًا.","OllamaBizError": "حدث خطأ أثناء طلب خدمة Ollama، يرجى استكشاف الأخطاء وإصلاحها أو إعادة المحاولة بناءً على المعلومات التالية.",diff --git a/locales/bg-BG/modelRuntime.json b/locales/bg-BG/modelRuntime.jsonindex f5e0bcc73d8..007fac3eb36 100644--- a/locales/bg-BG/modelRuntime.json+++ b/locales/bg-BG/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Съжаляваме, доставчикът отхвърли заявката като неправилно форматирана. Моля, проверете входните данни или опитайте с друг модел.","InvalidVertexCredentials": "Неуспешно удостоверяване във Vertex. Моля, проверете вашите идентификационни данни и опитайте отново.","LocationNotSupportError": "Съжаляваме, вашето текущо местоположение не поддържа тази услуга на модела. Това може да се дължи на регионални ограничения или липса на наличност на услугата. Моля, потвърдете дали текущото местоположение поддържа използването на тази услуга или опитайте от друго местоположение.",- "ModelEmptyCompletion": "Моделът върна празен отговор. Обикновено това се оправя при повторен опит; ако продължи, опитайте да опростите заявката или да смените модела.",+ "ModelEmptyCompletion": "Доставчикът на модела върна празен отговор. Дори без видимо съдържание, тази заявка може да доведе до разходи. Можете да опитате отново или да смените модела и да опитате пак.","ModelNotFound": "Съжаляваме, заявеният модел не може да бъде намерен. Той може да не съществува или да нямате необходимите права за достъп. Моля, опитайте отново след промяна на API ключа или коригиране на правата за достъп.","NoAvailableChannel": "Съжаляваме, проксито или маршрутизаторът няма наличен канал за заявения модел. Моля, сменете конфигурацията на канала/ключа или опитайте отново по-късно.","OllamaBizError": "Грешка при заявка към услугата Ollama, моля, отстранете проблема или опитайте отново въз основа на следната информация.",diff --git a/locales/de-DE/modelRuntime.json b/locales/de-DE/modelRuntime.jsonindex 748c9a8410c..6d9193d113d 100644--- a/locales/de-DE/modelRuntime.json+++ b/locales/de-DE/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Entschuldigung, der Upstream-Anbieter hat die Anfrage als fehlerhaft abgelehnt. Bitte überprüfen Sie die Eingabe oder versuchen Sie ein anderes Modell.","InvalidVertexCredentials": "Vertex-Authentifizierung fehlgeschlagen. Bitte überprüfen Sie Ihre Anmeldedaten und versuchen Sie es erneut.","LocationNotSupportError": "Entschuldigung, Ihr aktueller Standort unterstützt diesen Modelldienst nicht. Dies kann auf regionale Einschränkungen oder die Nichtverfügbarkeit des Dienstes zurückzuführen sein. Bitte überprüfen Sie, ob der aktuelle Standort die Nutzung dieses Dienstes unterstützt, oder versuchen Sie es von einem anderen Standort aus.",- "ModelEmptyCompletion": "Das Modell hat eine leere Antwort zurückgegeben. Dies klärt sich normalerweise bei einem erneuten Versuch; falls das Problem weiterhin besteht, versuchen Sie, die Anfrage zu vereinfachen oder das Modell zu wechseln.",+ "ModelEmptyCompletion": "Der Modellanbieter hat eine leere Antwort zurückgegeben. Auch ohne sichtbaren Inhalt können für diese Anfrage Kosten anfallen. Sie können es erneut versuchen oder das Modell wechseln und es erneut versuchen.","ModelNotFound": "Entschuldigung, das angeforderte Modell konnte nicht gefunden werden. Es existiert möglicherweise nicht oder Sie haben nicht die erforderlichen Zugriffsberechtigungen. Bitte versuchen Sie es erneut, nachdem Sie den API-Schlüssel geändert oder Ihre Zugriffsberechtigungen angepasst haben.","NoAvailableChannel": "Entschuldigung, der Proxy oder Router hat keinen verfügbaren Kanal für das angeforderte Modell. Bitte wechseln Sie die Kanal-/Schlüsselkonfiguration oder versuchen Sie es später erneut.","OllamaBizError": "Fehler bei der Anforderung des Ollama-Dienstes. Bitte beheben Sie das Problem oder versuchen Sie es erneut basierend auf den folgenden Informationen.",diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.jsonindex fd87033f97a..fd7d3b8cc77 100644--- a/locales/en-US/modelRuntime.json+++ b/locales/en-US/modelRuntime.json@@ -22,7 +22,8 @@"InvalidRequestFormat": "Sorry, the upstream provider rejected the request as malformed. Please check the input or try a different model.","InvalidVertexCredentials": "Vertex authentication failed. Please check your credentials and try again.","LocationNotSupportError": "We're sorry, your current location does not support this model service. This may be due to regional restrictions or the service not being available. Please confirm if the current location supports using this service, or try using a different location.",- "ModelEmptyCompletion": "The model returned an empty response. This usually clears up on retry; if it persists, try simplifying the request or switching models.",+ "ModelEmptyCompletion": "The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.",+ "ModelEmptyCompletionWithCost": "The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.","ModelNotFound": "Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.","NoAvailableChannel": "Sorry, the proxy or router has no available channel for the requested model. Please switch the channel/key configuration or try again later.","OllamaBizError": "Error requesting Ollama service, please troubleshoot or retry based on the following information",diff --git a/locales/es-ES/modelRuntime.json b/locales/es-ES/modelRuntime.jsonindex 92fed68fe02..f062a5db88e 100644--- a/locales/es-ES/modelRuntime.json+++ b/locales/es-ES/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Lo sentimos, el proveedor rechazó la solicitud por estar mal formada. Por favor, verifica la entrada o intenta con un modelo diferente.","InvalidVertexCredentials": "La autenticación de Vertex falló. Por favor, verifica tus credenciales y vuelve a intentarlo.","LocationNotSupportError": "Lo sentimos, tu ubicación actual no admite este servicio de modelo. Esto puede deberse a restricciones regionales o a que el servicio no está disponible. Por favor, confirma si la ubicación actual admite el uso de este servicio, o intenta usar una ubicación diferente.",- "ModelEmptyCompletion": "El modelo devolvió una respuesta vacía. Esto generalmente se soluciona al intentarlo de nuevo; si persiste, intente simplificar la solicitud o cambiar de modelo.",+ "ModelEmptyCompletion": "El proveedor del modelo devolvió una respuesta vacía. Incluso sin contenido visible, esta solicitud puede generar costos. Puedes intentarlo nuevamente o cambiar de modelo y probar otra vez.","ModelNotFound": "Lo sentimos, no se pudo encontrar el modelo solicitado. Puede que no exista o que no tengas los permisos de acceso necesarios. Por favor, vuelve a intentarlo después de cambiar la clave API o ajustar tus permisos de acceso.","NoAvailableChannel": "Lo sentimos, el proxy o enrutador no tiene un canal disponible para el modelo solicitado. Por favor, cambia la configuración del canal/clave o vuelve a intentarlo más tarde.","OllamaBizError": "Error al solicitar el servicio Ollama, por favor soluciona el problema o vuelve a intentarlo basándote en la información siguiente.",diff --git a/locales/fa-IR/modelRuntime.json b/locales/fa-IR/modelRuntime.jsonindex dd7bcef0a40..e12ecb6b85c 100644--- a/locales/fa-IR/modelRuntime.json+++ b/locales/fa-IR/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "متأسفیم، ارائهدهنده بالادستی درخواست را به دلیل قالب نامعتبر رد کرد. لطفاً ورودی را بررسی کرده یا از مدل دیگری استفاده کنید.","InvalidVertexCredentials": "احراز هویت Vertex ناموفق بود. لطفاً اطلاعات ورود خود را بررسی کرده و دوباره تلاش کنید.","LocationNotSupportError": "متأسفیم، مکان فعلی شما از این سرویس مدل پشتیبانی نمیکند. این ممکن است به دلیل محدودیتهای منطقهای یا عدم دسترسی سرویس باشد. لطفاً تأیید کنید که مکان فعلی از استفاده از این سرویس پشتیبانی میکند یا از مکان دیگری استفاده کنید.",- "ModelEmptyCompletion": "مدل پاسخی ارائه نکرد. این مشکل معمولاً با تلاش مجدد برطرف میشود؛ اگر ادامه داشت، درخواست را سادهتر کنید یا مدل را تغییر دهید.",+ "ModelEmptyCompletion": "ارائهدهنده مدل پاسخی خالی بازگرداند. حتی بدون محتوای قابل مشاهده، این درخواست ممکن است هزینههایی داشته باشد. میتوانید دوباره تلاش کنید یا مدل را تغییر داده و دوباره امتحان کنید.","ModelNotFound": "متأسفیم، مدل درخواست شده یافت نشد. ممکن است وجود نداشته باشد یا شما دسترسی لازم را نداشته باشید. لطفاً پس از تغییر کلید API یا تنظیم دسترسی خود دوباره تلاش کنید.","NoAvailableChannel": "متأسفیم، پراکسی یا روتر هیچ کانال موجودی برای مدل درخواست شده ندارد. لطفاً پیکربندی کانال/کلید را تغییر دهید یا بعداً دوباره تلاش کنید.","OllamaBizError": "خطا در درخواست سرویس Ollama، لطفاً مشکل را برطرف کنید یا دوباره تلاش کنید.",diff --git a/locales/fr-FR/modelRuntime.json b/locales/fr-FR/modelRuntime.jsonindex fa49d9d4970..8224912b965 100644--- a/locales/fr-FR/modelRuntime.json+++ b/locales/fr-FR/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Désolé, le fournisseur en amont a rejeté la requête comme étant mal formée. Veuillez vérifier l'entrée ou essayer un autre modèle.","InvalidVertexCredentials": "Échec de l'authentification Vertex. Veuillez vérifier vos identifiants et réessayer.","LocationNotSupportError": "Nous sommes désolés, votre emplacement actuel ne prend pas en charge ce service de modèle. Cela peut être dû à des restrictions régionales ou à l'indisponibilité du service. Veuillez vérifier si l'emplacement actuel permet d'utiliser ce service ou essayez un autre emplacement.",- "ModelEmptyCompletion": "Le modèle a renvoyé une réponse vide. Cela se résout généralement après une nouvelle tentative ; si le problème persiste, essayez de simplifier la demande ou de changer de modèle.",+ "ModelEmptyCompletion": "Le fournisseur de modèle a renvoyé une réponse vide. Même sans contenu visible, cette requête peut tout de même entraîner des frais. Vous pouvez réessayer ou changer de modèle et essayer à nouveau.","ModelNotFound": "Désolé, le modèle demandé n'a pas pu être trouvé. Il peut ne pas exister ou vous pourriez ne pas avoir les autorisations d'accès nécessaires. Veuillez réessayer après avoir modifié la clé API ou ajusté vos autorisations d'accès.","NoAvailableChannel": "Désolé, le proxy ou le routeur n'a aucun canal disponible pour le modèle demandé. Veuillez changer la configuration du canal/de la clé ou réessayer plus tard.","OllamaBizError": "Erreur lors de la demande au service Ollama, veuillez résoudre le problème ou réessayer en fonction des informations suivantes.",diff --git a/locales/it-IT/modelRuntime.json b/locales/it-IT/modelRuntime.jsonindex b35d45b7a1e..917acacd0f3 100644--- a/locales/it-IT/modelRuntime.json+++ b/locales/it-IT/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Spiacenti, il provider a monte ha rifiutato la richiesta perché malformata. Controlla l'input o prova un modello diverso.","InvalidVertexCredentials": "Autenticazione Vertex fallita. Controlla le tue credenziali e riprova.","LocationNotSupportError": "Spiacenti, la tua posizione attuale non supporta questo servizio modello. Questo potrebbe essere dovuto a restrizioni regionali o al fatto che il servizio non è disponibile. Conferma se la posizione attuale supporta l'uso di questo servizio o prova a utilizzare una posizione diversa.",- "ModelEmptyCompletion": "Il modello ha restituito una risposta vuota. Di solito il problema si risolve riprovando; se persiste, prova a semplificare la richiesta o a cambiare modello.",+ "ModelEmptyCompletion": "Il provider del modello ha restituito una risposta vuota. Anche senza contenuto visibile, questa richiesta potrebbe comunque comportare costi. Puoi riprovare o cambiare modello e tentare di nuovo.","ModelNotFound": "Spiacenti, il modello richiesto non è stato trovato. Potrebbe non esistere o potresti non avere i permessi di accesso necessari. Riprova dopo aver modificato la chiave API o regolato i permessi di accesso.","NoAvailableChannel": "Spiacenti, il proxy o il router non ha canali disponibili per il modello richiesto. Cambia la configurazione del canale/chiave o riprova più tardi.","OllamaBizError": "Errore durante la richiesta al servizio Ollama, risolvi il problema o riprova basandoti sulle informazioni seguenti.",diff --git a/locales/ja-JP/modelRuntime.json b/locales/ja-JP/modelRuntime.jsonindex 25578fbf9c9..78e4ff43848 100644--- a/locales/ja-JP/modelRuntime.json+++ b/locales/ja-JP/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "申し訳ありませんが、上流プロバイダーがリクエストを不正な形式として拒否しました。入力を確認するか、別のモデルを試してください。","InvalidVertexCredentials": "Vertex認証に失敗しました。認証情報を確認して再試行してください。","LocationNotSupportError": "申し訳ありませんが、現在の場所ではこのモデルサービスを利用できません。地域制限やサービスの未提供が原因の可能性があります。現在の場所でこのサービスが利用可能か確認するか、別の場所を試してください。",- "ModelEmptyCompletion": "モデルが空の応答を返しました。通常は再試行で解消されますが、問題が続く場合はリクエストを簡略化するか、モデルを変更してみてください。",+ "ModelEmptyCompletion": "モデルプロバイダーから空の応答が返されました。内容が表示されなくても、このリクエストには料金が発生する可能性があります。再試行するか、モデルを切り替えて再度試してください。","ModelNotFound": "申し訳ありませんが、リクエストされたモデルが見つかりませんでした。存在しないか、必要なアクセス権がない可能性があります。APIキーを変更するか、アクセス権を調整して再試行してください。","NoAvailableChannel": "申し訳ありませんが、プロキシまたはルーターにリクエストされたモデルの利用可能なチャネルがありません。チャネル/キーの設定を切り替えるか、後で再試行してください。","OllamaBizError": "Ollamaサービスのリクエスト中にエラーが発生しました。以下の情報を基にトラブルシューティングを行うか、再試行してください。",diff --git a/locales/ko-KR/modelRuntime.json b/locales/ko-KR/modelRuntime.jsonindex 318b468342b..0bc361d3fe0 100644--- a/locales/ko-KR/modelRuntime.json+++ b/locales/ko-KR/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "죄송합니다. 상위 제공업체가 요청을 잘못된 형식으로 거부했습니다. 입력을 확인하거나 다른 모델을 시도하세요.","InvalidVertexCredentials": "Vertex 인증에 실패했습니다. 자격 증명을 확인하고 다시 시도하세요.","LocationNotSupportError": "죄송합니다. 현재 위치에서는 이 모델 서비스를 지원하지 않습니다. 이는 지역 제한 또는 서비스 미제공 때문일 수 있습니다. 현재 위치에서 이 서비스를 사용할 수 있는지 확인하거나 다른 위치를 시도하세요.",- "ModelEmptyCompletion": "모델이 빈 응답을 반환했습니다. 일반적으로 재시도하면 해결되며, 지속될 경우 요청을 간소화하거나 다른 모델로 전환해 보세요.",+ "ModelEmptyCompletion": "모델 제공자가 빈 응답을 반환했습니다. 콘텐츠가 보이지 않더라도 이 요청은 비용이 발생할 수 있습니다. 다시 시도하거나 모델을 변경하여 다시 시도해 보세요.","ModelNotFound": "죄송합니다. 요청한 모델을 찾을 수 없습니다. 모델이 존재하지 않거나 필요한 액세스 권한이 없을 수 있습니다. API 키를 변경하거나 액세스 권한을 조정한 후 다시 시도하세요.","NoAvailableChannel": "죄송합니다. 프록시 또는 라우터에 요청한 모델에 사용할 수 있는 채널이 없습니다. 채널/키 구성을 변경하거나 나중에 다시 시도하세요.","OllamaBizError": "Ollama 서비스 요청 중 오류가 발생했습니다. 아래 정보를 바탕으로 문제를 해결하거나 다시 시도하세요.",diff --git a/locales/nl-NL/modelRuntime.json b/locales/nl-NL/modelRuntime.jsonindex 66261c5918f..e20d42dc115 100644--- a/locales/nl-NL/modelRuntime.json+++ b/locales/nl-NL/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Sorry, de upstream-provider heeft het verzoek afgewezen als onjuist geformatteerd. Controleer de invoer of probeer een ander model.","InvalidVertexCredentials": "Vertex-authenticatie is mislukt. Controleer uw inloggegevens en probeer het opnieuw.","LocationNotSupportError": "Het spijt ons, uw huidige locatie ondersteunt deze modelservice niet. Dit kan te maken hebben met regionale beperkingen of de onbeschikbaarheid van de service. Controleer of de huidige locatie het gebruik van deze service ondersteunt, of probeer een andere locatie.",- "ModelEmptyCompletion": "Het model gaf een lege reactie terug. Dit lost zich meestal op bij een nieuwe poging; als het aanhoudt, probeer dan het verzoek te vereenvoudigen of van model te wisselen.",+ "ModelEmptyCompletion": "De modelprovider heeft een lege reactie teruggestuurd. Zelfs zonder zichtbare inhoud kunnen er kosten verbonden zijn aan dit verzoek. U kunt het opnieuw proberen of van model wisselen en het opnieuw proberen.","ModelNotFound": "Sorry, het gevraagde model kon niet worden gevonden. Het bestaat mogelijk niet of u heeft mogelijk niet de benodigde toegangsrechten. Probeer het opnieuw na het wijzigen van de API-sleutel of het aanpassen van uw toegangsrechten.","NoAvailableChannel": "Sorry, de proxy of router heeft geen beschikbaar kanaal voor het gevraagde model. Schakel de kanaal-/sleutelconfiguratie om of probeer het later opnieuw.","OllamaBizError": "Fout bij het aanvragen van de Ollama-service, los het probleem op of probeer het opnieuw op basis van de onderstaande informatie.",diff --git a/locales/pl-PL/modelRuntime.json b/locales/pl-PL/modelRuntime.jsonindex 59aa0f51264..09cb8bac0c2 100644--- a/locales/pl-PL/modelRuntime.json+++ b/locales/pl-PL/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Przepraszamy, dostawca upstream odrzucił żądanie jako nieprawidłowe. Proszę sprawdzić dane wejściowe lub spróbować innego modelu.","InvalidVertexCredentials": "Uwierzytelnianie Vertex nie powiodło się. Proszę sprawdzić swoje dane uwierzytelniające i spróbować ponownie.","LocationNotSupportError": "Przepraszamy, Twoja obecna lokalizacja nie obsługuje tej usługi modelu. Może to być spowodowane ograniczeniami regionalnymi lub niedostępnością usługi. Proszę potwierdzić, czy obecna lokalizacja obsługuje korzystanie z tej usługi, lub spróbować użyć innej lokalizacji.",- "ModelEmptyCompletion": "Model zwrócił pustą odpowiedź. Zazwyczaj problem ustępuje po ponownej próbie; jeśli się utrzymuje, spróbuj uprościć zapytanie lub zmienić model.",+ "ModelEmptyCompletion": "Dostawca modelu zwrócił pustą odpowiedź. Nawet bez widocznej treści, to żądanie może nadal generować koszty. Możesz spróbować ponownie lub zmienić model i spróbować jeszcze raz.","ModelNotFound": "Przepraszamy, żądany model nie został znaleziony. Może nie istnieć lub możesz nie mieć odpowiednich uprawnień dostępu. Proszę spróbować ponownie po zmianie klucza API lub dostosowaniu uprawnień dostępu.","NoAvailableChannel": "Przepraszamy, proxy lub router nie ma dostępnego kanału dla żądanego modelu. Proszę przełączyć konfigurację kanału/klucza lub spróbować ponownie później.","OllamaBizError": "Błąd podczas żądania usługi Ollama, proszę rozwiązać problem lub spróbować ponownie na podstawie poniższych informacji.",diff --git a/locales/pt-BR/modelRuntime.json b/locales/pt-BR/modelRuntime.jsonindex 9d989e93ec4..407302be12d 100644--- a/locales/pt-BR/modelRuntime.json+++ b/locales/pt-BR/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Desculpe, o provedor rejeitou a solicitação por estar malformada. Por favor, verifique a entrada ou tente um modelo diferente.","InvalidVertexCredentials": "Falha na autenticação do Vertex. Por favor, verifique suas credenciais e tente novamente.","LocationNotSupportError": "Desculpe, sua localização atual não suporta este serviço de modelo. Isso pode ser devido a restrições regionais ou indisponibilidade do serviço. Por favor, confirme se a localização atual suporta o uso deste serviço ou tente usar uma localização diferente.",- "ModelEmptyCompletion": "O modelo retornou uma resposta vazia. Isso geralmente se resolve ao tentar novamente; se persistir, tente simplificar a solicitação ou trocar de modelo.",+ "ModelEmptyCompletion": "O provedor do modelo retornou uma resposta vazia. Mesmo sem conteúdo visível, esta solicitação ainda pode gerar custos. Você pode tentar novamente ou trocar de modelo e tentar novamente.","ModelNotFound": "Desculpe, o modelo solicitado não pôde ser encontrado. Ele pode não existir ou você pode não ter as permissões de acesso necessárias. Por favor, tente novamente após alterar a chave de API ou ajustar suas permissões de acesso.","NoAvailableChannel": "Desculpe, o proxy ou roteador não possui um canal disponível para o modelo solicitado. Por favor, altere a configuração do canal/chave ou tente novamente mais tarde.","OllamaBizError": "Erro ao solicitar o serviço Ollama. Por favor, solucione o problema ou tente novamente com base nas informações a seguir.",diff --git a/locales/ru-RU/modelRuntime.json b/locales/ru-RU/modelRuntime.jsonindex a8981852caf..7df57b09e06 100644--- a/locales/ru-RU/modelRuntime.json+++ b/locales/ru-RU/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Извините, провайдер отклонил запрос как некорректный. Пожалуйста, проверьте ввод или попробуйте другую модель.","InvalidVertexCredentials": "Ошибка аутентификации Vertex. Пожалуйста, проверьте ваши учетные данные и повторите попытку.","LocationNotSupportError": "Извините, в вашем текущем местоположении эта модель недоступна. Это может быть связано с региональными ограничениями или недоступностью сервиса. Пожалуйста, проверьте, поддерживается ли использование этого сервиса в вашем местоположении, или попробуйте использовать другое местоположение.",- "ModelEmptyCompletion": "Модель вернула пустой ответ. Обычно это проходит при повторной попытке; если проблема сохраняется, попробуйте упростить запрос или сменить модель.",+ "ModelEmptyCompletion": "Поставщик модели вернул пустой ответ. Даже без видимого содержимого этот запрос может повлечь за собой расходы. Вы можете повторить попытку или сменить модель и попробовать снова.","ModelNotFound": "Извините, запрашиваемая модель не найдена. Она может не существовать, или у вас может не быть необходимых прав доступа. Пожалуйста, попробуйте снова, изменив API-ключ или настройки доступа.","NoAvailableChannel": "Извините, прокси или маршрутизатор не имеет доступного канала для запрашиваемой модели. Пожалуйста, переключите конфигурацию канала/ключа или повторите попытку позже.","OllamaBizError": "Ошибка при запросе сервиса Ollama. Пожалуйста, устраните неполадки или повторите попытку, используя следующую информацию.",diff --git a/locales/tr-TR/modelRuntime.json b/locales/tr-TR/modelRuntime.jsonindex fba6435e82e..3f7b7aea5a7 100644--- a/locales/tr-TR/modelRuntime.json+++ b/locales/tr-TR/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Üzgünüz, yukarı akış sağlayıcı isteği hatalı biçimlendirilmiş olarak reddetti. Lütfen girdiyi kontrol edin veya farklı bir model deneyin.","InvalidVertexCredentials": "Vertex kimlik doğrulaması başarısız oldu. Lütfen kimlik bilgilerinizi kontrol edip yeniden deneyin.","LocationNotSupportError": "Üzgünüz, mevcut konumunuz bu model hizmetini desteklemiyor. Bu durum bölgesel kısıtlamalardan veya hizmetin mevcut olmamasından kaynaklanıyor olabilir. Lütfen mevcut konumun bu hizmeti kullanmayı destekleyip desteklemediğini doğrulayın veya farklı bir konum deneyin.",- "ModelEmptyCompletion": "Model boş bir yanıt döndürdü. Bu genellikle yeniden deneme ile düzelir; eğer devam ederse, isteği basitleştirmeyi veya modelleri değiştirmeyi deneyin.",+ "ModelEmptyCompletion": "Model sağlayıcısı boş bir yanıt döndürdü. Görünür içerik olmasa bile, bu isteğin maliyeti olabilir. Tekrar deneyebilir veya modeli değiştirip yeniden deneyebilirsiniz.","ModelNotFound": "Üzgünüz, istenen model bulunamadı. Model mevcut olmayabilir veya gerekli erişim izinlerine sahip olmayabilirsiniz. Lütfen API Anahtarını değiştirip veya erişim izinlerinizi ayarladıktan sonra yeniden deneyin.","NoAvailableChannel": "Üzgünüz, proxy veya yönlendiricide istenen model için kullanılabilir bir kanal yok. Lütfen kanal/anahtar yapılandırmasını değiştirin veya daha sonra yeniden deneyin.","OllamaBizError": "Ollama hizmeti istenirken hata oluştu, lütfen aşağıdaki bilgilere dayanarak sorun giderin veya yeniden deneyin.",diff --git a/locales/vi-VN/modelRuntime.json b/locales/vi-VN/modelRuntime.jsonindex e37f0e8742e..b076c9cb404 100644--- a/locales/vi-VN/modelRuntime.json+++ b/locales/vi-VN/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "Rất tiếc, nhà cung cấp đã từ chối yêu cầu vì định dạng không hợp lệ. Vui lòng kiểm tra đầu vào hoặc thử một mô hình khác.","InvalidVertexCredentials": "Xác thực Vertex thất bại. Vui lòng kiểm tra thông tin xác thực của bạn và thử lại.","LocationNotSupportError": "Rất tiếc, vị trí hiện tại của bạn không hỗ trợ dịch vụ mô hình này. Điều này có thể do hạn chế khu vực hoặc dịch vụ không khả dụng. Vui lòng xác nhận xem vị trí hiện tại có hỗ trợ sử dụng dịch vụ này hay không, hoặc thử sử dụng một vị trí khác.",- "ModelEmptyCompletion": "Mô hình đã trả về một phản hồi trống. Thông thường, vấn đề này sẽ được khắc phục khi thử lại; nếu vẫn tiếp diễn, hãy thử đơn giản hóa yêu cầu hoặc chuyển sang mô hình khác.",+ "ModelEmptyCompletion": "Nhà cung cấp mô hình đã trả về một phản hồi trống. Ngay cả khi không có nội dung hiển thị, yêu cầu này vẫn có thể phát sinh chi phí. Bạn có thể thử lại hoặc chuyển đổi mô hình và thử lại.","ModelNotFound": "Rất tiếc, không thể tìm thấy mô hình được yêu cầu. Có thể mô hình không tồn tại hoặc bạn không có quyền truy cập cần thiết. Vui lòng thử lại sau khi thay đổi khóa API hoặc điều chỉnh quyền truy cập của bạn.","NoAvailableChannel": "Rất tiếc, proxy hoặc bộ định tuyến không có kênh khả dụng cho mô hình được yêu cầu. Vui lòng chuyển đổi cấu hình kênh/khóa hoặc thử lại sau.","OllamaBizError": "Lỗi khi yêu cầu dịch vụ Ollama, vui lòng khắc phục sự cố hoặc thử lại dựa trên thông tin sau.",diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.jsonindex 320dfe20c31..df63b36da3b 100644--- a/locales/zh-CN/modelRuntime.json+++ b/locales/zh-CN/modelRuntime.json@@ -22,7 +22,8 @@"InvalidRequestFormat": "抱歉,上游提供商拒绝了请求,因为格式不正确。请检查输入或尝试使用其他模型。","InvalidVertexCredentials": "Vertex身份验证失败。请检查您的凭据并重试。","LocationNotSupportError": "抱歉,您当前的位置不支持此模型服务。这可能是由于地区限制或服务不可用。请确认当前地点是否支持使用此服务,或尝试使用其他地点。",- "ModelEmptyCompletion": "模型返回了一个空响应。通常在重试后会解决;如果问题仍然存在,请尝试简化请求或切换模型。",+ "ModelEmptyCompletion": "模型供应商返回了空内容。即使没有可显示的内容,本次请求仍可能产生费用。你可以重试,或切换模型后再试。",+ "ModelEmptyCompletionWithCost": "模型供应商返回空内容,本次费用为 {{credits}} 积分。重试可能产生相近费用,也可切换模型。","ModelNotFound": "抱歉,未找到请求的模型。可能是模型不存在或您没有必要的访问权限。请在更改API密钥或调整访问权限后重试。","NoAvailableChannel": "抱歉,代理或路由器没有可用的通道来请求此模型。请切换通道/密钥配置或稍后重试。","OllamaBizError": "请求Ollama服务时发生错误,请根据以下信息进行排查或重试。",diff --git a/locales/zh-TW/modelRuntime.json b/locales/zh-TW/modelRuntime.jsonindex 0d4e649fb25..7ae5cbbb877 100644--- a/locales/zh-TW/modelRuntime.json+++ b/locales/zh-TW/modelRuntime.json@@ -22,7 +22,7 @@"InvalidRequestFormat": "抱歉,上游提供者拒絕了格式錯誤的請求。請檢查輸入或嘗試使用不同的模型。","InvalidVertexCredentials": "Vertex 身份驗證失敗。請檢查您的憑證並重試。","LocationNotSupportError": "抱歉,您當前的位置不支援此模型服務。這可能是由於地區限制或服務不可用所致。請確認當前位置是否支援使用此服務,或嘗試使用其他位置。",- "ModelEmptyCompletion": "模型返回了空的回應。通常在重試後會解決;如果問題持續,請嘗試簡化請求或切換模型。",+ "ModelEmptyCompletion": "模型提供者返回了空的回應。即使沒有可見內容,此請求仍可能產生費用。您可以重試或切換模型後再試一次。","ModelNotFound": "抱歉,找不到所請求的模型。它可能不存在或您可能沒有必要的訪問權限。請在更改 API 金鑰或調整訪問權限後重試。","NoAvailableChannel": "抱歉,代理或路由器沒有可用的通道來處理所請求的模型。請切換通道/金鑰配置或稍後重試。","OllamaBizError": "請求 Ollama 服務時發生錯誤,請根據以下資訊進行故障排除或重試。",diff --git a/packages/agent-runtime/src/utils/runtimeRetry.test.ts b/packages/agent-runtime/src/utils/runtimeRetry.test.tsindex e685852c987..32f108a1dd9 100644--- a/packages/agent-runtime/src/utils/runtimeRetry.test.ts+++ b/packages/agent-runtime/src/utils/runtimeRetry.test.ts@@ -9,17 +9,13 @@ import {} from './runtimeRetry';describe('runtimeRetry', () => {- it('resolves LLM retry policy with provider disables and empty completion floor', () => {- const emptyError = new Error('empty');- const options = {- isEmptyCompletionError: (error: unknown) => error === emptyError,- noRetryProviders: ['lobehub'],- };-- expect(resolveLLMRetryBudget('openai', new Error('rate limit'), options)).toBe(5);- expect(resolveLLMRetryBudget('lobehub', new Error('upstream failed'), options)).toBe(0);- expect(resolveLLMRetryBudget('lobehub', emptyError, options)).toBe(2);- expect(resolveLLMMaxAttempts('lobehub', options)).toBe(3);+ it('resolves LLM retry policy from provider-level configuration only', () => {+ const options = { noRetryProviders: ['lobehub'] };++ expect(resolveLLMRetryBudget('openai', options)).toBe(5);+ expect(resolveLLMRetryBudget('lobehub', options)).toBe(0);+ expect(resolveLLMMaxAttempts('openai', options)).toBe(6);+ expect(resolveLLMMaxAttempts('lobehub', options)).toBe(1);});it('calculates exponential LLM retry delay with a cap', () => {diff --git a/packages/agent-runtime/src/utils/runtimeRetry.ts b/packages/agent-runtime/src/utils/runtimeRetry.tsindex 0d06d2e65cb..56310502af9 100644--- a/packages/agent-runtime/src/utils/runtimeRetry.ts+++ b/packages/agent-runtime/src/utils/runtimeRetry.ts@@ -1,5 +1,4 @@const DEFAULT_LLM_MAX_RETRIES = 5;-const DEFAULT_EMPTY_COMPLETION_MAX_RETRIES = 2;const DEFAULT_LLM_RETRY_BASE_DELAY_MS = 1000;const DEFAULT_LLM_RETRY_MAX_DELAY_MS = 30_000;@@ -7,8 +6,6 @@ export type RuntimeRetryKind = 'retry' | 'stop';export type RuntimeToolFailureKind = 'replan' | 'retry' | 'stop';export interface LLMRetryPolicyOptions {- emptyCompletionMaxRetries?: number;- isEmptyCompletionError?: (error: unknown) => boolean;maxRetries?: number;noRetryProviders?: readonly string[];retryBaseDelayMs?: number;@@ -38,25 +35,11 @@ const resolveLLMMaxRetries = (provider: string, options: LLMRetryPolicyOptions =export const shouldRetryLLM = (kind: RuntimeRetryKind, attempt: number, maxRetries: number) =>kind === 'retry' && attempt <= maxRetries;-/**- * Retry budget for a specific failed attempt. Empty completions can opt into a- * dedicated floor even when the provider-level policy disables general retries.- */-export const resolveLLMRetryBudget = (- provider: string,- error: unknown,- options: LLMRetryPolicyOptions = {},-) =>- options.isEmptyCompletionError?.(error)- ? (options.emptyCompletionMaxRetries ?? DEFAULT_EMPTY_COMPLETION_MAX_RETRIES)- : resolveLLMMaxRetries(provider, options);--/** Loop bound — must accommodate the largest budget any error kind can request. */+export const resolveLLMRetryBudget = (provider: string, options: LLMRetryPolicyOptions = {}) =>+ resolveLLMMaxRetries(provider, options);+export const resolveLLMMaxAttempts = (provider: string, options: LLMRetryPolicyOptions = {}) =>- Math.max(- resolveLLMMaxRetries(provider, options),- options.emptyCompletionMaxRetries ?? DEFAULT_EMPTY_COMPLETION_MAX_RETRIES,- ) + 1;+ resolveLLMMaxRetries(provider, options) + 1;export const getLLMRetryDelayMs = (attempt: number, options: LLMRetryPolicyOptions = {}) =>Math.min(diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.tsindex 903b2198ce2..6771d9ab000 100644--- a/packages/locales/src/default/modelRuntime.ts+++ b/packages/locales/src/default/modelRuntime.ts@@ -44,7 +44,9 @@ export default {LocationNotSupportError:"We're sorry, your current location does not support this model service. This may be due to regional restrictions or the service not being available. Please confirm if the current location supports using this service, or try using a different location.",ModelEmptyCompletion:- 'The model returned an empty response. This usually clears up on retry; if it persists, try simplifying the request or switching models.',+ 'The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.',+ ModelEmptyCompletionWithCost:+ 'The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.',ModelNotFound:'Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.',NoAvailableChannel:diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 70f16326ed0..133a2d1f040 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -635,6 +635,7 @@ export interface EnabledAiModel {generation?: string;id: string;knowledgeCutoff?: string;+ maxOutput?: number;parameters?: ModelParamsSchema;pricing?: Pricing;providerId: string;diff --git a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.tsindex 4b04e898042..0f768accc0f 100644--- a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts@@ -15,10 +15,16 @@ describe('estimateChatCost', () => {expect(estimateChatOutputTokens(1000)).toBe(500);});- it('caps output tokens for large inputs', () => {+ it('uses 8192 as the fallback cap for large inputs', () => {expect(estimateChatOutputTokens(20_000)).toBe(8192);expect(estimateChatOutputTokens(1_000_000)).toBe(8192);});++ it('uses the effective request or model cap when provided', () => {+ expect(estimateChatOutputTokens(40_000, 32_000)).toBe(20_000);+ expect(estimateChatOutputTokens(40_000, 12_000)).toBe(12_000);+ expect(estimateChatOutputTokens(40_000, 4096)).toBe(4096);+ });});describe('estimateOpenAIChatInputTokens', () => {@@ -147,6 +153,19 @@ describe('estimateChatCost', () => {expect(estimateChatCostFromTokens(undefined, { textTokens: 1000 })).toBeUndefined();});+ it('forwards the effective output cap into the estimated usage', () => {+ const pricing: Pricing = {+ units: [{ name: 'textOutput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],+ };++ const estimate = estimateChatCostFromTokens(pricing, {+ maxOutputTokens: 12_000,+ textTokens: 40_000,+ });++ expect(estimate?.estimatedOutputTokens).toBe(12_000);+ });+it('falls multimodal input back to text pricing when dedicated modality units are missing', () => {const pricing: Pricing = {units: [{ name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],@@ -215,6 +234,20 @@ describe('estimateChatCost', () => {);});+ it('forwards the effective output cap into the message estimate', () => {+ const pricing: Pricing = {+ units: [{ name: 'textOutput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],+ };++ const estimate = estimateChatCostFromMessages(+ pricing,+ [{ content: 'hello world', role: 'user' }],+ { maxOutputTokens: 1 },+ );++ expect(estimate?.estimatedOutputTokens).toBe(1);+ });+it('forwards video inputs to video pricing units', () => {const pricing: Pricing = {units: [{ name: 'videoInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' }],diff --git a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.tsindex 4d9ad7d0146..371b8514d7b 100644--- a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts@@ -42,6 +42,11 @@ export interface EstimateOpenAIChatInputTokensOptions {export interface EstimateChatCostFromTokensInput {audioTokens?: number;imageTokens?: number;+ /**+ * Maximum output tokens from the request or model card. When omitted, the estimator uses the+ * default fallback cap.+ */+ maxOutputTokens?: number;/*** Optional expected output tokens. When omitted, the estimator uses a heuristic based on input* tokens.@@ -67,7 +72,13 @@ export interface ChatCostEstimate extends PricingComputationResult {}export interface EstimateChatCostFromMessagesOptions- extends ComputeChatCostOptions, EstimateOpenAIChatInputTokensOptions {}+ extends ComputeChatCostOptions, EstimateOpenAIChatInputTokensOptions {+ /**+ * Maximum output tokens from the request or model card. When omitted, the estimator uses the+ * default fallback cap.+ */+ maxOutputTokens?: number;+}const estimateSerializableTokens = (value: unknown): number => {if (value === undefined || value === null) return 0;@@ -82,10 +93,14 @@ const hasPricingUnit = (pricing: Pricing | undefined, unitName: PricingUnitName)/*** Estimates output tokens for budget pre-checks and UI hints.*- * The default heuristic assumes output is half of total input tokens, capped at 8192 tokens.+ * The default heuristic assumes output is half of total input tokens. A request/model limit caps+ * the estimate when provided; otherwise 8192 tokens is used as a fallback cap.*/-export function estimateChatOutputTokens(totalInputTokens: number): number {- return Math.min(totalInputTokens * OUTPUT_INPUT_RATIO, OUTPUT_TOKEN_CAP);+export function estimateChatOutputTokens(+ totalInputTokens: number,+ maxOutputTokens = OUTPUT_TOKEN_CAP,+): number {+ return Math.min(totalInputTokens * OUTPUT_INPUT_RATIO, maxOutputTokens);}/**@@ -154,8 +169,8 @@ export function estimateOpenAIChatInputTokens(/*** Estimates chat cost from known input token buckets.*- * `outputTextTokens` defaults to `estimateChatOutputTokens(totalInputTokens)`. Pricing lookup- * options are forwarded to `computeChatCost`.+ * `outputTextTokens` defaults to `estimateChatOutputTokens(totalInputTokens, maxOutputTokens)`.+ * Pricing lookup options are forwarded to `computeChatCost`.*/export function estimateChatCostFromTokens(pricing: Pricing | undefined,@@ -168,7 +183,7 @@ export function estimateChatCostFromTokens(const inputVideoTokens = input.videoTokens ?? 0;const totalInputTokens = inputTextTokens + inputImageTokens + inputAudioTokens + inputVideoTokens;const estimatedOutputTokens =- input.outputTextTokens ?? estimateChatOutputTokens(totalInputTokens);+ input.outputTextTokens ?? estimateChatOutputTokens(totalInputTokens, input.maxOutputTokens);const hasAudioInputUnit = hasPricingUnit(pricing, 'audioInput');const hasImageInputUnit = hasPricingUnit(pricing, 'imageInput');const hasVideoInputUnit = hasPricingUnit(pricing, 'videoInput');@@ -217,7 +232,14 @@ export function estimateChatCostFromMessages(messages: OpenAIChatMessage[],options: EstimateChatCostFromMessagesOptions = {},): ChatCostEstimate | undefined {- const { tools, imageTokenEstimate, lookupParams, usdToCnyRate, videoTokenEstimate } = options;+ const {+ tools,+ imageTokenEstimate,+ lookupParams,+ maxOutputTokens,+ usdToCnyRate,+ videoTokenEstimate,+ } = options;const inputTokens = estimateOpenAIChatInputTokens(messages, {imageTokenEstimate,tools,@@ -228,6 +250,7 @@ export function estimateChatCostFromMessages(pricing,{imageTokens: inputTokens.imageTokens,+ maxOutputTokens,textTokens: inputTokens.textTokens,videoTokens: inputTokens.videoTokens,},diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.tsindex db0cb224824..80fa9069071 100644--- a/packages/model-runtime/src/errors/modelEmptyCompletion.ts+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.ts@@ -3,6 +3,8 @@ import { AgentRuntimeErrorType } from '@lobechat/types';export interface ModelEmptyCompletionDiagnostics {attempt?: number;contentLength?: number;+ /** Calculated request cost in USD when pricing and usage are available. */+ cost?: number;finishReason?: string;imageCount?: number;maxAttempts?: number;@@ -10,34 +12,24 @@ export interface ModelEmptyCompletionDiagnostics {outputTokens?: number;provider?: string;reasoningLength?: number;- retryBudget?: number;- retryEvents?: Array<Record<string, unknown>>;toolCallCount?: number;}/**- * Thrown when the model returns an empty completion — no text content, no- * reasoning, no tool calls, no images, and ~0 output tokens. This is the "empty- * completion" failure mode: after a stalled tool loop the model effectively- * gives up and emits a blank turn, which the harness used to silently finalize- * to `done` while persisting an empty assistant message (empty bubble,- * `status=done, error=null`).+ * Thrown when the provider completes a request without user-visible content,+ * reasoning, tool calls, images, or grounding. Provider-reported output usage+ * does not make an otherwise blank turn visible to the user.*- * The `errorType` field tags it as the retryable `ModelEmptyCompletion` code- * (see `errors/specs.ts`, which classifies it as a retryable `provider` error)- * so that:- * 1. an LLM-error classifier resolves it to `retry`, letting the agent's- * `call_llm` retry loop re-attempt the turn (a retry typically yields real- * content).- * 2. If every retry is also empty, the terminal-error formatter enriches it- * into a readable, dashboard-visible error instead of a silent `done`.+ * The `errorType` tags this as the terminal `ModelEmptyCompletion` provider+ * error. Callers surface it immediately so the user can decide whether another+ * potentially billable request should be made.*/export class ModelEmptyError extends Error {readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;readonly diagnostics?: ModelEmptyCompletionDiagnostics;constructor(- message = 'Model returned an empty completion (no content, no tool calls, no output tokens).',+ message = 'The model provider returned an empty completion.',diagnostics?: ModelEmptyCompletionDiagnostics,) {super(message);@@ -47,18 +39,15 @@ export class ModelEmptyError extends Error {}/**- * Output-token count at or below this — combined with no content, reasoning,- * tool calls, or images — marks a turn as an empty completion.- * The observed failure case reported `out=1 token`.+ * Grounding is a valid non-text result only when the provider also reports+ * meaningful output usage.*/const EMPTY_COMPLETION_MAX_OUTPUT_TOKENS = 1;/**- * Detect the "empty completion" failure mode: the model returns a turn with no- * text, no reasoning, no tool calls, no images, and ~0 output tokens —- * typically after a stalled tool loop where it effectively gives up. Callers- * throw {@link ModelEmptyError} on a hit so the LLM retry loop re-attempts- * instead of silently finalizing to `done` with a blank assistant message.+ * Detect a completion with no user-visible output. Callers throw+ * {@link ModelEmptyError} so the blank turn surfaces as a terminal provider+ * error instead of silently finalizing as a successful assistant message.*/export const isEmptyModelCompletion = (params: {content: string;@@ -75,18 +64,9 @@ export const isEmptyModelCompletion = (params: {if (toolCallCount > 0) return false;if (imageCount > 0) return false;- // A turn can legitimately burn output tokens without producing any text we- // accumulate into `content`/`reasoning` — grounding/citation metadata is the- // known case. Only *that* signal justifies treating a positive token count as- // a non-empty completion.- //- // A high output-token count WITHOUT such a signal is not proof of a real- // reply — it means the model generated text we failed to capture (e.g. a- // post-tool answer turn whose streamed content was dropped by the sink). If we- // trusted the token count there, we would silently finalize to `done` with a- // blank assistant message the user still gets billed for. So we only take the- // token escape hatch when a real no-text output signal is present; otherwise- // fall through to `empty` and let the caller retry.+ // Grounding/citation metadata is a known valid no-text result. In every other+ // case, provider-reported output tokens may represent internal reasoning or+ // other billable work, but they do not give the user a visible completion.if (hasGrounding &&typeof outputTokens === 'number' &&diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.tsindex e1cf0ad40f2..1f59c9dc1fc 100644--- a/packages/model-runtime/src/errors/specs.ts+++ b/packages/model-runtime/src/errors/specs.ts@@ -592,13 +592,12 @@ export const ERROR_CODE_SPECS: SpecMap = {// `ProviderNoImageGenerated` (provider attribution, status 471).attribution: 'provider',httpStatus: 471,- // Retryable — re-issuing the same request usually yields a real response.- // The call_llm retry loop relies on this flag to re-attempt empty turns- // before they ever surface as a terminal error.- retryable: true,+ // A retry is a new, potentially billable provider request. Surface the+ // empty response immediately and let the user decide whether to retry.+ retryable: false,countAsFailure: true,description:- 'Model returned an empty completion (no content, no tool calls, ~0 output tokens), usually after a stalled tool loop.',+ 'Provider returned a completion with no user-visible content, tool calls, images, or grounding.',},// ─── 9xxx Config ──────────────────────────────────────────────────────diff --git a/src/business/client/hooks/useBusinessErrorContent.ts b/src/business/client/hooks/useBusinessErrorContent.tsindex 4194e7d1209..093f9fcc354 100644--- a/src/business/client/hooks/useBusinessErrorContent.ts+++ b/src/business/client/hooks/useBusinessErrorContent.ts@@ -1,12 +1,13 @@-import { type ErrorType } from '@lobechat/types';+import type { ChatMessageError } from '@lobechat/types';export interface BusinessErrorContentResult {errorType?: string;hideMessage?: boolean;+ message?: string;}export default function useBusinessErrorContent(- _errorType?: ErrorType | string,+ _error?: ChatMessageError | null,): BusinessErrorContentResult {return {};}diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 1e1ab9f63ce..4d84620298f 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -8,12 +8,20 @@ import { fireEvent, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import ErrorMessageExtra from './index';+import ErrorMessageExtra, { useErrorContent } from './index';const navigateMock = vi.fn();const updateMessageErrorMock = vi.fn();const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));+const missingTranslationKeys = vi.hoisted(() => new Set<string>());+const businessErrorContentMock = vi.hoisted(() =>+ vi.fn(() => ({+ errorType: undefined,+ hideMessage: false,+ message: undefined as string | undefined,+ })),+);vi.mock('@lobechat/business-const', async (importOriginal) => {const actual = (await importOriginal()) as typeof businessConstModule;@@ -63,7 +71,8 @@ vi.mock('@lobehub/ui', async (importOriginal) => {vi.mock('react-i18next', () => ({useTranslation: () => ({- t: (key: string) => key,+ t: (key: string, options?: Record<string, unknown>) =>+ missingTranslationKeys.has(key) ? (options?.defaultValue ?? key) : key,}),}));@@ -76,7 +85,7 @@ vi.mock('@/business/client/hooks/useBusinessErrorAlertConfig', () => ({}));vi.mock('@/business/client/hooks/useBusinessErrorContent', () => ({- default: () => ({ errorType: undefined, hideMessage: false }),+ default: businessErrorContentMock,}));vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () => ({@@ -143,9 +152,21 @@ vi.mock('@/features/Conversation/store', () => ({}),}));+const ErrorMessageWithContent = ({ data }: { data: any }) => {+ const error = useErrorContent(data.error);++ return <ErrorMessageExtra data={data} error={error} />;+};+describe('ErrorMessageExtra', () => {beforeEach(() => {+ missingTranslationKeys.clear();serverConfigMock.enableBusinessFeatures = false;+ businessErrorContentMock.mockReturnValue({+ errorType: undefined,+ hideMessage: false,+ message: undefined,+ });updateMessageErrorMock.mockClear();});@@ -368,4 +389,70 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText('Raw runtime error')).toBeInTheDocument();expect(screen.getByText(/"detail": "raw detail"/)).toBeInTheDocument();});++ it('shows the localized empty-completion message while retaining the raw error in details', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.ModelEmptyCompletion' }}+ data={{+ error: {+ body: { diagnostics: { attempt: 1, maxAttempts: 1, outputTokens: 25_617 } },+ message: 'The model provider returned an empty completion.',+ type: AgentRuntimeErrorType.ModelEmptyCompletion,+ } as any,+ id: 'msg-empty-completion',+ }}+ />,+ );++ expect(screen.getByText('response.ModelEmptyCompletion')).toBeInTheDocument();+ expect(+ screen.getByText(/"message": "The model provider returned an empty completion\."/),+ ).toBeInTheDocument();+ });++ it('prefers the business message while retaining the standard error details', () => {+ businessErrorContentMock.mockReturnValue({+ errorType: undefined,+ hideMessage: false,+ message: 'This request cost 5.98M credits.',+ });++ render(+ <ErrorMessageWithContent+ data={{+ error: {+ body: { diagnostics: { cost: 5.980_015, provider: 'lobehub' } },+ message: 'The model provider returned an empty completion.',+ type: AgentRuntimeErrorType.ModelEmptyCompletion,+ } as any,+ id: 'msg-empty-completion-cost',+ }}+ />,+ );++ expect(screen.getByText('This request cost 5.98M credits.')).toBeInTheDocument();+ expect(+ screen.getByText(/"message": "The model provider returned an empty completion\."/),+ ).toBeInTheDocument();+ });++ it('falls back to the raw message for a known error when localized content is unavailable', () => {+ missingTranslationKeys.add('modelRuntime:ExceededToolLimit');++ render(+ <ErrorMessageWithContent+ data={{+ error: {+ message: 'The provider rejected the tool count.',+ type: AgentRuntimeErrorType.ExceededToolLimit,+ } as any,+ id: 'msg-tool-limit-raw-fallback',+ }}+ />,+ );++ expect(screen.getByText('The provider rejected the tool count.')).toBeInTheDocument();+ expect(screen.queryByText('modelRuntime:ExceededToolLimit')).not.toBeInTheDocument();+ });});diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 52036546f8c..93d5dc4538e 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -3,6 +3,7 @@ import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';import { AgentRuntimeErrorType, getErrorCodeSpec } from '@lobechat/model-runtime';import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';import { type AlertProps } from '@lobehub/ui';import { Block, Highlighter, Skeleton } from '@lobehub/ui';import { memo, useCallback, useMemo } from 'react';@@ -58,6 +59,17 @@ const getRawErrorMessage = (error?: ChatMessageError | null) => {return;};+const getErrorDetails = (error?: ChatMessageError | null) => {+ if (!error) return;++ const rawErrorMessage = getRawErrorMessage(error);+ if (!rawErrorMessage) return error.body;+ if (isRecord(error.body)) return { ...error.body, message: rawErrorMessage };+ if (error.body !== undefined) return { body: error.body, message: rawErrorMessage };++ return { message: rawErrorMessage };+};+const loading = () => (<Blockalign={'center'}@@ -200,7 +212,11 @@ export const useErrorContent = (error: any) => {const { t } = useTranslation(['error', 'modelRuntime']);const providerName = useProviderName(error?.body?.provider || '');const businessAlertConfig = useBusinessErrorAlertConfig(error?.type);- const { errorType: businessErrorType, hideMessage } = useBusinessErrorContent(error?.type);+ const {+ errorType: businessErrorType,+ hideMessage,+ message: businessMessage,+ } = useBusinessErrorContent(error);return useMemo<AlertProps | undefined>(() => {if (!error) return;@@ -226,10 +242,18 @@ export const useErrorContent = (error: any) => {: getRuntimeErrorMessage(t, finalErrorType, { provider: providerName });return {- message: translatedMessage || rawErrorMessage,+ message: businessMessage || translatedMessage || rawErrorMessage,...alertConfig,};- }, [businessAlertConfig, businessErrorType, error, hideMessage, providerName, t]);+ }, [+ businessAlertConfig,+ businessErrorType,+ businessMessage,+ error,+ hideMessage,+ providerName,+ t,+ ]);};interface ErrorExtraProps {@@ -259,7 +283,12 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(const { canUseResource } = useConversationResourceAccess();const canCreate = canCreateContent && canUseResource;const sessionErrorBody = error?.body;- const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;+ const rawErrorMessage = getRawErrorMessage(error);+ const errorDetails = getErrorDetails(error);+ const localizedErrorMessage = hasLocalizedErrorMessage(error?.type)+ ? alertError?.message+ : undefined;+ const displayMessage = localizedErrorMessage ?? rawErrorMessage ?? alertError?.message;const delAndRegenerateMessage = useConversationStore((s) => s.delAndRegenerateMessage);const updateMessageError = useConversationStore((s) => s.updateMessageError);@@ -425,15 +454,15 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(id={data.id}error={{...alertError,- ...(rawErrorMessage ? { message: rawErrorMessage } : {}),- extra: data.error?.body ? (+ message: displayMessage,+ extra: errorDetails ? (<HighlighteractionIconSize={'small'}language={'json'}padding={8}variant={'borderless'}>- {JSON.stringify(data.error?.body, null, 2)}+ {JSON.stringify(errorDetails, null, 2)}</Highlighter>) : undefined,}}diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsxindex 721a79142f4..73d45566ad4 100644--- a/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/Checker.tsx@@ -3,6 +3,7 @@import { CheckCircleFilled } from '@ant-design/icons';import { type ChatMessageError } from '@lobechat/types';import { TraceNameMap } from '@lobechat/types';+import { isRecord, pickTrimmedString } from '@lobechat/utils/object';import { ModelIcon } from '@lobehub/icons';import { Alert, Flexbox, Highlighter, Icon } from '@lobehub/ui';import { Button, Select } from '@lobehub/ui/base-ui';@@ -26,12 +27,17 @@ const styles = createStaticStyles(({ css }) => ({const Error = memo<{ error: ChatMessageError }>(({ error }) => {const { t } = useTranslation(['error', 'modelRuntime']);const providerName = useProviderName(error.body?.provider);+ const bodyMessage = isRecord(error.body)+ ? pickTrimmedString(error.body.message)+ : pickTrimmedString(error.body);+ const fallbackMessage =+ pickTrimmedString(error.message) ?? bodyMessage ?? t('response.UnknownChatFetchError');return (<Flexbox gap={8} style={{ maxWidth: 600, width: '100%' }}><AlertshowIcon- title={getRuntimeErrorMessage(t, error.type, { provider: providerName })}+ title={getRuntimeErrorMessage(t, error.type, { provider: providerName }, fallbackMessage)}type={'error'}extra={<Flexbox paddingBlock={8} paddingInline={16}>diff --git a/src/store/chat/agents/transports/ClientLLMTransport.test.ts b/src/store/chat/agents/transports/ClientLLMTransport.test.tsindex 6e3b9b12b9c..aea1b6063eb 100644--- a/src/store/chat/agents/transports/ClientLLMTransport.test.ts+++ b/src/store/chat/agents/transports/ClientLLMTransport.test.ts@@ -9,7 +9,7 @@ import { ClientLLMTransport } from './ClientLLMTransport';// `chatService.getChatCompletion`) finishes with `grounding` + `usage`, and the// StreamingHandler surfaces the grounding as `metadata.search`.const grounding = { citations: ['https://example.com'] } as any;-const usage = { totalOutputTokens: 25_220 } as any;+const usage = { cost: 5.980_015, totalOutputTokens: 25_220 } as any;let finishGrounding: unknown = grounding;@@ -120,6 +120,8 @@ describe('ClientLLMTransport.runAttempt · empty-completion grounding guard', ()expect(result.ok).toBe(false);if (result.ok === false) {expect(result.error).toBeInstanceOf(ModelEmptyError);+ expect((result.error as ModelEmptyError).diagnostics).toMatchObject({ cost: 5.980_015 });+ expect(createTransport().retryPolicy.classifyError(result.error).kind).toBe('stop');}});});diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.tsindex b8000eb33ea..c797efff63f 100644--- a/src/store/chat/agents/transports/ClientLLMTransport.ts+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts@@ -10,12 +10,17 @@ import type {LLMTransport,} from '@lobechat/agent-runtime';import {- classifyLLMError,+ createLLMErrorClassifier,resolveLLMMaxAttempts,resolveLLMRetryBudget,} from '@lobechat/agent-runtime';import { BRANDING_PROVIDER } from '@lobechat/business-const';-import { isEmptyModelCompletion, ModelEmptyError } from '@lobechat/model-runtime';+import {+ ERROR_CODE_SPECS,+ getErrorCodeSpec,+ isEmptyModelCompletion,+ ModelEmptyError,+} from '@lobechat/model-runtime';import type { ChatMessageError, MessageMetadata, ModelReasoning } from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';import { t } from 'i18next';@@ -31,10 +36,14 @@ import type { ClientLLMModelParameters } from './ClientContextBuilder';import type { ClientRuntimeSession } from './ClientRuntimeStreamSink';const CLIENT_LLM_RETRY_POLICY = {- isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,noRetryProviders: [BRANDING_PROVIDER],};+const classifyClientLLMError = createLLMErrorClassifier({+ errorCodeSpecs: Object.values(ERROR_CODE_SPECS),+ getErrorCodeSpec,+});+const createStreamExecutionError = (errorData: unknown) => {if (errorData instanceof Error) return errorData;@@ -113,21 +122,14 @@ class ClientLLMRetryPolicy implements LLMRetryPolicy {) {}classifyError(error: unknown) {- return classifyLLMError(error);+ return classifyClientLLMError(error);}maxAttempts(provider: string) {return resolveLLMMaxAttempts(provider, CLIENT_LLM_RETRY_POLICY);}- onError({ error, events, interrupted, retryBudget }: LLMCallErrorInput) {- if (error instanceof ModelEmptyError && error.diagnostics) {- error.diagnostics.retryBudget = retryBudget;- error.diagnostics.retryEvents = events- .filter((event) => event.type === 'stream_retry')- .map((event) => event.data);- }-+ onError({ error, interrupted }: LLMCallErrorInput) {if (interrupted || !this.session.assistantMessageId) return;const localizedError = toChatMessageError(@@ -149,8 +151,8 @@ class ClientLLMRetryPolicy implements LLMRetryPolicy {// The package publishes the canonical stream_retry event through StreamSink.}- resolveRetryBudget(provider: string, error: unknown) {- return resolveLLMRetryBudget(provider, error, CLIENT_LLM_RETRY_POLICY);+ resolveRetryBudget(provider: string) {+ return resolveLLMRetryBudget(provider, CLIENT_LLM_RETRY_POLICY);}async waitForRetry(delayMs: number): Promise<void> {@@ -319,6 +321,7 @@ export class ClientLLMTransport implements LLMTransport {error: new ModelEmptyError(undefined, {attempt: input.attempt,contentLength: output.content.length,+ cost: output.usage?.cost,finishReason: output.finishReason,imageCount: output.imageList.length,maxAttempts: input.maxAttempts,diff --git a/src/utils/locale/runtimeErrorMessage.test.ts b/src/utils/locale/runtimeErrorMessage.test.tsnew file mode 100644index 00000000000..10d1b64c604--- /dev/null+++ b/src/utils/locale/runtimeErrorMessage.test.ts@@ -0,0 +1,33 @@+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';+import { describe, expect, it } from 'vitest';++import { getRuntimeErrorMessage } from './runtimeErrorMessage';++const createTranslator =+ (translations: Record<string, string>) => (key: string, options?: Record<string, unknown>) =>+ translations[key] ?? String(options?.defaultValue ?? key);++describe('getRuntimeErrorMessage', () => {+ it('returns the localized runtime error message when the key exists', () => {+ const t = createTranslator({+ 'modelRuntime:ModelEmptyCompletion': 'Localized empty completion',+ });++ expect(getRuntimeErrorMessage(t, AgentRuntimeErrorType.ModelEmptyCompletion)).toBe(+ 'Localized empty completion',+ );+ });++ it('returns the raw fallback when a registered runtime error has no locale key', () => {+ const t = createTranslator({});++ expect(+ getRuntimeErrorMessage(+ t,+ AgentRuntimeErrorType.InvalidGithubCopilotToken,+ undefined,+ 'The GitHub Copilot token is invalid.',+ ),+ ).toBe('The GitHub Copilot token is invalid.');+ });+});diff --git a/src/utils/locale/runtimeErrorMessage.ts b/src/utils/locale/runtimeErrorMessage.tsindex 4c8d2e58e8e..521f647f52e 100644--- a/src/utils/locale/runtimeErrorMessage.ts+++ b/src/utils/locale/runtimeErrorMessage.ts@@ -23,11 +23,12 @@ export const getRuntimeErrorMessage = (t: unknown,code: string | number | undefined,vars?: Record<string, unknown>,+ fallbackMessage = '',): string => {if (code === undefined || code === null || code === '') return '';const key =typeof code === 'string' && getErrorCodeSpec(code)? `modelRuntime:${code}`: `response.${code}`;- return (t as LooseT)(key, vars);+ return (t as LooseT)(key, { ...vars, defaultValue: fallbackMessage });};