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): capture Gemini multimodal content_part/reasoning_part output (#15535)

Arvin Xu0ac53b4e80a9
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index 751d16e8159..0f52d8ce405 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -71,6 +71,7 @@ import { type MessageModel, MessageModel as MessageModelClass } from '@/database
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { type LobeChatDatabase } from '@/database/type';
+import { fileEnv } from '@/envs/file';
import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';
import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/types';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
@@ -91,6 +92,7 @@ import {
} from '@/server/services/toolExecution';
import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';
import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';
+import { nanoid } from '@/utils/uuid';
import { dispatchClientTool } from './dispatchClientTool';
import { formatErrorEventData } from './formatErrorEventData';
@@ -1084,6 +1086,50 @@ export const createRuntimeExecutors = (
}
};
+ // 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);
// OTel chat span β€” wraps all retry attempts; TTFT recorded on the first
@@ -1119,8 +1165,10 @@ export const createRuntimeExecutors = (
let streamError: any = undefined;
const contentParts: ContentPart[] = [];
const reasoningParts: ContentPart[] = [];
- const hasContentImages = false;
- const hasReasoningImages = false;
+ const contentImageUploads: Promise<void>[] = [];
+ const reasoningImageUploads: Promise<void>[] = [];
+ let hasContentImages = false;
+ let hasReasoningImages = false;
textBuffer = '';
reasoningBuffer = '';
@@ -1222,6 +1270,74 @@ export const createRuntimeExecutors = (
}, BUFFER_INTERVAL);
}
},
+ // 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;
+ }
+
+ 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);
+ }
+ },
+ 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);
+ }
+ },
onToolsCalling: async ({ toolsCalling: raw }) => {
const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);
// Attach source (origin) and executor (dispatch target) for routing.
@@ -1286,6 +1402,12 @@ export const createRuntimeExecutors = (
await flushReasoningBuffer();
clearAttemptBuffers();
+ // 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]);
+ }
+
// 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
diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 378c1567adb..c963a14f706 100644
--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -76,6 +76,22 @@ vi.mock('@/config/klavis', () => ({
klavisEnv: { KLAVIS_API_KEY: undefined },
}));
+// fileEnv uses @t3-oss/env-core; stub the only field the runtime reads so the
+// generated-image upload pathname is deterministic.
+vi.mock('@/envs/file', () => ({
+ fileEnv: { NEXT_PUBLIC_S3_FILE_PATH: 'files' },
+}));
+
+// FileService is constructed by the runtime to persist model-generated images.
+// `mockUploadBase64` is the spy multimodal-image tests assert against.
+const { mockUploadBase64 } = vi.hoisted(() => ({ mockUploadBase64: vi.fn() }));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFileAccessUrl: vi.fn().mockResolvedValue('https://files.example/access'),
+ uploadBase64: mockUploadBase64,
+ })),
+}));
+
describe('RuntimeExecutors', () => {
let mockMessageModel: any;
let mockStreamManager: any;
@@ -477,6 +493,141 @@ describe('RuntimeExecutors', () => {
);
});
+ // Gemini 2.5+/3 thinking streams deliver assistant text/reasoning as
+ // content_part / reasoning_part events instead of plain text / reasoning.
+ // These must be captured or the turn finalizes to a blank `done`.
+ describe('multimodal content_part / reasoning_part', () => {
+ const geminiInstruction = (overrides?: any) => ({
+ payload: {
+ messages: [{ content: 'Hi', role: 'user' }],
+ model: 'gemini-3.1-flash-lite-preview',
+ provider: 'google',
+ tools: [],
+ ...overrides,
+ },
+ type: 'call_llm' as const,
+ });
+
+ it('captures assistant text delivered via content_part', async () => {
+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {
+ await options?.callback?.onContentPart?.({
+ content: 'Hello from Gemini.',
+ partType: 'text',
+ });
+ await options?.callback?.onCompletion?.({
+ finishReason: 'STOP',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ });
+ return new Response('done');
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const result = await executors.call_llm!(geminiInstruction(), createMockState());
+
+ // Previously the text was dropped β†’ persisted/state content was '' (blank done).
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ 'msg-123',
+ expect.objectContaining({ content: 'Hello from Gemini.' }),
+ );
+ expect(result.newState.messages.at(-1)).toEqual(
+ expect.objectContaining({ content: 'Hello from Gemini.', role: 'assistant' }),
+ );
+ });
+
+ it('captures reasoning delivered via reasoning_part', async () => {
+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {
+ await options?.callback?.onReasoningPart?.({
+ content: 'Let me think about this.',
+ partType: 'text',
+ });
+ await options?.callback?.onContentPart?.({ content: 'The answer.', partType: 'text' });
+ await options?.callback?.onCompletion?.({
+ usage: { totalInputTokens: 10, totalOutputTokens: 8, totalTokens: 18 },
+ });
+ return new Response('done');
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const result = await executors.call_llm!(geminiInstruction(), createMockState());
+
+ expect(result.newState.messages.at(-1)).toEqual(
+ expect.objectContaining({
+ content: 'The answer.',
+ reasoning: { content: 'Let me think about this.' },
+ role: 'assistant',
+ }),
+ );
+ });
+
+ it('coalesces consecutive content_part text chunks', async () => {
+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {
+ await options?.callback?.onContentPart?.({ content: 'Hello ', partType: 'text' });
+ await options?.callback?.onContentPart?.({ content: 'world.', partType: 'text' });
+ await options?.callback?.onCompletion?.({
+ usage: { totalInputTokens: 10, totalOutputTokens: 4, totalTokens: 14 },
+ });
+ return new Response('done');
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const result = await executors.call_llm!(geminiInstruction(), createMockState());
+
+ expect(result.newState.messages.at(-1)).toEqual(
+ expect.objectContaining({ content: 'Hello world.', role: 'assistant' }),
+ );
+ });
+
+ it('uploads content_part images to object storage and serializes URLs, never base64', async () => {
+ mockUploadBase64.mockResolvedValue({
+ fileId: 'file-1',
+ key: 'files/generations/2026/abc.png',
+ url: 'https://files.example/generations/abc.png',
+ });
+
+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {
+ await options?.callback?.onContentPart?.({
+ content: 'Here is an image:',
+ partType: 'text',
+ });
+ await options?.callback?.onContentPart?.({
+ content: 'BASE64IMAGEDATA',
+ mimeType: 'image/png',
+ partType: 'image',
+ });
+ await options?.callback?.onCompletion?.({
+ usage: { totalInputTokens: 10, totalOutputTokens: 6, totalTokens: 16 },
+ });
+ return new Response('done');
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ await executors.call_llm!(geminiInstruction(), createMockState());
+
+ // Raw base64 is uploaded to storage, pathname carries the right extension.
+ expect(mockUploadBase64).toHaveBeenCalledWith(
+ 'BASE64IMAGEDATA',
+ expect.stringMatching(/generations\/.+\.png$/),
+ );
+
+ // Persisted content is serialized multimodal parts referencing the S3
+ // URL β€” text + image in order β€” and never contains the raw base64.
+ const updateCall = mockMessageModel.update.mock.calls.find(
+ (c: any[]) => c[0] === 'msg-123' && typeof c[1]?.content === 'string',
+ );
+ expect(updateCall).toBeTruthy();
+ expect(updateCall![1].metadata).toEqual(expect.objectContaining({ isMultimodal: true }));
+ expect(updateCall![1].content).not.toContain('BASE64IMAGEDATA');
+ expect(JSON.parse(updateCall![1].content)).toEqual([
+ { text: 'Here is an image:', type: 'text' },
+ { image: 'https://files.example/generations/abc.png', type: 'image' },
+ ]);
+ });
+ });
+
it('should push assistant message with persisted DB id so request_human_approve can find parent', async () => {
const toolCallPayload = [
{