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(route-log): record image/video generation triggers (#14048)

YuTengjing17834d41c310
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index 6b84924d74b..ec979e5d364 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -18,9 +18,11 @@
"table.columns.trigger.enums.cron": "定时任务",
"table.columns.trigger.enums.eval": "基准评测",
"table.columns.trigger.enums.file_embedding": "文件嵌入",
+ "table.columns.trigger.enums.image": "图像生成",
"table.columns.trigger.enums.memory": "记忆提取",
"table.columns.trigger.enums.semantic_search": "知识搜索",
"table.columns.trigger.enums.topic": "话题总结",
+ "table.columns.trigger.enums.video": "视频生成",
"table.columns.trigger.title": "触发方式",
"table.columns.type.enums.chat": "文本生成",
"table.columns.type.enums.embedding": "嵌入",
diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.ts
index 8c6c445ce76..b2099658f71 100644
--- a/packages/model-runtime/src/core/BaseAI.ts
+++ b/packages/model-runtime/src/core/BaseAI.ts
@@ -4,8 +4,10 @@ import type OpenAI from 'openai';
import type {
ChatMethodOptions,
ChatStreamPayload,
+ CreateImageMethodOptions,
CreateImagePayload,
CreateImageResponse,
+ CreateVideoMethodOptions,
CreateVideoPayload,
CreateVideoResponse,
Embeddings,
@@ -24,9 +26,15 @@ import type {
export interface LobeRuntimeAI {
baseURL?: string;
chat?: (payload: ChatStreamPayload, options?: ChatMethodOptions) => Promise<Response>;
- createImage?: (payload: CreateImagePayload) => Promise<CreateImageResponse>;
+ createImage?: (
+ payload: CreateImagePayload,
+ options?: CreateImageMethodOptions,
+ ) => Promise<CreateImageResponse>;
- createVideo?: (payload: CreateVideoPayload) => Promise<CreateVideoResponse>;
+ createVideo?: (
+ payload: CreateVideoPayload,
+ options?: CreateVideoMethodOptions,
+ ) => Promise<CreateVideoResponse>;
embeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<Embeddings[]>;
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index bf9d0b51375..dc25f47ed6f 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -7,6 +7,7 @@ import type { ChatStreamCallbacks, ChatStreamPayload, ModelRuntimeHooks } from '
import { LobeOpenAI, ModelRuntime } from '../index';
import { providerRuntimeMap } from '../runtimeMap';
import type { CreateImagePayload } from '../types/image';
+import type { CreateVideoPayload } from '../types/video';
/**
* Mock createTraceOptions for testing purposes.
@@ -248,7 +249,7 @@ describe('ModelRuntime', () => {
const result = await mockModelRuntime.createImage(payload);
- expect(LobeOpenAI.prototype.createImage).toHaveBeenCalledWith(payload);
+ expect(LobeOpenAI.prototype.createImage).toHaveBeenCalledWith(payload, undefined);
expect(result).toBe(mockResponse);
});
@@ -274,6 +275,58 @@ describe('ModelRuntime', () => {
expect(result).toBeUndefined();
});
+
+ it('should forward options to the underlying runtime', async () => {
+ const payload: CreateImagePayload = {
+ model: 'dall-e-3',
+ params: { prompt: 'a cat', width: 512, height: 512 },
+ };
+ const mockResponse = { imageUrl: 'x', width: 512, height: 512 };
+ const createImage = vi.fn().mockResolvedValue(mockResponse);
+
+ // @ts-ignore - injecting a minimal runtime for this case
+ mockModelRuntime['_runtime'] = { createImage };
+
+ const options = { metadata: { trigger: 'image' } };
+ const result = await mockModelRuntime.createImage(payload, options);
+
+ expect(createImage).toHaveBeenCalledWith(payload, options);
+ expect(result).toBe(mockResponse);
+ });
+ });
+
+ describe('ModelRuntime createVideo method', () => {
+ it('should forward payload and options to the underlying runtime', async () => {
+ const payload: CreateVideoPayload = {
+ model: 'sora-1',
+ params: { prompt: 'a cat' } as any,
+ };
+ const mockResponse = { inferenceId: 'job-1' };
+ const createVideo = vi.fn().mockResolvedValue(mockResponse);
+
+ // @ts-ignore - injecting a minimal runtime for this case
+ mockModelRuntime['_runtime'] = { createVideo };
+
+ const options = { metadata: { trigger: 'video' } };
+ const result = await mockModelRuntime.createVideo(payload, options);
+
+ expect(createVideo).toHaveBeenCalledWith(payload, options);
+ expect(result).toBe(mockResponse);
+ });
+
+ it('should handle undefined createVideo method gracefully', async () => {
+ const payload: CreateVideoPayload = {
+ model: 'sora-1',
+ params: { prompt: 'a cat' } as any,
+ };
+
+ // @ts-ignore - testing edge case
+ mockModelRuntime['_runtime'] = { createVideo: undefined };
+
+ const result = await mockModelRuntime.createVideo(payload);
+
+ expect(result).toBeUndefined();
+ });
});
describe('ModelRuntime models method', () => {
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 07e79d2b3c0..6dafe1b13d2 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -19,8 +19,16 @@ import type {
TextToSpeechPayload,
} from '../types';
import { AgentRuntimeErrorType } from '../types/error';
-import type { AuthenticatedImageRuntime, CreateImagePayload } from '../types/image';
-import type { CreateVideoPayload, HandleCreateVideoWebhookPayload } from '../types/video';
+import type {
+ AuthenticatedImageRuntime,
+ CreateImageMethodOptions,
+ CreateImagePayload,
+} from '../types/image';
+import type {
+ CreateVideoMethodOptions,
+ CreateVideoPayload,
+ HandleCreateVideoWebhookPayload,
+} from '../types/video';
import { AgentRuntimeError } from '../utils/createError';
import type { LobeRuntimeAI } from './BaseAI';
@@ -198,12 +206,12 @@ export class ModelRuntime {
}
}
- async createImage(payload: CreateImagePayload) {
- return this._runtime.createImage?.(payload);
+ async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {
+ return this._runtime.createImage?.(payload, options);
}
- async createVideo(payload: CreateVideoPayload) {
- return this._runtime.createVideo?.(payload);
+ async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {
+ return this._runtime.createVideo?.(payload, options);
}
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 2767fedb6ac..af06cbefe4b 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -734,6 +734,99 @@ describe('createRouterRuntime', () => {
expect(result).toEqual({ imageUrl: 'https://example.com/image.png' });
expect(mockCreateImage).toHaveBeenCalledWith(payload);
});
+
+ it('should forward options.metadata to onRouteAttempt', async () => {
+ const mockCreateImage = vi
+ .fn()
+ .mockResolvedValue({ imageUrl: 'https://example.com/image.png' });
+ const onRouteAttempt = vi.fn().mockResolvedValue(undefined);
+
+ class MockRuntime implements LobeRuntimeAI {
+ createImage = mockCreateImage;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt,
+ routers: [
+ {
+ apiType: 'openai',
+ options: {},
+ runtime: MockRuntime as any,
+ models: ['gpt-image-1'],
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ const payload = { model: 'gpt-image-1', params: { prompt: 'a cat' } };
+ const metadata = { trigger: 'image' };
+
+ await runtime.createImage(payload, { metadata });
+
+ expect(mockCreateImage).toHaveBeenCalledWith(payload);
+ expect(onRouteAttempt).toHaveBeenCalledWith(expect.objectContaining({ metadata }));
+ });
+ });
+
+ describe('createVideo method', () => {
+ it('should call createVideo on the correct runtime', async () => {
+ const mockCreateVideo = vi.fn().mockResolvedValue({ inferenceId: 'job-1' });
+
+ class MockRuntime implements LobeRuntimeAI {
+ createVideo = mockCreateVideo;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: [
+ {
+ apiType: 'openai',
+ options: {},
+ runtime: MockRuntime as any,
+ models: ['sora-1'],
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ const payload = { model: 'sora-1', params: { prompt: 'a cat' } } as any;
+
+ const result = await runtime.createVideo(payload);
+ expect(result).toEqual({ inferenceId: 'job-1' });
+ expect(mockCreateVideo).toHaveBeenCalledWith(payload);
+ });
+
+ it('should forward options.metadata to onRouteAttempt', async () => {
+ const mockCreateVideo = vi.fn().mockResolvedValue({ inferenceId: 'job-1' });
+ const onRouteAttempt = vi.fn().mockResolvedValue(undefined);
+
+ class MockRuntime implements LobeRuntimeAI {
+ createVideo = mockCreateVideo;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt,
+ routers: [
+ {
+ apiType: 'openai',
+ options: {},
+ runtime: MockRuntime as any,
+ models: ['sora-1'],
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ const payload = { model: 'sora-1', params: { prompt: 'a cat' } } as any;
+ const metadata = { trigger: 'video' };
+
+ await runtime.createVideo(payload, { metadata });
+
+ expect(mockCreateVideo).toHaveBeenCalledWith(payload);
+ expect(onRouteAttempt).toHaveBeenCalledWith(expect.objectContaining({ metadata }));
+ });
});
describe('generateObject method', () => {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 7a0f81434a5..bfba0e73541 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -15,8 +15,10 @@ import type {
ChatMethodOptions,
ChatStreamCallbacks,
ChatStreamPayload,
+ CreateImageMethodOptions,
CreateImagePayload,
CreateImageResponse,
+ CreateVideoMethodOptions,
CreateVideoPayload,
CreateVideoResponse,
EmbeddingsOptions,
@@ -482,12 +484,20 @@ export const createRouterRuntime = ({
}
}
- async createImage(payload: CreateImagePayload) {
- return this.runWithFallback(payload.model, (runtime) => runtime.createImage!(payload));
+ async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {
+ return this.runWithFallback(
+ payload.model,
+ (runtime) => runtime.createImage!(payload),
+ options?.metadata,
+ );
}
- async createVideo(payload: CreateVideoPayload) {
- return this.runWithFallback(payload.model, (runtime) => runtime.createVideo!(payload));
+ async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {
+ return this.runWithFallback(
+ payload.model,
+ (runtime) => runtime.createVideo!(payload),
+ options?.metadata,
+ );
}
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
diff --git a/packages/model-runtime/src/types/image.ts b/packages/model-runtime/src/types/image.ts
index 5cd446d6bc6..24a7b53fef9 100644
--- a/packages/model-runtime/src/types/image.ts
+++ b/packages/model-runtime/src/types/image.ts
@@ -6,6 +6,11 @@ export type CreateImagePayload = {
params: RuntimeImageGenParams;
};
+export interface CreateImageMethodOptions {
+ /** Metadata passed to hooks (billing, tracing, etc.) */
+ metadata?: Record<string, unknown>;
+}
+
/**
* Why return width and height?
* 1. The configured width may differ from the actual generated width, which needs to be stored in the generation asset
diff --git a/packages/model-runtime/src/types/video.ts b/packages/model-runtime/src/types/video.ts
index eec50bde8ab..07c821d002e 100644
--- a/packages/model-runtime/src/types/video.ts
+++ b/packages/model-runtime/src/types/video.ts
@@ -12,6 +12,11 @@ export type CreateVideoPayload = {
params: RuntimeVideoGenParams;
};
+export interface CreateVideoMethodOptions {
+ /** Metadata passed to hooks (billing, tracing, etc.) */
+ metadata?: Record<string, unknown>;
+}
+
export type CreateVideoResponse =
| {
inferenceId: string;
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 963318d5c85..65542be02eb 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -5,9 +5,11 @@ export enum RequestTrigger {
Cron = 'cron',
Eval = 'eval',
FileEmbedding = 'file_embedding',
+ Image = 'image',
Memory = 'memory',
SemanticSearch = 'semantic_search',
Topic = 'topic',
+ Video = 'video',
}
// ******* Runtime Biz Error ******* //
diff --git a/src/locales/default/spend.ts b/src/locales/default/spend.ts
index e532d3216dd..521c507685c 100644
--- a/src/locales/default/spend.ts
+++ b/src/locales/default/spend.ts
@@ -18,9 +18,11 @@ export default {
'table.columns.trigger.enums.cron': 'Scheduled Task',
'table.columns.trigger.enums.eval': 'Benchmark Eval',
'table.columns.trigger.enums.file_embedding': 'File Embedding',
+ 'table.columns.trigger.enums.image': 'Image Generation',
'table.columns.trigger.enums.memory': 'Memory Extraction',
'table.columns.trigger.enums.semantic_search': 'Knowledge Search',
'table.columns.trigger.enums.topic': 'Topic Summary',
+ 'table.columns.trigger.enums.video': 'Video Generation',
'table.columns.trigger.title': 'Trigger',
'table.columns.type.enums.chat': 'Text Generation',
'table.columns.type.enums.embedding': 'Embedding',
diff --git a/src/server/routers/async/image.ts b/src/server/routers/async/image.ts
index 2e773b35d59..72d41d68388 100644
--- a/src/server/routers/async/image.ts
+++ b/src/server/routers/async/image.ts
@@ -5,7 +5,12 @@ import {
resolveBusinessModelMapping,
} from '@lobechat/business-model-runtime';
import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@lobechat/types';
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ RequestTrigger,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { type RuntimeImageGenParams } from 'model-bank';
@@ -272,10 +277,13 @@ export const imageRouter = router({
// Check if operation has been cancelled
checkAbortSignal(signal);
log('Agent runtime initialized, calling createImage');
- const response = await modelRuntime.createImage!({
- model: resolvedModelId,
- params: params as unknown as RuntimeImageGenParams,
- });
+ const response = await modelRuntime.createImage!(
+ {
+ model: resolvedModelId,
+ params: params as unknown as RuntimeImageGenParams,
+ },
+ { metadata: { trigger: RequestTrigger.Image } },
+ );
if (!response) {
log('Create image response is empty');
diff --git a/src/server/routers/lambda/userMemories.ts b/src/server/routers/lambda/userMemories.ts
index bf47dbf166e..3939cf51325 100644
--- a/src/server/routers/lambda/userMemories.ts
+++ b/src/server/routers/lambda/userMemories.ts
@@ -920,6 +920,14 @@ export const userMemoriesRouter = router({
retrieveMemoryForTopic: memoryProcedure
.input(z.object({ topicId: z.string() }))
.query(async ({ ctx, input }) => {
+ // Dev-only escape hatch: skip the embedding + memory search triggered by topic
+ // load / switch, so chat debugging logs aren't drowned in `text-embedding-3-small`
+ // router-runtime output. Only honored in non-production builds.
+ if (process.env.NODE_ENV !== 'production' && process.env.DEV_DISABLE_AUTO_MEMORY === '1') {
+ console.info('[dev] skip retrieveMemoryForTopic (DEV_DISABLE_AUTO_MEMORY=1)');
+ return EMPTY_SEARCH_RESULT;
+ }
+
try {
// Get concatenated user messages for this topic
const userMemoryTopicRepo = new UserMemoryTopicRepository(ctx.serverDB, ctx.userId);
diff --git a/src/server/routers/lambda/video/index.ts b/src/server/routers/lambda/video/index.ts
index a4bafb15a0d..1c44814b0a1 100644
--- a/src/server/routers/lambda/video/index.ts
+++ b/src/server/routers/lambda/video/index.ts
@@ -4,6 +4,7 @@ import {
buildMappedBusinessModelFields,
resolveBusinessModelMapping,
} from '@lobechat/business-model-runtime';
+import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { and, eq } from 'drizzle-orm';
import { after } from 'next/server';
@@ -217,11 +218,14 @@ export const videoRouter = router({
const callbackUrl = `${callbackBaseUrl}/api/webhooks/video/${provider}?token=${webhookToken}`;
log('Using callback URL: %s', callbackUrl);
- const response = await modelRuntime.createVideo({
- callbackUrl,
- model: resolvedModelId,
- params: generationParams,
- });
+ const response = await modelRuntime.createVideo(
+ {
+ callbackUrl,
+ model: resolvedModelId,
+ params: generationParams,
+ },
+ { metadata: { trigger: RequestTrigger.Video } },
+ );
log('Video task submitted successfully, inferenceId: %s', response?.inferenceId);
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 561a9fcc55d..7d6bd152b45 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -11,6 +11,7 @@ import {
type ConversationContext,
type SendMessageParams,
type SendMessageServerResponse,
+ type UIChatMessage,
} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { TRPCClientError } from '@trpc/client';
@@ -700,10 +701,31 @@ export class ConversationLifecycleActionImpl {
if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, true);
+ // Dev-only fast path: fall back to slicing the first user message instead of calling
+ // the LLM. Keeps chat logs uncluttered while still giving the topic a usable title.
+ // Only honored in non-production builds so a misconfigured prod env can't disable it.
+ const shouldSliceTopicTitle =
+ process.env.NODE_ENV !== 'production' &&
+ process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC === '1';
+
+ const applyTopicTitle = async (topicId: string, messages: UIChatMessage[]) => {
+ if (!shouldSliceTopicTitle) {
+ await this.#get().summaryTopicTitle(topicId, messages);
+ return;
+ }
+
+ const firstUserText = messages.find((m) => m.role === 'user')?.content?.trim() ?? '';
+ const title = firstUserText.slice(0, 30) || 'New Topic';
+ await this.#get().internal_updateTopic(topicId, { title });
+ // summaryTopicTitle would normally clear loading via onLoadingChange; do it manually.
+ this.#get().internal_updateTopicLoading(topicId, false);
+ console.info('[dev] sliced topic title (NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC=1):', title);
+ };
+
const summaryTitle = async () => {
// check activeTopic and then auto update topic title
if (data.isCreateNewTopic) {
- await this.#get().summaryTopicTitle(data.topicId, data.messages);
+ await applyTopicTitle(data.topicId, data.messages);
return;
}
@@ -716,7 +738,7 @@ export class ConversationLifecycleActionImpl {
.getDisplayMessagesByKey(messageMapKey({ agentId, topicId: topic.id }))(this.#get())
.filter((item) => item.id !== data.assistantMessageId);
- await this.#get().summaryTopicTitle(topic.id, chats);
+ await applyTopicTitle(topic.id, chats);
}
};