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 call llm attempt transport (#17027)

Arvin Xuaa0ef836aeea
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.test.ts
new file mode 100644
index 00000000000..6ce24945edc
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.test.ts
@@ -0,0 +1,51 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FileService } from '@/server/services/file';
+
+import { ServerBlobStore } from './ServerBlobStore';
+
+const { getFileAccessUrl, uploadBase64 } = vi.hoisted(() => ({
+ getFileAccessUrl: vi.fn().mockResolvedValue('https://files.example/access'),
+ uploadBase64: vi.fn().mockResolvedValue({
+ fileId: 'file-1',
+ key: 'files/image.png',
+ url: 'https://files.example/image.png',
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ getFileAccessUrl, uploadBase64 })),
+}));
+
+describe('ServerBlobStore', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('defers FileService construction until the first blob operation', async () => {
+ const store = new ServerBlobStore({} as LobeChatDatabase, 'user-1', 'workspace-1');
+
+ expect(FileService).not.toHaveBeenCalled();
+
+ await store.persistBase64('BASE64', 'files/image.png');
+ await store.resolveUrl({ id: 'file-1' });
+
+ expect(FileService).toHaveBeenCalledTimes(1);
+ expect(uploadBase64).toHaveBeenCalledWith('BASE64', 'files/image.png');
+ expect(getFileAccessUrl).toHaveBeenCalledWith({ id: 'file-1' });
+ });
+
+ it('surfaces missing storage configuration only when blob IO is requested', async () => {
+ vi.mocked(FileService).mockImplementationOnce(() => {
+ throw new Error('S3 environment variables are not set completely');
+ });
+ const createStore = () => new ServerBlobStore({} as LobeChatDatabase, 'user-1');
+
+ expect(createStore).not.toThrow();
+ const store = createStore();
+ await expect(store.persistBase64('BASE64', 'files/image.png')).rejects.toThrow(
+ 'S3 environment variables are not set completely',
+ );
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.ts
new file mode 100644
index 00000000000..1ed0816a095
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerBlobStore.ts
@@ -0,0 +1,27 @@
+import type { BlobRef, BlobStore } from '@lobechat/agent-runtime';
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { FileService } from '@/server/services/file';
+
+export class ServerBlobStore implements BlobStore {
+ private fileService?: FileService;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ async persistBase64(base64Data: string, pathname: string) {
+ return this.getFileService().uploadBase64(base64Data, pathname);
+ }
+
+ async resolveUrl(ref: BlobRef) {
+ return this.getFileService().getFileAccessUrl(ref);
+ }
+
+ private getFileService() {
+ this.fileService ??= new FileService(this.db, this.userId, this.workspaceId);
+ return this.fileService;
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index 445f8d8f5c7..49c22d3ea2f 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -1,14 +1,22 @@
import type {
+ BlobStore,
+ LLMAttemptExecution,
+ LLMAttemptInput,
LLMStreamPayload,
LLMStreamResult,
LLMTransport,
LLMTurnInput,
} from '@lobechat/agent-runtime';
-import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import {
+ type ChatStreamPayload,
+ consumeStreamUntilDone,
+ type ModelRuntime,
+} from '@lobechat/model-runtime';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import type { RuntimeExecutorContext } from '../context';
+import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
import { executeServerCallLlmTurn } from './serverCallLlmExecutor';
const getErrorMessage = (error: unknown): string => {
@@ -26,29 +34,38 @@ const getErrorMessage = (error: unknown): string => {
* returns the aggregated content/usage that package executors need.
*/
export class ServerLLMTransport implements LLMTransport {
- constructor(private readonly ctx: RuntimeExecutorContext) {}
+ constructor(
+ private readonly ctx: RuntimeExecutorContext,
+ private readonly blobStore?: BlobStore,
+ ) {}
executeTurn(input: LLMTurnInput): ReturnType<NonNullable<LLMTransport['executeTurn']>> {
+ let modelRuntimePromise: ReturnType<ServerLLMTransport['createModelRuntime']> | undefined;
+
return executeServerCallLlmTurn(this.ctx, {
assistantMessage: input.assistantMessage,
context: input.context,
model: input.model,
provider: input.provider,
+ runAttempt: async (attemptInput) => {
+ modelRuntimePromise ??= this.createModelRuntime(input.provider);
+ return this.runAttemptWithRuntime(attemptInput, await modelRuntimePromise);
+ },
state: input.state,
stepLabel: input.stepLabel,
});
}
+ async runAttempt(input: LLMAttemptInput): Promise<LLMAttemptExecution> {
+ const modelRuntime = await this.createModelRuntime(input.provider);
+ return this.runAttemptWithRuntime(input, modelRuntime);
+ }
+
async stream(
payload: LLMStreamPayload,
handlers?: Parameters<LLMTransport['stream']>[1],
): Promise<LLMStreamResult> {
- const runtime = await initModelRuntimeFromDB(
- this.ctx.serverDB,
- this.ctx.userId!,
- payload.provider,
- this.ctx.workspaceId,
- );
+ const runtime = await this.createModelRuntime(payload.provider);
const { provider: _provider, ...runtimePayload } = payload;
let content = '';
let usage: LLMStreamResult['usage'];
@@ -81,4 +98,59 @@ export class ServerLLMTransport implements LLMTransport {
handlers?.onFinish?.(result);
return result;
}
+
+ private createModelRuntime(provider: string) {
+ return initModelRuntimeFromDB(
+ this.ctx.serverDB,
+ this.ctx.userId!,
+ provider,
+ this.ctx.workspaceId,
+ );
+ }
+
+ private async runAttemptWithRuntime(
+ input: LLMAttemptInput,
+ modelRuntime: Pick<ModelRuntime, 'chat'>,
+ ): Promise<LLMAttemptExecution> {
+ const resolved = input.context.resolvedTools;
+ if (!resolved) throw new Error('Resolved tools are required for a server LLM attempt');
+
+ const tools = resolved.tools.length > 0 ? resolved.tools : undefined;
+ const chatPayload = {
+ messages: input.context.messages as ChatStreamPayload['messages'],
+ model: input.model,
+ stream: this.ctx.stream ?? true,
+ tools,
+ ...(input.context.modelParameters as Partial<ChatStreamPayload>),
+ ...(typeof input.context.preserveThinking === 'boolean' && {
+ preserveThinking: input.context.preserveThinking,
+ }),
+ };
+ const operationLogId = `${this.ctx.operationId}:${this.ctx.stepIndex}`;
+ const attempt = createServerCallLlmAttempt({
+ attempt: input.attempt,
+ blobStore: this.blobStore,
+ chatPayload,
+ ctx: this.ctx,
+ events: input.events,
+ maxAttempts: input.maxAttempts,
+ messageCount: chatPayload.messages.length,
+ model: input.model,
+ modelRuntime,
+ onFirstChunk: input.onFirstChunk ?? (() => {}),
+ operationLogId,
+ provider: input.provider,
+ resolved,
+ topicId: input.state.metadata?.topicId,
+ trigger: input.state.metadata?.trigger,
+ });
+
+ try {
+ await attempt.execute();
+ return { ok: true, output: attempt.snapshot() };
+ } catch (error) {
+ attempt.clearBuffers();
+ return { error, ok: false, output: attempt.snapshot() };
+ }
+ }
}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
index be48f313597..90693f51fe7 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
@@ -1,4 +1,4 @@
-import type { AgentEvent } from '@lobechat/agent-runtime';
+import type { AgentEvent, BlobStore } 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';
@@ -20,12 +20,6 @@ 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'],
@@ -45,7 +39,10 @@ const resolved = {
],
} as ServerCallLlmTooling['resolved'];
-const createAttempt = (runCallbacks: (options: ChatMethodOptions) => Promise<void>) => {
+const createAttempt = (
+ runCallbacks: (options: ChatMethodOptions) => Promise<void>,
+ blobStore?: BlobStore,
+) => {
const publishStreamChunk = vi.fn().mockResolvedValue('event-1');
const streamManager = {
publishStreamChunk,
@@ -68,6 +65,7 @@ const createAttempt = (runCallbacks: (options: ChatMethodOptions) => Promise<voi
const onFirstChunk = vi.fn();
const attempt = createServerCallLlmAttempt({
attempt: 1,
+ blobStore,
chatPayload: {
messages: [{ content: 'Question', role: 'user' }],
model: 'test-model',
@@ -119,18 +117,20 @@ describe('ServerCallLlmAttempt', () => {
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({
+ const snapshot = attempt.snapshot();
+
+ expect(snapshot.content).toBe('Visible answer');
+ expect(snapshot.reasoning).toBe('Reasoning');
+ expect(snapshot.grounding).toEqual({ searchQueries: ['docs'] });
+ expect(snapshot.finishReason).toBe('tool_use');
+ expect(snapshot.speed).toEqual({ tps: 20, ttft: 100 });
+ expect(snapshot.usage).toEqual({
totalInputTokens: 10,
totalOutputTokens: 5,
totalTokens: 15,
});
- expect(attempt.toolCalls).toEqual([rawToolCall]);
- expect(attempt.toolsCalling).toEqual([
+ expect(snapshot.toolCalls).toEqual([rawToolCall]);
+ expect(snapshot.toolsCalling).toEqual([
expect.objectContaining({
apiName: 'search',
executor: 'server',
@@ -172,10 +172,14 @@ describe('ServerCallLlmAttempt', () => {
message: 'LLM stream error: provider stream failed',
status: 503,
});
- attempt.streamSink.clearBuffers();
+ attempt.clearBuffers();
- expect(attempt.streamSink.content).toBe('Partial answer');
- expect(attempt.usage).toEqual({ totalOutputTokens: 3 });
+ expect(attempt.snapshot()).toEqual(
+ expect.objectContaining({
+ content: 'Partial answer',
+ usage: { totalOutputTokens: 3 },
+ }),
+ );
});
it('salvages a natural-stop answer emitted only in reasoning', async () => {
@@ -190,8 +194,51 @@ describe('ServerCallLlmAttempt', () => {
await attempt.execute();
- expect(attempt.answerSalvagedFromReasoning).toBe(true);
- expect(attempt.streamSink.content).toBe('Final answer from reasoning');
- expect(attempt.streamSink.thinkingContent).toBe('');
+ expect(attempt.snapshot()).toEqual(
+ expect.objectContaining({
+ answerSalvagedFromReasoning: true,
+ content: 'Final answer from reasoning',
+ reasoning: '',
+ }),
+ );
+ });
+
+ it('persists generated images through BlobStore and snapshots the resolved URL', async () => {
+ const blobStore: BlobStore = {
+ persistBase64: vi.fn().mockResolvedValue({
+ fileId: 'file-1',
+ key: 'files/generations/image.png',
+ url: 'https://files.example/image.png',
+ }),
+ resolveUrl: vi.fn(),
+ };
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onContentPart?.({ content: 'Generated image:', partType: 'text' });
+ await callback?.onContentPart?.({
+ content: 'BASE64_IMAGE',
+ mimeType: 'image/png',
+ partType: 'image',
+ });
+ await callback?.onCompletion?.({
+ text: '',
+ usage: { totalOutputTokens: 1 },
+ });
+ }, blobStore);
+
+ await attempt.execute();
+
+ expect(blobStore.persistBase64).toHaveBeenCalledWith(
+ 'BASE64_IMAGE',
+ expect.stringMatching(/files\/generations\/.+\.png$/),
+ );
+ expect(attempt.snapshot()).toEqual(
+ expect.objectContaining({
+ contentParts: [
+ { text: 'Generated image:', type: 'text' },
+ { image: 'https://files.example/image.png', type: 'image' },
+ ],
+ hasContentImages: true,
+ }),
+ );
});
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index 6909bc995df..7c716b32e57 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -1,4 +1,4 @@
-import type { AgentEvent } from '@lobechat/agent-runtime';
+import type { AgentEvent, BlobStore, LLMAttemptOutput } from '@lobechat/agent-runtime';
import { ToolNameResolver } from '@lobechat/context-engine';
import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
import {
@@ -26,6 +26,7 @@ import type { ServerCallLlmTooling } from './serverCallLlmTooling';
interface CreateServerCallLlmAttemptInput {
attempt: number;
+ blobStore?: BlobStore;
chatPayload: ChatStreamPayload;
ctx: RuntimeExecutorContext;
events: AgentEvent[];
@@ -57,19 +58,13 @@ const createStreamExecutionError = (errorData: unknown) => {
};
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 answerSalvagedFromReasoning = false;
private readonly attempt: number;
private readonly chatPayload: ChatStreamPayload;
private readonly ctx: RuntimeExecutorContext;
+ private finishReason?: string;
+ private grounding: GroundingSearch | null = null;
+ private readonly imageList: ChatImageItem[] = [];
private readonly maxAttempts: number;
private readonly messageCount: number;
private readonly model: string;
@@ -78,12 +73,18 @@ export class ServerCallLlmAttempt {
private readonly operationLogId: string;
private readonly provider: string;
private readonly resolved: ServerCallLlmTooling['resolved'];
+ private speed?: ModelPerformance;
+ private readonly streamSink: ServerCallLlmStreamSink;
private streamError?: unknown;
+ private toolCalls: MessageToolCall[] = [];
+ private toolsCalling: ChatToolPayload[] = [];
private readonly topicId?: string;
private readonly trigger?: unknown;
+ private usage?: ModelUsage;
constructor({
attempt,
+ blobStore,
chatPayload,
ctx,
events,
@@ -109,7 +110,12 @@ export class ServerCallLlmAttempt {
this.operationLogId = operationLogId;
this.provider = provider;
this.resolved = resolved;
- this.streamSink = createServerCallLlmStreamSink({ ctx, events, operationLogId });
+ this.streamSink = createServerCallLlmStreamSink({
+ blobStore,
+ ctx,
+ events,
+ operationLogId,
+ });
this.topicId = topicId;
this.trigger = trigger;
}
@@ -232,6 +238,29 @@ export class ServerCallLlmAttempt {
this.logResult();
}
+ clearBuffers() {
+ this.streamSink.clearBuffers();
+ }
+
+ snapshot(): LLMAttemptOutput {
+ return {
+ answerSalvagedFromReasoning: this.answerSalvagedFromReasoning,
+ content: this.streamSink.content,
+ contentParts: [...this.streamSink.contentParts],
+ finishReason: this.finishReason,
+ grounding: this.grounding,
+ hasContentImages: this.streamSink.hasContentImages,
+ hasReasoningImages: this.streamSink.hasReasoningImages,
+ imageList: [...this.imageList],
+ reasoning: this.streamSink.thinkingContent,
+ reasoningParts: [...this.streamSink.reasoningParts],
+ speed: this.speed,
+ toolCalls: [...this.toolCalls],
+ toolsCalling: [...this.toolsCalling],
+ usage: this.usage,
+ };
+ }
+
private async assertNonEmptyCompletion() {
if (
isEmptyModelCompletion({
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
index 7c4e1c4e4f1..ad574a1c9a5 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
@@ -5,12 +5,13 @@ import {
type GeneralAgentCallLLMResultPayload,
getLLMRetryDelayMs,
type InstructionExecutionResult,
+ type LLMTransport,
resolveLLMMaxAttempts,
resolveLLMRetryBudget,
shouldRetryLLM,
} from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { type ChatStreamPayload, ModelEmptyError } from '@lobechat/model-runtime';
+import { ModelEmptyError } from '@lobechat/model-runtime';
import {
context as otelContext,
SpanKind,
@@ -24,13 +25,10 @@ import {
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-
import { type RuntimeExecutorContext } from '../context';
import { isOperationInterrupted, log, sleep } from '../executorHelpers';
import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
-import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
import {
finalizeServerCallLlmResult,
persistInterruptedServerCallLlmResult,
@@ -41,6 +39,7 @@ interface ServerCallLlmExecutionContext {
context: ContextBuildOutput;
model: string;
provider: string;
+ runAttempt: NonNullable<LLMTransport['runAttempt']>;
state: AgentState;
stepLabel?: string;
}
@@ -67,16 +66,12 @@ class ServerCallLlmTurn {
context,
model,
provider,
+ runAttempt,
stepLabel,
} = prepared;
- const {
- messages: preparedMessages,
- modelParameters: resolvedExtendParams,
- preserveThinking: preserveThinkingForPayload,
- replayAssistantReasoning: shouldReplayAssistantReasoning,
- resolvedTools: resolved,
- } = context;
- const processedMessages = preparedMessages as ChatStreamPayload['messages'];
+ const { messages: preparedMessages, replayAssistantReasoning: shouldReplayAssistantReasoning } =
+ context;
+ const processedMessages = preparedMessages as Array<{ role?: string }>;
const operationLogId = `${operationId}:${stepIndex}`;
log(
'[%s][call_llm] Starting operation with prepared assistant message: %s',
@@ -85,8 +80,9 @@ class ServerCallLlmTurn {
);
try {
- if (!resolved) throw new Error('Resolved tools are required for a server LLM turn');
- const tools = resolved.tools.length > 0 ? resolved.tools : undefined;
+ if (!context.resolvedTools) {
+ throw new Error('Resolved tools are required for a server LLM turn');
+ }
// A turn must carry at least one non-system message. Anthropic-compatible
// providers (anthropic / deepseek) move `role: system` into a separate
@@ -104,29 +100,7 @@ class ServerCallLlmTurn {
);
}
- // Initialize ModelRuntime (read user's keyVaults from database)
- const modelRuntime = await initModelRuntimeFromDB(
- ctx.serverDB,
- ctx.userId!,
- provider,
- ctx.workspaceId,
- );
-
- // Construct ChatStreamPayload
const stream = ctx.stream ?? true;
- const chatPayload = {
- messages: processedMessages,
- model,
- stream,
- tools,
- // ModelExtendParams keeps provider-specific effort/thinking values as loose
- // strings (e.g. hy3's 'no_think'); the runtime payload narrows them, so cast.
- ...(resolvedExtendParams as Partial<ChatStreamPayload>),
- ...(typeof preserveThinkingForPayload === 'boolean' && {
- preserveThinking: preserveThinkingForPayload,
- }),
- };
-
const maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);
// OTel chat span — wraps all retry attempts; TTFT recorded on the first
@@ -153,32 +127,27 @@ class ServerCallLlmTurn {
try {
return await otelContext.with(chatCtx, async () => {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- const llmAttempt = createServerCallLlmAttempt({
+ const execution = await runAttempt({
attempt,
- chatPayload,
- ctx,
+ context,
events,
maxAttempts,
- messageCount: processedMessages.length,
model,
- modelRuntime,
onFirstChunk,
- operationLogId,
provider,
- resolved,
- topicId: state.metadata?.topicId,
- trigger: state.metadata?.trigger,
+ state,
});
+ const llmAttempt = execution.output;
try {
- await llmAttempt.execute();
+ if (!execution.ok) throw execution.error;
+
const {
answerSalvagedFromReasoning,
finishReason: currentStepFinishReason,
grounding,
imageList,
speed: currentStepSpeed,
- streamSink,
toolCalls: tool_calls,
toolsCalling,
usage: currentStepUsage,
@@ -187,9 +156,9 @@ class ServerCallLlmTurn {
// Add a complete llm_stream event (including all streaming chunks)
events.push({
result: {
- content: streamSink.content,
+ content: llmAttempt.content,
finishReason: currentStepFinishReason,
- reasoning: streamSink.thinkingContent,
+ reasoning: llmAttempt.reasoning,
tool_calls,
usage: currentStepUsage,
},
@@ -199,11 +168,11 @@ class ServerCallLlmTurn {
// Publish stream end event
await streamManager.publishStreamEvent(operationId, {
data: {
- finalContent: streamSink.content,
+ finalContent: llmAttempt.content,
grounding,
...(stepLabel && { stepLabel }),
imageList: imageList.length > 0 ? imageList : undefined,
- reasoning: streamSink.thinkingContent || undefined,
+ reasoning: llmAttempt.reasoning || undefined,
toolsCalling,
usage: currentStepUsage,
},
@@ -249,7 +218,7 @@ class ServerCallLlmTurn {
shouldReplayAssistantReasoning,
state,
stepLabel,
- streamOutput: streamSink,
+ streamOutput: llmAttempt,
toolCalls: tool_calls,
toolsCalling,
visibleOutputEndPublishedStepIndex,
@@ -275,7 +244,7 @@ class ServerCallLlmTurn {
hasToolsCalling: toolsCalling.length > 0,
// Pass assistant message ID as parentMessageId for tool calls
parentMessageId: assistantMessageItem.id,
- result: { content: streamSink.content, tool_calls },
+ result: { content: llmAttempt.content, tool_calls },
toolsCalling,
} as GeneralAgentCallLLMResultPayload,
phase: 'llm_result' as const,
@@ -290,8 +259,6 @@ class ServerCallLlmTurn {
},
};
} catch (error) {
- llmAttempt.streamSink.clearBuffers();
-
const classified = classifyLLMError(error);
const interrupted = await isOperationInterrupted(ctx);
@@ -357,7 +324,7 @@ class ServerCallLlmTurn {
currentStepUsage: llmAttempt.usage,
messageModel: ctx.messageModel,
operationLogId,
- streamOutput: llmAttempt.streamSink,
+ streamOutput: llmAttempt,
toolsCalling: llmAttempt.toolsCalling,
});
}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts
index 9d81d489cd1..225e040525e 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.test.ts
@@ -23,16 +23,16 @@ const createStreamOutput = (
contentParts: Array<{ image: string; type: 'image' } | { text: string; type: 'text' }>;
hasContentImages: boolean;
hasReasoningImages: boolean;
+ reasoning: string;
reasoningParts: Array<{ image: string; type: 'image' } | { text: string; type: 'text' }>;
- thinkingContent: string;
}>,
) => ({
content: 'Answer',
contentParts: [],
hasContentImages: false,
hasReasoningImages: false,
+ reasoning: 'Reasoning',
reasoningParts: [],
- thinkingContent: 'Reasoning',
...overrides,
});
@@ -160,7 +160,7 @@ describe('serverCallLlmFinalizer', () => {
{ text: 'Visual reasoning', type: 'text' },
{ image: 'https://example.com/reasoning.png', type: 'image' },
],
- thinkingContent: 'Visual reasoning',
+ reasoning: 'Visual reasoning',
}),
toolCalls: [],
toolsCalling: [],
@@ -199,7 +199,7 @@ describe('serverCallLlmFinalizer', () => {
assistantMessageId: 'assistant-empty',
messageModel,
operationLogId: 'operation-1:0',
- streamOutput: createStreamOutput({ content: '', thinkingContent: '' }),
+ streamOutput: createStreamOutput({ content: '', reasoning: '' }),
toolsCalling: [],
});
expect(update).not.toHaveBeenCalled();
@@ -210,7 +210,7 @@ describe('serverCallLlmFinalizer', () => {
currentStepUsage: { totalOutputTokens: 4 },
messageModel,
operationLogId: 'operation-1:0',
- streamOutput: createStreamOutput({ content: 'Partial', thinkingContent: 'Thinking' }),
+ streamOutput: createStreamOutput({ content: 'Partial', reasoning: 'Thinking' }),
toolsCalling: [],
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts
index 26c8648c546..c6af83c450c 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmFinalizer.ts
@@ -1,4 +1,4 @@
-import { type AgentState, UsageCounter } from '@lobechat/agent-runtime';
+import { type AgentState, type LLMAttemptOutput, UsageCounter } from '@lobechat/agent-runtime';
import type {
ChatImageItem,
ChatToolPayload,
@@ -14,16 +14,15 @@ import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/u
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,
+ LLMAttemptOutput,
| 'content'
| 'contentParts'
| 'hasContentImages'
| 'hasReasoningImages'
+ | 'reasoning'
| 'reasoningParts'
- | 'thinkingContent'
>;
interface ServerCallLlmMessageMetadata extends MessageMetadata {
@@ -94,7 +93,7 @@ const buildFinalReasoning = (
};
}
- return streamOutput.thinkingContent ? { content: streamOutput.thinkingContent } : undefined;
+ return streamOutput.reasoning ? { content: streamOutput.reasoning } : undefined;
};
const sanitizePersistedTools = (toolsCalling: ChatToolPayload[]) =>
@@ -205,7 +204,7 @@ export const persistInterruptedServerCallLlmResult = async ({
streamOutput,
toolsCalling,
}: PersistInterruptedServerCallLlmResultInput): Promise<void> => {
- if (!streamOutput.content && !streamOutput.thinkingContent && toolsCalling.length === 0) return;
+ if (!streamOutput.content && !streamOutput.reasoning && toolsCalling.length === 0) return;
try {
await messageModel.update(assistantMessageId, {
@@ -215,16 +214,14 @@ export const persistInterruptedServerCallLlmResult = async ({
currentStepUsage,
interruptedMidStream: true,
}),
- reasoning: streamOutput.thinkingContent
- ? { content: streamOutput.thinkingContent }
- : undefined,
+ reasoning: streamOutput.reasoning ? { content: streamOutput.reasoning } : undefined,
tools: sanitizePersistedTools(toolsCalling),
});
log(
'[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',
operationLogId,
streamOutput.content.length,
- streamOutput.thinkingContent.length,
+ streamOutput.reasoning.length,
toolsCalling.length,
);
} catch (error) {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
index 3cc6a8c6f52..8803c07e58c 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
@@ -1,17 +1,16 @@
-import type { AgentEvent } from '@lobechat/agent-runtime';
+import type { AgentEvent, BlobStore, LLMAttemptContentPart } 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' };
+export type ServerCallLlmContentPart = LLMAttemptContentPart;
interface CreateServerCallLlmStreamSinkInput {
+ blobStore?: BlobStore;
ctx: RuntimeExecutorContext;
events: AgentEvent[];
operationLogId: string;
@@ -38,9 +37,9 @@ export class ServerCallLlmStreamSink {
readonly reasoningParts: ServerCallLlmContentPart[] = [];
thinkingContent = '';
+ private readonly blobStore?: BlobStore;
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 = '';
@@ -49,18 +48,12 @@ export class ServerCallLlmStreamSink {
private textBuffer = '';
private textBufferTimer: NodeJS.Timeout | null = null;
- constructor({ ctx, events, operationLogId }: CreateServerCallLlmStreamSinkInput) {
+ constructor({ blobStore, ctx, events, operationLogId }: CreateServerCallLlmStreamSinkInput) {
+ this.blobStore = blobStore;
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;
}
@@ -230,11 +223,11 @@ export class ServerCallLlmStreamSink {
base64: string,
mimeType: string | undefined,
): Promise<void> {
- if (!this.imageUploadService) return Promise.resolve();
+ if (!this.blobStore) 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)
+ return this.blobStore
+ .persistBase64(base64, pathname)
.then(({ url }) => {
parts[partIndex] = { image: url, type: 'image' };
})
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
index dab155aade4..629f5def374 100644
--- a/apps/server/src/modules/AgentRuntime/buildHost.ts
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -1,5 +1,6 @@
import type { AgentRuntimeHost } from '@lobechat/agent-runtime';
+import { ServerBlobStore } from './adapters/ServerBlobStore';
import { ServerCompressionTransport } from './adapters/ServerCompressionTransport';
import { ServerContextBuilder } from './adapters/ServerContextBuilder';
import { ServerLifecycleSink } from './adapters/ServerLifecycleSink';
@@ -19,40 +20,46 @@ import { buildPostProcessUrl } from './executorHelpers';
* is the "server only registers adapters" seam — package-hosted executors take
* the host instead of the raw ctx.
*
- * Grows as more executors migrate (tools / llm / context / blob / lifecycle
- * adapters get added here); today it covers the transport-backed lightweight
- * executors such as `finish`, `request_human_approve`, and `resolve_*`.
+ * Keep concrete service construction here so package executors only see narrow
+ * message, model, context, blob, stream, operation, and tool ports.
*/
-export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({
- // Only present when the operation registered hooks — mirrors the prior
- // `if (ctx.hookDispatcher)` guard in the human-approve executor.
- lifecycle: ctx.hookDispatcher
- ? new ServerLifecycleSink(ctx.hookDispatcher, ctx.operationId)
- : undefined,
- operation: {
- operationId: ctx.operationId,
- stepIndex: ctx.stepIndex,
- topicId: ctx.topicId,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- },
- transports: {
- compression: ctx.userId
- ? new ServerCompressionTransport(ctx.serverDB, ctx.userId, ctx.workspaceId)
+export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => {
+ const blob = ctx.userId
+ ? new ServerBlobStore(ctx.serverDB, ctx.userId, ctx.workspaceId)
+ : undefined;
+
+ return {
+ // Only present when the operation registered hooks — mirrors the prior
+ // `if (ctx.hookDispatcher)` guard in the human-approve executor.
+ lifecycle: ctx.hookDispatcher
+ ? new ServerLifecycleSink(ctx.hookDispatcher, ctx.operationId)
: undefined,
- context: new ServerContextBuilder(ctx),
- llm: ctx.userId ? new ServerLLMTransport(ctx) : undefined,
- messages: new ServerMessageTransport(ctx.messageModel, {
- postProcessUrl: buildPostProcessUrl(ctx),
- }),
- operationStore: new ServerOperationStore(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId,
- ctx.topicId,
- ),
- stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),
- subAgent: ctx.execSubAgent ? new ServerSubAgentTransport(ctx) : undefined,
- tools: new ServerToolTransport(ctx),
- },
-});
+ operation: {
+ operationId: ctx.operationId,
+ stepIndex: ctx.stepIndex,
+ topicId: ctx.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ },
+ transports: {
+ blob,
+ compression: ctx.userId
+ ? new ServerCompressionTransport(ctx.serverDB, ctx.userId, ctx.workspaceId)
+ : undefined,
+ context: new ServerContextBuilder(ctx),
+ llm: ctx.userId ? new ServerLLMTransport(ctx, blob) : undefined,
+ messages: new ServerMessageTransport(ctx.messageModel, {
+ postProcessUrl: buildPostProcessUrl(ctx),
+ }),
+ operationStore: new ServerOperationStore(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ctx.topicId,
+ ),
+ stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),
+ subAgent: ctx.execSubAgent ? new ServerSubAgentTransport(ctx) : undefined,
+ tools: new ServerToolTransport(ctx),
+ },
+ };
+};
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
index 39be28eda9f..66b6c8ae16c 100644
--- a/packages/agent-runtime/src/transport/llm.ts
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -1,6 +1,14 @@
-import type { ModelUsage, OpenAIChatMessage } from '@lobechat/types';
+import type {
+ ChatImageItem,
+ ChatToolPayload,
+ GroundingSearch,
+ MessageToolCall,
+ ModelPerformance,
+ ModelUsage,
+ OpenAIChatMessage,
+} from '@lobechat/types';
-import type { AgentState, CallLLMPayload, InstructionExecutionResult } from '../types';
+import type { AgentEvent, AgentState, CallLLMPayload, InstructionExecutionResult } from '../types';
import type { ContextBuildOutput } from './context';
import type { RuntimeMessageRef } from './message';
@@ -34,6 +42,40 @@ export interface LLMStreamHandlers {
onText?: (text: string) => void;
}
+export type LLMAttemptContentPart =
+ { image: string; type: 'image' } | { text: string; type: 'text' };
+
+export interface LLMAttemptOutput {
+ answerSalvagedFromReasoning: boolean;
+ content: string;
+ contentParts: LLMAttemptContentPart[];
+ finishReason?: string;
+ grounding: GroundingSearch | null;
+ hasContentImages: boolean;
+ hasReasoningImages: boolean;
+ imageList: ChatImageItem[];
+ reasoning: string;
+ reasoningParts: LLMAttemptContentPart[];
+ speed?: ModelPerformance;
+ toolCalls: MessageToolCall[];
+ toolsCalling: ChatToolPayload[];
+ usage?: ModelUsage;
+}
+
+export interface LLMAttemptInput {
+ attempt: number;
+ context: ContextBuildOutput;
+ events: AgentEvent[];
+ maxAttempts: number;
+ model: string;
+ onFirstChunk?: () => void;
+ provider: string;
+ state: AgentState;
+}
+
+export type LLMAttemptExecution =
+ { error: unknown; ok: false; output: LLMAttemptOutput } | { ok: true; output: LLMAttemptOutput };
+
export interface LLMTurnInput {
assistantMessage: RuntimeMessageRef;
context: ContextBuildOutput;
@@ -55,10 +97,12 @@ export interface LLMTurnInput {
export interface LLMTransport {
/**
* Executes one prepared model turn. The package executor owns instruction
- * setup while the adapter owns host-specific context, retry, and persistence
- * until those phases move onto narrower transport ports.
+ * setup/context while the adapter owns retry and persistence until those
+ * phases move onto narrower transport ports.
*/
executeTurn?: (input: LLMTurnInput) => Promise<InstructionExecutionResult>;
+ /** Executes one model attempt and returns both successful or partial output. */
+ runAttempt?: (input: LLMAttemptInput) => Promise<LLMAttemptExecution>;
stream: (
payload: LLMStreamPayload,
handlers?: LLMStreamHandlers,