π€― 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-runtime): retry empty LLM completions instead of silent done (#15355)
Arvin Xu45a6f2b440f6
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.tsindex 72a705ea009..faeb83190cd 100644--- a/packages/model-runtime/src/errors/specs.ts+++ b/packages/model-runtime/src/errors/specs.ts@@ -570,6 +570,24 @@ export const ERROR_CODE_SPECS: SpecMap = {isFallback: true,description: 'Bare upstream HTTP error with no further context (e.g. "400 status code").',},+ [AgentRuntimeErrorType.ModelEmptyCompletion]: {+ code: AgentRuntimeErrorType.ModelEmptyCompletion,+ numericId: 8014,+ category: 'provider',+ severity: 'warning',+ // The provider returned a successful (HTTP 200) but empty response β its+ // own behavior, not our bug and not a timeout. Mirrors the image analog+ // `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,+ countAsFailure: true,+ description:+ 'Model returned an empty completion (no content, no tool calls, ~0 output tokens), usually after a stalled tool loop.',+ },// βββ 9xxx Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββ[AgentRuntimeErrorType.InvalidOllamaArgs]: {diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex b57f05fd42e..cf94424893b 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -114,6 +114,15 @@ export const AgentRuntimeErrorType = {InvalidBedrockCredentials: 'InvalidBedrockCredentials',InvalidVertexCredentials: 'InvalidVertexCredentials',StreamChunkError: 'StreamChunkError',+ /**+ * The model returned an empty completion β no text content, no tool calls,+ * and ~0 output tokens β typically after a stalled tool loop where it+ * effectively gives up. Retryable: re-issuing the same request usually+ * yields a real response. Without this code the harness silently finalized+ * to `done` and persisted a blank assistant message (empty bubble). See+ * LOBE-9834.+ */+ ModelEmptyCompletion: 'ModelEmptyCompletion',/*** A persistence-layer query / transaction failed (Drizzle "Failed query:* β¦"). Harness-side: the DB write/read or txn could not complete anddiff --git a/src/locales/default/modelRuntime.ts b/src/locales/default/modelRuntime.tsindex 959d37a43bf..f4df70cc7a6 100644--- a/src/locales/default/modelRuntime.ts+++ b/src/locales/default/modelRuntime.ts@@ -43,6 +43,8 @@ export default {'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.',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/src/server/modules/AgentRuntime/ModelEmptyError.ts b/src/server/modules/AgentRuntime/ModelEmptyError.tsnew file mode 100644index 00000000000..3d830f956df--- /dev/null+++ b/src/server/modules/AgentRuntime/ModelEmptyError.ts@@ -0,0 +1,27 @@+import { AgentRuntimeErrorType } from '@lobechat/types';++/**+ * Thrown by the `call_llm` executor when the model returns an empty completion+ * β no text content, no reasoning, no tool calls, no images, and ~0 output+ * tokens. This is the LOBE-9834 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`).+ *+ * The `errorType` field tags it as the retryable `ModelEmptyCompletion` code so+ * that:+ * 1. `classifyLLMError` resolves it to `retry`, letting the executor's LLM+ * retry loop re-attempt the turn (a retry typically yields real content).+ * 2. If every retry is also empty, `formatErrorForState` enriches it into a+ * readable, dashboard-visible terminal error instead of a silent `done`.+ */+export class ModelEmptyError extends Error {+ readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;++ constructor(+ message = 'Model returned an empty completion (no content, no tool calls, no output tokens).',+ ) {+ super(message);+ this.name = 'ModelEmptyError';+ }+}diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 4e226b54ea5..b00a30fe490 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -100,6 +100,7 @@ import {isPersistFatal,markPersistFatal,} from './messagePersistErrors';+import { ModelEmptyError } from './ModelEmptyError';import { resolveToolTimeoutMs } from './resolveToolTimeout';import { type IStreamEventManager } from './types';@@ -117,6 +118,54 @@ const LLM_MAX_RETRIES = 5;const LLM_RETRY_BASE_DELAY_MS = 1000;const LLM_RETRY_MAX_DELAY_MS = 30_000;+/**+ * Retry budget for empty completions (LOBE-9834), applied independently of+ * `resolveLLMMaxRetries`. The branded provider gets 0 general retries because+ * its own fallback chain already re-routes failed requests β but an+ * HTTP-200-but-empty turn never triggered that chain, so it must still be+ * re-issued. A small budget is enough: empty turns almost always self-heal on+ * the first retry.+ */+const EMPTY_COMPLETION_MAX_RETRIES = 2;++/**+ * Output-token count at or below this β combined with no content, reasoning,+ * tool calls, or images β marks a turn as an empty completion (LOBE-9834).+ * The observed failure case reported `out=1 token`.+ */+const EMPTY_COMPLETION_MAX_OUTPUT_TOKENS = 1;++/**+ * Detect the "empty completion" failure mode (LOBE-9834): 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 `ModelEmptyError` on a hit so the LLM retry loop re-attempts+ * instead of silently finalizing to `done` with a blank assistant message.+ */+const isEmptyModelCompletion = (params: {+ content: string;+ imageCount: number;+ outputTokens: number | undefined;+ reasoning: string;+ toolCallCount: number;+}): boolean => {+ const { content, reasoning, toolCallCount, imageCount, outputTokens } = params;++ if (content.trim().length > 0) return false;+ if (reasoning.trim().length > 0) return false;+ if (toolCallCount > 0) return false;+ if (imageCount > 0) return false;++ // When the provider reports output tokens, only treat as empty if it's ~0.+ // Guards against rare cases where structured output we don't accumulate into+ // `content`/`reasoning` here (e.g. grounding) still consumed real tokens.+ if (typeof outputTokens === 'number' && outputTokens > EMPTY_COMPLETION_MAX_OUTPUT_TOKENS) {+ return false;+ }++ return true;+};+const GEN_AI_FUNCTION_TOOL_TYPE: ToolType = 'function';type ToolFailureKind = 'replan' | 'retry' | 'stop';@@ -194,6 +243,24 @@ const resolveLLMMaxRetries = (provider: string) =>// again here multiplies the same failed routed request across every channel.provider === BRANDING_PROVIDER ? 0 : LLM_MAX_RETRIES;+/**+ * Retry budget for a *specific* failed attempt. This is provider policy ++ * error-type override, so it can only be resolved once the error exists (in the+ * catch) β unlike {@link resolveLLMMaxRetries}, which runs before the request.+ *+ * Empty completions (LOBE-9834) bypass the per-provider policy: the branded+ * provider's 0-retry rule exists to avoid re-routing its own already-failed+ * requests, but an HTTP-200-but-empty turn never hit that fallback chain, so it+ * must still be re-issued. Folding this into `resolveLLMMaxRetries` would wrongly+ * grant the floor to *every* branded error.+ */+const resolveLLMRetryBudget = (provider: string, error: unknown) =>+ error instanceof ModelEmptyError ? EMPTY_COMPLETION_MAX_RETRIES : resolveLLMMaxRetries(provider);++/** Loop bound β must accommodate the largest budget any error kind can request. */+const resolveLLMMaxAttempts = (provider: string) =>+ Math.max(resolveLLMMaxRetries(provider), EMPTY_COMPLETION_MAX_RETRIES) + 1;+const resolveRuntimeHistoryCount = (historyCount?: number) => {if (historyCount === undefined) return undefined;@@ -934,8 +1001,7 @@ export const createRuntimeExecutors = (}};- const llmMaxRetries = resolveLLMMaxRetries(provider);- const maxAttempts = llmMaxRetries + 1;+ const maxAttempts = resolveLLMMaxAttempts(provider);// OTel chat span β wraps all retry attempts; TTFT recorded on the first// text/reasoning chunk regardless of which attempt produced it (the@@ -1132,6 +1198,37 @@ export const createRuntimeExecutors = (await flushReasoningBuffer();clearAttemptBuffers();+ // Empty-completion guard (LOBE-9834): if the model produced+ // nothing actionable β no content, reasoning, tool calls, images,+ // or output tokens β throw so the retry loop below re-attempts the+ // turn instead of finalizing to `done` with a blank assistant+ // message. Skipped when the user interrupted mid-stream, where an+ // empty turn is expected and must not be retried.+ const reportedOutputTokens =+ currentStepUsage && typeof currentStepUsage === 'object'+ ? (currentStepUsage as { totalOutputTokens?: unknown }).totalOutputTokens+ : undefined;++ if (+ isEmptyModelCompletion({+ content,+ imageCount: imageList.length,+ outputTokens:+ typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,+ reasoning: thinkingContent,+ toolCallCount: toolsCalling.length + tool_calls.length,+ }) &&+ !(await isOperationInterrupted(ctx))+ ) {+ log(+ '[%s] Model returned an empty completion (attempt %d/%d) β throwing ModelEmptyError to retry',+ operationLogId,+ attempt,+ maxAttempts,+ );+ throw new ModelEmptyError();+ }+log(`[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,content.length,@@ -1336,7 +1433,9 @@ export const createRuntimeExecutors = (const classified = classifyLLMError(error);const interrupted = await isOperationInterrupted(ctx);- if (!interrupted && shouldRetryLLM(classified.kind, attempt, llmMaxRetries)) {+ const retryBudget = resolveLLMRetryBudget(provider, error);++ if (!interrupted && shouldRetryLLM(classified.kind, attempt, retryBudget)) {const delayMs = getLLMRetryDelayMs(attempt);log(diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 3741ed6769e..d34d3b8b996 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as ContextEngineering from '@/server/modules/Mecha/ContextEngineering';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { ModelEmptyError } from '../ModelEmptyError';import { createRuntimeExecutors, type RuntimeExecutorContext } from '../RuntimeExecutors';const mockCreateCompressionGroup = vi.fn();@@ -30,7 +31,13 @@ const mockBuiltinModels = vi.hoisted(() => [// Mock dependenciesvi.mock('@/server/modules/ModelRuntime', () => ({initModelRuntimeFromDB: vi.fn().mockResolvedValue({- chat: vi.fn().mockResolvedValue(new Response('done')),+ // Emit a minimal non-empty completion so the call_llm empty-completion+ // guard (LOBE-9834) doesn't treat the default mock as a "gave up" turn and+ // throw ModelEmptyError. Tests that exercise real output override this.+ chat: vi.fn().mockImplementation(async (_payload: any, options: any) => {+ await options?.callback?.onText?.('done');+ return new Response('done');+ }),}),}));@@ -392,6 +399,84 @@ describe('RuntimeExecutors', () => {);});+ it('retries empty completions on the branded provider then throws ModelEmptyError (LOBE-9834)', async () => {+ // A "gave up" turn: no onText / onThinking / onToolsCalling and ~0 output+ // tokens β mirrors the LOBE-9834 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');+ });+ // 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();++ const promise = executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-pro',+ provider: 'lobehub',+ tools: [],+ },+ type: 'call_llm' as const,+ },+ state,+ );+ // Drive the retry backoff sleeps to completion.+ const settled = expect(promise).rejects.toBeInstanceOf(ModelEmptyError);+ 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.+ await settled;+ // EMPTY_COMPLETION_MAX_RETRIES (2) retries β 3 total attempts.+ expect(mockChat).toHaveBeenCalledTimes(3);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does NOT treat a content-bearing completion as empty', async () => {+ // Empty output-token usage but real text content β a legitimate reply,+ // must not trip the empty-completion guard.+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {+ await options?.callback?.onText?.('Here is your answer.');+ await options?.callback?.onCompletion?.({+ usage: { totalInputTokens: 10, totalOutputTokens: 0, totalTokens: 10 },+ });+ return new Response('done');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const result = await executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-pro',+ provider: 'lobehub',+ tools: [],+ },+ type: 'call_llm' as const,+ },+ state,+ );++ expect(result.newState.messages.at(-1)).toEqual(+ expect.objectContaining({ content: 'Here is your answer.', role: 'assistant' }),+ );+ });+it('should push assistant message with persisted DB id so request_human_approve can find parent', async () => {const toolCallPayload = [{@@ -920,7 +1005,10 @@ describe('RuntimeExecutors', () => {let mockChat: ReturnType<typeof vi.fn>;beforeEach(() => {- mockChat = vi.fn().mockResolvedValue(new Response('done'));+ mockChat = vi.fn().mockImplementation(async (_payload: any, options: any) => {+ await options?.callback?.onText?.('done');+ return new Response('done');+ });vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);});@@ -1036,7 +1124,10 @@ describe('RuntimeExecutors', () => {let engineSpy: any;beforeEach(() => {- mockChat = vi.fn().mockResolvedValue(new Response('done'));+ mockChat = vi.fn().mockImplementation(async (_payload: any, options: any) => {+ await options?.callback?.onText?.('done');+ return new Response('done');+ });vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);engineSpy = vi.spyOn(ContextEngineering, 'serverMessagesEngine');});diff --git a/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.tsindex 12350b964d8..7162b0818a5 100644--- a/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { classifyLLMError } from '../llmErrorClassification';+import { ModelEmptyError } from '../ModelEmptyError';describe('classifyLLMError', () => {it('should classify rate limit errors as retry', () => {@@ -81,9 +82,14 @@ 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 (LOBE-9834)', () => {+ expect(classifyLLMError(new ModelEmptyError()).kind).toBe('retry');+ });});describe('legacy retry overrides', () => {diff --git a/src/server/modules/AgentRuntime/formatErrorForState.test.ts b/src/server/modules/AgentRuntime/formatErrorForState.test.tsindex 84bd29fd260..52026b00a90 100644--- a/src/server/modules/AgentRuntime/formatErrorForState.test.ts+++ b/src/server/modules/AgentRuntime/formatErrorForState.test.ts@@ -2,6 +2,7 @@ import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';import { describe, expect, it } from 'vitest';import { formatErrorForState } from './formatErrorForState';+import { ModelEmptyError } from './ModelEmptyError';describe('formatErrorForState', () => {describe('input normalization', () => {@@ -53,6 +54,21 @@ describe('formatErrorForState', () => {});});+ it('enriches a thrown ModelEmptyError into a readable retryable terminal error (LOBE-9834)', () => {+ const result = formatErrorForState(new ModelEmptyError());++ // The `errorType` field must win over the generic Error β InternalServerError+ // path so the terminal state is classified and dashboard-visible instead of+ // a silent `done`.+ expect(result.type).toBe(AgentRuntimeErrorType.ModelEmptyCompletion);+ expect(result.category).toBe('provider');+ expect(result.attribution).toBe('provider');+ expect(result.retryable).toBe(true);+ expect(result.countAsFailure).toBe(true);+ expect(result.numericId).toBe(8014);+ expect(result.message).toContain('empty completion');+ });+it('marks provider-side rate limits as retryable with provider attribution', () => {const result = formatErrorForState({errorType: AgentRuntimeErrorType.RateLimitExceeded,