🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: route call_llm through runtime transport (#16947)
Arvin Xudd7c9b45366a
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex 235afd69377..854db419a46 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -1,5 +1,6 @@import type { AgentInstruction, InstructionExecutor } from '@lobechat/agent-runtime';import {+ callLlm as createCallLlmExecutor,callTool as createCallToolExecutor,callToolsBatch as createCallToolsBatchExecutor,compressContext as createCompressContextExecutor,@@ -13,7 +14,6 @@ import {import { buildHost } from './buildHost';import type { RuntimeExecutorContext } from './context';-import { callLlm } from './executors/callLlm';export { type RuntimeExecutorContext } from './context';@@ -25,7 +25,7 @@ export const createRuntimeExecutors = (const host = buildHost(ctx);return {- call_llm: callLlm(ctx),+ call_llm: createCallLlmExecutor(host),call_tool: createCallToolExecutor(host),call_tools_batch: createCallToolsBatchExecutor(host),compress_context: createCompressContextExecutor(host),diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 6d611177c17..80adbde9ad6 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -1,9 +1,16 @@-import type { LLMStreamPayload, LLMStreamResult, LLMTransport } from '@lobechat/agent-runtime';+import type {+ LLMCallExecuteInput,+ LLMStreamPayload,+ LLMStreamResult,+ LLMTransport,+} from '@lobechat/agent-runtime';import { consumeStreamUntilDone } from '@lobechat/model-runtime';-import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import type { RuntimeExecutorContext } from '../context';+import { callLlm as createServerCallLlmExecutor } from './serverCallLlmExecutor';+const getErrorMessage = (error: unknown): string => {if (error instanceof Error && error.message) return error.message;if (typeof error === 'string' && error) return error;@@ -19,21 +26,21 @@ const getErrorMessage = (error: unknown): string => {* returns the aggregated content/usage that package executors need.*/export class ServerLLMTransport implements LLMTransport {- constructor(- private readonly serverDB: LobeChatDatabase,- private readonly userId: string,- private readonly workspaceId?: string,- ) {}+ constructor(private readonly ctx: RuntimeExecutorContext) {}++ executeCall(input: LLMCallExecuteInput): ReturnType<NonNullable<LLMTransport['executeCall']>> {+ return createServerCallLlmExecutor(this.ctx)(input.instruction, input.state);+ }async stream(payload: LLMStreamPayload,handlers?: Parameters<LLMTransport['stream']>[1],): Promise<LLMStreamResult> {const runtime = await initModelRuntimeFromDB(- this.serverDB,- this.userId,+ this.ctx.serverDB,+ this.ctx.userId!,payload.provider,- this.workspaceId,+ this.ctx.workspaceId,);const { provider: _provider, ...runtimePayload } = payload;let content = '';@@ -54,7 +61,7 @@ export class ServerLLMTransport implements LLMTransport {handlers?.onText?.(text);},},- user: this.userId,+ user: this.ctx.userId,});await consumeStreamUntilDone(response);diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tssimilarity index 99%rename from apps/server/src/modules/AgentRuntime/executors/callLlm.tsrename to apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tsindex c3f4a8e067d..c520298280f 100644--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts@@ -103,11 +103,11 @@ import {sleep,timing,} from '../executorHelpers';+import { resolveRunActiveDeviceId } from '../executors/resolveRunActiveDeviceId';import { formatErrorEventData } from '../formatErrorEventData';import { classifyLLMError } from '../llmErrorClassification';import { createConversationParentMissingError } from '../messagePersistErrors';import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';-import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';const SERVER_LLM_RETRY_POLICY = {isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.tsindex c8c46973036..55fec1f0c7d 100644--- a/apps/server/src/modules/AgentRuntime/buildHost.ts+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts@@ -39,7 +39,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({compression: ctx.userId? new ServerCompressionTransport(ctx.serverDB, ctx.userId, ctx.workspaceId): undefined,- llm: ctx.userId ? new ServerLLMTransport(ctx.serverDB, ctx.userId, ctx.workspaceId) : undefined,+ llm: ctx.userId ? new ServerLLMTransport(ctx) : undefined,messages: new ServerMessageTransport(ctx.messageModel, {postProcessUrl: buildPostProcessUrl(ctx),}),diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsnew file mode 100644index 00000000000..6c5c9a60e3b--- /dev/null+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost, LLMTransport, MessageTransport, StreamSink } from '../transport';+import type { AgentInstructionCallLlm, AgentState } from '../types';+import { callLlm } from './callLlm';++const createState = (): AgentState => ({+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ messages: [],+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls: 0,+ processingTimeMs: 0,+ tokens: { input: 0, output: 0, total: 0 },+ },+ tools: {+ byTool: [],+ totalCalls: 0,+ totalTimeMs: 0,+ },+ },+});++const instruction: AgentInstructionCallLlm = {+ payload: {+ messages: [{ content: 'hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm',+};++const createMessageTransport = (): MessageTransport => ({+ createAssistantMessage: vi.fn(),+ createToolMessage: vi.fn(),+ deleteMessage: vi.fn(),+ findById: vi.fn(),+ query: vi.fn(),+ update: vi.fn(),+ updatePluginState: vi.fn(),+ updateToolMessage: vi.fn(),+});++const createStreamSink = (): StreamSink => ({+ publishChunk: vi.fn(),+ publishEvent: vi.fn(),+});++const createHost = (llm: LLMTransport): AgentRuntimeHost => ({+ operation: { operationId: 'op-1', stepIndex: 0 },+ transports: {+ llm,+ messages: createMessageTransport(),+ stream: createStreamSink(),+ },+});++describe('callLlm executor', () => {+ it('delegates call_llm execution to the LLM transport', async () => {+ const state = createState();+ const expected = {+ events: [],+ newState: state,+ };+ const executeCall = vi.fn().mockResolvedValue(expected);+ const host = createHost({+ executeCall,+ stream: vi.fn(),+ });++ await expect(callLlm(host)(instruction, state)).resolves.toBe(expected);+ expect(executeCall).toHaveBeenCalledWith({ instruction, state });+ });++ it('throws when the LLM transport does not provide executeCall', async () => {+ const host = createHost({+ stream: vi.fn(),+ });++ await expect(callLlm(host)(instruction, createState())).rejects.toThrow(+ 'LLMTransport.executeCall is required for call_llm executor',+ );+ });+});diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsnew file mode 100644index 00000000000..6f77d1ec3ee--- /dev/null+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -0,0 +1,32 @@+import type { AgentRuntimeHost, LLMCallExecuteInput } from '../transport';+import type { AgentInstruction, InstructionExecutor } from '../types';++interface LLMCallTransport {+ executeCall: (input: LLMCallExecuteInput) => ReturnType<InstructionExecutor>;+}++const requireLLMCallTransport = (host: AgentRuntimeHost) => {+ const llm = host.transports.llm;+ if (!llm?.executeCall) {+ throw new Error('LLMTransport.executeCall is required for call_llm executor');+ }+ return llm as NonNullable<AgentRuntimeHost['transports']['llm']> & LLMCallTransport;+};++/**+ * `call_llm` executor — transitional transport-backed entry point.+ *+ * The server-specific implementation still lives behind the LLM transport while+ * the remaining context/stream/persist internals are broken into package-owned+ * ports. This removes the direct server executor registration first, matching+ * the migration shape used by the other runtime executors.+ */+export const callLlm =+ (host: AgentRuntimeHost): InstructionExecutor =>+ async (instruction, state) => {+ const llm = requireLLMCallTransport(host);+ return llm.executeCall({+ instruction: instruction as Extract<AgentInstruction, { type: 'call_llm' }>,+ state,+ });+ };diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.tsindex d12db2dc400..23af7d6752a 100644--- a/packages/agent-runtime/src/executors/index.ts+++ b/packages/agent-runtime/src/executors/index.ts@@ -1,3 +1,4 @@+export * from './callLlm';export * from './compressContext';export * from './finish';export * from './humanApprove';diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.tsindex ce70edec370..c1208978c43 100644--- a/packages/agent-runtime/src/transport/llm.ts+++ b/packages/agent-runtime/src/transport/llm.ts@@ -1,6 +1,11 @@import type { ModelUsage, OpenAIChatMessage } from '@lobechat/types';-import type { CallLLMPayload } from '../types';+import type {+ AgentInstructionCallLlm,+ AgentState,+ CallLLMPayload,+ InstructionExecutor,+} from '../types';export interface LLMStreamPayload {[key: string]: unknown;@@ -32,6 +37,11 @@ export interface LLMStreamHandlers {onText?: (text: string) => void;}+export interface LLMCallExecuteInput {+ instruction: AgentInstructionCallLlm;+ state: AgentState;+}+/*** Streams a model completion. Server adapter wraps `initModelRuntimeFromDB` +* `ModelRuntime.chat` + `consumeStreamUntilDone`; the client adapter wraps@@ -42,6 +52,13 @@ export interface LLMStreamHandlers {* `@lobechat/model-runtime`.*/export interface LLMTransport {+ /**+ * Executes a full agent `call_llm` instruction. This is a transitional port:+ * the server adapter can keep provider/context/persistence specifics while+ * the package owns the executor registration point. The internals are split+ * into smaller context/stream/persist ports in the next migration slices.+ */+ executeCall?: (input: LLMCallExecuteInput) => ReturnType<InstructionExecutor>;stream: (payload: LLMStreamPayload,handlers?: LLMStreamHandlers,