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): don't trust output tokens as proof of a non-empty completion (#17365)

Arvin Xu4cd292c0ef50
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index 6ed1ff5a4c5..e4a795f109b 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -277,6 +277,7 @@ export class ServerCallLlmAttempt {
if (
isEmptyModelCompletion({
content: this.streamSink.content,
+ hasGrounding: !!this.grounding,
imageCount: this.imageList.length,
outputTokens: this.usage?.totalOutputTokens,
reasoning: this.streamSink.thinkingContent,
diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.test.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.test.ts
new file mode 100644
index 00000000000..52a494c1697
--- /dev/null
+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+
+import { isEmptyModelCompletion } from './modelEmptyCompletion';
+
+describe('isEmptyModelCompletion', () => {
+ const base = {
+ content: '',
+ imageCount: 0,
+ outputTokens: 0,
+ reasoning: '',
+ toolCallCount: 0,
+ };
+
+ it('treats a turn with real text content as non-empty', () => {
+ expect(isEmptyModelCompletion({ ...base, content: 'hello' })).toBe(false);
+ });
+
+ it('treats a reasoning-only turn as non-empty', () => {
+ expect(isEmptyModelCompletion({ ...base, reasoning: 'thinking...' })).toBe(false);
+ });
+
+ it('treats a tool-call turn as non-empty', () => {
+ expect(isEmptyModelCompletion({ ...base, toolCallCount: 1 })).toBe(false);
+ });
+
+ it('treats an image turn as non-empty', () => {
+ expect(isEmptyModelCompletion({ ...base, imageCount: 1 })).toBe(false);
+ });
+
+ it('flags a truly blank turn (no content, ~0 output tokens) as empty', () => {
+ expect(isEmptyModelCompletion({ ...base, outputTokens: 1 })).toBe(true);
+ });
+
+ it('flags a blank turn with undefined output tokens as empty', () => {
+ expect(isEmptyModelCompletion({ ...base, outputTokens: undefined })).toBe(true);
+ });
+
+ // The regression this guard closes: a post-tool answer turn where the model
+ // generated tens of thousands of output tokens but the streamed text was
+ // dropped before it reached `content`. Without a grounding signal, a high
+ // output-token count must NOT be trusted as a real reply β€” otherwise the turn
+ // silently finalizes to `done` with a blank, still-billed assistant message.
+ it('flags empty content with high output tokens as empty when no grounding is present', () => {
+ expect(
+ isEmptyModelCompletion({ ...base, outputTokens: 25_220, reasoning: '', content: '' }),
+ ).toBe(true);
+ });
+
+ it('does not flag empty content with high output tokens when grounding IS present', () => {
+ // Grounding/citation metadata legitimately consumes tokens without emitting
+ // text we accumulate β€” keep the original escape hatch for that case only.
+ expect(isEmptyModelCompletion({ ...base, outputTokens: 25_220, hasGrounding: true })).toBe(
+ false,
+ );
+ });
+
+ it('ignores grounding when it did not consume output tokens', () => {
+ expect(isEmptyModelCompletion({ ...base, outputTokens: 1, hasGrounding: true })).toBe(true);
+ });
+});
diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
index 0b2044f7519..db0cb224824 100644
--- a/packages/model-runtime/src/errors/modelEmptyCompletion.ts
+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
@@ -62,22 +62,36 @@ const EMPTY_COMPLETION_MAX_OUTPUT_TOKENS = 1;
*/
export const isEmptyModelCompletion = (params: {
content: string;
+ hasGrounding?: boolean;
imageCount: number;
outputTokens: number | undefined;
reasoning: string;
toolCallCount: number;
}): boolean => {
- const { content, reasoning, toolCallCount, imageCount, outputTokens } = params;
+ const { content, reasoning, toolCallCount, imageCount, outputTokens, hasGrounding } = 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) {
+ // 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.
+ if (
+ hasGrounding &&
+ typeof outputTokens === 'number' &&
+ outputTokens > EMPTY_COMPLETION_MAX_OUTPUT_TOKENS
+ ) {
return false;
}
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.test.ts b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
new file mode 100644
index 00000000000..6e3b9b12b9c
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
@@ -0,0 +1,125 @@
+import { ModelEmptyError } from '@lobechat/model-runtime';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ChatStore } from '../../store';
+import { ClientLLMTransport } from './ClientLLMTransport';
+
+// A grounding-only completion streams no text into `content`, but carries
+// citation metadata and burns real output tokens. The stream (driven via
+// `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;
+
+let finishGrounding: unknown = grounding;
+
+vi.mock('@/services/chat', () => ({
+ chatService: {
+ getChatCompletion: vi.fn(async (_params: any, options: any) => {
+ await options.onFinish?.('', {
+ grounding: finishGrounding,
+ traceId: 'trace-1',
+ type: 'stop',
+ usage,
+ });
+ }),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({ getFileStoreState: () => ({}) }));
+
+vi.mock('../StreamingHandler', () => ({
+ StreamingHandler: class {
+ handleFinish(finishData: any) {
+ return {
+ content: '',
+ finishType: finishData.type,
+ isFunctionCall: false,
+ metadata: { search: finishData.grounding ?? undefined, usage: finishData.usage },
+ toolCalls: [],
+ tools: [],
+ usage: finishData.usage,
+ };
+ }
+ getOutput() {
+ return '';
+ }
+ getThinkingContent() {
+ return '';
+ }
+ getContentParts() {
+ return [];
+ }
+ getReasoningParts() {
+ return [];
+ }
+ handleChunk() {}
+ hasContentImages() {
+ return false;
+ }
+ hasReasoningImages() {
+ return false;
+ }
+ },
+}));
+
+const createTransport = () => {
+ const operation = {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ status: 'running',
+ };
+ const store = {
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ internal_dispatchMessage: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ internal_transformToolCalls: vi.fn((calls: unknown) => calls),
+ operations: { 'op-1': operation },
+ startOperation: vi.fn(() => ({ operationId: 'reasoning-op' })),
+ } as unknown as ChatStore;
+
+ return new ClientLLMTransport({
+ get: () => store,
+ operationId: 'op-1',
+ session: { assistantMessageId: 'msg-1' } as any,
+ });
+};
+
+const input = {
+ attempt: 1,
+ context: {
+ messages: [],
+ modelParameters: { options: {}, params: {} },
+ resolvedTools: { tools: [] },
+ },
+ events: [],
+ maxAttempts: 3,
+ model: 'gpt-5.6-sol',
+ provider: 'lobehub',
+ state: {},
+} as any;
+
+describe('ClientLLMTransport.runAttempt Β· empty-completion grounding guard', () => {
+ beforeEach(() => {
+ finishGrounding = grounding;
+ });
+
+ it('keeps a grounding-only completion (empty content, positive output tokens) as a success', async () => {
+ finishGrounding = grounding;
+ const result = await createTransport().runAttempt(input);
+
+ expect(result.ok).toBe(true);
+ expect(result.output.grounding).toEqual(grounding);
+ });
+
+ it('still flags a truly empty completion (no content, no grounding) as ModelEmptyError', async () => {
+ finishGrounding = null;
+ const result = await createTransport().runAttempt(input);
+
+ expect(result.ok).toBe(false);
+ if (result.ok === false) {
+ expect(result.error).toBeInstanceOf(ModelEmptyError);
+ }
+ });
+});
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
index 6811508ab0e..b8000eb33ea 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -307,6 +307,7 @@ export class ClientLLMTransport implements LLMTransport {
if (
isEmptyModelCompletion({
content: output.content,
+ hasGrounding: !!output.grounding,
imageCount: output.imageList.length + (output.hasContentImages ? 1 : 0),
outputTokens: output.usage?.totalOutputTokens,
reasoning: output.thinkingContent,