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.

♻️ refactor: extract server call llm attempt (#17003)

Arvin Xu728bd5ee1458
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
new file mode 100644
index 00000000000..be48f313597
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
@@ -0,0 +1,197 @@
+import type { AgentEvent } from '@lobechat/agent-runtime';
+import { ToolNameResolver } from '@lobechat/context-engine';
+import type { ChatMethodOptions, ModelRuntime } from '@lobechat/model-runtime';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeExecutorContext } from '../context';
+import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
+import type { ServerCallLlmTooling } from './serverCallLlmTooling';
+
+vi.mock('@lobechat/model-runtime', async () => {
+ const { isEmptyModelCompletion, ModelEmptyError } =
+ await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');
+ const { consumeStreamUntilDone } =
+ await import('../../../../../../packages/model-runtime/src/utils/consumeStream');
+
+ return { consumeStreamUntilDone, isEmptyModelCompletion, ModelEmptyError };
+});
+
+vi.mock('@/envs/file', () => ({
+ fileEnv: { NEXT_PUBLIC_S3_FILE_PATH: 'files' },
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ uploadBase64: vi.fn(),
+ })),
+}));
+
+const toolName = new ToolNameResolver().generate('workspace', 'search', 'builtin');
+const resolved = {
+ enabledToolIds: ['workspace'],
+ executorMap: { workspace: 'server' },
+ manifestMap: {},
+ promptManifestMap: {},
+ sourceMap: { workspace: 'builtin' },
+ tools: [
+ {
+ function: {
+ description: 'Search the workspace',
+ name: toolName,
+ parameters: { type: 'object' },
+ },
+ type: 'function',
+ },
+ ],
+} as ServerCallLlmTooling['resolved'];
+
+const createAttempt = (runCallbacks: (options: ChatMethodOptions) => Promise<void>) => {
+ const publishStreamChunk = vi.fn().mockResolvedValue('event-1');
+ const streamManager = {
+ publishStreamChunk,
+ publishStreamEvent: vi.fn().mockResolvedValue('event-2'),
+ } as unknown as RuntimeExecutorContext['streamManager'];
+ const ctx = {
+ messageModel: {} as RuntimeExecutorContext['messageModel'],
+ operationId: 'operation-1',
+ serverDB: {} as RuntimeExecutorContext['serverDB'],
+ stepIndex: 2,
+ streamManager,
+ toolExecutionService: {} as RuntimeExecutorContext['toolExecutionService'],
+ userId: 'user-1',
+ } satisfies RuntimeExecutorContext;
+ const chat = vi.fn(async (_payload, options?: ChatMethodOptions) => {
+ await runCallbacks(options!);
+ return new Response('done');
+ });
+ const events: AgentEvent[] = [];
+ const onFirstChunk = vi.fn();
+ const attempt = createServerCallLlmAttempt({
+ attempt: 1,
+ chatPayload: {
+ messages: [{ content: 'Question', role: 'user' }],
+ model: 'test-model',
+ stream: true,
+ tools: resolved.tools,
+ },
+ ctx,
+ events,
+ maxAttempts: 3,
+ messageCount: 1,
+ model: 'test-model',
+ modelRuntime: { chat } as unknown as Pick<ModelRuntime, 'chat'>,
+ onFirstChunk,
+ operationLogId: 'operation-1:2',
+ provider: 'test-provider',
+ resolved,
+ topicId: 'topic-1',
+ trigger: 'user',
+ });
+
+ return { attempt, chat, events, onFirstChunk, publishStreamChunk };
+};
+
+describe('ServerCallLlmAttempt', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('collects callback output and exposes a completed attempt snapshot', async () => {
+ const rawToolCall = {
+ function: { arguments: '{"query":"docs"}', name: toolName },
+ id: 'call-1',
+ type: 'function' as const,
+ };
+ const { attempt, events, onFirstChunk, publishStreamChunk } = createAttempt(
+ async ({ callback }) => {
+ await callback?.onText?.('Visible answer');
+ await callback?.onThinking?.('Reasoning');
+ await callback?.onGrounding?.({ searchQueries: ['docs'] });
+ await callback?.onToolsCalling?.({ chunk: [], toolsCalling: [rawToolCall] });
+ await callback?.onCompletion?.({
+ finishReason: 'tool_use',
+ speed: { tps: 20, ttft: 100 },
+ text: '',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ });
+ },
+ );
+
+ await attempt.execute();
+
+ expect(attempt.streamSink.content).toBe('Visible answer');
+ expect(attempt.streamSink.thinkingContent).toBe('Reasoning');
+ expect(attempt.grounding).toEqual({ searchQueries: ['docs'] });
+ expect(attempt.finishReason).toBe('tool_use');
+ expect(attempt.speed).toEqual({ tps: 20, ttft: 100 });
+ expect(attempt.usage).toEqual({
+ totalInputTokens: 10,
+ totalOutputTokens: 5,
+ totalTokens: 15,
+ });
+ expect(attempt.toolCalls).toEqual([rawToolCall]);
+ expect(attempt.toolsCalling).toEqual([
+ expect.objectContaining({
+ apiName: 'search',
+ executor: 'server',
+ id: 'call-1',
+ identifier: 'workspace',
+ source: 'builtin',
+ }),
+ ]);
+ expect(onFirstChunk).toHaveBeenCalledTimes(2);
+ expect(events).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ chunk: { text: 'Visible answer', type: 'text' } }),
+ expect.objectContaining({ chunk: { text: 'Reasoning', type: 'reasoning' } }),
+ ]),
+ );
+ expect(publishStreamChunk).toHaveBeenCalledWith(
+ 'operation-1',
+ 2,
+ expect.objectContaining({ chunkType: 'tools_calling' }),
+ );
+ });
+
+ it('keeps partial output and usage readable after a stream error', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onText?.('Partial answer');
+ await callback?.onCompletion?.({
+ text: '',
+ usage: { totalOutputTokens: 3 },
+ });
+ await callback?.onError?.({
+ errorType: 'ProviderBizError',
+ message: 'provider stream failed',
+ status: 503,
+ });
+ });
+
+ await expect(attempt.execute()).rejects.toMatchObject({
+ errorType: 'ProviderBizError',
+ message: 'LLM stream error: provider stream failed',
+ status: 503,
+ });
+ attempt.streamSink.clearBuffers();
+
+ expect(attempt.streamSink.content).toBe('Partial answer');
+ expect(attempt.usage).toEqual({ totalOutputTokens: 3 });
+ });
+
+ it('salvages a natural-stop answer emitted only in reasoning', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onThinking?.('Final answer from reasoning');
+ await callback?.onCompletion?.({
+ finishReason: 'stop',
+ text: '',
+ usage: { totalOutputTokens: 5 },
+ });
+ });
+
+ await attempt.execute();
+
+ expect(attempt.answerSalvagedFromReasoning).toBe(true);
+ expect(attempt.streamSink.content).toBe('Final answer from reasoning');
+ expect(attempt.streamSink.thinkingContent).toBe('');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
new file mode 100644
index 00000000000..6909bc995df
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -0,0 +1,314 @@
+import type { AgentEvent } from '@lobechat/agent-runtime';
+import { ToolNameResolver } from '@lobechat/context-engine';
+import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
+import {
+ consumeStreamUntilDone,
+ isEmptyModelCompletion,
+ ModelEmptyError,
+} from '@lobechat/model-runtime';
+import type {
+ ChatImageItem,
+ ChatToolPayload,
+ GroundingSearch,
+ MessageToolCall,
+ ModelPerformance,
+ ModelUsage,
+} from '@lobechat/types';
+import { pickString, toRecord } from '@lobechat/utils/object';
+
+import type { RuntimeExecutorContext } from '../context';
+import { isOperationInterrupted, log, timing } from '../executorHelpers';
+import {
+ createServerCallLlmStreamSink,
+ type ServerCallLlmStreamSink,
+} from './serverCallLlmStreamSink';
+import type { ServerCallLlmTooling } from './serverCallLlmTooling';
+
+interface CreateServerCallLlmAttemptInput {
+ attempt: number;
+ chatPayload: ChatStreamPayload;
+ ctx: RuntimeExecutorContext;
+ events: AgentEvent[];
+ maxAttempts: number;
+ messageCount: number;
+ model: string;
+ modelRuntime: Pick<ModelRuntime, 'chat'>;
+ onFirstChunk: () => void;
+ operationLogId: string;
+ provider: string;
+ resolved: ServerCallLlmTooling['resolved'];
+ topicId?: string;
+ trigger?: unknown;
+}
+
+const createStreamExecutionError = (errorData: unknown) => {
+ const errorRecord = toRecord(errorData);
+ const message = pickString(errorRecord?.message);
+ const error = new Error(
+ message ? `LLM stream error: ${message}` : `LLM stream error: ${JSON.stringify(errorData)}`,
+ );
+
+ if (errorRecord) {
+ const { message: _message, ...details } = errorRecord;
+ Object.assign(error, details);
+ }
+
+ return error;
+};
+
+export class ServerCallLlmAttempt {
+ answerSalvagedFromReasoning = false;
+ finishReason?: string;
+ grounding: GroundingSearch | null = null;
+ readonly imageList: ChatImageItem[] = [];
+ speed?: ModelPerformance;
+ readonly streamSink: ServerCallLlmStreamSink;
+ toolCalls: MessageToolCall[] = [];
+ toolsCalling: ChatToolPayload[] = [];
+ usage?: ModelUsage;
+
+ private readonly attempt: number;
+ private readonly chatPayload: ChatStreamPayload;
+ private readonly ctx: RuntimeExecutorContext;
+ private readonly maxAttempts: number;
+ private readonly messageCount: number;
+ private readonly model: string;
+ private readonly modelRuntime: Pick<ModelRuntime, 'chat'>;
+ private readonly onFirstChunk: () => void;
+ private readonly operationLogId: string;
+ private readonly provider: string;
+ private readonly resolved: ServerCallLlmTooling['resolved'];
+ private streamError?: unknown;
+ private readonly topicId?: string;
+ private readonly trigger?: unknown;
+
+ constructor({
+ attempt,
+ chatPayload,
+ ctx,
+ events,
+ maxAttempts,
+ messageCount,
+ model,
+ modelRuntime,
+ onFirstChunk,
+ operationLogId,
+ provider,
+ resolved,
+ topicId,
+ trigger,
+ }: CreateServerCallLlmAttemptInput) {
+ this.attempt = attempt;
+ this.chatPayload = chatPayload;
+ this.ctx = ctx;
+ this.maxAttempts = maxAttempts;
+ this.messageCount = messageCount;
+ this.model = model;
+ this.modelRuntime = modelRuntime;
+ this.onFirstChunk = onFirstChunk;
+ this.operationLogId = operationLogId;
+ this.provider = provider;
+ this.resolved = resolved;
+ this.streamSink = createServerCallLlmStreamSink({ ctx, events, operationLogId });
+ this.topicId = topicId;
+ this.trigger = trigger;
+ }
+
+ async execute(): Promise<void> {
+ log(
+ '[%s][call_llm] calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)',
+ this.operationLogId,
+ this.attempt,
+ this.maxAttempts,
+ this.model,
+ this.messageCount,
+ this.chatPayload.tools?.length ?? 0,
+ );
+
+ const response = await this.modelRuntime.chat(this.chatPayload, {
+ callback: {
+ onBase64Image: async ({ image }) => {
+ this.onFirstChunk();
+ await this.streamSink.appendBase64Image(image);
+ },
+ onCompletion: async (data) => {
+ if (data.usage) this.usage = data.usage;
+ if (data.speed) this.speed = data.speed;
+ if (data.finishReason) this.finishReason = data.finishReason;
+ },
+ onContentPart: async (part) => {
+ this.onFirstChunk();
+ await this.streamSink.appendContentPart(part);
+ },
+ onError: async (errorData) => {
+ this.streamError = errorData;
+ console.error(`[${this.operationLogId}][stream_error]`, errorData);
+ },
+ onGrounding: async (groundingData) => {
+ log(`[${this.operationLogId}][grounding] %O`, groundingData);
+ this.grounding = groundingData;
+
+ await this.ctx.streamManager.publishStreamChunk(
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ {
+ chunkType: 'grounding',
+ grounding: groundingData,
+ },
+ );
+ },
+ onReasoningPart: async (part) => {
+ this.onFirstChunk();
+ await this.streamSink.appendReasoningPart(part);
+ },
+ onText: async (text) => {
+ this.onFirstChunk();
+ timing(
+ '[%s] onText received chunk at %d, length: %d',
+ this.operationLogId,
+ Date.now(),
+ text.length,
+ );
+ await this.streamSink.appendText(text);
+ },
+ onThinking: async (reasoning) => {
+ this.onFirstChunk();
+ timing(
+ '[%s] onThinking received chunk at %d, length: %d',
+ this.operationLogId,
+ Date.now(),
+ reasoning.length,
+ );
+ await this.streamSink.appendThinking(reasoning);
+ },
+ onToolsCalling: async ({ toolsCalling: raw }) => {
+ const resolvedCalls = new ToolNameResolver().resolve(
+ raw,
+ this.resolved.promptManifestMap,
+ this.resolved.tools.map((tool) => tool.function.name),
+ );
+ const payload = resolvedCalls.map((toolCall) => ({
+ ...toolCall,
+ executor: this.resolved.executorMap?.[toolCall.identifier],
+ source: this.resolved.sourceMap[toolCall.identifier],
+ }));
+
+ this.toolsCalling = payload;
+ // Keep raw arguments through execution so malformed JSON can reach the
+ // tool error path and give the model a self-repair signal. Finalizers
+ // sanitize only the persisted DB and replay-state copies.
+ this.toolCalls = raw;
+
+ await this.streamSink.flushTextBuffer();
+ await this.ctx.streamManager.publishStreamChunk(
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ {
+ chunkType: 'tools_calling',
+ toolsCalling: payload,
+ },
+ );
+ },
+ },
+ metadata: {
+ operationId: this.ctx.operationId,
+ topicId: this.topicId,
+ trigger: this.trigger,
+ },
+ user: this.ctx.userId,
+ });
+
+ await consumeStreamUntilDone(response);
+
+ if (this.streamError) throw createStreamExecutionError(this.streamError);
+
+ await this.streamSink.flushTextBuffer();
+ await this.streamSink.flushReasoningBuffer();
+ this.streamSink.clearBuffers();
+ await this.streamSink.waitForImageUploads();
+
+ await this.assertNonEmptyCompletion();
+ this.salvageAnswerFromReasoning();
+ this.logResult();
+ }
+
+ private async assertNonEmptyCompletion() {
+ if (
+ isEmptyModelCompletion({
+ content: this.streamSink.content,
+ imageCount: this.imageList.length,
+ outputTokens: this.usage?.totalOutputTokens,
+ reasoning: this.streamSink.thinkingContent,
+ toolCallCount: this.toolsCalling.length + this.toolCalls.length,
+ }) &&
+ !(await isOperationInterrupted(this.ctx))
+ ) {
+ log(
+ '[%s] Model returned an empty completion (attempt %d/%d) β€” throwing ModelEmptyError to retry',
+ this.operationLogId,
+ this.attempt,
+ this.maxAttempts,
+ );
+ throw new ModelEmptyError(undefined, {
+ attempt: this.attempt,
+ contentLength: this.streamSink.content.length,
+ finishReason: this.finishReason,
+ imageCount: this.imageList.length,
+ maxAttempts: this.maxAttempts,
+ model: this.model,
+ outputTokens: this.usage?.totalOutputTokens,
+ provider: this.provider,
+ reasoningLength: this.streamSink.thinkingContent.length,
+ toolCallCount: this.toolsCalling.length + this.toolCalls.length,
+ });
+ }
+ }
+
+ private logResult() {
+ log(
+ '[%s] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s',
+ this.operationLogId,
+ this.streamSink.content.length,
+ this.streamSink.thinkingContent.length,
+ this.toolsCalling.length,
+ this.usage ? 'yes' : 'none',
+ );
+
+ if (this.streamSink.thinkingContent) {
+ log(`[${this.operationLogId}][reasoning]`, this.streamSink.thinkingContent);
+ }
+ if (this.streamSink.content) {
+ log(`[${this.operationLogId}][content]`, this.streamSink.content);
+ }
+ if (this.toolsCalling.length > 0) {
+ log(`[${this.operationLogId}][toolsCalling] `, this.toolsCalling);
+ }
+ if (this.usage) {
+ log(`[${this.operationLogId}][usage] %O`, this.usage);
+ }
+ }
+
+ private salvageAnswerFromReasoning() {
+ const isTerminalNaturalStop = this.finishReason === 'end_turn' || this.finishReason === 'stop';
+ if (
+ isTerminalNaturalStop &&
+ this.toolsCalling.length === 0 &&
+ this.toolCalls.length === 0 &&
+ this.streamSink.content.trim().length === 0 &&
+ this.streamSink.thinkingContent.trim().length > 0 &&
+ !this.streamSink.hasReasoningImages
+ ) {
+ log(
+ '[%s] answer-in-thinking salvage: promoting %d chars of reasoning to content',
+ this.operationLogId,
+ this.streamSink.thinkingContent.length,
+ );
+ this.streamSink.content = this.streamSink.thinkingContent;
+ this.streamSink.thinkingContent = '';
+ this.answerSalvagedFromReasoning = true;
+ }
+ }
+}
+
+export const createServerCallLlmAttempt = (input: CreateServerCallLlmAttemptInput) =>
+ new ServerCallLlmAttempt(input);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
index f64daf24851..05984b57e1a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
@@ -10,13 +10,7 @@ import {
shouldRetryLLM,
} from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { ToolNameResolver } from '@lobechat/context-engine';
-import {
- type ChatStreamPayload,
- consumeStreamUntilDone,
- isEmptyModelCompletion,
- ModelEmptyError,
-} from '@lobechat/model-runtime';
+import { type ChatStreamPayload, ModelEmptyError } from '@lobechat/model-runtime';
import {
context as otelContext,
SpanKind,
@@ -29,28 +23,20 @@ import {
chatSpanName,
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
-import type {
- ChatImageItem,
- ChatToolPayload,
- GroundingSearch,
- MessageToolCall,
- ModelPerformance,
- ModelUsage,
-} from '@lobechat/types';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { type RuntimeExecutorContext } from '../context';
-import { isOperationInterrupted, log, sleep, timing } from '../executorHelpers';
+import { isOperationInterrupted, log, sleep } from '../executorHelpers';
import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
+import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';
import {
finalizeServerCallLlmResult,
persistInterruptedServerCallLlmResult,
} from './serverCallLlmFinalizer';
-import { createServerCallLlmStreamSink } from './serverCallLlmStreamSink';
import { resolveServerCallLlmTooling, type ServerCallLlmTooling } from './serverCallLlmTooling';
interface PreparedCallLLMContext {
@@ -243,6 +229,9 @@ export const callLlm =
// semantic span represents the LLM call from the agent's perspective).
const llmStartTime = Date.now();
let firstChunkAt: number | undefined;
+ const onFirstChunk = () => {
+ if (firstChunkAt === undefined) firstChunkAt = Date.now() - llmStartTime;
+ };
const chatSpan = agentRuntimeTracer.startSpan(chatSpanName(model), {
attributes: buildChatRequestAttributes({
conversationId: state.metadata?.topicId,
@@ -259,291 +248,36 @@ export const callLlm =
try {
return await otelContext.with(chatCtx, async () => {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- const streamSink = createServerCallLlmStreamSink({
+ const llmAttempt = createServerCallLlmAttempt({
+ attempt,
+ chatPayload,
ctx,
events,
+ maxAttempts,
+ messageCount: processedMessages.length,
+ model,
+ modelRuntime,
+ onFirstChunk,
operationLogId,
+ provider,
+ resolved,
+ topicId: state.metadata?.topicId,
+ trigger: state.metadata?.trigger,
});
- let toolsCalling: ChatToolPayload[] = [];
- let tool_calls: MessageToolCall[] = [];
- const imageList: ChatImageItem[] = [];
- let grounding: GroundingSearch | null = null;
- let currentStepUsage: ModelUsage | undefined;
- let currentStepSpeed: ModelPerformance | undefined;
- let currentStepFinishReason: string | undefined = undefined;
- let streamError: any = undefined;
- // Set when a terminal turn's answer was salvaged from the reasoning
- // channel (see the answer-in-thinking guard below) β€” surfaced in
- // message metadata for observability.
- let answerSalvagedFromReasoning = false;
try {
- log(
- `${stagePrefix} calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)`,
- attempt,
- maxAttempts,
- model,
- processedMessages.length,
- tools?.length ?? 0,
- );
-
- // Call model-runtime chat
- const response = await modelRuntime.chat(chatPayload, {
- callback: {
- onCompletion: async (data) => {
- // Capture usage (may or may not include cost)
- if (data.usage) {
- currentStepUsage = data.usage;
- }
- // Capture performance metrics (tps / ttft / duration / latency)
- if (data.speed) {
- currentStepSpeed = data.speed;
- }
- // Capture provider's terminal finishReason so soft interrupts
- // (e.g. Gemini RECITATION / MAX_TOKENS with empty content)
- // are visible in tracing instead of being silently swallowed.
- if (data.finishReason) {
- currentStepFinishReason = data.finishReason;
- }
- },
- onGrounding: async (groundingData) => {
- log(`[${operationLogId}][grounding] %O`, groundingData);
- grounding = groundingData;
-
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'grounding',
- grounding: groundingData,
- });
- },
- onText: async (text) => {
- if (firstChunkAt === undefined) {
- firstChunkAt = Date.now() - llmStartTime;
- }
- timing(
- '[%s] onText received chunk at %d, length: %d',
- operationLogId,
- Date.now(),
- text.length,
- );
- await streamSink.appendText(text);
- },
- onThinking: async (reasoning) => {
- if (firstChunkAt === undefined) {
- firstChunkAt = Date.now() - llmStartTime;
- }
- timing(
- '[%s] onThinking received chunk at %d, length: %d',
- operationLogId,
- Date.now(),
- reasoning.length,
- );
- await streamSink.appendThinking(reasoning);
- },
- // Gemini 2.5+/3 multimodal streams deliver assistant text and
- // reasoning as `content_part`/`reasoning_part` events (triggered by
- // thought parts / thoughtSignature) instead of plain `text`/
- // `reasoning`. Without these handlers the text is silently dropped:
- // `onCompletion` still reports usage tokens, so the empty-completion
- // guard sees outputTokens > 0 and finalizes the turn to a blank
- // `done`. Mirror onText/onThinking for text parts so streaming,
- // persistence and tracing all capture the content; upload image
- // parts to object storage and serialize the multimodal content
- // (text + image URLs, in order) β€” never persist raw base64.
- onContentPart: async (part) => {
- if (firstChunkAt === undefined) {
- firstChunkAt = Date.now() - llmStartTime;
- }
-
- await streamSink.appendContentPart(part);
- },
- // Some Gemini / Nano Banana image responses arrive via the
- // legacy single-image `base64_image` event instead of
- // `content_part` (the Google stream transform emits it when a
- // response can't be classified as multimodal). Without this
- // handler the image is silently dropped server-side β€” never
- // uploaded, never persisted β€” and, on channels that omit the
- // Image response modality, the raw base64 leaks into text and
- // bloats the context. Mirror the onContentPart image branch:
- // register a placeholder part, upload to object storage, and
- // mark the turn multimodal so raw base64 never lands in content.
- onBase64Image: async ({ image }) => {
- if (firstChunkAt === undefined) {
- firstChunkAt = Date.now() - llmStartTime;
- }
-
- await streamSink.appendBase64Image(image);
- },
- onReasoningPart: async (part) => {
- if (firstChunkAt === undefined) {
- firstChunkAt = Date.now() - llmStartTime;
- }
-
- await streamSink.appendReasoningPart(part);
- },
- onToolsCalling: async ({ toolsCalling: raw }) => {
- const resolvedCalls = new ToolNameResolver().resolve(
- raw,
- resolved.promptManifestMap,
- resolved.tools.map((tool) => tool.function.name),
- );
- // Attach source (origin) and executor (dispatch target) for routing.
- // `arguments` are kept RAW here on purpose so the tool executor can
- // still detect malformed JSON and return an `INVALID_JSON_ARGUMENTS`
- // tool-result with the original bad string β€” that's the
- // self-reflection signal the model needs to fix its own output.
- // Sanitization happens later, only at the persist boundaries
- // (DB write and state.messages push) to protect strict providers
- // replaying history. See .
- const payload = resolvedCalls.map((p) => ({
- ...p,
- executor: resolved.executorMap?.[p.identifier],
- source: resolved.sourceMap[p.identifier],
- }));
- // log(`[${operationLogId}][toolsCalling]`, payload);
- toolsCalling = payload;
- tool_calls = raw;
-
- await streamSink.flushTextBuffer();
-
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: payload,
- });
- },
- onError: async (errorData) => {
- streamError = errorData;
- console.error(`[${operationLogId}][stream_error]`, errorData);
- },
- },
- metadata: {
- operationId,
- topicId: state.metadata?.topicId,
- trigger: state.metadata?.trigger,
- },
- user: ctx.userId,
- });
-
- // Consume stream to ensure all callbacks complete execution
- await consumeStreamUntilDone(response);
-
- // If a stream error was captured via onError callback, throw to propagate the error
- if (streamError) {
- const streamExecutionError = new Error(
- typeof streamError.message === 'string'
- ? `LLM stream error: ${streamError.message}`
- : `LLM stream error: ${JSON.stringify(streamError)}`,
- );
- const { message: _message, ...restStreamError } = streamError as Record<
- string,
- unknown
- >;
- Object.assign(streamExecutionError, restStreamError);
- throw streamExecutionError;
- }
-
- await streamSink.flushTextBuffer();
- await streamSink.flushReasoningBuffer();
- streamSink.clearBuffers();
-
- // Wait for any model-generated image uploads to finish so the
- // persisted multimodal content references S3 URLs, not base64.
- await streamSink.waitForImageUploads();
-
- // Empty-completion guard: 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: streamSink.content,
- imageCount: imageList.length,
- outputTokens:
- typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,
- reasoning: streamSink.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(undefined, {
- attempt,
- contentLength: streamSink.content.length,
- finishReason: currentStepFinishReason,
- imageCount: imageList.length,
- maxAttempts,
- model,
- outputTokens:
- typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,
- provider,
- reasoningLength: streamSink.thinkingContent.length,
- toolCallCount: toolsCalling.length + tool_calls.length,
- });
- }
-
- // Answer-in-thinking salvage: some thinking-mode models β€” notably
- // DeepSeek V4 over the Anthropic-compatible API β€” occasionally emit
- // the final user-facing answer inside the reasoning channel and stop
- // naturally with an empty text block. The reasoning is then rendered
- // as a collapsed "thinking" panel, so the user sees a blank reply.
- // When a turn ends naturally with no tool calls and no visible
- // content but non-empty text reasoning, promote the reasoning to be
- // the answer. This is a backstop; the primary fix is replaying the
- // real assistant reasoning in history (see modelForcesPreserveThinking
- // above) which sharply reduces how often the model does this.
- const isTerminalNaturalStop =
- currentStepFinishReason === 'end_turn' || currentStepFinishReason === 'stop';
- if (
- isTerminalNaturalStop &&
- toolsCalling.length === 0 &&
- tool_calls.length === 0 &&
- streamSink.content.trim().length === 0 &&
- streamSink.thinkingContent.trim().length > 0 &&
- !streamSink.hasReasoningImages
- ) {
- log(
- '[%s] answer-in-thinking salvage: promoting %d chars of reasoning to content',
- operationLogId,
- streamSink.thinkingContent.length,
- );
- streamSink.content = streamSink.thinkingContent;
- streamSink.thinkingContent = '';
- answerSalvagedFromReasoning = true;
- }
-
- log(
- `[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,
- streamSink.content.length,
- streamSink.thinkingContent.length,
- toolsCalling.length,
- currentStepUsage ? 'yes' : 'none',
- );
-
- if (streamSink.thinkingContent) {
- log(`[${operationLogId}][reasoning]`, streamSink.thinkingContent);
- }
- if (streamSink.content) {
- log(`[${operationLogId}][content]`, streamSink.content);
- }
- if (toolsCalling.length > 0) {
- log(`[${operationLogId}][toolsCalling] `, toolsCalling);
- }
-
- // Log usage information
- if (currentStepUsage) {
- log(`[${operationLogId}][usage] %O`, currentStepUsage);
- }
+ await llmAttempt.execute();
+ const {
+ answerSalvagedFromReasoning,
+ finishReason: currentStepFinishReason,
+ grounding,
+ imageList,
+ speed: currentStepSpeed,
+ streamSink,
+ toolCalls: tool_calls,
+ toolsCalling,
+ usage: currentStepUsage,
+ } = llmAttempt;
// Add a complete llm_stream event (including all streaming chunks)
events.push({
@@ -651,7 +385,7 @@ export const callLlm =
},
};
} catch (error) {
- streamSink.clearBuffers();
+ llmAttempt.streamSink.clearBuffers();
const classified = classifyLLMError(error);
const interrupted = await isOperationInterrupted(ctx);
@@ -714,12 +448,12 @@ export const callLlm =
if (interrupted) {
await persistInterruptedServerCallLlmResult({
assistantMessageId: assistantMessageItem.id,
- currentStepSpeed,
- currentStepUsage,
+ currentStepSpeed: llmAttempt.speed,
+ currentStepUsage: llmAttempt.usage,
messageModel: ctx.messageModel,
operationLogId,
- streamOutput: streamSink,
- toolsCalling,
+ streamOutput: llmAttempt.streamSink,
+ toolsCalling: llmAttempt.toolsCalling,
});
}