Skip to content

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

πŸ› fix(agent-runtime): retry network empty completions (#19083)

Arvin Xub1e342ff3f5c
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index d20a2fee1fb..9da51af195b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -1173,6 +1173,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
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?.({
+ finishReason: 'network_error',
usage: {
cost: 5.980_015,
totalInputTokens: 100,
@@ -1204,7 +1205,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(error.diagnostics).toMatchObject({
attempt: 1,
cost: 5.980_015,
- maxAttempts: 1,
+ maxAttempts: 4,
model: 'deepseek-v4-pro',
outputTokens: 25_617,
provider: 'lobehub',
@@ -5480,6 +5481,160 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
).toBe(false);
});
+ it('should retry a no-usage empty completion caused by a network error once', async () => {
+ vi.useFakeTimers();
+
+ const mockChat = vi
+ .fn()
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onCompletion?.({ finishReason: 'network_error', text: '' });
+ return new Response('done');
+ })
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onText?.('recovered');
+ await options.callback.onCompletion?.({
+ finishReason: 'stop',
+ usage: { totalInputTokens: 10, totalOutputTokens: 2, totalTokens: 12 },
+ });
+ return new Response('done');
+ });
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'glm-5.3-flash',
+ parentMessageId: 'parent-msg-123',
+ provider: 'lobehub',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+
+ await vi.runOnlyPendingTimersAsync();
+
+ const result = await resultPromise;
+
+ expect(mockChat).toHaveBeenCalledTimes(2);
+ expect(result.nextContext?.phase).toBe('llm_result');
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ 'msg-123',
+ expect.objectContaining({ content: 'recovered' }),
+ );
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ data: expect.objectContaining({ attempt: 2, delayMs: 1000, maxAttempts: 4 }),
+ type: 'stream_retry',
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should retry a third-party no-usage network empty completion too', async () => {
+ vi.useFakeTimers();
+
+ const mockChat = vi
+ .fn()
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onCompletion?.({ finishReason: 'network_error', text: '' });
+ return new Response('done');
+ })
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onText?.('recovered');
+ await options.callback.onCompletion?.({
+ finishReason: 'stop',
+ usage: { totalInputTokens: 10, totalOutputTokens: 2, totalTokens: 12 },
+ });
+ return new Response('done');
+ });
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-5',
+ parentMessageId: 'parent-msg-123',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+
+ await vi.runOnlyPendingTimersAsync();
+
+ const result = await resultPromise;
+
+ // Nothing was produced and nothing was billed, so the drop is as
+ // retryable on a BYOK route as on the first-party one.
+ expect(mockChat).toHaveBeenCalledTimes(2);
+ expect(result.nextContext?.phase).toBe('llm_result');
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ 'msg-123',
+ expect.objectContaining({ content: 'recovered' }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should stop after three retries when network empty completions continue', async () => {
+ vi.useFakeTimers();
+
+ const mockChat = vi.fn().mockImplementation(async (_payload: any, options: any) => {
+ await options.callback.onCompletion?.({ finishReason: 'network_error', text: '' });
+ return new Response('done');
+ });
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'glm-5.3-flash',
+ parentMessageId: 'parent-msg-123',
+ provider: 'lobehub',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+ const rejection = expect(resultPromise).rejects.toMatchObject({
+ diagnostics: expect.objectContaining({ attempt: 4, maxAttempts: 4 }),
+ errorType: 'ModelEmptyCompletion',
+ });
+
+ await vi.runOnlyPendingTimersAsync();
+ await Promise.resolve();
+ await vi.runOnlyPendingTimersAsync();
+ await Promise.resolve();
+ await vi.runOnlyPendingTimersAsync();
+ await rejection;
+
+ expect(mockChat).toHaveBeenCalledTimes(4);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('should retry llm execution, emit stream_retry, and commit only the successful attempt', async () => {
vi.useFakeTimers();
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index 9efa8f8ad4b..b359a91fe21 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -17,6 +17,7 @@ import { BRANDING_PROVIDER } from '@lobechat/business-const';
import {
type ChatStreamPayload,
consumeStreamUntilDone,
+ ModelEmptyError,
type ModelRuntime,
} from '@lobechat/model-runtime';
import {
@@ -54,15 +55,61 @@ const SERVER_LLM_RETRY_POLICY = {
noRetryProviders: [BRANDING_PROVIDER],
};
+const NETWORK_EMPTY_COMPLETION_MAX_RETRIES = 3;
+const NETWORK_EMPTY_COMPLETION_MAX_ATTEMPTS = NETWORK_EMPTY_COMPLETION_MAX_RETRIES + 1;
+
+/**
+ * A stream that died on the transport before the model produced anything: no
+ * content, no reasoning, no image, no tool call and β€” decisively β€” neither cost
+ * nor output tokens, so the attempt billed nothing.
+ *
+ * `ModelEmptyCompletion` is non-retryable by spec precisely because "a retry is
+ * a new, potentially billable provider request". That reasoning is what these
+ * diagnostics rule out, which is why this narrow shape may retry while every
+ * other empty completion still surfaces immediately.
+ *
+ * Deliberately provider-independent: the zero-output, zero-cost diagnostics
+ * carry the whole safety argument on their own. A BYOK stream dropping
+ * mid-flight is the same failure, and nothing about a first-party route makes
+ * an unbilled network drop more retryable than a third-party one.
+ */
+const isRetryableNetworkEmptyCompletion = (error: unknown) => {
+ if (!(error instanceof ModelEmptyError)) return false;
+
+ const diagnostics = error.diagnostics;
+ return (
+ diagnostics?.finishReason === 'network_error' &&
+ diagnostics.contentLength === 0 &&
+ diagnostics.reasoningLength === 0 &&
+ diagnostics.imageCount === 0 &&
+ diagnostics.toolCallCount === 0 &&
+ diagnostics.cost === undefined &&
+ diagnostics.outputTokens === undefined
+ );
+};
+
class ServerLLMRetryPolicy implements LLMRetryPolicy {
constructor(private readonly ctx: RuntimeExecutorContext) {}
classifyError(error: unknown) {
- return classifyLLMError(error);
+ const classified = classifyLLMError(error);
+ return isRetryableNetworkEmptyCompletion(error)
+ ? { ...classified, kind: 'retry' as const }
+ : classified;
}
+ /**
+ * The executor fixes the attempt ceiling before any error exists, so it has to
+ * leave room for the error-driven network-empty budget below. Providers that
+ * already allow more keep their own ceiling; only a no-retry provider is
+ * lifted, and `resolveRetryBudget` still refuses every other error of theirs
+ * at the first attempt.
+ */
maxAttempts(provider: string) {
- return resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);
+ return Math.max(
+ resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY),
+ NETWORK_EMPTY_COMPLETION_MAX_ATTEMPTS,
+ );
}
onError({ error }: LLMCallErrorInput) {
@@ -84,7 +131,8 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {
);
}
- resolveRetryBudget(provider: string) {
+ resolveRetryBudget(provider: string, error: unknown) {
+ if (isRetryableNetworkEmptyCompletion(error)) return NETWORK_EMPTY_COMPLETION_MAX_RETRIES;
return resolveLLMRetryBudget(provider, SERVER_LLM_RETRY_POLICY);
}