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: move call_llm shell into runtime package (#16948)

Arvin Xua95ed61579ce
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index 80adbde9ad6..7142f7154ad 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -29,7 +29,13 @@ export class ServerLLMTransport implements LLMTransport {
constructor(private readonly ctx: RuntimeExecutorContext) {}
executeCall(input: LLMCallExecuteInput): ReturnType<NonNullable<LLMTransport['executeCall']>> {
- return createServerCallLlmExecutor(this.ctx)(input.instruction, input.state);
+ return createServerCallLlmExecutor(this.ctx, {
+ assistantMessage: input.assistantMessage,
+ model: input.model,
+ parentId: input.parentId,
+ provider: input.provider,
+ stepLabel: input.stepLabel,
+ })(input.instruction, input.state);
}
async stream(
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index 4b539b1fb4e..85c3311ef77 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -50,7 +50,19 @@ export class ServerMessageTransport implements MessageTransport {
async findById(id: string): Promise<RuntimeMessageRef | undefined> {
const message = await this.messageModel.findById(id);
- return message ? { id: message.id } : undefined;
+ return message
+ ? {
+ agentId: message.agentId,
+ groupId: message.groupId,
+ id: message.id,
+ model: message.model,
+ parentId: message.parentId,
+ provider: message.provider,
+ role: message.role,
+ threadId: message.threadId,
+ topicId: message.topicId,
+ }
+ : undefined;
}
async query(
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
index c520298280f..30961ef5d77 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
@@ -109,13 +109,21 @@ import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+interface PreparedCallLLMContext {
+ assistantMessage: { id: string };
+ model: string;
+ parentId?: string;
+ provider: string;
+ stepLabel?: string;
+}
+
const SERVER_LLM_RETRY_POLICY = {
isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,
noRetryProviders: [BRANDING_PROVIDER],
};
export const callLlm =
- (ctx: RuntimeExecutorContext): InstructionExecutor =>
+ (ctx: RuntimeExecutorContext, prepared?: PreparedCallLLMContext): InstructionExecutor =>
async (instruction, state) => {
const { payload } = instruction as Extract<AgentInstruction, { type: 'call_llm' }>;
const llmPayload = payload as CallLLMPayload;
@@ -124,8 +132,9 @@ export const callLlm =
let visibleOutputEndPublishedStepIndex: number | undefined;
// Fallback to state's modelRuntimeConfig if not in payload
- const model = llmPayload.model || state.modelRuntimeConfig?.model;
- const provider = llmPayload.provider || state.modelRuntimeConfig?.provider;
+ const model = prepared?.model ?? llmPayload.model ?? state.modelRuntimeConfig?.model;
+ const provider =
+ prepared?.provider ?? llmPayload.provider ?? state.modelRuntimeConfig?.provider;
// Resolve tools via ToolResolver (unified tool injection).
//
// Single-track device gate: `buildStepToolDelta` treats activeDeviceId as
@@ -191,7 +200,8 @@ export const callLlm =
log(`${stagePrefix} Starting operation`);
// Get parentId from payload (parentId or parentMessageId depending on payload type)
- const parentId = llmPayload.parentId || (llmPayload as any).parentMessageId;
+ const parentId =
+ prepared?.parentId ?? llmPayload.parentId ?? (llmPayload as any).parentMessageId;
// Parent existence preflight ():
// If the parent was deleted concurrently (e.g. user deleted topic mid-run),
@@ -199,7 +209,7 @@ export const callLlm =
// already done the LLM call and spent tokens. Check first β€” fail fast,
// save cost, and surface a typed error the frontend can act on instead of
// a raw SQL error.
- if (parentId) {
+ if (!prepared && parentId) {
const parentExists = await ctx.messageModel.findById(parentId);
if (!parentExists) {
const error = createConversationParentMissingError(parentId);
@@ -222,7 +232,10 @@ export const callLlm =
// refetch β€” chunks would silently no-op against the missing id (LOBE-11501).
let assistantMessageSeed: Record<string, unknown> | undefined;
- if (existingAssistantMessageId) {
+ if (prepared) {
+ assistantMessageItem = prepared.assistantMessage;
+ log(`${stagePrefix} Using prepared assistant message: %s`, assistantMessageItem.id);
+ } else if (existingAssistantMessageId) {
// Use existing assistant message (created by execAgent)
assistantMessageItem = { id: existingAssistantMessageId };
log(`${stagePrefix} Using existing assistant message: %s`, existingAssistantMessageId);
@@ -246,30 +259,32 @@ export const callLlm =
}
// Publish stream start event
- const stepLabel = (instruction as any).stepLabel;
- await streamManager.publishStreamEvent(operationId, {
- data: {
- // Only the seed fields the client needs β€” not the whole DB row.
- assistantMessage: {
- id: assistantMessageItem.id,
- ...(assistantMessageSeed && {
- agentId: assistantMessageSeed.agentId,
- groupId: assistantMessageSeed.groupId,
- model: assistantMessageSeed.model,
- parentId: assistantMessageSeed.parentId,
- provider: assistantMessageSeed.provider,
- role: assistantMessageSeed.role,
- threadId: assistantMessageSeed.threadId,
- topicId: assistantMessageSeed.topicId,
- }),
+ const stepLabel = prepared?.stepLabel ?? (instruction as any).stepLabel;
+ if (!prepared) {
+ await streamManager.publishStreamEvent(operationId, {
+ data: {
+ // Only the seed fields the client needs β€” not the whole DB row.
+ assistantMessage: {
+ id: assistantMessageItem.id,
+ ...(assistantMessageSeed && {
+ agentId: assistantMessageSeed.agentId,
+ groupId: assistantMessageSeed.groupId,
+ model: assistantMessageSeed.model,
+ parentId: assistantMessageSeed.parentId,
+ provider: assistantMessageSeed.provider,
+ role: assistantMessageSeed.role,
+ threadId: assistantMessageSeed.threadId,
+ topicId: assistantMessageSeed.topicId,
+ }),
+ },
+ model,
+ provider,
+ ...(stepLabel && { stepLabel }),
},
- model,
- provider,
- ...(stepLabel && { stepLabel }),
- },
- stepIndex,
- type: 'stream_start',
- });
+ stepIndex,
+ type: 'stream_start',
+ });
+ }
try {
type ContentPart = { text: string; type: 'text' } | { image: string; type: 'image' };
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 6c5c9a60e3b..e5445fedbae 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -15,6 +15,11 @@ const createState = (): AgentState => ({
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [],
+ metadata: {
+ agentId: 'agent-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
operationId: 'op-1',
status: 'running',
stepCount: 0,
@@ -50,10 +55,10 @@ const instruction: AgentInstructionCallLlm = {
};
const createMessageTransport = (): MessageTransport => ({
- createAssistantMessage: vi.fn(),
+ createAssistantMessage: vi.fn().mockResolvedValue({ id: 'assistant-1' }),
createToolMessage: vi.fn(),
deleteMessage: vi.fn(),
- findById: vi.fn(),
+ findById: vi.fn().mockResolvedValue({ id: 'parent-1' }),
query: vi.fn(),
update: vi.fn(),
updatePluginState: vi.fn(),
@@ -65,30 +70,109 @@ const createStreamSink = (): StreamSink => ({
publishEvent: vi.fn(),
});
-const createHost = (llm: LLMTransport): AgentRuntimeHost => ({
+const createHost = (
+ llm: LLMTransport,
+ messages = createMessageTransport(),
+ stream = createStreamSink(),
+): AgentRuntimeHost => ({
operation: { operationId: 'op-1', stepIndex: 0 },
transports: {
llm,
- messages: createMessageTransport(),
- stream: createStreamSink(),
+ messages,
+ stream,
},
});
describe('callLlm executor', () => {
- it('delegates call_llm execution to the LLM transport', async () => {
+ it('prepares the assistant message and 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(),
+ const messages = createMessageTransport();
+ const stream = createStreamSink();
+ const host = createHost(
+ {
+ executeCall,
+ stream: vi.fn(),
+ },
+ messages,
+ stream,
+ );
+ const instructionWithParent: AgentInstructionCallLlm = {
+ payload: {
+ ...instruction.payload,
+ parentId: 'parent-1',
+ },
+ type: 'call_llm',
+ };
+
+ await expect(callLlm(host)(instructionWithParent, state)).resolves.toBe(expected);
+ expect(messages.findById).toHaveBeenCalledWith('parent-1');
+ expect(messages.createAssistantMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ content: '',
+ model: 'gpt-4',
+ parentId: 'parent-1',
+ provider: 'openai',
+ role: 'assistant',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ }),
+ );
+ expect(stream.publishEvent).toHaveBeenCalledWith({
+ data: {
+ assistantMessage: { id: 'assistant-1' },
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ stepIndex: 0,
+ type: 'stream_start',
});
+ expect(executeCall).toHaveBeenCalledWith({
+ assistantMessage: { id: 'assistant-1' },
+ instruction: instructionWithParent,
+ model: 'gpt-4',
+ parentId: 'parent-1',
+ provider: 'openai',
+ state,
+ stepLabel: undefined,
+ });
+ });
+
+ it('reuses an existing assistant message without creating a new one', async () => {
+ const state = createState();
+ const expected = {
+ events: [],
+ newState: state,
+ };
+ const executeCall = vi.fn().mockResolvedValue(expected);
+ const messages = createMessageTransport();
+ const host = createHost(
+ {
+ executeCall,
+ stream: vi.fn(),
+ },
+ messages,
+ );
+ const reuseInstruction: AgentInstructionCallLlm = {
+ payload: {
+ ...instruction.payload,
+ assistantMessageId: 'assistant-existing',
+ },
+ type: 'call_llm',
+ };
- await expect(callLlm(host)(instruction, state)).resolves.toBe(expected);
- expect(executeCall).toHaveBeenCalledWith({ instruction, state });
+ await expect(callLlm(host)(reuseInstruction, state)).resolves.toBe(expected);
+ expect(messages.createAssistantMessage).not.toHaveBeenCalled();
+ expect(executeCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assistantMessage: { id: 'assistant-existing' },
+ }),
+ );
});
it('throws when the LLM transport does not provide executeCall', async () => {
@@ -100,4 +184,41 @@ describe('callLlm executor', () => {
'LLMTransport.executeCall is required for call_llm executor',
);
});
+
+ it('fails before creating an assistant message when the parent message is missing', async () => {
+ const messages = createMessageTransport();
+ vi.mocked(messages.findById).mockResolvedValue(undefined);
+ const stream = createStreamSink();
+ const host = createHost(
+ {
+ executeCall: vi.fn(),
+ stream: vi.fn(),
+ },
+ messages,
+ stream,
+ );
+ const instructionWithParent: AgentInstructionCallLlm = {
+ payload: {
+ ...instruction.payload,
+ parentMessageId: 'missing-parent',
+ },
+ type: 'call_llm',
+ };
+
+ await expect(callLlm(host)(instructionWithParent, createState())).rejects.toMatchObject({
+ errorType: 'ConversationParentMissing',
+ parentId: 'missing-parent',
+ });
+ expect(messages.createAssistantMessage).not.toHaveBeenCalled();
+ expect(stream.publishEvent).toHaveBeenCalledWith({
+ data: {
+ error:
+ 'Conversation parent message missing-parent no longer exists. It was likely deleted while the operation was running.',
+ errorType: 'ConversationParentMissing',
+ phase: 'parent_message_preflight',
+ },
+ stepIndex: 0,
+ type: 'error',
+ });
+ });
});
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index 6f77d1ec3ee..b3f06cfa013 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -1,5 +1,7 @@
import type { AgentRuntimeHost, LLMCallExecuteInput } from '../transport';
-import type { AgentInstruction, InstructionExecutor } from '../types';
+import type { AgentInstruction, CallLLMPayload, InstructionExecutor } from '../types';
+
+const CONVERSATION_PARENT_MISSING_ERROR_TYPE = 'ConversationParentMissing';
interface LLMCallTransport {
executeCall: (input: LLMCallExecuteInput) => ReturnType<InstructionExecutor>;
@@ -13,6 +15,55 @@ const requireLLMCallTransport = (host: AgentRuntimeHost) => {
return llm as NonNullable<AgentRuntimeHost['transports']['llm']> & LLMCallTransport;
};
+const createConversationParentMissingError = (parentId: string) => {
+ const error = new Error(
+ `Conversation parent message ${parentId} no longer exists. It was likely deleted while the operation was running.`,
+ );
+ Object.assign(error, {
+ errorType: CONVERSATION_PARENT_MISSING_ERROR_TYPE,
+ parentId,
+ });
+ return error;
+};
+
+const formatErrorEventData = (error: Error & { errorType?: unknown }, phase: string) => ({
+ error: error.message,
+ errorType: typeof error.errorType === 'string' ? error.errorType : error.name,
+ phase,
+});
+
+const pickSeedField = (source: object, key: string) => {
+ const value = (source as Record<string, unknown>)[key];
+ return value === undefined ? undefined : value;
+};
+
+const buildAssistantMessageSeed = (
+ assistantMessage: { id: string },
+ seed: object = assistantMessage,
+) => ({
+ id: assistantMessage.id,
+ ...(pickSeedField(seed, 'agentId') !== undefined && {
+ agentId: pickSeedField(seed, 'agentId'),
+ }),
+ ...(pickSeedField(seed, 'groupId') !== undefined && {
+ groupId: pickSeedField(seed, 'groupId'),
+ }),
+ ...(pickSeedField(seed, 'model') !== undefined && { model: pickSeedField(seed, 'model') }),
+ ...(pickSeedField(seed, 'parentId') !== undefined && {
+ parentId: pickSeedField(seed, 'parentId'),
+ }),
+ ...(pickSeedField(seed, 'provider') !== undefined && {
+ provider: pickSeedField(seed, 'provider'),
+ }),
+ ...(pickSeedField(seed, 'role') !== undefined && { role: pickSeedField(seed, 'role') }),
+ ...(pickSeedField(seed, 'threadId') !== undefined && {
+ threadId: pickSeedField(seed, 'threadId'),
+ }),
+ ...(pickSeedField(seed, 'topicId') !== undefined && {
+ topicId: pickSeedField(seed, 'topicId'),
+ }),
+});
+
/**
* `call_llm` executor β€” transitional transport-backed entry point.
*
@@ -24,9 +75,72 @@ const requireLLMCallTransport = (host: AgentRuntimeHost) => {
export const callLlm =
(host: AgentRuntimeHost): InstructionExecutor =>
async (instruction, state) => {
+ const { operation, transports } = host;
const llm = requireLLMCallTransport(host);
+ const { payload } = instruction as Extract<AgentInstruction, { type: 'call_llm' }>;
+ const llmPayload = payload as CallLLMPayload & {
+ assistantMessageId?: string;
+ parentMessageId?: string;
+ };
+ const model = llmPayload.model || state.modelRuntimeConfig?.model;
+ const provider = llmPayload.provider || state.modelRuntimeConfig?.provider;
+
+ if (!model || !provider) {
+ throw new Error('Model and provider are required for call_llm instruction');
+ }
+
+ const parentId = llmPayload.parentId || llmPayload.parentMessageId;
+ if (parentId) {
+ const parentExists = await transports.messages.findById(parentId);
+ if (!parentExists) {
+ const error = createConversationParentMissingError(parentId);
+ await transports.stream.publishEvent({
+ data: formatErrorEventData(error, 'parent_message_preflight'),
+ stepIndex: operation.stepIndex,
+ type: 'error',
+ });
+ throw error;
+ }
+ }
+
+ const existingAssistantMessageId = llmPayload.assistantMessageId;
+ const assistantMessage = existingAssistantMessageId
+ ? { id: existingAssistantMessageId }
+ : await transports.messages.createAssistantMessage({
+ agentId: state.metadata!.agentId!,
+ content: '',
+ groupId: state.metadata?.groupId ?? undefined,
+ model,
+ parentId,
+ provider,
+ role: 'assistant',
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ });
+
+ const assistantMessageSeed = existingAssistantMessageId
+ ? ((await transports.messages.findById(existingAssistantMessageId)) ?? assistantMessage)
+ : assistantMessage;
+ const stepLabel = (instruction as { stepLabel?: string }).stepLabel;
+
+ await transports.stream.publishEvent({
+ data: {
+ assistantMessage: buildAssistantMessageSeed(assistantMessage, assistantMessageSeed),
+ model,
+ provider,
+ ...(stepLabel && { stepLabel }),
+ },
+ stepIndex: operation.stepIndex,
+ type: 'stream_start',
+ });
+
return llm.executeCall({
+ assistantMessage,
instruction: instruction as Extract<AgentInstruction, { type: 'call_llm' }>,
+ model,
+ parentId,
+ provider,
state,
+ stepLabel,
});
};
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
index c1208978c43..ae23ad34d94 100644
--- a/packages/agent-runtime/src/transport/llm.ts
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -6,6 +6,7 @@ import type {
CallLLMPayload,
InstructionExecutor,
} from '../types';
+import type { RuntimeMessageRef } from './message';
export interface LLMStreamPayload {
[key: string]: unknown;
@@ -38,8 +39,13 @@ export interface LLMStreamHandlers {
}
export interface LLMCallExecuteInput {
+ assistantMessage: RuntimeMessageRef;
instruction: AgentInstructionCallLlm;
+ model: string;
+ parentId?: string;
+ provider: string;
state: AgentState;
+ stepLabel?: string;
}
/**
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index 7d06a3b42c8..edfaa0e8b5a 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -2,7 +2,15 @@ import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@l
/** Minimal reference an executor needs back after creating a message. */
export interface RuntimeMessageRef {
+ agentId?: string | null;
+ groupId?: string | null;
id: string;
+ model?: string | null;
+ parentId?: string | null;
+ provider?: string | null;
+ role?: string;
+ threadId?: string | null;
+ topicId?: string | null;
}
export interface QueryMessagesInput {