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 finalizer (#16984)

Arvin Xu8188e914e7f3
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 7e399b2b574..eb1f69bbcc7 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -1697,6 +1697,31 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('should clear stale grounding when a reused assistant message receives no grounding', async () => {
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const existingAssistantId = 'existing-grounded-assistant';
+
+ await executors.call_llm!(
+ {
+ payload: {
+ assistantMessageId: existingAssistantId,
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ existingAssistantId,
+ expect.objectContaining({ search: null }),
+ );
+ });
+
it('should create new assistant message when assistantMessageId is not provided', async () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
index 88012d5a78c..f64daf24851 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
@@ -8,7 +8,6 @@ import {
resolveLLMMaxAttempts,
resolveLLMRetryBudget,
shouldRetryLLM,
- UsageCounter,
} from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { ToolNameResolver } from '@lobechat/context-engine';
@@ -30,8 +29,14 @@ import {
chatSpanName,
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload, type MessageToolCall } from '@lobechat/types';
-import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';
+import type {
+ ChatImageItem,
+ ChatToolPayload,
+ GroundingSearch,
+ MessageToolCall,
+ ModelPerformance,
+ ModelUsage,
+} from '@lobechat/types';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
@@ -40,8 +45,11 @@ import { isOperationInterrupted, log, sleep, timing } from '../executorHelpers';
import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
-import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';
+import {
+ finalizeServerCallLlmResult,
+ persistInterruptedServerCallLlmResult,
+} from './serverCallLlmFinalizer';
import { createServerCallLlmStreamSink } from './serverCallLlmStreamSink';
import { resolveServerCallLlmTooling, type ServerCallLlmTooling } from './serverCallLlmTooling';
@@ -258,10 +266,10 @@ export const callLlm =
});
let toolsCalling: ChatToolPayload[] = [];
let tool_calls: MessageToolCall[] = [];
- const imageList: any[] = [];
- let grounding: any = null;
- let currentStepUsage: any = undefined;
- let currentStepSpeed: any = undefined;
+ 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
@@ -589,146 +597,33 @@ export const callLlm =
log('[%s:%d] call_llm completed', operationId, stepIndex);
- // ===== 1. First save original usage to message.metadata =====
- // Determine final content - use serialized parts if has images, otherwise plain text
- const finalContent = streamSink.hasContentImages
- ? serializePartsForStorage(streamSink.contentParts)
- : streamSink.content;
-
- // Determine final reasoning - handle multimodal reasoning
- let finalReasoning: any = undefined;
- if (streamSink.hasReasoningImages) {
- // Has images, use multimodal format
- finalReasoning = {
- content: serializePartsForStorage(streamSink.reasoningParts),
- isMultimodal: true,
- };
- } else if (streamSink.thinkingContent) {
- // Has text from reasoning but no images
- finalReasoning = {
- content: streamSink.thinkingContent,
- };
- }
-
- // preserveThinking only gates whether reasoning is replayed into the
- // next LLM payload (state.messages); the DB copy powers UI display
- // after refresh and must always be saved.
- const replayedReasoning = shouldReplayAssistantReasoning ? finalReasoning : undefined;
-
- try {
- // Build metadata object
- const metadata: Record<string, any> = {};
- if (currentStepUsage && typeof currentStepUsage === 'object') {
- // Flat fields are kept for backward-compatible readers; `usage`
- // is the canonical nested shape new readers should consume.
- Object.assign(metadata, currentStepUsage);
- metadata.usage = currentStepUsage;
- }
- if (currentStepSpeed && typeof currentStepSpeed === 'object') {
- Object.assign(metadata, currentStepSpeed);
- metadata.performance = currentStepSpeed;
- }
- if (streamSink.hasContentImages) {
- metadata.isMultimodal = true;
- }
- if (answerSalvagedFromReasoning) {
- metadata.answerSalvagedFromReasoning = true;
- }
-
- // Sanitize tool_call `arguments` before persisting to DB so malformed
- // JSON (e.g. Qwen emitting `{, ...}`) can't poison future context
- // builds and 400 strict providers like NVIDIA NIM. See .
- const persistedTools =
- toolsCalling.length > 0
- ? toolsCalling.map((t) => ({
- ...t,
- arguments: sanitizeToolCallArguments(t.arguments),
- }))
- : undefined;
-
- await ctx.messageModel.update(assistantMessageItem.id, {
- content: finalContent,
- imageList: imageList.length > 0 ? imageList : undefined,
- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
- reasoning: finalReasoning,
- search: grounding,
- tools: persistedTools,
- });
- } catch (error) {
- console.error('[call_llm] Failed to update message:', error);
- }
-
- // ===== 2. Then accumulate to AgentState =====
- const newState = structuredClone(state);
-
- // state.messages flows into the next LLM call payload, so entries
- // must be safe for strict-provider history replay:
- // - drop tool_calls with empty name (undispatchable, and strict
- // providers 400 on nameless entries)
- // - coerce malformed JSON `arguments` to valid JSON
- const sanitizedToolCalls =
- tool_calls.length > 0
- ? tool_calls
- .filter((tc) => !!tc.function.name)
- .map((tc) => ({
- ...tc,
- function: {
- ...tc.function,
- arguments: sanitizeToolCallArguments(tc.function.arguments),
- },
- }))
- : [];
- const stateToolCalls = sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;
-
- newState.messages.push({
- content: streamSink.content,
- id: assistantMessageItem.id,
- reasoning: replayedReasoning,
- role: 'assistant',
- tool_calls: stateToolCalls,
+ const newState = await finalizeServerCallLlmResult({
+ answerSalvagedFromReasoning,
+ assistantMessageId: assistantMessageItem.id,
+ currentStepSpeed,
+ currentStepUsage,
+ grounding,
+ imageList,
+ messageModel: ctx.messageModel,
+ model,
+ provider,
+ shouldReplayAssistantReasoning,
+ state,
+ stepLabel,
+ streamOutput: streamSink,
+ toolCalls: tool_calls,
+ toolsCalling,
+ visibleOutputEndPublishedStepIndex,
});
- if (currentStepUsage) {
- // Use UsageCounter to uniformly accumulate usage and cost
- const { usage, cost } = UsageCounter.accumulateLLM({
- cost: newState.cost,
- model: llmPayload.model,
- modelUsage: currentStepUsage,
- provider: llmPayload.provider,
- usage: newState.usage,
- });
-
- newState.usage = usage;
- if (cost) newState.cost = cost;
- }
-
- // Propagate stepLabel from instruction to state metadata for hook consumers
- if (stepLabel || visibleOutputEndPublishedStepIndex !== undefined) {
- const stateMetadata = { ...newState.metadata };
- if (stepLabel) stateMetadata._stepLabel = stepLabel;
- if (visibleOutputEndPublishedStepIndex !== undefined) {
- stateMetadata[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY] =
- visibleOutputEndPublishedStepIndex;
- }
- newState.metadata = stateMetadata;
- }
-
// Record chat response attributes on the OTel span.
- const usageRecord = currentStepUsage as
- | {
- inputCachedTokens?: number;
- outputReasoningTokens?: number;
- totalInputTokens?: number;
- totalOutputTokens?: number;
- }
- | undefined;
chatSpan.setAttributes(
buildChatResponseAttributes({
- cacheReadInputTokens: usageRecord?.inputCachedTokens,
+ cacheReadInputTokens: currentStepUsage?.inputCachedTokens,
finishReasons: currentStepFinishReason ? [currentStepFinishReason] : undefined,
- inputTokens: usageRecord?.totalInputTokens,
- outputTokens: usageRecord?.totalOutputTokens,
- reasoningOutputTokens: usageRecord?.outputReasoningTokens,
+ inputTokens: currentStepUsage?.totalInputTokens,
+ outputTokens: currentStepUsage?.totalOutputTokens,
+ reasoningOutputTokens: currentStepUsage?.outputReasoningTokens,
timeToFirstChunkMs: firstChunkAt,
}),
);
@@ -810,52 +705,22 @@ export const callLlm =
}
// Cancel/interrupt path: when the user stops mid-stream, the model-runtime
- // stream is aborted before reaching the post-stream finalize (line ~1078),
+ // stream is aborted before reaching the post-stream finalize,
// so the DB row remains a LOADING_FLAT placeholder. Without this fix,
// agent_runtime_end would push the placeholder as the source-of-truth
// to the client, clobbering the streamed content accumulated in memory.
// We persist whatever partial content the stream callbacks already
// accumulated so that reload/end snapshots reflect actual progress.
- if (
- interrupted &&
- (streamSink.content || streamSink.thinkingContent || toolsCalling.length > 0)
- ) {
- try {
- const persistedTools =
- toolsCalling.length > 0
- ? toolsCalling.map((t) => ({
- ...t,
- arguments: sanitizeToolCallArguments(t.arguments),
- }))
- : undefined;
- const interruptedReasoning = streamSink.thinkingContent
- ? { content: streamSink.thinkingContent }
- : undefined;
- const interruptedMetadata: Record<string, any> = { interruptedMidStream: true };
- if (currentStepUsage && typeof currentStepUsage === 'object') {
- Object.assign(interruptedMetadata, currentStepUsage);
- interruptedMetadata.usage = currentStepUsage;
- }
- if (currentStepSpeed && typeof currentStepSpeed === 'object') {
- Object.assign(interruptedMetadata, currentStepSpeed);
- interruptedMetadata.performance = currentStepSpeed;
- }
- await ctx.messageModel.update(assistantMessageItem.id, {
- content: streamSink.content,
- metadata: interruptedMetadata,
- reasoning: interruptedReasoning,
- tools: persistedTools,
- });
- log(
- '[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',
- operationLogId,
- streamSink.content.length,
- streamSink.thinkingContent.length,
- toolsCalling.length,
- );
- } catch (persistErr) {
- log('[%s] Interrupted finalize update failed: %O', operationLogId, persistErr);
- }
+ if (interrupted) {
+ await persistInterruptedServerCallLlmResult({
+ assistantMessageId: assistantMessageItem.id,
+ currentStepSpeed,
+ currentStepUsage,
+ messageModel: ctx.messageModel,
+ operationLogId,
+ streamOutput: streamSink,
+ toolsCalling,
+ });
}
throw error;
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts
new file mode 100644
index 00000000000..9d81d489cd1
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts
@@ -0,0 +1,228 @@
+import { AgentRuntime } from '@lobechat/agent-runtime';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeExecutorContext } from '../context';
+import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+import {
+ finalizeServerCallLlmResult,
+ persistInterruptedServerCallLlmResult,
+} from './serverCallLlmFinalizer';
+
+const createMessageModel = () => {
+ const update = vi.fn().mockResolvedValue({ success: true });
+
+ return {
+ messageModel: { update } as unknown as RuntimeExecutorContext['messageModel'],
+ update,
+ };
+};
+
+const createStreamOutput = (
+ overrides?: Partial<{
+ content: string;
+ contentParts: Array<{ image: string; type: 'image' } | { text: string; type: 'text' }>;
+ hasContentImages: boolean;
+ hasReasoningImages: boolean;
+ reasoningParts: Array<{ image: string; type: 'image' } | { text: string; type: 'text' }>;
+ thinkingContent: string;
+ }>,
+) => ({
+ content: 'Answer',
+ contentParts: [],
+ hasContentImages: false,
+ hasReasoningImages: false,
+ reasoningParts: [],
+ thinkingContent: 'Reasoning',
+ ...overrides,
+});
+
+describe('serverCallLlmFinalizer', () => {
+ it('persists the message and builds replay-safe state with resolved model usage', async () => {
+ const { messageModel, update } = createMessageModel();
+ const state = AgentRuntime.createInitialState({
+ messages: [{ content: 'Question', role: 'user' }],
+ metadata: { topicId: 'topic-1' },
+ operationId: 'operation-1',
+ });
+ const currentStepUsage = {
+ cost: 0.05,
+ totalInputTokens: 10,
+ totalOutputTokens: 5,
+ totalTokens: 15,
+ };
+
+ const newState = await finalizeServerCallLlmResult({
+ answerSalvagedFromReasoning: true,
+ assistantMessageId: 'assistant-1',
+ currentStepSpeed: { tps: 12, ttft: 120 },
+ currentStepUsage,
+ grounding: { searchQueries: ['query'] },
+ imageList: [],
+ messageModel,
+ model: 'fallback-model',
+ provider: 'fallback-provider',
+ shouldReplayAssistantReasoning: true,
+ state,
+ stepLabel: 'research:answer',
+ streamOutput: createStreamOutput(),
+ toolCalls: [
+ {
+ function: { arguments: 'not-json', name: 'search' },
+ id: 'call-1',
+ type: 'function',
+ },
+ {
+ function: { arguments: '{}', name: '' },
+ id: 'call-without-name',
+ type: 'function',
+ },
+ ],
+ toolsCalling: [
+ {
+ apiName: 'search',
+ arguments: 'not-json',
+ id: 'call-1',
+ identifier: 'search-tool',
+ type: 'default',
+ },
+ ],
+ visibleOutputEndPublishedStepIndex: 3,
+ });
+
+ expect(update).toHaveBeenCalledWith(
+ 'assistant-1',
+ expect.objectContaining({
+ content: 'Answer',
+ metadata: expect.objectContaining({
+ answerSalvagedFromReasoning: true,
+ performance: { tps: 12, ttft: 120 },
+ usage: currentStepUsage,
+ }),
+ reasoning: { content: 'Reasoning' },
+ search: { searchQueries: ['query'] },
+ tools: [expect.objectContaining({ arguments: '{}' })],
+ }),
+ );
+ expect(state.messages).toHaveLength(1);
+ expect(newState.messages.at(-1)).toEqual({
+ content: 'Answer',
+ id: 'assistant-1',
+ reasoning: { content: 'Reasoning' },
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ type: 'function',
+ },
+ ],
+ });
+ expect(newState.usage.llm).toMatchObject({
+ apiCalls: 1,
+ tokens: { input: 10, output: 5, total: 15 },
+ });
+ expect(newState.cost.llm.byModel).toEqual([
+ expect.objectContaining({
+ id: 'fallback-provider/fallback-model',
+ model: 'fallback-model',
+ provider: 'fallback-provider',
+ }),
+ ]);
+ expect(newState.metadata).toMatchObject({
+ _stepLabel: 'research:answer',
+ [VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY]: 3,
+ });
+ });
+
+ it('persists multimodal content while keeping reasoning replay gated', async () => {
+ const { messageModel, update } = createMessageModel();
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+
+ const newState = await finalizeServerCallLlmResult({
+ answerSalvagedFromReasoning: false,
+ assistantMessageId: 'assistant-1',
+ grounding: null,
+ imageList: [],
+ messageModel,
+ model: 'gemini',
+ provider: 'google',
+ shouldReplayAssistantReasoning: false,
+ state,
+ streamOutput: createStreamOutput({
+ content: 'Image answer',
+ contentParts: [
+ { text: 'Image answer', type: 'text' },
+ { image: 'https://example.com/image.png', type: 'image' },
+ ],
+ hasContentImages: true,
+ hasReasoningImages: true,
+ reasoningParts: [
+ { text: 'Visual reasoning', type: 'text' },
+ { image: 'https://example.com/reasoning.png', type: 'image' },
+ ],
+ thinkingContent: 'Visual reasoning',
+ }),
+ toolCalls: [],
+ toolsCalling: [],
+ });
+
+ expect(update).toHaveBeenCalledWith(
+ 'assistant-1',
+ expect.objectContaining({
+ content: JSON.stringify([
+ { text: 'Image answer', type: 'text' },
+ { image: 'https://example.com/image.png', type: 'image' },
+ ]),
+ metadata: { isMultimodal: true },
+ reasoning: {
+ content: JSON.stringify([
+ { text: 'Visual reasoning', type: 'text' },
+ { image: 'https://example.com/reasoning.png', type: 'image' },
+ ]),
+ isMultimodal: true,
+ },
+ }),
+ );
+ expect(newState.messages.at(-1)).toEqual({
+ content: 'Image answer',
+ id: 'assistant-1',
+ reasoning: undefined,
+ role: 'assistant',
+ tool_calls: undefined,
+ });
+ });
+
+ it('persists partial interrupted output and skips empty interruptions', async () => {
+ const { messageModel, update } = createMessageModel();
+
+ await persistInterruptedServerCallLlmResult({
+ assistantMessageId: 'assistant-empty',
+ messageModel,
+ operationLogId: 'operation-1:0',
+ streamOutput: createStreamOutput({ content: '', thinkingContent: '' }),
+ toolsCalling: [],
+ });
+ expect(update).not.toHaveBeenCalled();
+
+ await persistInterruptedServerCallLlmResult({
+ assistantMessageId: 'assistant-partial',
+ currentStepSpeed: { tps: 8 },
+ currentStepUsage: { totalOutputTokens: 4 },
+ messageModel,
+ operationLogId: 'operation-1:0',
+ streamOutput: createStreamOutput({ content: 'Partial', thinkingContent: 'Thinking' }),
+ toolsCalling: [],
+ });
+
+ expect(update).toHaveBeenCalledWith('assistant-partial', {
+ content: 'Partial',
+ metadata: expect.objectContaining({
+ interruptedMidStream: true,
+ performance: { tps: 8 },
+ usage: { totalOutputTokens: 4 },
+ }),
+ reasoning: { content: 'Thinking' },
+ tools: undefined,
+ });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts
new file mode 100644
index 00000000000..26c8648c546
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts
@@ -0,0 +1,233 @@
+import { type AgentState, UsageCounter } from '@lobechat/agent-runtime';
+import type {
+ ChatImageItem,
+ ChatToolPayload,
+ GroundingSearch,
+ MessageMetadata,
+ MessageToolCall,
+ ModelPerformance,
+ ModelReasoning,
+ ModelUsage,
+} from '@lobechat/types';
+import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';
+
+import type { RuntimeExecutorContext } from '../context';
+import { log } from '../executorHelpers';
+import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+import type { ServerCallLlmStreamSink } from './serverCallLlmStreamSink';
+
+type ServerCallLlmCollectedOutput = Pick<
+ ServerCallLlmStreamSink,
+ | 'content'
+ | 'contentParts'
+ | 'hasContentImages'
+ | 'hasReasoningImages'
+ | 'reasoningParts'
+ | 'thinkingContent'
+>;
+
+interface ServerCallLlmMessageMetadata extends MessageMetadata {
+ answerSalvagedFromReasoning?: boolean;
+ interruptedMidStream?: boolean;
+}
+
+interface FinalizeServerCallLlmResultInput {
+ answerSalvagedFromReasoning: boolean;
+ assistantMessageId: string;
+ currentStepSpeed?: ModelPerformance;
+ currentStepUsage?: ModelUsage;
+ grounding: GroundingSearch | null;
+ imageList: ChatImageItem[];
+ messageModel: RuntimeExecutorContext['messageModel'];
+ model: string;
+ provider: string;
+ shouldReplayAssistantReasoning: boolean;
+ state: AgentState;
+ stepLabel?: string;
+ streamOutput: ServerCallLlmCollectedOutput;
+ toolCalls: MessageToolCall[];
+ toolsCalling: ChatToolPayload[];
+ visibleOutputEndPublishedStepIndex?: number;
+}
+
+interface PersistInterruptedServerCallLlmResultInput {
+ assistantMessageId: string;
+ currentStepSpeed?: ModelPerformance;
+ currentStepUsage?: ModelUsage;
+ messageModel: RuntimeExecutorContext['messageModel'];
+ operationLogId: string;
+ streamOutput: ServerCallLlmCollectedOutput;
+ toolsCalling: ChatToolPayload[];
+}
+
+const buildMessageMetadata = ({
+ answerSalvagedFromReasoning,
+ currentStepSpeed,
+ currentStepUsage,
+ hasContentImages,
+ interruptedMidStream,
+}: {
+ answerSalvagedFromReasoning?: boolean;
+ currentStepSpeed?: ModelPerformance;
+ currentStepUsage?: ModelUsage;
+ hasContentImages?: boolean;
+ interruptedMidStream?: boolean;
+}): ServerCallLlmMessageMetadata | undefined => {
+ const metadata: ServerCallLlmMessageMetadata = {
+ ...(currentStepUsage && { ...currentStepUsage, usage: currentStepUsage }),
+ ...(currentStepSpeed && { ...currentStepSpeed, performance: currentStepSpeed }),
+ ...(hasContentImages && { isMultimodal: true }),
+ ...(answerSalvagedFromReasoning && { answerSalvagedFromReasoning: true }),
+ ...(interruptedMidStream && { interruptedMidStream: true }),
+ };
+
+ return Object.keys(metadata).length > 0 ? metadata : undefined;
+};
+
+const buildFinalReasoning = (
+ streamOutput: ServerCallLlmCollectedOutput,
+): ModelReasoning | undefined => {
+ if (streamOutput.hasReasoningImages) {
+ return {
+ content: serializePartsForStorage(streamOutput.reasoningParts),
+ isMultimodal: true,
+ };
+ }
+
+ return streamOutput.thinkingContent ? { content: streamOutput.thinkingContent } : undefined;
+};
+
+const sanitizePersistedTools = (toolsCalling: ChatToolPayload[]) =>
+ toolsCalling.length > 0
+ ? toolsCalling.map((tool) => ({
+ ...tool,
+ arguments: sanitizeToolCallArguments(tool.arguments),
+ }))
+ : undefined;
+
+const sanitizeStateToolCalls = (toolCalls: MessageToolCall[]) => {
+ const sanitizedToolCalls = toolCalls
+ .filter((toolCall) => !!toolCall.function.name)
+ .map((toolCall) => ({
+ ...toolCall,
+ function: {
+ ...toolCall.function,
+ arguments: sanitizeToolCallArguments(toolCall.function.arguments),
+ },
+ }));
+
+ return sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;
+};
+
+export const finalizeServerCallLlmResult = async ({
+ answerSalvagedFromReasoning,
+ assistantMessageId,
+ currentStepSpeed,
+ currentStepUsage,
+ grounding,
+ imageList,
+ messageModel,
+ model,
+ provider,
+ shouldReplayAssistantReasoning,
+ state,
+ stepLabel,
+ streamOutput,
+ toolCalls,
+ toolsCalling,
+ visibleOutputEndPublishedStepIndex,
+}: FinalizeServerCallLlmResultInput): Promise<AgentState> => {
+ const finalContent = streamOutput.hasContentImages
+ ? serializePartsForStorage(streamOutput.contentParts)
+ : streamOutput.content;
+ const finalReasoning = buildFinalReasoning(streamOutput);
+ const metadata = buildMessageMetadata({
+ answerSalvagedFromReasoning,
+ currentStepSpeed,
+ currentStepUsage,
+ hasContentImages: streamOutput.hasContentImages,
+ });
+
+ try {
+ await messageModel.update(assistantMessageId, {
+ content: finalContent,
+ imageList: imageList.length > 0 ? imageList : undefined,
+ metadata,
+ reasoning: finalReasoning,
+ search: grounding,
+ tools: sanitizePersistedTools(toolsCalling),
+ });
+ } catch (error) {
+ console.error('[call_llm] Failed to update message:', error);
+ }
+
+ const newState = structuredClone(state);
+ newState.messages.push({
+ content: streamOutput.content,
+ id: assistantMessageId,
+ reasoning: shouldReplayAssistantReasoning ? finalReasoning : undefined,
+ role: 'assistant',
+ tool_calls: sanitizeStateToolCalls(toolCalls),
+ });
+
+ if (currentStepUsage) {
+ const { usage, cost } = UsageCounter.accumulateLLM({
+ cost: newState.cost,
+ model,
+ modelUsage: currentStepUsage,
+ provider,
+ usage: newState.usage,
+ });
+
+ newState.usage = usage;
+ if (cost) newState.cost = cost;
+ }
+
+ if (stepLabel || visibleOutputEndPublishedStepIndex !== undefined) {
+ const stateMetadata = { ...newState.metadata };
+ if (stepLabel) stateMetadata._stepLabel = stepLabel;
+ if (visibleOutputEndPublishedStepIndex !== undefined) {
+ stateMetadata[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY] =
+ visibleOutputEndPublishedStepIndex;
+ }
+ newState.metadata = stateMetadata;
+ }
+
+ return newState;
+};
+
+export const persistInterruptedServerCallLlmResult = async ({
+ assistantMessageId,
+ currentStepSpeed,
+ currentStepUsage,
+ messageModel,
+ operationLogId,
+ streamOutput,
+ toolsCalling,
+}: PersistInterruptedServerCallLlmResultInput): Promise<void> => {
+ if (!streamOutput.content && !streamOutput.thinkingContent && toolsCalling.length === 0) return;
+
+ try {
+ await messageModel.update(assistantMessageId, {
+ content: streamOutput.content,
+ metadata: buildMessageMetadata({
+ currentStepSpeed,
+ currentStepUsage,
+ interruptedMidStream: true,
+ }),
+ reasoning: streamOutput.thinkingContent
+ ? { content: streamOutput.thinkingContent }
+ : undefined,
+ tools: sanitizePersistedTools(toolsCalling),
+ });
+ log(
+ '[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',
+ operationLogId,
+ streamOutput.content.length,
+ streamOutput.thinkingContent.length,
+ toolsCalling.length,
+ );
+ } catch (error) {
+ log('[%s] Interrupted finalize update failed: %O', operationLogId, error);
+ }
+};
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index 7d33658139f..7a9dc1ad55e 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -102,7 +102,7 @@ export interface UpdateMessageParams {
provider?: string;
reasoning?: ModelReasoning;
role?: string;
- search?: GroundingSearch;
+ search?: GroundingSearch | null;
toolCalls?: MessageToolCall[];
tools?: ChatToolPayload[] | null;
traceId?: string;
@@ -135,7 +135,7 @@ export const UpdateMessageParamsSchema = z
provider: z.string().optional(),
reasoning: ModelReasoningSchema.optional(),
role: z.string().optional(),
- search: GroundingSearchSchema.optional(),
+ search: GroundingSearchSchema.nullish(),
toolCalls: z.array(MessageToolCallSchema).optional(),
tools: z.array(ChatToolPayloadSchema).nullish(),
traceId: z.string().optional(),