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 stream sink (#16973)

Arvin Xuea4e8e205b04
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
index 675362a7c6f..88012d5a78c 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
@@ -33,10 +33,7 @@ import {
import { type ChatToolPayload, type MessageToolCall } from '@lobechat/types';
import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';
-import { fileEnv } from '@/envs/file';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-import { FileService } from '@/server/services/file';
-import { nanoid } from '@/utils/uuid';
import { type RuntimeExecutorContext } from '../context';
import { isOperationInterrupted, log, sleep, timing } from '../executorHelpers';
@@ -45,6 +42,7 @@ import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';
+import { createServerCallLlmStreamSink } from './serverCallLlmStreamSink';
import { resolveServerCallLlmTooling, type ServerCallLlmTooling } from './serverCallLlmTooling';
interface PreparedCallLLMContext {
@@ -177,7 +175,6 @@ export const callLlm =
}
try {
- type ContentPart = { text: string; type: 'text' } | { image: string; type: 'image' };
const {
preserveThinkingForPayload,
processedMessages,
@@ -231,114 +228,6 @@ export const callLlm =
}),
};
- // Buffer: accumulate text and reasoning, send every 50ms
- const BUFFER_INTERVAL = 50;
- let textBuffer = '';
- let reasoningBuffer = '';
-
- let textBufferTimer: NodeJS.Timeout | null = null;
- let reasoningBufferTimer: NodeJS.Timeout | null = null;
-
- const flushTextBuffer = async () => {
- const delta = textBuffer;
- textBuffer = '';
-
- if (!!delta) {
- log(`[${operationLogId}] flushTextBuffer:`, delta);
-
- // Build standard Agent Runtime event
- events.push({
- chunk: { text: delta, type: 'text' },
- type: 'llm_stream',
- });
-
- const publishStart = Date.now();
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'text',
- content: delta,
- });
- timing(
- '[%s] flushTextBuffer published at %d, took %dms, length: %d',
- operationLogId,
- publishStart,
- Date.now() - publishStart,
- delta.length,
- );
- }
- };
-
- const flushReasoningBuffer = async () => {
- const delta = reasoningBuffer;
-
- reasoningBuffer = '';
-
- if (!!delta) {
- log(`[${operationLogId}] flushReasoningBuffer:`, delta);
-
- events.push({
- chunk: { text: delta, type: 'reasoning' },
- type: 'llm_stream',
- });
-
- const publishStart = Date.now();
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'reasoning',
- reasoning: delta,
- });
- timing(
- '[%s] flushReasoningBuffer published at %d, took %dms, length: %d',
- operationLogId,
- publishStart,
- Date.now() - publishStart,
- delta.length,
- );
- }
- };
-
- // File service + date shard used to persist model-generated images
- // (Gemini multimodal `content_part`/`reasoning_part` images) to object
- // storage, built once and reused across parts. The `userId` check only
- // satisfies its optional type β€” it is always present in this executor.
- // A missing-S3-config failure surfaces later at uploadBase64 (caught per
- // image in uploadPartImage), never at construction.
- const imageUploadService = ctx.userId ? new FileService(ctx.serverDB, ctx.userId) : undefined;
- const imageUploadDate = new Date().toISOString().split('T')[0];
-
- // Coalesce a streamed text chunk into the trailing text part (mirrors the
- // client StreamingHandler) so serialized multimodal content stays compact
- // and preserves text/image ordering.
- const appendTextPart = (parts: ContentPart[], text: string) => {
- const last = parts.at(-1);
- if (last && last.type === 'text') {
- parts[parts.length - 1] = { text: last.text + text, type: 'text' };
- } else {
- parts.push({ text, type: 'text' });
- }
- };
-
- // Persist a base64 image part to object storage and swap the placeholder
- // part for one referencing the uploaded URL. Runs concurrently with the
- // rest of the stream; a failed upload leaves the inline data-URI so the
- // image still renders. Never stores raw base64 in the message on success.
- const uploadPartImage = (
- parts: ContentPart[],
- partIndex: number,
- base64: string,
- mimeType: string | undefined,
- ): Promise<void> => {
- if (!imageUploadService) return Promise.resolve();
- const ext = mimeType?.split('/')[1] || 'png';
- const pathname = `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/generations/${imageUploadDate}/${nanoid()}.${ext}`;
- return imageUploadService
- .uploadBase64(base64, pathname)
- .then(({ url }) => {
- parts[partIndex] = { image: url, type: 'image' };
- })
- .catch((error) => {
- console.error(`[${operationLogId}][content_part] image upload failed:`, error);
- });
- };
-
const maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);
// OTel chat span β€” wraps all retry attempts; TTFT recorded on the first
@@ -362,43 +251,23 @@ export const callLlm =
try {
return await otelContext.with(chatCtx, async () => {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- let content = '';
+ const streamSink = createServerCallLlmStreamSink({
+ ctx,
+ events,
+ operationLogId,
+ });
let toolsCalling: ChatToolPayload[] = [];
let tool_calls: MessageToolCall[] = [];
- let thinkingContent = '';
const imageList: any[] = [];
let grounding: any = null;
let currentStepUsage: any = undefined;
let currentStepSpeed: any = undefined;
let currentStepFinishReason: string | undefined = undefined;
let streamError: any = undefined;
- const contentParts: ContentPart[] = [];
- const reasoningParts: ContentPart[] = [];
- const contentImageUploads: Promise<void>[] = [];
- const reasoningImageUploads: Promise<void>[] = [];
- let hasContentImages = false;
- let hasReasoningImages = false;
// 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;
- textBuffer = '';
- reasoningBuffer = '';
-
- const clearAttemptBuffers = () => {
- if (textBufferTimer) {
- clearTimeout(textBufferTimer);
- textBufferTimer = null;
- }
-
- if (reasoningBufferTimer) {
- clearTimeout(reasoningBufferTimer);
- reasoningBufferTimer = null;
- }
-
- textBuffer = '';
- reasoningBuffer = '';
- };
try {
log(
@@ -448,17 +317,7 @@ export const callLlm =
Date.now(),
text.length,
);
- content += text;
-
- textBuffer += text;
-
- // If no timer exists, create one
- if (!textBufferTimer) {
- textBufferTimer = setTimeout(async () => {
- await flushTextBuffer();
- textBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
+ await streamSink.appendText(text);
},
onThinking: async (reasoning) => {
if (firstChunkAt === undefined) {
@@ -470,18 +329,7 @@ export const callLlm =
Date.now(),
reasoning.length,
);
- thinkingContent += reasoning;
-
- // Buffer reasoning content
- reasoningBuffer += reasoning;
-
- // If no timer exists, create one
- if (!reasoningBufferTimer) {
- reasoningBufferTimer = setTimeout(async () => {
- await flushReasoningBuffer();
- reasoningBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
+ await streamSink.appendThinking(reasoning);
},
// Gemini 2.5+/3 multimodal streams deliver assistant text and
// reasoning as `content_part`/`reasoning_part` events (triggered by
@@ -498,29 +346,7 @@ export const callLlm =
firstChunkAt = Date.now() - llmStartTime;
}
- if (part.partType === 'image') {
- const partIndex = contentParts.length;
- contentParts.push({
- image: `data:${part.mimeType || 'image/png'};base64,${part.content}`,
- type: 'image',
- });
- hasContentImages = true;
- contentImageUploads.push(
- uploadPartImage(contentParts, partIndex, part.content, part.mimeType),
- );
- return;
- }
-
- content += part.content;
- appendTextPart(contentParts, part.content);
- textBuffer += part.content;
-
- if (!textBufferTimer) {
- textBufferTimer = setTimeout(async () => {
- await flushTextBuffer();
- textBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
+ await streamSink.appendContentPart(part);
},
// Some Gemini / Nano Banana image responses arrive via the
// legacy single-image `base64_image` event instead of
@@ -537,43 +363,14 @@ export const callLlm =
firstChunkAt = Date.now() - llmStartTime;
}
- // `image.data` is a full data URI (`data:<mime>;base64,<...>`).
- const mimeType = /^data:([^;]+);/.exec(image.data)?.[1];
- const partIndex = contentParts.length;
- contentParts.push({ image: image.data, type: 'image' });
- hasContentImages = true;
- contentImageUploads.push(
- uploadPartImage(contentParts, partIndex, image.data, mimeType),
- );
+ await streamSink.appendBase64Image(image);
},
onReasoningPart: async (part) => {
if (firstChunkAt === undefined) {
firstChunkAt = Date.now() - llmStartTime;
}
- if (part.partType === 'image') {
- const partIndex = reasoningParts.length;
- reasoningParts.push({
- image: `data:${part.mimeType || 'image/png'};base64,${part.content}`,
- type: 'image',
- });
- hasReasoningImages = true;
- reasoningImageUploads.push(
- uploadPartImage(reasoningParts, partIndex, part.content, part.mimeType),
- );
- return;
- }
-
- thinkingContent += part.content;
- appendTextPart(reasoningParts, part.content);
- reasoningBuffer += part.content;
-
- if (!reasoningBufferTimer) {
- reasoningBufferTimer = setTimeout(async () => {
- await flushReasoningBuffer();
- reasoningBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
+ await streamSink.appendReasoningPart(part);
},
onToolsCalling: async ({ toolsCalling: raw }) => {
const resolvedCalls = new ToolNameResolver().resolve(
@@ -598,10 +395,7 @@ export const callLlm =
toolsCalling = payload;
tool_calls = raw;
- // If textBuffer exists, flush it first
- if (!!textBuffer) {
- await flushTextBuffer();
- }
+ await streamSink.flushTextBuffer();
await streamManager.publishStreamChunk(operationId, stepIndex, {
chunkType: 'tools_calling',
@@ -639,15 +433,13 @@ export const callLlm =
throw streamExecutionError;
}
- await flushTextBuffer();
- await flushReasoningBuffer();
- clearAttemptBuffers();
+ 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.
- if (contentImageUploads.length > 0 || reasoningImageUploads.length > 0) {
- await Promise.allSettled([...contentImageUploads, ...reasoningImageUploads]);
- }
+ await streamSink.waitForImageUploads();
// Empty-completion guard: if the model produced
// nothing actionable β€” no content, reasoning, tool calls, images,
@@ -662,11 +454,11 @@ export const callLlm =
if (
isEmptyModelCompletion({
- content,
+ content: streamSink.content,
imageCount: imageList.length,
outputTokens:
typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,
- reasoning: thinkingContent,
+ reasoning: streamSink.thinkingContent,
toolCallCount: toolsCalling.length + tool_calls.length,
}) &&
!(await isOperationInterrupted(ctx))
@@ -679,7 +471,7 @@ export const callLlm =
);
throw new ModelEmptyError(undefined, {
attempt,
- contentLength: content.length,
+ contentLength: streamSink.content.length,
finishReason: currentStepFinishReason,
imageCount: imageList.length,
maxAttempts,
@@ -687,7 +479,7 @@ export const callLlm =
outputTokens:
typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,
provider,
- reasoningLength: thinkingContent.length,
+ reasoningLength: streamSink.thinkingContent.length,
toolCallCount: toolsCalling.length + tool_calls.length,
});
}
@@ -708,33 +500,33 @@ export const callLlm =
isTerminalNaturalStop &&
toolsCalling.length === 0 &&
tool_calls.length === 0 &&
- content.trim().length === 0 &&
- thinkingContent.trim().length > 0 &&
- !hasReasoningImages
+ 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,
- thinkingContent.length,
+ streamSink.thinkingContent.length,
);
- content = thinkingContent;
- thinkingContent = '';
+ streamSink.content = streamSink.thinkingContent;
+ streamSink.thinkingContent = '';
answerSalvagedFromReasoning = true;
}
log(
`[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,
- content.length,
- thinkingContent.length,
+ streamSink.content.length,
+ streamSink.thinkingContent.length,
toolsCalling.length,
currentStepUsage ? 'yes' : 'none',
);
- if (thinkingContent) {
- log(`[${operationLogId}][reasoning]`, thinkingContent);
+ if (streamSink.thinkingContent) {
+ log(`[${operationLogId}][reasoning]`, streamSink.thinkingContent);
}
- if (content) {
- log(`[${operationLogId}][content]`, content);
+ if (streamSink.content) {
+ log(`[${operationLogId}][content]`, streamSink.content);
}
if (toolsCalling.length > 0) {
log(`[${operationLogId}][toolsCalling] `, toolsCalling);
@@ -748,9 +540,9 @@ export const callLlm =
// Add a complete llm_stream event (including all streaming chunks)
events.push({
result: {
- content,
+ content: streamSink.content,
finishReason: currentStepFinishReason,
- reasoning: thinkingContent,
+ reasoning: streamSink.thinkingContent,
tool_calls,
usage: currentStepUsage,
},
@@ -760,11 +552,11 @@ export const callLlm =
// Publish stream end event
await streamManager.publishStreamEvent(operationId, {
data: {
- finalContent: content,
+ finalContent: streamSink.content,
grounding,
...(stepLabel && { stepLabel }),
imageList: imageList.length > 0 ? imageList : undefined,
- reasoning: thinkingContent || undefined,
+ reasoning: streamSink.thinkingContent || undefined,
toolsCalling,
usage: currentStepUsage,
},
@@ -799,22 +591,22 @@ export const callLlm =
// ===== 1. First save original usage to message.metadata =====
// Determine final content - use serialized parts if has images, otherwise plain text
- const finalContent = hasContentImages
- ? serializePartsForStorage(contentParts)
- : content;
+ const finalContent = streamSink.hasContentImages
+ ? serializePartsForStorage(streamSink.contentParts)
+ : streamSink.content;
// Determine final reasoning - handle multimodal reasoning
let finalReasoning: any = undefined;
- if (hasReasoningImages) {
+ if (streamSink.hasReasoningImages) {
// Has images, use multimodal format
finalReasoning = {
- content: serializePartsForStorage(reasoningParts),
+ content: serializePartsForStorage(streamSink.reasoningParts),
isMultimodal: true,
};
- } else if (thinkingContent) {
+ } else if (streamSink.thinkingContent) {
// Has text from reasoning but no images
finalReasoning = {
- content: thinkingContent,
+ content: streamSink.thinkingContent,
};
}
@@ -836,7 +628,7 @@ export const callLlm =
Object.assign(metadata, currentStepSpeed);
metadata.performance = currentStepSpeed;
}
- if (hasContentImages) {
+ if (streamSink.hasContentImages) {
metadata.isMultimodal = true;
}
if (answerSalvagedFromReasoning) {
@@ -889,7 +681,7 @@ export const callLlm =
const stateToolCalls = sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;
newState.messages.push({
- content,
+ content: streamSink.content,
id: assistantMessageItem.id,
reasoning: replayedReasoning,
role: 'assistant',
@@ -949,7 +741,7 @@ export const callLlm =
hasToolsCalling: toolsCalling.length > 0,
// Pass assistant message ID as parentMessageId for tool calls
parentMessageId: assistantMessageItem.id,
- result: { content, tool_calls },
+ result: { content: streamSink.content, tool_calls },
toolsCalling,
} as GeneralAgentCallLLMResultPayload,
phase: 'llm_result' as const,
@@ -964,7 +756,7 @@ export const callLlm =
},
};
} catch (error) {
- clearAttemptBuffers();
+ streamSink.clearBuffers();
const classified = classifyLLMError(error);
const interrupted = await isOperationInterrupted(ctx);
@@ -1024,7 +816,10 @@ export const callLlm =
// 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 && (content || thinkingContent || toolsCalling.length > 0)) {
+ if (
+ interrupted &&
+ (streamSink.content || streamSink.thinkingContent || toolsCalling.length > 0)
+ ) {
try {
const persistedTools =
toolsCalling.length > 0
@@ -1033,8 +828,8 @@ export const callLlm =
arguments: sanitizeToolCallArguments(t.arguments),
}))
: undefined;
- const interruptedReasoning = thinkingContent
- ? { content: thinkingContent }
+ const interruptedReasoning = streamSink.thinkingContent
+ ? { content: streamSink.thinkingContent }
: undefined;
const interruptedMetadata: Record<string, any> = { interruptedMidStream: true };
if (currentStepUsage && typeof currentStepUsage === 'object') {
@@ -1046,7 +841,7 @@ export const callLlm =
interruptedMetadata.performance = currentStepSpeed;
}
await ctx.messageModel.update(assistantMessageItem.id, {
- content,
+ content: streamSink.content,
metadata: interruptedMetadata,
reasoning: interruptedReasoning,
tools: persistedTools,
@@ -1054,8 +849,8 @@ export const callLlm =
log(
'[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',
operationLogId,
- content.length,
- thinkingContent.length,
+ streamSink.content.length,
+ streamSink.thinkingContent.length,
toolsCalling.length,
);
} catch (persistErr) {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
new file mode 100644
index 00000000000..3cc6a8c6f52
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
@@ -0,0 +1,248 @@
+import type { AgentEvent } from '@lobechat/agent-runtime';
+import type { Base64ImageData, ContentPartData } from '@lobechat/model-runtime';
+
+import { fileEnv } from '@/envs/file';
+import { FileService } from '@/server/services/file';
+import { nanoid } from '@/utils/uuid';
+
+import type { RuntimeExecutorContext } from '../context';
+import { log, timing } from '../executorHelpers';
+
+export type ServerCallLlmContentPart =
+ { image: string; type: 'image' } | { text: string; type: 'text' };
+
+interface CreateServerCallLlmStreamSinkInput {
+ ctx: RuntimeExecutorContext;
+ events: AgentEvent[];
+ operationLogId: string;
+}
+
+const BUFFER_INTERVAL = 300;
+
+const appendTextPart = (parts: ServerCallLlmContentPart[], text: string) => {
+ const last = parts.at(-1);
+ if (last && last.type === 'text') {
+ parts[parts.length - 1] = { text: last.text + text, type: 'text' };
+ } else {
+ parts.push({ text, type: 'text' });
+ }
+};
+
+export class ServerCallLlmStreamSink {
+ content = '';
+ readonly contentImageUploads: Promise<void>[] = [];
+ readonly contentParts: ServerCallLlmContentPart[] = [];
+ hasContentImages = false;
+ hasReasoningImages = false;
+ readonly reasoningImageUploads: Promise<void>[] = [];
+ readonly reasoningParts: ServerCallLlmContentPart[] = [];
+ thinkingContent = '';
+
+ private readonly events: AgentEvent[];
+ private readonly imageUploadDate = new Date().toISOString().split('T')[0];
+ private readonly imageUploadService?: FileService;
+ private readonly operationId: string;
+ private readonly operationLogId: string;
+ private reasoningBuffer = '';
+ private reasoningBufferTimer: NodeJS.Timeout | null = null;
+ private readonly stepIndex: number;
+ private textBuffer = '';
+ private textBufferTimer: NodeJS.Timeout | null = null;
+
+ constructor({ ctx, events, operationLogId }: CreateServerCallLlmStreamSinkInput) {
+ this.events = events;
+ this.operationId = ctx.operationId;
+ this.operationLogId = operationLogId;
+ this.stepIndex = ctx.stepIndex;
+ // File service + date shard used to persist model-generated images
+ // (Gemini multimodal `content_part`/`reasoning_part` images) to object
+ // storage, built once and reused across parts. The `userId` check only
+ // satisfies its optional type β€” it is always present in this executor.
+ // A missing-S3-config failure surfaces later at uploadBase64 (caught per
+ // image in uploadPartImage), never at construction.
+ this.imageUploadService = ctx.userId ? new FileService(ctx.serverDB, ctx.userId) : undefined;
+ this.streamManager = ctx.streamManager;
+ }
+
+ private readonly streamManager: RuntimeExecutorContext['streamManager'];
+
+ async appendContentPart(part: ContentPartData) {
+ if (part.partType === 'image') {
+ const partIndex = this.contentParts.length;
+ this.contentParts.push({
+ image: `data:${part.mimeType || 'image/png'};base64,${part.content}`,
+ type: 'image',
+ });
+ this.hasContentImages = true;
+ this.contentImageUploads.push(
+ this.uploadPartImage(this.contentParts, partIndex, part.content, part.mimeType),
+ );
+ return;
+ }
+
+ this.content += part.content;
+ appendTextPart(this.contentParts, part.content);
+ this.queueText(part.content);
+ }
+
+ async appendReasoningPart(part: ContentPartData) {
+ if (part.partType === 'image') {
+ const partIndex = this.reasoningParts.length;
+ this.reasoningParts.push({
+ image: `data:${part.mimeType || 'image/png'};base64,${part.content}`,
+ type: 'image',
+ });
+ this.hasReasoningImages = true;
+ this.reasoningImageUploads.push(
+ this.uploadPartImage(this.reasoningParts, partIndex, part.content, part.mimeType),
+ );
+ return;
+ }
+
+ this.thinkingContent += part.content;
+ appendTextPart(this.reasoningParts, part.content);
+ this.queueReasoning(part.content);
+ }
+
+ async appendText(text: string) {
+ this.content += text;
+ this.queueText(text);
+ }
+
+ async appendThinking(reasoning: string) {
+ this.thinkingContent += reasoning;
+ this.queueReasoning(reasoning);
+ }
+
+ async appendBase64Image(image: Base64ImageData) {
+ // `image.data` is a full data URI (`data:<mime>;base64,<...>`).
+ const mimeType = /^data:([^;]+);/.exec(image.data)?.[1];
+ const partIndex = this.contentParts.length;
+ this.contentParts.push({ image: image.data, type: 'image' });
+ this.hasContentImages = true;
+ this.contentImageUploads.push(
+ this.uploadPartImage(this.contentParts, partIndex, image.data, mimeType),
+ );
+ }
+
+ clearBuffers() {
+ if (this.textBufferTimer) {
+ clearTimeout(this.textBufferTimer);
+ this.textBufferTimer = null;
+ }
+
+ if (this.reasoningBufferTimer) {
+ clearTimeout(this.reasoningBufferTimer);
+ this.reasoningBufferTimer = null;
+ }
+
+ this.textBuffer = '';
+ this.reasoningBuffer = '';
+ }
+
+ async flushReasoningBuffer() {
+ const delta = this.reasoningBuffer;
+
+ this.reasoningBuffer = '';
+
+ if (!!delta) {
+ log(`[${this.operationLogId}] flushReasoningBuffer:`, delta);
+
+ this.events.push({
+ chunk: { text: delta, type: 'reasoning' },
+ type: 'llm_stream',
+ });
+
+ const publishStart = Date.now();
+ await this.streamManager.publishStreamChunk(this.operationId, this.stepIndex, {
+ chunkType: 'reasoning',
+ reasoning: delta,
+ });
+ timing(
+ '[%s] flushReasoningBuffer published at %d, took %dms, length: %d',
+ this.operationLogId,
+ publishStart,
+ Date.now() - publishStart,
+ delta.length,
+ );
+ }
+ }
+
+ async flushTextBuffer() {
+ const delta = this.textBuffer;
+ this.textBuffer = '';
+
+ if (!!delta) {
+ log(`[${this.operationLogId}] flushTextBuffer:`, delta);
+
+ // Build standard Agent Runtime event
+ this.events.push({
+ chunk: { text: delta, type: 'text' },
+ type: 'llm_stream',
+ });
+
+ const publishStart = Date.now();
+ await this.streamManager.publishStreamChunk(this.operationId, this.stepIndex, {
+ chunkType: 'text',
+ content: delta,
+ });
+ timing(
+ '[%s] flushTextBuffer published at %d, took %dms, length: %d',
+ this.operationLogId,
+ publishStart,
+ Date.now() - publishStart,
+ delta.length,
+ );
+ }
+ }
+
+ async waitForImageUploads() {
+ if (this.contentImageUploads.length > 0 || this.reasoningImageUploads.length > 0) {
+ await Promise.allSettled([...this.contentImageUploads, ...this.reasoningImageUploads]);
+ }
+ }
+
+ private queueReasoning(reasoning: string) {
+ this.reasoningBuffer += reasoning;
+
+ if (!this.reasoningBufferTimer) {
+ this.reasoningBufferTimer = setTimeout(async () => {
+ await this.flushReasoningBuffer();
+ this.reasoningBufferTimer = null;
+ }, BUFFER_INTERVAL);
+ }
+ }
+
+ private queueText(text: string) {
+ this.textBuffer += text;
+
+ if (!this.textBufferTimer) {
+ this.textBufferTimer = setTimeout(async () => {
+ await this.flushTextBuffer();
+ this.textBufferTimer = null;
+ }, BUFFER_INTERVAL);
+ }
+ }
+
+ private uploadPartImage(
+ parts: ServerCallLlmContentPart[],
+ partIndex: number,
+ base64: string,
+ mimeType: string | undefined,
+ ): Promise<void> {
+ if (!this.imageUploadService) return Promise.resolve();
+ const ext = mimeType?.split('/')[1] || 'png';
+ const pathname = `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/generations/${this.imageUploadDate}/${nanoid()}.${ext}`;
+ return this.imageUploadService
+ .uploadBase64(base64, pathname)
+ .then(({ url }) => {
+ parts[partIndex] = { image: url, type: 'image' };
+ })
+ .catch((error) => {
+ console.error(`[${this.operationLogId}][content_part] image upload failed:`, error);
+ });
+ }
+}
+
+export const createServerCallLlmStreamSink = (input: CreateServerCallLlmStreamSinkInput) =>
+ new ServerCallLlmStreamSink(input);
diff --git a/packages/model-runtime/src/core/usageConverters/openai.test.ts b/packages/model-runtime/src/core/usageConverters/openai.test.ts
index 8c81d9d225c..4fd140d3194 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.test.ts
@@ -550,6 +550,9 @@ describe('convertUsage', () => {
cache_write_tokens: 400_000,
},
output_tokens: 0,
+ output_tokens_details: {
+ reasoning_tokens: 0,
+ },
total_tokens: 1_000_000,
} as OpenAI.Responses.ResponseUsage;