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.

✨ feat: add visual understanding tool (#14378)

YuTengjingb5d7696dbd9b
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 55baf26eb04..6404b80e33f 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -32,7 +32,7 @@ jobs:
runs-on: ubuntu-latest
name: Test Packages
env:
- PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/python-interpreter @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory model-bank'
+ PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/python-interpreter @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/builtin-tool-lobe-agent model-bank'
steps:
- uses: actions/checkout@v6
diff --git a/package.json b/package.json
index 55d885a4851..38a8edf0132 100644
--- a/package.json
+++ b/package.json
@@ -221,6 +221,7 @@
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
"@lobechat/builtin-tool-knowledge-base": "workspace:*",
+ "@lobechat/builtin-tool-lobe-agent": "workspace:*",
"@lobechat/builtin-tool-local-system": "workspace:*",
"@lobechat/builtin-tool-memory": "workspace:*",
"@lobechat/builtin-tool-message": "workspace:*",
diff --git a/packages/agent-runtime/src/core/UsageCounter.ts b/packages/agent-runtime/src/core/UsageCounter.ts
index 117135e3810..0c5d5ede5d2 100644
--- a/packages/agent-runtime/src/core/UsageCounter.ts
+++ b/packages/agent-runtime/src/core/UsageCounter.ts
@@ -79,6 +79,7 @@ export class UsageCounter {
'inputTextTokens',
'inputImageTokens',
'inputAudioTokens',
+ 'inputVideoTokens',
'inputCitationTokens',
'inputToolTokens',
'outputTextTokens',
diff --git a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
index 5cde3f2b7bc..1629c782f89 100644
--- a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
@@ -663,6 +663,7 @@ describe('UsageCounter', () => {
cost: 0.05,
inputAudioTokens: 10,
inputImageTokens: 20,
+ inputVideoTokens: 30,
outputAudioTokens: 5,
outputImageTokens: 15,
totalInputTokens: 30,
@@ -674,6 +675,7 @@ describe('UsageCounter', () => {
cost: 0.03,
inputAudioTokens: 15,
inputImageTokens: 25,
+ inputVideoTokens: 35,
outputAudioTokens: 8,
outputImageTokens: 12,
totalInputTokens: 40,
@@ -700,6 +702,7 @@ describe('UsageCounter', () => {
cost: 0.08,
inputAudioTokens: 25,
inputImageTokens: 45,
+ inputVideoTokens: 65,
outputAudioTokens: 13,
outputImageTokens: 27,
totalInputTokens: 70,
@@ -803,6 +806,7 @@ describe('UsageCounter', () => {
inputCitationTokens: 10,
inputImageTokens: 20,
inputTextTokens: 100,
+ inputVideoTokens: 40,
inputWriteCacheTokens: 30,
outputAudioTokens: 3,
outputImageTokens: 8,
@@ -823,6 +827,7 @@ describe('UsageCounter', () => {
inputCitationTokens: 5,
inputImageTokens: 10,
inputTextTokens: 50,
+ inputVideoTokens: 20,
inputWriteCacheTokens: 15,
outputAudioTokens: 2,
outputImageTokens: 4,
@@ -858,6 +863,7 @@ describe('UsageCounter', () => {
inputCitationTokens: 15,
inputImageTokens: 30,
inputTextTokens: 150,
+ inputVideoTokens: 60,
inputWriteCacheTokens: 45,
outputAudioTokens: 5,
outputImageTokens: 12,
diff --git a/packages/builtin-tool-lobe-agent/package.json b/packages/builtin-tool-lobe-agent/package.json
new file mode 100644
index 00000000000..52839bab11f
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@lobechat/builtin-tool-lobe-agent",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./executor": "./src/executor/index.ts"
+ },
+ "main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'",
+ "test:update": "vitest -u"
+ },
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-lobe-agent/src/executor/index.ts b/packages/builtin-tool-lobe-agent/src/executor/index.ts
new file mode 100644
index 00000000000..582a654193d
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/executor/index.ts
@@ -0,0 +1,245 @@
+import type { BuiltinToolContext, BuiltinToolResult, ChatStreamPayload } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+
+import { LobeAgentManifest } from '../manifest';
+import type { AnalyzeVisualMediaParams } from '../types';
+import { LobeAgentApiName } from '../types';
+import type { VisualFileItem } from '../visualMedia';
+import {
+ buildAnalyzeVisualMediaContent,
+ createUrlVisualFileItems,
+ createVisualFileItems,
+ formatVisualMediaUrlValidationError,
+ getUnexpectedAnalyzeVisualMediaArgumentKeys,
+ hasUserVisualFiles,
+ normalizeAnalyzeVisualMediaInput,
+ selectVisualFileItems,
+ validateVisualMediaUrls,
+} from '../visualMedia';
+
+interface VisualSourceMessage {
+ parentId?: string;
+}
+
+const getVisualUnderstandingConfig = async () => {
+ const { getServerConfigStoreState, serverConfigSelectors } = await import('@/store/serverConfig');
+ const serverConfigState = getServerConfigStoreState();
+
+ return serverConfigState
+ ? serverConfigSelectors.visualUnderstanding(serverConfigState)
+ : undefined;
+};
+
+const createAbortController = (signal?: AbortSignal) => {
+ const abortController = new AbortController();
+
+ if (signal?.aborted) {
+ abortController.abort();
+ return abortController;
+ }
+
+ signal?.addEventListener('abort', () => abortController.abort(), { once: true });
+
+ return abortController;
+};
+
+const isVisualSourceMessage = (message: unknown): message is VisualSourceMessage =>
+ !!message && typeof message === 'object';
+
+class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {
+ readonly identifier = LobeAgentManifest.identifier;
+ protected readonly apiEnum = LobeAgentApiName;
+
+ analyzeVisualMedia = async (
+ params: AnalyzeVisualMediaParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const config = await getVisualUnderstandingConfig();
+
+ if (!config?.provider || !config.model) {
+ return {
+ error: {
+ message: 'Visual understanding model is not configured',
+ type: 'PluginSettingsInvalid',
+ },
+ success: false,
+ };
+ }
+
+ if (!params.question?.trim()) {
+ return {
+ error: { message: '`question` is required', type: 'InvalidToolArguments' },
+ success: false,
+ };
+ }
+
+ const { requestedRefs, requestedUrls } = normalizeAnalyzeVisualMediaInput(
+ params as unknown as Record<PropertyKey, unknown>,
+ );
+ if (requestedRefs.length === 0 && requestedUrls.length === 0) {
+ const unexpectedKeys = getUnexpectedAnalyzeVisualMediaArgumentKeys(
+ params as unknown as Record<PropertyKey, unknown>,
+ );
+ const aliasHint =
+ unexpectedKeys.length > 0 ? ` Do not use ${unexpectedKeys.join(', ')}.` : '';
+
+ return {
+ error: {
+ message: `Either \`refs\` or \`urls\` is required and must include at least one visual file ref or media URL.${aliasHint}`,
+ type: 'InvalidToolArguments',
+ },
+ success: false,
+ };
+ }
+
+ const urlValidation = validateVisualMediaUrls(requestedUrls);
+ const urlValidationError = formatVisualMediaUrlValidationError(urlValidation);
+ if (urlValidationError) {
+ return {
+ error: {
+ message: urlValidationError,
+ type: 'InvalidToolArguments',
+ },
+ success: false,
+ };
+ }
+
+ const selectedUrls = createUrlVisualFileItems(urlValidation.validUrls);
+ let selectedRefs: VisualFileItem[] = [];
+
+ if (requestedRefs.length > 0) {
+ const [{ getChatStoreState }, { dbMessageSelectors }] = await Promise.all([
+ import('@/store/chat'),
+ import('@/store/chat/selectors'),
+ ]);
+
+ const chatState = getChatStoreState();
+ const sourceCandidate =
+ ctx.sourceMessageId && dbMessageSelectors.getDbMessageById(ctx.sourceMessageId)(chatState);
+ const toolMessage = dbMessageSelectors.getDbMessageById(ctx.messageId)(chatState);
+ const assistantMessage =
+ isVisualSourceMessage(toolMessage) &&
+ toolMessage.parentId &&
+ dbMessageSelectors.getDbMessageById(toolMessage.parentId)(chatState);
+ const parentUserMessage =
+ isVisualSourceMessage(assistantMessage) &&
+ assistantMessage.parentId &&
+ dbMessageSelectors.getDbMessageById(assistantMessage.parentId)(chatState);
+ const sourceMessage = hasUserVisualFiles(sourceCandidate)
+ ? sourceCandidate
+ : hasUserVisualFiles(parentUserMessage)
+ ? parentUserMessage
+ : dbMessageSelectors.latestUserMessage(chatState);
+ const activeVisualMessages = dbMessageSelectors
+ .activeDbMessages(chatState)
+ .filter(hasUserVisualFiles);
+ const visualMessages = [
+ ...(hasUserVisualFiles(sourceMessage) ? [sourceMessage] : []),
+ ...activeVisualMessages.filter((message) => message.id !== sourceMessage?.id),
+ ];
+ const files = visualMessages.flatMap((message) =>
+ createVisualFileItems(message, message.imageList, message.videoList),
+ );
+
+ if (files.length === 0) {
+ return {
+ error: {
+ message: 'No visual files are available in the current message',
+ type: 'VisualFilesNotFound',
+ },
+ success: false,
+ };
+ }
+
+ const selectableFiles = files;
+ const { invalidRefs, selected } = selectVisualFileItems(selectableFiles, requestedRefs);
+
+ if (invalidRefs?.length) {
+ const availableRefs = selectableFiles.map((file) => file.ref);
+
+ return {
+ content: `Unknown file refs: ${invalidRefs.join(', ')}. Available refs: ${availableRefs.join(', ')}`,
+ error: { message: 'Unknown visual file refs', type: 'InvalidToolArguments' },
+ state: { availableFiles: selectableFiles, invalidRefs },
+ success: false,
+ };
+ }
+
+ selectedRefs = selected;
+ }
+
+ const selectedItems = [...selectedRefs, ...selectedUrls];
+
+ if (selectedItems.length === 0) {
+ return {
+ error: { message: 'No visual files selected', type: 'InvalidToolArguments' },
+ success: false,
+ };
+ }
+
+ let content = '';
+ let error: { message?: string } | undefined;
+ let usage: unknown;
+ const abortController = createAbortController(ctx.signal);
+ const { chatService } = await import('@/services/chat');
+
+ const payload = {
+ max_tokens: 2000,
+ messages: [
+ {
+ content: buildAnalyzeVisualMediaContent(selectedItems, params.question, {
+ includeFallbackInstruction: true,
+ includeFileSummary: true,
+ }),
+ role: 'user' as const,
+ },
+ ],
+ model: config.model,
+ provider: config.provider,
+ stream: true,
+ } satisfies Partial<ChatStreamPayload>;
+
+ await chatService.getChatCompletion(payload, {
+ onFinish: async (output, metadata) => {
+ content = output || content;
+ usage = metadata.usage;
+ },
+ onErrorHandle: (err) => {
+ error = err;
+ },
+ onMessageHandle: (chunk) => {
+ if (chunk.type === 'text') content += chunk.text || '';
+ },
+ signal: abortController.signal,
+ });
+
+ if (abortController.signal.aborted) {
+ return { stop: true, success: false };
+ }
+
+ if (error) {
+ return {
+ error: {
+ body: error,
+ message: error.message ?? 'Visual understanding request failed',
+ type: 'PluginServerError',
+ },
+ success: false,
+ };
+ }
+
+ return {
+ content,
+ state: {
+ files: selectedItems,
+ model: config.model,
+ provider: config.provider,
+ trigger: 'lobe-agent.analyzeVisualMedia',
+ usage,
+ },
+ success: true,
+ };
+ };
+}
+
+export const lobeAgentExecutor = new LobeAgentExecutor();
diff --git a/packages/builtin-tool-lobe-agent/src/index.ts b/packages/builtin-tool-lobe-agent/src/index.ts
new file mode 100644
index 00000000000..9919d9c8377
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/index.ts
@@ -0,0 +1,4 @@
+export * from './manifest';
+export * from './systemRole';
+export * from './types';
+export * from './visualMedia';
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.test.ts b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
new file mode 100644
index 00000000000..d3080933972
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { LobeAgentManifest } from './manifest';
+
+describe('LobeAgentManifest', () => {
+ it('should keep the package metadata generic for future Lobe Agent capabilities', () => {
+ expect(LobeAgentManifest.meta.avatar).toBe('🤖');
+ expect(LobeAgentManifest.meta.description).toBe('Run built-in Lobe Agent capabilities.');
+ expect(LobeAgentManifest.meta.readme).toContain(
+ 'built-in assistant capabilities that can be expanded over time',
+ );
+ });
+
+ it('should describe visual analysis as a fallback tool', () => {
+ const apiDescription = LobeAgentManifest.api[0].description;
+
+ expect(apiDescription).toContain('native multimodal capability');
+ expect(apiDescription).toContain('use this tool only as a fallback');
+ expect(apiDescription).toContain('msg_xxx.image_1');
+ expect(apiDescription).toContain('Use only stable refs');
+ expect(apiDescription).toContain('answer the user directly with the result');
+ });
+});
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
new file mode 100644
index 00000000000..e8662a93f6e
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -0,0 +1,52 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { LobeAgentApiName, LobeAgentIdentifier } from './types';
+
+export const LobeAgentManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ "Analyze images or videos selected by visual file refs or direct media URLs and answer a visual question. Prefer the active model's native multimodal capability when it can inspect the visual media directly; use this tool only as a fallback when the active model cannot inspect the requested images or videos. Use only stable refs shown in <files_info>, such as msg_xxx.image_1 or msg_xxx.video_1. Pass refs for message attachments, or urls for direct media URLs that are not available as message refs. After this tool returns, answer the user directly with the result.",
+ name: LobeAgentApiName.analyzeVisualMedia,
+ parameters: {
+ additionalProperties: false,
+ anyOf: [{ required: ['refs'] }, { required: ['urls'] }],
+ properties: {
+ question: {
+ description: 'The visual question or task to answer.',
+ type: 'string',
+ },
+ refs: {
+ description:
+ 'Stable visual file ref strings to analyze, such as ["msg_xxx.image_1"] or ["msg_xxx.video_1"].',
+ items: {
+ type: 'string',
+ },
+ minItems: 1,
+ type: 'array',
+ },
+ urls: {
+ description: 'Direct image or video URLs to analyze when no message file ref exists.',
+ items: {
+ type: 'string',
+ },
+ minItems: 1,
+ type: 'array',
+ },
+ },
+ required: ['question'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: LobeAgentIdentifier,
+ meta: {
+ avatar: '🤖',
+ description: 'Run built-in Lobe Agent capabilities.',
+ readme: 'Lobe Agent provides built-in assistant capabilities that can be expanded over time.',
+ title: 'Lobe Agent',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.ts
new file mode 100644
index 00000000000..eccdfee451b
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts
@@ -0,0 +1 @@
+export const systemPrompt = `Use Lobe Agent capabilities only when the active model needs built-in assistance. Prefer the active model's native capabilities whenever they are sufficient. Follow each tool's description and schema, and use tool results to answer the user directly.`;
diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.ts
new file mode 100644
index 00000000000..e817334182c
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/types.ts
@@ -0,0 +1,13 @@
+export const LobeAgentIdentifier = 'lobe-agent';
+
+export const LobeAgentApiName = {
+ analyzeVisualMedia: 'analyzeVisualMedia',
+} as const;
+
+export type LobeAgentApiNameType = (typeof LobeAgentApiName)[keyof typeof LobeAgentApiName];
+
+export interface AnalyzeVisualMediaParams {
+ question: string;
+ refs?: string[];
+ urls?: string[];
+}
diff --git a/packages/builtin-tool-lobe-agent/src/visualMedia.test.ts b/packages/builtin-tool-lobe-agent/src/visualMedia.test.ts
new file mode 100644
index 00000000000..fc746977a72
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/visualMedia.test.ts
@@ -0,0 +1,190 @@
+import { createVisualFileRef } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildAnalyzeVisualMediaContent,
+ createUrlVisualFileItems,
+ createVisualFileItems,
+ filterAllowedVisualMediaUrls,
+ formatVisualMediaUrlValidationError,
+ hasUserVisualFiles,
+ MAX_VISUAL_MEDIA_URL_LENGTH,
+ MAX_VISUAL_MEDIA_URLS,
+ normalizeStringArray,
+ selectVisualFileItems,
+ validateVisualMediaUrls,
+} from './visualMedia';
+
+describe('visualMedia', () => {
+ it('should normalize string array tool arguments', () => {
+ expect(normalizeStringArray([' image_1 ', '', 42, 'video_1'])).toEqual(['image_1', 'video_1']);
+ expect(normalizeStringArray('image_1')).toEqual([]);
+ });
+
+ it('should allow only http, https and visual data urls', () => {
+ expect(
+ filterAllowedVisualMediaUrls([
+ 'https://example.com/image.png',
+ 'http://example.com/video.mp4',
+ 'data:image/png;base64,abcd',
+ 'data:video/mp4;base64,abcd',
+ 'data:text/plain;base64,abcd',
+ 'file:///private/image.png',
+ 'ftp://example.com/image.png',
+ 'not-a-url',
+ ]),
+ ).toEqual({
+ invalidUrls: [
+ 'data:text/plain;base64,abcd',
+ 'file:///private/image.png',
+ 'ftp://example.com/image.png',
+ 'not-a-url',
+ ],
+ validUrls: [
+ 'https://example.com/image.png',
+ 'http://example.com/video.mp4',
+ 'data:image/png;base64,abcd',
+ 'data:video/mp4;base64,abcd',
+ ],
+ });
+ });
+
+ it('should reject too many or oversized direct visual media urls', () => {
+ const urls = Array.from(
+ { length: MAX_VISUAL_MEDIA_URLS + 1 },
+ (_, index) => `https://example.com/image-${index}.png`,
+ );
+ const tooManyValidation = validateVisualMediaUrls(urls);
+
+ expect(tooManyValidation.tooManyUrls).toBe(true);
+ expect(formatVisualMediaUrlValidationError(tooManyValidation)).toContain(
+ `At most ${MAX_VISUAL_MEDIA_URLS} URLs are supported`,
+ );
+
+ const oversizedUrl = `data:image/png;base64,${'a'.repeat(MAX_VISUAL_MEDIA_URL_LENGTH)}`;
+ const oversizedValidation = validateVisualMediaUrls([oversizedUrl]);
+
+ expect(oversizedValidation.oversizedUrls).toEqual([oversizedUrl]);
+ expect(formatVisualMediaUrlValidationError(oversizedValidation)).toContain(
+ `${MAX_VISUAL_MEDIA_URL_LENGTH} character limit`,
+ );
+ });
+
+ it('should create visual file refs for message attachments', () => {
+ const items = createVisualFileItems(
+ { id: 'msg-1' },
+ [{ alt: 'image.png', id: 'file-image', url: 'https://example.com/image.png' }],
+ [{ alt: 'video.mp4', id: 'file-video', url: 'https://example.com/video.mp4' }],
+ );
+
+ expect(items).toEqual([
+ {
+ description: 'image.png',
+ id: 'file-image',
+ localRef: 'image_1',
+ messageId: 'msg-1',
+ name: 'image.png',
+ ref: createVisualFileRef({ index: 0, messageId: 'msg-1', type: 'image' }),
+ type: 'image',
+ uri: 'https://example.com/image.png',
+ },
+ {
+ description: 'video.mp4',
+ id: 'file-video',
+ localRef: 'video_1',
+ messageId: 'msg-1',
+ name: 'video.mp4',
+ ref: createVisualFileRef({ index: 0, messageId: 'msg-1', type: 'video' }),
+ type: 'video',
+ uri: 'https://example.com/video.mp4',
+ },
+ ]);
+ });
+
+ it('should infer URL item type and name from direct media urls', () => {
+ expect(
+ createUrlVisualFileItems([
+ 'https://example.com/path/generated.png',
+ 'https://example.com/video.webm?download=1',
+ 'data:video/mp4;base64,abcd',
+ ]),
+ ).toMatchObject([
+ { name: 'generated.png', ref: 'url_1', type: 'image' },
+ { name: 'video.webm', ref: 'url_2', type: 'video' },
+ { name: 'URL 3', ref: 'url_3', type: 'video' },
+ ]);
+ });
+
+ it('should build shared visual media model content', () => {
+ const content = buildAnalyzeVisualMediaContent(
+ [
+ {
+ description: 'generated.png',
+ localRef: 'url_1',
+ name: 'generated.png',
+ ref: 'url_1',
+ type: 'image',
+ uri: 'https://example.com/generated.png',
+ },
+ ],
+ 'what is this?',
+ { includeFallbackInstruction: true, includeFileSummary: true },
+ );
+
+ expect(content).toEqual([
+ expect.objectContaining({
+ text: expect.stringContaining('Files:\n- url_1: generated.png (image)'),
+ type: 'text',
+ }),
+ {
+ image_url: { detail: 'auto', url: 'https://example.com/generated.png' },
+ type: 'image_url',
+ },
+ ]);
+ });
+
+ it('should select only stable refs from visual messages', () => {
+ const currentItems = createVisualFileItems({ id: 'msg-current' }, [
+ { alt: 'current.png', id: 'file-current', url: 'https://example.com/current.png' },
+ ]);
+ const previousItems = createVisualFileItems({ id: 'msg-previous' }, [
+ { alt: 'previous.png', id: 'file-previous', url: 'https://example.com/previous.png' },
+ ]);
+ const previousStableRef = createVisualFileRef({
+ index: 0,
+ messageId: 'msg-previous',
+ type: 'image',
+ });
+ const currentStableRef = createVisualFileRef({
+ index: 0,
+ messageId: 'msg-current',
+ type: 'image',
+ });
+
+ expect(
+ selectVisualFileItems(
+ [...currentItems, ...previousItems],
+ [currentStableRef, previousStableRef, 'image_1', 'missing'],
+ ),
+ ).toMatchObject({
+ availableRefs: [currentStableRef, previousStableRef],
+ invalidRefs: ['image_1', 'missing'],
+ selected: [currentItems[0], previousItems[0]],
+ });
+ });
+
+ it('should only treat user messages with visual attachments as user visual files', () => {
+ expect(
+ hasUserVisualFiles({
+ imageList: [{ id: 'file-image', url: 'https://example.com/image.png' }],
+ role: 'user',
+ }),
+ ).toBe(true);
+ expect(
+ hasUserVisualFiles({
+ imageList: [{ id: 'file-image', url: 'https://example.com/image.png' }],
+ role: 'assistant',
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/builtin-tool-lobe-agent/src/visualMedia.ts b/packages/builtin-tool-lobe-agent/src/visualMedia.ts
new file mode 100644
index 00000000000..398da17d914
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/src/visualMedia.ts
@@ -0,0 +1,278 @@
+import type { ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import { createVisualFileRef, createVisualLocalRef } from '@lobechat/types';
+
+export interface VisualFileItem {
+ description: string;
+ id?: string;
+ localRef: string;
+ messageId?: string;
+ name: string;
+ ref: string;
+ type: 'image' | 'video';
+ uri: string;
+}
+
+export interface VisualSourceMessage {
+ id?: string;
+ imageList?: ChatImageItem[];
+ role?: string;
+ videoList?: ChatVideoItem[];
+}
+
+const VIDEO_URL_PATTERN = /\.(?:mp4|m4v|mov|webm|mpeg|mpg|avi|mkv)(?:[?#]|$)/i;
+const VISUAL_DATA_URL_PATTERN = /^data:(?:image|video)\//i;
+const ALLOWED_REMOTE_VISUAL_MEDIA_URL_PROTOCOLS = new Set(['http:', 'https:']);
+const ANALYZE_VISUAL_MEDIA_ARGUMENT_KEYS = new Set(['question', 'refs', 'urls']);
+
+export const MAX_VISUAL_MEDIA_URLS = 8;
+export const MAX_VISUAL_MEDIA_URL_LENGTH = 2_000_000;
+
+export interface AnalyzeVisualMediaContentOptions {
+ includeFallbackInstruction?: boolean;
+ includeFileSummary?: boolean;
+}
+
+export interface AnalyzeVisualMediaNormalizedInput {
+ requestedRefs: string[];
+ requestedUrls: string[];
+}
+
+export interface VisualMediaUrlValidationResult {
+ invalidUrls: string[];
+ oversizedUrls: string[];
+ tooManyUrls: boolean;
+ totalUrls: number;
+ validUrls: string[];
+}
+
+export const normalizeStringArray = (value: unknown) =>
+ Array.isArray(value)
+ ? value
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
+ .filter((item) => item.length > 0)
+ : [];
+
+export const normalizeAnalyzeVisualMediaInput = (
+ params: Record<PropertyKey, unknown>,
+): AnalyzeVisualMediaNormalizedInput => ({
+ requestedRefs: normalizeStringArray(params.refs),
+ requestedUrls: normalizeStringArray(params.urls),
+});
+
+export const getUnexpectedAnalyzeVisualMediaArgumentKeys = (params: Record<PropertyKey, unknown>) =>
+ Object.keys(params).filter((key) => !ANALYZE_VISUAL_MEDIA_ARGUMENT_KEYS.has(key));
+
+export const isAllowedVisualMediaUrl = (url: string) => {
+ try {
+ const parsed = new URL(url);
+
+ if (ALLOWED_REMOTE_VISUAL_MEDIA_URL_PROTOCOLS.has(parsed.protocol)) return true;
+
+ return parsed.protocol === 'data:' && VISUAL_DATA_URL_PATTERN.test(url);
+ } catch {
+ return false;
+ }
+};
+
+export const validateVisualMediaUrls = (urls: string[]): VisualMediaUrlValidationResult => {
+ const validUrls: string[] = [];
+ const invalidUrls: string[] = [];
+ const oversizedUrls: string[] = [];
+
+ for (const url of urls.slice(0, MAX_VISUAL_MEDIA_URLS)) {
+ if (url.length > MAX_VISUAL_MEDIA_URL_LENGTH) {
+ oversizedUrls.push(url);
+ continue;
+ }
+
+ if (isAllowedVisualMediaUrl(url)) {
+ validUrls.push(url);
+ } else {
+ invalidUrls.push(url);
+ }
+ }
+
+ return {
+ invalidUrls,
+ oversizedUrls,
+ tooManyUrls: urls.length > MAX_VISUAL_MEDIA_URLS,
+ totalUrls: urls.length,
+ validUrls,
+ };
+};
+
+export const filterAllowedVisualMediaUrls = (urls: string[]) => {
+ const { invalidUrls, validUrls } = validateVisualMediaUrls(urls);
+
+ return { invalidUrls, validUrls };
+};
+
+const formatVisualMediaUrlForError = (url: string) => {
+ const value = url.startsWith('data:') ? `${url.split(',')[0]},...` : url;
+
+ return value.length > 120 ? `${value.slice(0, 117)}...` : value;
+};
+
+export const formatVisualMediaUrlValidationError = (validation: VisualMediaUrlValidationResult) => {
+ const messages: string[] = [];
+
+ if (validation.tooManyUrls) {
+ messages.push(
+ `Too many visual media URLs: ${validation.totalUrls}. At most ${MAX_VISUAL_MEDIA_URLS} URLs are supported.`,
+ );
+ }
+
+ if (validation.oversizedUrls.length > 0) {
+ messages.push(
+ `Visual media URLs exceed the ${MAX_VISUAL_MEDIA_URL_LENGTH} character limit: ${validation.oversizedUrls
+ .map(formatVisualMediaUrlForError)
+ .join(', ')}.`,
+ );
+ }
+
+ if (validation.invalidUrls.length > 0) {
+ messages.push(
+ `Unsupported visual media URLs: ${validation.invalidUrls
+ .map(formatVisualMediaUrlForError)
+ .join(', ')}.`,
+ );
+ }
+
+ if (messages.length === 0) return;
+
+ return `${messages.join(' ')} Only http:, https:, data:image/* and data:video/* URLs are supported.`;
+};
+
+export const hasVisualFiles = (message: unknown): message is VisualSourceMessage =>
+ !!message &&
+ typeof message === 'object' &&
+ (((message as VisualSourceMessage).imageList?.length ?? 0) > 0 ||
+ ((message as VisualSourceMessage).videoList?.length ?? 0) > 0);
+
+export const hasUserVisualFiles = (message: unknown): message is VisualSourceMessage =>
+ !!message &&
+ typeof message === 'object' &&
+ (message as VisualSourceMessage).role === 'user' &&
+ hasVisualFiles(message);
+
+export const createVisualFileItems = (
+ message: VisualSourceMessage | undefined,
+ images: ChatImageItem[] = [],
+ videos: ChatVideoItem[] = [],
+): VisualFileItem[] => [
+ ...images.map((image, index) => {
+ const name = image.alt || image.id || `Image ${index + 1}`;
+
+ return {
+ description: image.alt || `Image ${index + 1}`,
+ id: image.id,
+ localRef: createVisualLocalRef('image', index),
+ messageId: message?.id,
+ name,
+ ref: createVisualFileRef({ index, messageId: message?.id, type: 'image' }),
+ type: 'image' as const,
+ uri: image.url,
+ };
+ }),
+ ...videos.map((video, index) => {
+ const name = video.alt || video.id || `Video ${index + 1}`;
+
+ return {
+ description: video.alt || `Video ${index + 1}`,
+ id: video.id,
+ localRef: createVisualLocalRef('video', index),
+ messageId: message?.id,
+ name,
+ ref: createVisualFileRef({ index, messageId: message?.id, type: 'video' }),
+ type: 'video' as const,
+ uri: video.url,
+ };
+ }),
+];
+
+export const inferVisualTypeFromUrl = (url: string): VisualFileItem['type'] => {
+ if (/^data:video\//i.test(url)) return 'video';
+ if (/^data:image\//i.test(url)) return 'image';
+
+ return VIDEO_URL_PATTERN.test(url) ? 'video' : 'image';
+};
+
+export const getVisualUrlName = (url: string, index: number) => {
+ try {
+ const parsed = new URL(url);
+
+ if (parsed.protocol === 'data:') return `URL ${index + 1}`;
+
+ return parsed.pathname.split('/').findLast(Boolean) || `URL ${index + 1}`;
+ } catch {
+ return `URL ${index + 1}`;
+ }
+};
+
+export const createUrlVisualFileItems = (urls: string[]): VisualFileItem[] =>
+ urls.map((url, index) => {
+ const type = inferVisualTypeFromUrl(url);
+ const name = getVisualUrlName(url, index);
+
+ return {
+ description: name,
+ localRef: `url_${index + 1}`,
+ name,
+ ref: `url_${index + 1}`,
+ type,
+ uri: url,
+ };
+ });
+
+export const selectVisualFileItems = (items: VisualFileItem[], refs?: string[]) => {
+ if (!refs || refs.length === 0) return { availableRefs: [], invalidRefs: [], selected: [] };
+
+ const findItem = (ref: string) => items.find((item) => item.ref === ref);
+ const selected = refs
+ .map((ref) => findItem(ref))
+ .filter((item): item is VisualFileItem => !!item);
+ const invalidRefs = refs.filter((ref) => !findItem(ref));
+ const availableRefs = items.map((item) => item.ref);
+
+ return { availableRefs, invalidRefs, selected };
+};
+
+export const buildAnalyzeVisualMediaContent = (
+ items: VisualFileItem[],
+ question: string,
+ options: AnalyzeVisualMediaContentOptions = {},
+) => {
+ const textLines = ['Analyze the attached visual media and answer the user question.'];
+
+ if (options.includeFallbackInstruction) {
+ textLines.push('Do not mention that you are a fallback tool unless it is relevant.');
+ }
+
+ if (options.includeFileSummary) {
+ textLines.push(
+ '',
+ 'Files:',
+ items.map((file) => `- ${file.ref}: ${file.name} (${file.type})`).join('\n'),
+ );
+ }
+
+ textLines.push('', `Question: ${question}`);
+
+ return [
+ {
+ text: textLines.join('\n'),
+ type: 'text' as const,
+ },
+ ...items.map((file) =>
+ file.type === 'image'
+ ? {
+ image_url: { detail: 'auto' as const, url: file.uri },
+ type: 'image_url' as const,
+ }
+ : {
+ type: 'video_url' as const,
+ video_url: { url: file.uri },
+ },
+ ),
+ ];
+};
diff --git a/packages/builtin-tool-lobe-agent/vitest.config.mts b/packages/builtin-tool-lobe-agent/vitest.config.mts
new file mode 100644
index 00000000000..52f86e133c7
--- /dev/null
+++ b/packages/builtin-tool-lobe-agent/vitest.config.mts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index b97f6fb1e1a..905c8cd885f 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -31,6 +31,7 @@
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
"@lobechat/builtin-tool-knowledge-base": "workspace:*",
+ "@lobechat/builtin-tool-lobe-agent": "workspace:*",
"@lobechat/builtin-tool-local-system": "workspace:*",
"@lobechat/builtin-tool-memory": "workspace:*",
"@lobechat/builtin-tool-message": "workspace:*",
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index 587f8178327..963d394e814 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -10,6 +10,7 @@ import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-bu
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { NotebookManifest } from '@lobechat/builtin-tool-notebook';
@@ -43,5 +44,6 @@ export const builtinToolIdentifiers: string[] = [
LobeActivatorManifest.identifier,
WebBrowsingManifest.identifier,
UserInteractionManifest.identifier,
+ LobeAgentManifest.identifier,
WebOnboardingManifest.identifier,
];
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index c1f6b5fccb1..bb66947e511 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -12,6 +12,7 @@ import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-bu
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { MessageManifest } from '@lobechat/builtin-tool-message';
@@ -45,6 +46,7 @@ export const defaultToolIds = [
AgentDocumentsManifest.identifier,
GTDManifest.identifier,
TaskManifest.identifier,
+ LobeAgentManifest.identifier,
];
/**
@@ -87,6 +89,7 @@ export const runtimeManagedToolIds = [
LocalSystemManifest.identifier,
MemoryManifest.identifier,
RemoteDeviceManifest.identifier,
+ LobeAgentManifest.identifier,
WebBrowsingManifest.identifier,
];
@@ -261,6 +264,12 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: BriefManifest,
type: 'builtin',
},
+ {
+ hidden: true,
+ identifier: LobeAgentManifest.identifier,
+ manifest: LobeAgentManifest,
+ type: 'builtin',
+ },
];
const recommendedBuiltinIds = new Set(
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index aa9d179ff59..44b41bf7094 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -438,7 +438,7 @@ export class MessagesEngine {
new ReactionFeedbackProcessor({ enabled: true }),
// Message content processing (image encoding, multimodal)
new MessageContentProcessor({
- fileContext: fileContext || { enabled: true, includeFileUrl: true },
+ fileContext: fileContext || { enabled: true, includeFileUrl: false },
isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
isCanUseVision: capabilities?.isCanUseVision || (() => true),
model,
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index 6ded4fe4504..c347e8dfb66 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -389,7 +389,7 @@ describe('MessagesEngine', () => {
expect(result).toBeDefined();
});
- it('should default to enabled with includeFileUrl true', async () => {
+ it('should default to enabled without file URLs', async () => {
const params = createBasicParams();
const engine = new MessagesEngine(params);
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index f379c923274..074c0af08e4 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -212,9 +212,13 @@ export class MessageContentProcessor extends BaseProcessor {
// Add file context (if file context is enabled and has files, images or videos)
if ((hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled) {
const filesContext = filesPrompts({
- addUrl: this.config.fileContext.includeFileUrl ?? true,
+ // Signed file URLs are volatile and can break provider-side prefix cache reuse.
+ // Keep file refs stable by default; structured multimodal parts still carry
+ // the fetchable URL when the target model supports the media type.
+ addUrl: this.config.fileContext.includeFileUrl ?? false,
fileList: message.fileList,
imageList: message.imageList || [],
+ messageId: message.id,
videoList: message.videoList || [],
});
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 9a229b34b98..bc5a3d73fd1 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -357,6 +357,12 @@ describe('MessageContentProcessor', () => {
expect(content[0].type).toBe('text');
expect(content[0].text).toContain('SYSTEM CONTEXT');
expect(content[0].text).toContain('Hello');
+ expect(content[0].text).toContain('<image ref="msg_1cs5ql.image_1" name="test.png"></image>');
+ expect(content[0].text).toContain(
+ '<file id="file1" name="test.txt" type="text/plain" size="100"></file>',
+ );
+ expect(content[0].text).not.toContain('http://example.com/image.jpg');
+ expect(content[0].text).not.toContain('http://example.com/test.txt');
});
it('should not add file context when disabled', async () => {
diff --git a/packages/conversation-flow/src/parse.ts b/packages/conversation-flow/src/parse.ts
index c2fcaa96cc5..69136fc0540 100644
--- a/packages/conversation-flow/src/parse.ts
+++ b/packages/conversation-flow/src/parse.ts
@@ -63,6 +63,7 @@ export function parse(messages: Message[], messageGroups?: MessageGroupMetadata[
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputVideoTokens',
'inputToolTokens',
'inputWriteCacheTokens',
'latency',
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 12e901cb0f8..8798a248202 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -805,6 +805,7 @@ export class FlatListBuilder {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputVideoTokens',
'inputToolTokens',
'inputWriteCacheTokens',
'latency',
@@ -951,6 +952,7 @@ export class FlatListBuilder {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputVideoTokens',
'inputToolTokens',
'inputWriteCacheTokens',
'latency',
diff --git a/packages/conversation-flow/src/transformation/MessageTransformer.ts b/packages/conversation-flow/src/transformation/MessageTransformer.ts
index 84f5cc12b5f..12cb456e700 100644
--- a/packages/conversation-flow/src/transformation/MessageTransformer.ts
+++ b/packages/conversation-flow/src/transformation/MessageTransformer.ts
@@ -61,6 +61,7 @@ export class MessageTransformer {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputVideoTokens',
'inputToolTokens',
'inputWriteCacheTokens',
'outputAudioTokens',
@@ -122,6 +123,7 @@ export class MessageTransformer {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputVideoTokens',
'inputToolTokens',
'inputWriteCacheTokens',
'outputAudioTokens',
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 5114cb8f199..9945566f254 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -229,6 +229,7 @@ export class MessageModel {
createdAt: messages.createdAt,
updatedAt: messages.updatedAt,
+ sessionId: messages.sessionId,
topicId: messages.topicId,
parentId: messages.parentId,
threadId: messages.threadId,
@@ -568,6 +569,7 @@ export class MessageModel {
createdAt: messages.createdAt,
updatedAt: messages.updatedAt,
+ sessionId: messages.sessionId,
topicId: messages.topicId,
parentId: messages.parentId,
threadId: messages.threadId,
diff --git a/packages/model-bank/src/aiModels/google.ts b/packages/model-bank/src/aiModels/google.ts
index d5ddf028b9f..2dde1bd79ac 100644
--- a/packages/model-bank/src/aiModels/google.ts
+++ b/packages/model-bank/src/aiModels/google.ts
@@ -131,8 +131,9 @@ const googleChatModels: AIChatModelCard[] = [
approximatePricePerImage: 0.067,
units: [
{ name: 'imageOutput', rate: 60, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
],
},
releasedAt: '2026-02-26',
@@ -179,6 +180,33 @@ const googleChatModels: AIChatModelCard[] = [
],
unit: 'millionTokens',
},
+ {
+ name: 'imageInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'videoInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'audioInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
{
name: 'textOutput',
strategy: 'tiered',
@@ -224,6 +252,9 @@ const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.025, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -254,6 +285,9 @@ const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.05, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
{
lookup: { prices: { '1h': 1 }, pricingParams: ['ttl'] },
@@ -290,6 +324,7 @@ const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'imageOutput', rate: 120, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -335,6 +370,33 @@ const googleChatModels: AIChatModelCard[] = [
],
unit: 'millionTokens',
},
+ {
+ name: 'imageInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'videoInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'audioInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
{
name: 'textOutput',
strategy: 'tiered',
@@ -377,6 +439,9 @@ const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.075, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
diff --git a/packages/model-bank/src/aiModels/lobehub/chat/google.ts b/packages/model-bank/src/aiModels/lobehub/chat/google.ts
index 9003577bdf4..72ef6537097 100644
--- a/packages/model-bank/src/aiModels/lobehub/chat/google.ts
+++ b/packages/model-bank/src/aiModels/lobehub/chat/google.ts
@@ -37,6 +37,33 @@ export const googleChatModels: AIChatModelCard[] = [
],
unit: 'millionTokens',
},
+ {
+ name: 'imageInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'videoInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'audioInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
{
name: 'textOutput',
strategy: 'tiered',
@@ -85,6 +112,9 @@ export const googleChatModels: AIChatModelCard[] = [
strategy: 'fixed',
unit: 'millionTokens',
},
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{
name: 'textInput_cacheRead',
rate: 0.05,
@@ -122,6 +152,9 @@ export const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.025, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -167,6 +200,33 @@ export const googleChatModels: AIChatModelCard[] = [
],
unit: 'millionTokens',
},
+ {
+ name: 'imageInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'videoInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'audioInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1.25, upTo: 200_000 },
+ { rate: 2.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
{
name: 'textOutput',
strategy: 'tiered',
@@ -212,6 +272,9 @@ export const googleChatModels: AIChatModelCard[] = [
strategy: 'fixed',
unit: 'millionTokens',
},
+ { name: 'imageInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -241,8 +304,9 @@ export const googleChatModels: AIChatModelCard[] = [
approximatePricePerImage: 0.067,
units: [
{ name: 'imageOutput', rate: 60, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
],
},
releasedAt: '2026-02-26',
@@ -271,6 +335,7 @@ export const googleChatModels: AIChatModelCard[] = [
units: [
{ name: 'imageOutput', rate: 120, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },
],
},
diff --git a/packages/model-bank/src/aiModels/vertexai.ts b/packages/model-bank/src/aiModels/vertexai.ts
index ebc734b69bf..b66165ad90d 100644
--- a/packages/model-bank/src/aiModels/vertexai.ts
+++ b/packages/model-bank/src/aiModels/vertexai.ts
@@ -21,8 +21,9 @@ const vertexaiChatModels: AIChatModelCard[] = [
approximatePricePerImage: 0.067,
units: [
{ name: 'imageOutput', rate: 60, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
],
},
releasedAt: '2026-02-26',
@@ -69,6 +70,33 @@ const vertexaiChatModels: AIChatModelCard[] = [
],
unit: 'millionTokens',
},
+ {
+ name: 'imageInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'videoInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'audioInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2, upTo: 200_000 },
+ { rate: 4, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
{
name: 'textOutput',
strategy: 'tiered',
@@ -114,6 +142,9 @@ const vertexaiChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.025, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -203,6 +234,9 @@ const vertexaiChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.05, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
{
lookup: { prices: { '1h': 1 }, pricingParams: ['ttl'] },
@@ -239,6 +273,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
units: [
{ name: 'imageOutput', rate: 120, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -267,6 +302,9 @@ const vertexaiChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.31, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
],
},
@@ -336,6 +374,9 @@ const vertexaiChatModels: AIChatModelCard[] = [
units: [
{ name: 'textInput_cacheRead', rate: 0.075, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
{ name: 'textOutput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },
],
},
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index ee8424d82a9..74d8803034b 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -147,6 +147,7 @@ export type PricingUnitName =
| 'imageOutput'
// Video-based pricing units
+ | 'videoInput'
| 'videoGeneration';
export type PricingUnitType =
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 2de60d6086f..ace3c4961d9 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -567,7 +567,7 @@ describe('GoogleGenerativeAIStream', () => {
// usage
'id: chat_1\n',
'event: usage\n',
- `data: {"inputCacheMissTokens":1439,"inputCachedTokens":14286,"inputTextTokens":15725,"outputImageTokens":0,"outputTextTokens":1053,"totalInputTokens":15725,"totalOutputTokens":1053,"totalTokens":16778}\n\n`,
+ `data: {"inputCachedTextTokens":14286,"inputCacheMissTokens":1439,"inputCachedTokens":14286,"inputTextTokens":15725,"outputImageTokens":0,"outputTextTokens":1053,"totalInputTokens":15725,"totalOutputTokens":1053,"totalTokens":16778}\n\n`,
]);
});
diff --git a/packages/model-runtime/src/core/usageConverters/google-ai.test.ts b/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
index 446a88075de..22399ca27be 100644
--- a/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
@@ -14,10 +14,15 @@ describe('convertGoogleAIUsage', () => {
{ modality: MediaModality.TEXT, tokenCount: 30 },
{ modality: MediaModality.IMAGE, tokenCount: 10 },
],
+ cacheTokensDetails: [
+ { modality: MediaModality.TEXT, tokenCount: 4 },
+ { modality: MediaModality.VIDEO, tokenCount: 2 },
+ ],
promptTokenCount: 70,
promptTokensDetails: [
{ modality: MediaModality.TEXT, tokenCount: 60 },
{ modality: MediaModality.IMAGE, tokenCount: 5 },
+ { modality: MediaModality.VIDEO, tokenCount: 4 },
],
thoughtsTokenCount: 12,
totalTokenCount: 122,
@@ -27,10 +32,15 @@ describe('convertGoogleAIUsage', () => {
expect(result).toEqual({
inputAudioTokens: undefined,
+ inputCachedAudioTokens: undefined,
+ inputCachedImageTokens: undefined,
+ inputCachedTextTokens: 4,
inputCacheMissTokens: 64,
inputCachedTokens: 6,
+ inputCachedVideoTokens: 2,
inputImageTokens: 5,
inputTextTokens: 60,
+ inputVideoTokens: 4,
outputImageTokens: 10,
outputReasoningTokens: 12,
outputTextTokens: 30,
@@ -55,10 +65,15 @@ describe('convertGoogleAIUsage', () => {
expect(result).toEqual({
inputAudioTokens: undefined,
+ inputCachedAudioTokens: undefined,
+ inputCachedImageTokens: undefined,
+ inputCachedTextTokens: undefined,
inputCacheMissTokens: undefined,
inputCachedTokens: undefined,
+ inputCachedVideoTokens: undefined,
inputImageTokens: 3,
inputTextTokens: undefined,
+ inputVideoTokens: undefined,
outputImageTokens: 15,
outputReasoningTokens: 5,
outputTextTokens: 40,
@@ -99,15 +114,20 @@ describe('convertGoogleAIUsage', () => {
expect(result).toEqual({
inputAudioTokens: undefined,
+ inputCachedAudioTokens: undefined,
+ inputCachedImageTokens: undefined,
+ inputCachedTextTokens: undefined,
inputCacheMissTokens: undefined,
inputCachedTokens: undefined,
+ inputCachedVideoTokens: undefined,
inputImageTokens: undefined,
inputTextTokens: undefined,
inputToolTokens: 7596,
+ inputVideoTokens: undefined,
outputImageTokens: 0,
outputReasoningTokens: undefined,
outputTextTokens: 367,
- totalInputTokens: 7646, // promptTokenCount (50) + toolUsePromptTokenCount (7596)
+ totalInputTokens: 7646, // promptTokenCount (50) + toolUsePromptTokenCount (7596)
totalOutputTokens: 367,
totalTokens: 8013,
});
diff --git a/packages/model-runtime/src/core/usageConverters/google-ai.ts b/packages/model-runtime/src/core/usageConverters/google-ai.ts
index 9f3f088263d..26564715489 100644
--- a/packages/model-runtime/src/core/usageConverters/google-ai.ts
+++ b/packages/model-runtime/src/core/usageConverters/google-ai.ts
@@ -38,11 +38,16 @@ export const convertGoogleAIUsage = (
const normalizedUsage = {
inputAudioTokens: getTokenCount(usage.promptTokensDetails, MediaModality.AUDIO),
+ inputCachedAudioTokens: getTokenCount(usage.cacheTokensDetails, MediaModality.AUDIO),
+ inputCachedImageTokens: getTokenCount(usage.cacheTokensDetails, MediaModality.IMAGE),
+ inputCachedTextTokens: getTokenCount(usage.cacheTokensDetails, MediaModality.TEXT),
inputCacheMissTokens,
inputCachedTokens: usage.cachedContentTokenCount,
+ inputCachedVideoTokens: getTokenCount(usage.cacheTokensDetails, MediaModality.VIDEO),
inputImageTokens: getTokenCount(usage.promptTokensDetails, MediaModality.IMAGE),
inputTextTokens: getTokenCount(usage.promptTokensDetails, MediaModality.TEXT),
inputToolTokens: toolUseTokens,
+ inputVideoTokens: getTokenCount(usage.promptTokensDetails, MediaModality.VIDEO),
outputImageTokens,
outputReasoningTokens: reasoningTokens,
outputTextTokens,
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index 72a24b9f768..5dd3da9c93a 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -3,6 +3,7 @@ import type { Pricing } from 'model-bank';
import anthropicChatModels from 'model-bank/anthropic';
import azureChatModels from 'model-bank/azure';
import googleChatModels from 'model-bank/google';
+import { lobehubChatModels } from 'model-bank/lobehub';
import openaiChatModels from 'model-bank/openai';
import { describe, expect, it } from 'vitest';
@@ -207,6 +208,208 @@ describe('computeChatPricing', () => {
expect(imageOutput?.credits).toBe(12_000);
});
+ it('charges Gemini 3.1 Flash-Lite image, video, and audio input tokens', () => {
+ const pricing = googleChatModels.find(
+ (model: { id: string }) => model.id === 'gemini-3.1-flash-lite-preview',
+ )?.pricing;
+ expect(pricing).toBeDefined();
+
+ const usage: ModelTokensUsage = {
+ inputAudioTokens: 443,
+ inputImageTokens: 1104,
+ inputTextTokens: 123,
+ inputVideoTokens: 1188,
+ outputTextTokens: 346,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+ expect(result?.totalCredits).toBe(1345);
+ expect(result?.totalCost).toBeCloseTo(0.001345, 6);
+
+ const { breakdown } = result!;
+ expect(breakdown).toHaveLength(5);
+
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.credits).toBe(31);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')?.credits).toBe(276);
+ expect(breakdown.find((item) => item.unit.name === 'videoInput')?.credits).toBe(297);
+ expect(breakdown.find((item) => item.unit.name === 'audioInput')?.credits).toBe(222);
+ expect(breakdown.find((item) => item.unit.name === 'textOutput')?.credits).toBe(519);
+ });
+
+ it('charges multimodal input units for LobeHub-hosted Gemini 3 Flash', () => {
+ const pricing = lobehubChatModels.find(
+ (model: { id: string }) => model.id === 'gemini-3-flash-preview',
+ )?.pricing;
+ expect(pricing).toBeDefined();
+
+ const usage: ModelTokensUsage = {
+ inputAudioTokens: 400,
+ inputImageTokens: 200,
+ inputTextTokens: 100,
+ inputVideoTokens: 300,
+ outputTextTokens: 10,
+ totalInputTokens: 1000,
+ totalOutputTokens: 10,
+ totalTokens: 1010,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+ expect(result?.totalCredits).toBe(730);
+
+ const { breakdown } = result!;
+ expect(breakdown).toHaveLength(5);
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.credits).toBe(50);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')?.credits).toBe(100);
+ expect(breakdown.find((item) => item.unit.name === 'videoInput')?.credits).toBe(150);
+ expect(breakdown.find((item) => item.unit.name === 'audioInput')?.credits).toBe(400);
+ expect(breakdown.find((item) => item.unit.name === 'textOutput')?.credits).toBe(30);
+ });
+
+ it('charges multimodal input units for LobeHub-hosted tiered Gemini Pro', () => {
+ const pricing = lobehubChatModels.find(
+ (model: { id: string }) => model.id === 'gemini-2.5-pro',
+ )?.pricing;
+ expect(pricing).toBeDefined();
+
+ const usage: ModelTokensUsage = {
+ inputAudioTokens: 400,
+ inputImageTokens: 200,
+ inputTextTokens: 100,
+ inputVideoTokens: 300,
+ outputTextTokens: 10,
+ totalInputTokens: 1000,
+ totalOutputTokens: 10,
+ totalTokens: 1010,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+ expect(result?.totalCredits).toBe(1350);
+
+ const { breakdown } = result!;
+ expect(breakdown).toHaveLength(5);
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.credits).toBe(125);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')?.credits).toBe(250);
+ expect(breakdown.find((item) => item.unit.name === 'videoInput')?.credits).toBe(375);
+ expect(breakdown.find((item) => item.unit.name === 'audioInput')?.credits).toBe(500);
+ expect(breakdown.find((item) => item.unit.name === 'textOutput')?.credits).toBe(100);
+ });
+
+ it('bills Google cache reads with cached modality details without double counting', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput_cacheRead', rate: 0.2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const usage: ModelTokensUsage = {
+ inputCacheMissTokens: 40,
+ inputCachedTokens: 60,
+ inputCachedTextTokens: 50,
+ inputCachedVideoTokens: 10,
+ inputTextTokens: 80,
+ inputVideoTokens: 20,
+ outputTextTokens: 10,
+ totalInputTokens: 100,
+ totalOutputTokens: 10,
+ totalTokens: 110,
+ };
+
+ const result = computeChatCost(pricing, usage);
+
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+
+ const { breakdown, totalCredits } = result!;
+ expect(breakdown.find((item) => item.unit.name === 'textInput_cacheRead')?.quantity).toBe(60);
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(30);
+ expect(breakdown.find((item) => item.unit.name === 'videoInput')?.quantity).toBe(10);
+ expect(totalCredits).toBe(232);
+ });
+
+ it('splits cache reads by modality when dedicated modality cache units exist', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput_cacheRead', rate: 0.2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput_cacheRead', rate: 0.4, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput_cacheRead', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 32, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const usage: ModelTokensUsage = {
+ inputAudioTokens: 40,
+ inputCachedAudioTokens: 30,
+ inputCachedImageTokens: 10,
+ inputCachedTextTokens: 50,
+ inputCachedTokens: 90,
+ inputImageTokens: 20,
+ inputTextTokens: 80,
+ outputTextTokens: 10,
+ totalInputTokens: 140,
+ totalOutputTokens: 10,
+ totalTokens: 150,
+ };
+
+ const result = computeChatCost(pricing, usage);
+
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+
+ const { breakdown, totalCredits } = result!;
+ expect(breakdown.find((item) => item.unit.name === 'textInput_cacheRead')?.quantity).toBe(50);
+ expect(breakdown.find((item) => item.unit.name === 'audioInput_cacheRead')?.quantity).toBe(
+ 30,
+ );
+ expect(breakdown.find((item) => item.unit.name === 'imageInput_cacheRead')?.quantity).toBe(
+ 10,
+ );
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(30);
+ expect(breakdown.find((item) => item.unit.name === 'audioInput')?.quantity).toBe(10);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')?.quantity).toBe(10);
+ expect(totalCredits).toBe(577);
+ });
+
+ it('charges image input at the official Gemini 3.1 Flash Image rate', () => {
+ const pricing = lobehubChatModels.find(
+ (model: { id: string }) => model.id === 'gemini-3.1-flash-image-preview',
+ )?.pricing;
+ expect(pricing).toBeDefined();
+
+ const usage: ModelTokensUsage = {
+ inputImageTokens: 200,
+ inputTextTokens: 100,
+ outputImageTokens: 20,
+ outputTextTokens: 10,
+ totalInputTokens: 300,
+ totalOutputTokens: 30,
+ totalTokens: 330,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+ expect(result?.totalCredits).toBe(1380);
+
+ const { breakdown } = result!;
+ expect(breakdown).toHaveLength(4);
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.credits).toBe(50);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')?.credits).toBe(100);
+ expect(breakdown.find((item) => item.unit.name === 'textOutput')?.credits).toBe(30);
+ expect(breakdown.find((item) => item.unit.name === 'imageOutput')?.credits).toBe(1200);
+ });
+
it('handles multi-modal image generation for Nano Banana', () => {
const pricing = googleChatModels.find(
(model: { id: string }) => model.id === 'gemini-2.5-flash-image',
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
index 5a40c51bbd9..b0652387d2b 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
@@ -52,12 +52,73 @@ export interface PricingComputationResult {
totalCredits: number;
}
-type UnitQuantityResolver = (usage: ModelTokensUsage) => number | undefined;
+interface UnitQuantityResolverContext {
+ hasDedicatedModalityCacheReadUnit: boolean;
+}
+
+type UnitQuantityResolver = (
+ usage: ModelTokensUsage,
+ context: UnitQuantityResolverContext,
+) => number | undefined;
+
+const hasCachedModalityBreakdown = (usage: ModelTokensUsage) =>
+ typeof usage.inputCachedTextTokens === 'number' ||
+ typeof usage.inputCachedImageTokens === 'number' ||
+ typeof usage.inputCachedAudioTokens === 'number' ||
+ typeof usage.inputCachedVideoTokens === 'number';
+
+const subtractCachedTokens = (
+ totalTokens: number | undefined,
+ cachedTokens: number | undefined,
+): number | undefined => {
+ if (typeof totalTokens !== 'number') return undefined;
+
+ return Math.max(0, totalTokens - (cachedTokens ?? 0));
+};
+
+const resolveInputTextTokens = (usage: ModelTokensUsage) => {
+ if (hasCachedModalityBreakdown(usage)) {
+ return subtractCachedTokens(usage.inputTextTokens, usage.inputCachedTextTokens);
+ }
+
+ return usage.inputTextTokens;
+};
+
+const resolveInputImageTokens = (usage: ModelTokensUsage) => {
+ if (hasCachedModalityBreakdown(usage)) {
+ return subtractCachedTokens(usage.inputImageTokens, usage.inputCachedImageTokens);
+ }
+
+ return usage.inputImageTokens;
+};
+
+const resolveInputAudioTokens = (usage: ModelTokensUsage) => {
+ if (hasCachedModalityBreakdown(usage)) {
+ return subtractCachedTokens(usage.inputAudioTokens, usage.inputCachedAudioTokens);
+ }
+
+ return usage.inputAudioTokens;
+};
+
+const resolveInputVideoTokens = (usage: ModelTokensUsage) => {
+ if (hasCachedModalityBreakdown(usage)) {
+ return subtractCachedTokens(usage.inputVideoTokens, usage.inputCachedVideoTokens);
+ }
+
+ return usage.inputVideoTokens;
+};
const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResolver>> = {
textInput: (usage) => {
const toolTokens = usage.inputToolTokens ?? 0;
+ if (hasCachedModalityBreakdown(usage)) {
+ const textTokens = resolveInputTextTokens(usage);
+ if (textTokens === undefined && toolTokens === 0) return undefined;
+
+ return (textTokens ?? 0) + toolTokens;
+ }
+
if (usage.inputCacheMissTokens !== undefined) {
// inputCacheMissTokens only covers non-cached prompt tokens;
// tool-use tokens (e.g. grounding results) are billed at the same input rate
@@ -78,9 +139,15 @@ const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResol
return usage.totalInputTokens;
}
- return usage.inputTextTokens ?? usage.totalInputTokens;
+ return resolveInputTextTokens(usage) ?? usage.totalInputTokens;
+ },
+ textInput_cacheRead: (usage, context) => {
+ if (hasCachedModalityBreakdown(usage) && context.hasDedicatedModalityCacheReadUnit) {
+ return usage.inputCachedTextTokens;
+ }
+
+ return usage.inputCachedTokens;
},
- textInput_cacheRead: (usage) => usage.inputCachedTokens,
textInput_cacheWrite: (usage) => usage.inputWriteCacheTokens,
// reasoning tokens cost within output tokens
textOutput: (usage) => {
@@ -102,15 +169,16 @@ const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResol
return undefined;
},
- imageInput: (usage) => usage.inputImageTokens,
- imageInput_cacheRead: () => undefined,
+ imageInput: resolveInputImageTokens,
+ imageInput_cacheRead: (usage) => usage.inputCachedImageTokens,
imageOutput: (usage) => usage.outputImageTokens,
+ videoInput: resolveInputVideoTokens,
+
imageGeneration: () => undefined,
- audioInput: (usage) => usage.inputAudioTokens,
- // TODO: Support this when ModelTokensUsage includes this data
- audioInput_cacheRead: () => undefined,
+ audioInput: resolveInputAudioTokens,
+ audioInput_cacheRead: (usage) => usage.inputCachedAudioTokens,
audioOutput: (usage) => usage.outputAudioTokens,
};
@@ -243,9 +311,13 @@ const computeLookupCredits = (
};
};
-const resolveQuantity = (unit: PricingUnit, usage: ModelTokensUsage) => {
+const resolveQuantity = (
+ unit: PricingUnit,
+ usage: ModelTokensUsage,
+ context: UnitQuantityResolverContext,
+) => {
const resolver = UNIT_QUANTITY_RESOLVERS[unit.name as PricingUnitName];
- const quantity = resolver?.(usage);
+ const quantity = resolver?.(usage, context);
return typeof quantity === 'number' ? quantity : undefined;
};
@@ -264,9 +336,14 @@ export const computeChatCost = (
const issues: PricingComputationIssue[] = [];
const currency = pricing.currency || 'USD';
const usdToCnyRate = options?.usdToCnyRate ?? USD_TO_CNY;
+ const pricingUnitNames = new Set(pricing.units.map((unit) => unit.name));
+ const resolverContext: UnitQuantityResolverContext = {
+ hasDedicatedModalityCacheReadUnit:
+ pricingUnitNames.has('audioInput_cacheRead') || pricingUnitNames.has('imageInput_cacheRead'),
+ };
for (const unit of pricing.units) {
- const quantity = resolveQuantity(unit, usage);
+ const quantity = resolveQuantity(unit, usage, resolverContext);
if (quantity === undefined) continue;
if (unit.strategy === 'fixed') {
diff --git a/packages/prompts/src/prompts/files/image.ts b/packages/prompts/src/prompts/files/image.ts
index 07de468d1ff..8752a2f8f76 100644
--- a/packages/prompts/src/prompts/files/image.ts
+++ b/packages/prompts/src/prompts/files/image.ts
@@ -1,16 +1,29 @@
import type { ChatImageItem } from '@lobechat/types';
+import { createVisualFileRef } from '@lobechat/types';
-const imagePrompt = (item: ChatImageItem, attachUrl: boolean) =>
- attachUrl
- ? `<image name="${item.alt}" url="${item.url}"></image>`
- : `<image name="${item.alt}"></image>`;
+const imagePrompt = (
+ item: ChatImageItem,
+ attachUrl: boolean,
+ index: number,
+ messageId?: string,
+) => {
+ const ref = createVisualFileRef({ index, messageId, type: 'image' });
-export const imagesPrompts = (imageList: ChatImageItem[], attachUrl: boolean) => {
+ return attachUrl
+ ? `<image ref="${ref}" name="${item.alt}" url="${item.url}"></image>`
+ : `<image ref="${ref}" name="${item.alt}"></image>`;
+};
+
+export const imagesPrompts = (
+ imageList: ChatImageItem[],
+ attachUrl: boolean,
+ messageId?: string,
+) => {
if (imageList.length === 0) return '';
const prompt = `<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-${imageList.map((item) => imagePrompt(item, attachUrl)).join('\n')}
+${imageList.map((item, index) => imagePrompt(item, attachUrl, index, messageId)).join('\n')}
</images>`;
return prompt.trim();
diff --git a/packages/prompts/src/prompts/files/index.test.ts b/packages/prompts/src/prompts/files/index.test.ts
index 4023e4dc43b..66cb119c58b 100644
--- a/packages/prompts/src/prompts/files/index.test.ts
+++ b/packages/prompts/src/prompts/files/index.test.ts
@@ -1,4 +1,5 @@
import type { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import { createVisualFileRef } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { filesPrompts } from './index';
@@ -41,7 +42,7 @@ describe('filesPrompts', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="test image" url="https://example.com/image.jpg"></image>
+<image ref="image_1" name="test image" url="https://example.com/image.jpg"></image>
</images>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -87,7 +88,7 @@ describe('filesPrompts', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="test image" url="https://example.com/image.jpg"></image>
+<image ref="image_1" name="test image" url="https://example.com/image.jpg"></image>
</images>
<files>
<files_docstring>here are user upload files you can refer to</files_docstring>
@@ -135,8 +136,8 @@ describe('filesPrompts', () => {
expect(result).toContain('second image');
expect(result).toContain('document.docx');
- expect(result).toMatch(/<image.*?>.*<image.*?>/s); // Check for multiple image tags
- expect(result).toMatch(/<file.*?>.*<file.*?>/s); // Check for multiple file tags
+ expect(result.match(/<image\b/g)).toHaveLength(2);
+ expect(result.match(/<file\b/g)).toHaveLength(2);
});
it('should handle without url', () => {
@@ -176,8 +177,8 @@ describe('filesPrompts', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
- <image name="test image"></image>
- <image name="second image"></image>
+ <image ref="image_1" name="test image"></image>
+ <image ref="image_2" name="second image"></image>
</images>
<files>
<files_docstring>here are user upload files you can refer to</files_docstring>
@@ -189,6 +190,25 @@ describe('filesPrompts', () => {
`);
});
+ it('should generate stable visual refs when message id is provided', () => {
+ const messageId = 'message-with-visual-media';
+ const imageRef = createVisualFileRef({ index: 0, messageId, type: 'image' });
+ const videoRef = createVisualFileRef({ index: 0, messageId, type: 'video' });
+
+ const result = filesPrompts({
+ imageList: [mockImage],
+ messageId,
+ videoList: [mockVideo],
+ });
+
+ expect(result).toContain(
+ `<image ref="${imageRef}" name="test image" url="https://example.com/image.jpg"></image>`,
+ );
+ expect(result).toContain(
+ `<video ref="${videoRef}" name="test video" url="https://example.com/video.mp4"></video>`,
+ );
+ });
+
describe('Video functionality', () => {
it('should generate prompt with only videos', () => {
const result = filesPrompts({
@@ -205,7 +225,7 @@ describe('filesPrompts', () => {
<files_info>
<videos>
<videos_docstring>here are user upload videos you can refer to</videos_docstring>
-<video name="test video" url="https://example.com/video.mp4"></video>
+<video ref="video_1" name="test video" url="https://example.com/video.mp4"></video>
</videos>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -228,11 +248,11 @@ describe('filesPrompts', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="test image" url="https://example.com/image.jpg"></image>
+<image ref="image_1" name="test image" url="https://example.com/image.jpg"></image>
</images>
<videos>
<videos_docstring>here are user upload videos you can refer to</videos_docstring>
-<video name="test video" url="https://example.com/video.mp4"></video>
+<video ref="video_1" name="test video" url="https://example.com/video.mp4"></video>
</videos>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -256,7 +276,7 @@ describe('filesPrompts', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="test image" url="https://example.com/image.jpg"></image>
+<image ref="image_1" name="test image" url="https://example.com/image.jpg"></image>
</images>
<files>
<files_docstring>here are user upload files you can refer to</files_docstring>
@@ -264,7 +284,7 @@ describe('filesPrompts', () => {
</files>
<videos>
<videos_docstring>here are user upload videos you can refer to</videos_docstring>
-<video name="test video" url="https://example.com/video.mp4"></video>
+<video ref="video_1" name="test video" url="https://example.com/video.mp4"></video>
</videos>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -287,7 +307,7 @@ describe('filesPrompts', () => {
expect(result).toContain('test video');
expect(result).toContain('second video');
- expect(result).toMatch(/<video.*?>.*<video.*?>/s); // Check for multiple video tags
+ expect(result.match(/<video\b/g)).toHaveLength(2);
});
it('should handle videos without url when addUrl is false', () => {
@@ -306,7 +326,7 @@ describe('filesPrompts', () => {
<files_info>
<videos>
<videos_docstring>here are user upload videos you can refer to</videos_docstring>
- <video name="test video"></video>
+ <video ref="video_1" name="test video"></video>
</videos>
</files_info>
<!-- END SYSTEM CONTEXT -->"
diff --git a/packages/prompts/src/prompts/files/index.ts b/packages/prompts/src/prompts/files/index.ts
index f90bae66636..d7d4d05c006 100644
--- a/packages/prompts/src/prompts/files/index.ts
+++ b/packages/prompts/src/prompts/files/index.ts
@@ -12,10 +12,12 @@ export const filesPrompts = ({
fileList,
videoList,
addUrl = true,
+ messageId,
}: {
addUrl?: boolean;
fileList?: ChatFileItem[];
imageList?: ChatImageItem[];
+ messageId?: string;
videoList?: ChatVideoItem[];
}) => {
const hasImages = (imageList || []).length > 0;
@@ -25,9 +27,9 @@ export const filesPrompts = ({
if (!hasImages && !hasFiles && !hasVideos) return '';
const contentParts = [
- hasImages ? imagesPrompts(imageList!, addUrl) : '',
+ hasImages ? imagesPrompts(imageList!, addUrl, messageId) : '',
hasFiles ? filePrompts(fileList!, addUrl) : '',
- hasVideos ? videosPrompts(videoList!, addUrl) : '',
+ hasVideos ? videosPrompts(videoList!, addUrl, messageId) : '',
].filter(Boolean);
const prompt = `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
diff --git a/packages/prompts/src/prompts/files/video.ts b/packages/prompts/src/prompts/files/video.ts
index fbb37a4aa44..fef84680a78 100644
--- a/packages/prompts/src/prompts/files/video.ts
+++ b/packages/prompts/src/prompts/files/video.ts
@@ -1,16 +1,29 @@
import type { ChatVideoItem } from '@lobechat/types';
+import { createVisualFileRef } from '@lobechat/types';
-const videoPrompt = (item: ChatVideoItem, attachUrl: boolean) =>
- attachUrl
- ? `<video name="${item.alt}" url="${item.url}"></video>`
- : `<video name="${item.alt}"></video>`;
+const videoPrompt = (
+ item: ChatVideoItem,
+ attachUrl: boolean,
+ index: number,
+ messageId?: string,
+) => {
+ const ref = createVisualFileRef({ index, messageId, type: 'video' });
-export const videosPrompts = (videoList: ChatVideoItem[], addUrl: boolean = true) => {
+ return attachUrl
+ ? `<video ref="${ref}" name="${item.alt}" url="${item.url}"></video>`
+ : `<video ref="${ref}" name="${item.alt}"></video>`;
+};
+
+export const videosPrompts = (
+ videoList: ChatVideoItem[],
+ addUrl: boolean = true,
+ messageId?: string,
+) => {
if (videoList.length === 0) return '';
const prompt = `<videos>
<videos_docstring>here are user upload videos you can refer to</videos_docstring>
-${videoList.map((item) => videoPrompt(item, addUrl)).join('\n')}
+${videoList.map((item, index) => videoPrompt(item, addUrl, index, messageId)).join('\n')}
</videos>`;
return prompt.trim();
diff --git a/packages/types/package.json b/packages/types/package.json
index b8d2cd75935..dfbd02a150e 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -4,6 +4,11 @@
"private": true,
"type": "module",
"main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'",
+ "test:update": "vitest -u"
+ },
"dependencies": {
"@lobechat/python-interpreter": "workspace:*",
"@lobechat/web-crawler": "workspace:*",
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 98713eba805..be16b7d2699 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -34,13 +34,33 @@ export interface LocalSystemToolSnapshot {
export interface ModelTokensUsage {
// Prediction tokens
acceptedPredictionTokens?: number;
+ /**
+ * Total input audio tokens for the request. This is a modality breakdown, not
+ * a cache-miss count.
+ */
inputAudioTokens?: number;
+ /**
+ * Cached audio tokens for the request.
+ */
+ inputCachedAudioTokens?: number;
+ /**
+ * Cached image tokens for the request.
+ */
+ inputCachedImageTokens?: number;
+ /**
+ * Cached text tokens for the request.
+ */
+ inputCachedTextTokens?: number;
// Input tokens breakdown
/**
* user prompt input
*/
// Input cache tokens
inputCachedTokens?: number;
+ /**
+ * Cached video tokens for the request.
+ */
+ inputCachedVideoTokens?: number;
inputCacheMissTokens?: number;
/**
@@ -48,15 +68,25 @@ export interface ModelTokensUsage {
*/
inputCitationTokens?: number;
/**
- * user prompt image
+ * Total user prompt image tokens for the request. This is a modality
+ * breakdown, not a cache-miss count.
*/
inputImageTokens?: number;
+ /**
+ * Total user prompt text tokens for the request. This is a modality
+ * breakdown, not a cache-miss count.
+ */
inputTextTokens?: number;
-
/**
* tool use prompt tokens (Google AI / Vertex AI)
*/
inputToolTokens?: number;
+
+ /**
+ * Total user prompt video tokens for the request. This is a modality
+ * breakdown, not a cache-miss count.
+ */
+ inputVideoTokens?: number;
inputWriteCacheTokens?: number;
outputAudioTokens?: number;
outputImageTokens?: number;
@@ -78,9 +108,14 @@ export const ModelUsageSchema = z.object({
inputCachedTokens: z.number().optional(),
inputCacheMissTokens: z.number().optional(),
inputWriteCacheTokens: z.number().optional(),
+ inputCachedTextTokens: z.number().optional(),
+ inputCachedImageTokens: z.number().optional(),
+ inputCachedAudioTokens: z.number().optional(),
+ inputCachedVideoTokens: z.number().optional(),
inputTextTokens: z.number().optional(),
inputImageTokens: z.number().optional(),
inputAudioTokens: z.number().optional(),
+ inputVideoTokens: z.number().optional(),
inputCitationTokens: z.number().optional(),
inputToolTokens: z.number().optional(),
@@ -193,8 +228,16 @@ export interface MessageMetadata {
/** @deprecated use `metadata.usage` instead */
inputAudioTokens?: number;
/** @deprecated use `metadata.usage` instead */
+ inputCachedAudioTokens?: number;
+ /** @deprecated use `metadata.usage` instead */
+ inputCachedImageTokens?: number;
+ /** @deprecated use `metadata.usage` instead */
+ inputCachedTextTokens?: number;
+ /** @deprecated use `metadata.usage` instead */
inputCachedTokens?: number;
/** @deprecated use `metadata.usage` instead */
+ inputCachedVideoTokens?: number;
+ /** @deprecated use `metadata.usage` instead */
inputCacheMissTokens?: number;
/** @deprecated use `metadata.usage` instead */
inputCitationTokens?: number;
@@ -205,6 +248,8 @@ export interface MessageMetadata {
/** @deprecated use `metadata.usage` instead */
inputToolTokens?: number;
/** @deprecated use `metadata.usage` instead */
+ inputVideoTokens?: number;
+ /** @deprecated use `metadata.usage` instead */
inputWriteCacheTokens?: number;
/**
* Tool inspect expanded state
diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.ts
index 014a5a2989e..c05c44626bd 100644
--- a/packages/types/src/openai/chat.ts
+++ b/packages/types/src/openai/chat.ts
@@ -33,8 +33,15 @@ interface UserMessageContentPartImage {
};
type: 'image_url';
}
+interface UserMessageContentPartVideo {
+ type: 'video_url';
+ video_url: { url: string };
+}
-export type UserMessageContentPart = UserMessageContentPartText | UserMessageContentPartImage;
+export type UserMessageContentPart =
+ | UserMessageContentPartText
+ | UserMessageContentPartImage
+ | UserMessageContentPartVideo;
export interface OpenAIChatMessage {
/**
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index d87a04670d3..b603ffd9ed6 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -34,6 +34,11 @@ export interface GlobalMemoryConfig {
userMemory?: GlobalMemoryExtractionConfig;
}
+export interface VisualUnderstandingConfig {
+ model: string;
+ provider: string;
+}
+
export interface ServerModelProviderConfig {
enabled?: boolean;
enabledModels?: string[];
@@ -67,6 +72,7 @@ export interface GlobalServerConfig {
enableMagicLink?: boolean;
enableMarketTrustedClient?: boolean;
enableUploadFileToServer?: boolean;
+ enableVisualUnderstanding?: boolean;
image?: PartialDeep<UserImageConfig>;
memory?: GlobalMemoryConfig;
oAuthSSOProviders?: string[];
@@ -74,6 +80,7 @@ export interface GlobalServerConfig {
telemetry: {
langfuse?: boolean;
};
+ visualUnderstanding?: VisualUnderstandingConfig;
}
export interface GlobalBillboardItemLocaleFields {
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 37d8e186967..9f2fb022bf6 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -462,6 +462,11 @@ export interface BuiltinToolContext {
*/
signal?: AbortSignal;
+ /**
+ * The source user message ID for tools that need to inspect the current turn.
+ */
+ sourceMessageId?: string;
+
/**
* Step context computed at the beginning of each step
* Contains dynamic state like GTD todos that changes between steps
diff --git a/packages/types/src/tool/index.ts b/packages/types/src/tool/index.ts
index b65531765fb..0329cda2fe7 100644
--- a/packages/types/src/tool/index.ts
+++ b/packages/types/src/tool/index.ts
@@ -31,3 +31,4 @@ export * from './manifest';
export * from './plugin';
export * from './search';
export * from './tool';
+export * from './visualRef';
diff --git a/packages/types/src/tool/visualRef.test.ts b/packages/types/src/tool/visualRef.test.ts
new file mode 100644
index 00000000000..2c0d42e8256
--- /dev/null
+++ b/packages/types/src/tool/visualRef.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { createVisualFileRef, createVisualLocalRef, createVisualMessageRef } from './visualRef';
+
+describe('visualRef', () => {
+ it('should create local refs for current-message visual files', () => {
+ expect(createVisualLocalRef('image', 0)).toBe('image_1');
+ expect(createVisualLocalRef('video', 1)).toBe('video_2');
+
+ expect(createVisualFileRef({ index: 0, type: 'image' })).toBe('image_1');
+ expect(createVisualFileRef({ index: 1, type: 'video' })).toBe('video_2');
+ });
+
+ it('should create stable message-scoped refs without exposing raw message ids', () => {
+ const messageId = 'msg_real_database_id';
+ const messageRef = createVisualMessageRef(messageId);
+
+ expect(messageRef).toMatch(/^msg_[a-z0-9]+$/);
+ expect(messageRef).not.toContain(messageId);
+ expect(createVisualMessageRef(messageId)).toBe(messageRef);
+ expect(createVisualFileRef({ index: 0, messageId, type: 'image' })).toBe(
+ `${messageRef}.image_1`,
+ );
+ });
+});
diff --git a/packages/types/src/tool/visualRef.ts b/packages/types/src/tool/visualRef.ts
new file mode 100644
index 00000000000..2d8aefb18c6
--- /dev/null
+++ b/packages/types/src/tool/visualRef.ts
@@ -0,0 +1,28 @@
+export type VisualFileType = 'image' | 'video';
+
+interface CreateVisualFileRefOptions {
+ index: number;
+ messageId?: string;
+ type: VisualFileType;
+}
+
+export const createVisualLocalRef = (type: VisualFileType, index: number) => `${type}_${index + 1}`;
+
+const hashMessageId = (messageId: string) => {
+ let hash = 2166136261;
+
+ for (const char of messageId) {
+ hash ^= char.charCodeAt(0);
+ hash = Math.imul(hash, 16777619);
+ }
+
+ return (hash >>> 0).toString(36).slice(0, 6);
+};
+
+export const createVisualMessageRef = (messageId: string) => `msg_${hashMessageId(messageId)}`;
+
+export const createVisualFileRef = ({ index, messageId, type }: CreateVisualFileRefOptions) => {
+ const localRef = createVisualLocalRef(type, index);
+
+ return messageId ? `${createVisualMessageRef(messageId)}.${localRef}` : localRef;
+};
diff --git a/packages/types/vitest.config.mts b/packages/types/vitest.config.mts
new file mode 100644
index 00000000000..52f86e133c7
--- /dev/null
+++ b/packages/types/vitest.config.mts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'node',
+ },
+});
diff --git a/src/components/DragUpload/useDragUpload.test.tsx b/src/components/DragUpload/useDragUpload.test.tsx
index 76cfaf055c9..e15b1080ee1 100644
--- a/src/components/DragUpload/useDragUpload.test.tsx
+++ b/src/components/DragUpload/useDragUpload.test.tsx
@@ -4,14 +4,14 @@ import { App } from 'antd';
import { type Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { getContainer, useDragUpload } from './useDragUpload';
// Mock the hooks and components
-vi.mock('@/hooks/useModelSupportVision');
+vi.mock('@/hooks/useVisualMediaUploadAbility');
vi.mock('@/store/agent');
vi.mock('antd', async () => {
const actual = await vi.importActual<typeof AntdModule>('antd');
@@ -32,16 +32,17 @@ vi.mock('antd', async () => {
describe('useDragUpload', () => {
let mockOnUploadFiles: Mock;
- let mockMessage: { warning: Mock };
beforeEach(() => {
mockOnUploadFiles = vi.fn();
- mockMessage = { warning: vi.fn() };
vi.useFakeTimers();
document.body.innerHTML = '';
// Mock the hooks
- (useModelSupportVision as Mock).mockReturnValue(false);
+ (useVisualMediaUploadAbility as Mock).mockReturnValue({
+ canUploadImage: false,
+ canUploadVideo: false,
+ });
(useAgentStore as unknown as Mock).mockImplementation((selector) => {
if (selector === agentSelectors.currentAgentModel) return 'test-model';
if (selector === agentSelectors.currentAgentModelProvider) return 'test-provider';
@@ -206,7 +207,10 @@ describe('useDragUpload', () => {
});
it('should allow image files when vision is supported', async () => {
- (useModelSupportVision as Mock).mockReturnValue(true);
+ (useVisualMediaUploadAbility as Mock).mockReturnValue({
+ canUploadImage: true,
+ canUploadVideo: false,
+ });
renderHook(() => useDragUpload(mockOnUploadFiles));
@@ -235,6 +239,36 @@ describe('useDragUpload', () => {
expect(mockOnUploadFiles).toHaveBeenCalledWith([mockImageFile]);
expect(App.useApp().message.warning).not.toHaveBeenCalled();
});
+
+ it('should allow image files when visual understanding fallback is enabled', async () => {
+ (useVisualMediaUploadAbility as Mock).mockReturnValue({
+ canUploadImage: true,
+ canUploadVideo: true,
+ });
+
+ renderHook(() => useDragUpload(mockOnUploadFiles));
+
+ const mockImageFile = new File([''], 'test.png', { type: 'image/png' });
+ const pasteEvent = new Event('paste') as ClipboardEvent;
+ Object.defineProperty(pasteEvent, 'clipboardData', {
+ value: {
+ items: [
+ {
+ kind: 'file',
+ getAsFile: () => mockImageFile,
+ webkitGetAsEntry: () => null,
+ },
+ ],
+ },
+ });
+
+ await act(async () => {
+ window.dispatchEvent(pasteEvent);
+ });
+
+ expect(mockOnUploadFiles).toHaveBeenCalledWith([mockImageFile]);
+ expect(App.useApp().message.warning).not.toHaveBeenCalled();
+ });
});
describe('getContainer', () => {
diff --git a/src/components/DragUpload/useDragUpload.tsx b/src/components/DragUpload/useDragUpload.tsx
index 89f3f5eb9ba..4301e2daf2b 100644
--- a/src/components/DragUpload/useDragUpload.tsx
+++ b/src/components/DragUpload/useDragUpload.tsx
@@ -1,9 +1,8 @@
-
import { App } from 'antd';
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -78,9 +77,24 @@ export const useDragUpload = (onUploadFiles: (files: File[]) => Promise<void>) =
const model = useAgentStore(agentSelectors.currentAgentModel);
const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
- const supportVision = useModelSupportVision(model, provider);
+ const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
- const handleDragEnter = (e: DragEvent) => {
+ const warnIfVisualUploadUnsupported = useCallback(
+ (files: File[]) => {
+ const hasImageFiles = files.some((file) => file.type.startsWith('image/'));
+ const hasVideoFiles = files.some((file) => file.type.startsWith('video/'));
+
+ if ((hasImageFiles && !canUploadImage) || (hasVideoFiles && !canUploadVideo)) {
+ message.warning(t('upload.clientMode.visionNotSupported'));
+ return true;
+ }
+
+ return false;
+ },
+ [canUploadImage, canUploadVideo, message, t],
+ );
+
+ const handleDragEnter = useCallback((e: DragEvent) => {
if (!e.dataTransfer?.items || e.dataTransfer.items.length === 0) return;
const isFile = e.dataTransfer.types.includes('Files');
@@ -89,9 +103,9 @@ export const useDragUpload = (onUploadFiles: (files: File[]) => Promise<void>) =
e.preventDefault();
setIsDragging(true);
}
- };
+ }, []);
- const handleDragLeave = (e: DragEvent) => {
+ const handleDragLeave = useCallback((e: DragEvent) => {
if (!e.dataTransfer?.items || e.dataTransfer.items.length === 0) return;
const isFile = e.dataTransfer.types.includes('Files');
@@ -105,54 +119,50 @@ export const useDragUpload = (onUploadFiles: (files: File[]) => Promise<void>) =
setIsDragging(false);
}
}
- };
+ }, []);
- const handleDrop = async (e: DragEvent) => {
- if (!e.dataTransfer?.items || e.dataTransfer.items.length === 0) return;
+ const handleDrop = useCallback(
+ async (e: DragEvent) => {
+ if (!e.dataTransfer?.items || e.dataTransfer.items.length === 0) return;
- const isFile = e.dataTransfer.types.includes('Files');
- if (!isFile) return;
+ const isFile = e.dataTransfer.types.includes('Files');
+ if (!isFile) return;
- e.preventDefault();
+ e.preventDefault();
- // reset counter
- dragCounter.current = 0;
+ // reset counter
+ dragCounter.current = 0;
- setIsDragging(false);
- const items = Array.from(e.dataTransfer?.items);
+ setIsDragging(false);
+ const items = Array.from(e.dataTransfer?.items);
- const files = await getFileListFromDataTransferItems(items);
+ const files = await getFileListFromDataTransferItems(items);
- if (files.length === 0) return;
+ if (files.length === 0) return;
- // Check if there are image files and the model does not support vision
- const hasImageFiles = files.some((file) => file.type.startsWith('image/'));
- if (hasImageFiles && !supportVision) {
- message.warning(t('upload.clientMode.visionNotSupported'));
- return;
- }
+ if (warnIfVisualUploadUnsupported(files)) return;
- // upload files
- onUploadFiles(files);
- };
+ // upload files
+ onUploadFiles(files);
+ },
+ [onUploadFiles, warnIfVisualUploadUnsupported],
+ );
- const handlePaste = async (event: ClipboardEvent) => {
- // get files from clipboard
- if (!event.clipboardData) return;
- const items = Array.from(event.clipboardData?.items);
+ const handlePaste = useCallback(
+ async (event: ClipboardEvent) => {
+ // get files from clipboard
+ if (!event.clipboardData) return;
+ const items = Array.from(event.clipboardData?.items);
- const files = await getFileListFromDataTransferItems(items);
- if (files.length === 0) return;
+ const files = await getFileListFromDataTransferItems(items);
+ if (files.length === 0) return;
- // Check if there are image files and the model does not support vision
- const hasImageFiles = files.some((file) => file.type.startsWith('image/'));
- if (hasImageFiles && !supportVision) {
- message.warning(t('upload.clientMode.visionNotSupported'));
- return;
- }
+ if (warnIfVisualUploadUnsupported(files)) return;
- onUploadFiles(files);
- };
+ onUploadFiles(files);
+ },
+ [onUploadFiles, warnIfVisualUploadUnsupported],
+ );
useEffect(() => {
if (getContainer()) return;
@@ -179,7 +189,7 @@ export const useDragUpload = (onUploadFiles: (files: File[]) => Promise<void>) =
window.removeEventListener('drop', handleDrop);
window.removeEventListener('paste', handlePaste);
};
- }, [handleDragEnter, handleDragOver, handleDragLeave, handleDrop, handlePaste]);
+ }, [handleDragEnter, handleDragLeave, handleDrop, handlePaste]);
return isDragging;
};
diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.ts
index aa30c42f060..09fb6991d01 100644
--- a/src/components/DragUploadZone/useUploadFiles.ts
+++ b/src/components/DragUploadZone/useUploadFiles.ts
@@ -1,6 +1,6 @@
import { useCallback } from 'react';
-import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useFileStore } from '@/store/file';
interface UseUploadFilesOptions {
@@ -9,8 +9,8 @@ interface UseUploadFilesOptions {
}
/**
- * Hook to handle file uploads with vision support filtering.
- * Filters out image files if the model does not support vision.
+ * Hook to handle file uploads with visual media support filtering.
+ * Filters out image/video files if the model cannot receive them directly or via fallback.
*
* @param options - The model and provider to check for vision support
* @returns handleUploadFiles - Callback to handle file uploads
@@ -18,23 +18,24 @@ interface UseUploadFilesOptions {
export const useUploadFiles = (options: UseUploadFilesOptions = {}) => {
const { model = '', provider = '' } = options;
- const canUploadImage = useModelSupportVision(model, provider);
+ const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
const uploadFiles = useFileStore((s) => s.uploadChatFiles);
const handleUploadFiles = useCallback(
async (files: File[]) => {
- // Filter out image files if the model does not support vision
+ // Filter out visual files if the model cannot receive them directly or via fallback.
const filteredFiles = files.filter((file) => {
- if (canUploadImage) return true;
- return !file.type.startsWith('image');
+ if (file.type.startsWith('image')) return canUploadImage;
+ if (file.type.startsWith('video')) return canUploadVideo;
+ return true;
});
if (filteredFiles.length > 0) {
uploadFiles(filteredFiles);
}
},
- [canUploadImage, uploadFiles],
+ [canUploadImage, canUploadVideo, uploadFiles],
);
- return { canUploadImage, handleUploadFiles };
+ return { canUploadImage, canUploadVideo, handleUploadFiles };
};
diff --git a/src/envs/tools.ts b/src/envs/tools.ts
index 3ff16cf97ea..a23d9dc8d1a 100644
--- a/src/envs/tools.ts
+++ b/src/envs/tools.ts
@@ -15,6 +15,8 @@ export const getToolsConfig = () => {
CRAWLER_IMPLS: process.env.CRAWLER_IMPLS,
SEARCH_PROVIDERS: process.env.SEARCH_PROVIDERS,
SEARXNG_URL: process.env.SEARXNG_URL,
+ VISUAL_UNDERSTANDING_MODEL: process.env.VISUAL_UNDERSTANDING_MODEL,
+ VISUAL_UNDERSTANDING_PROVIDER: process.env.VISUAL_UNDERSTANDING_PROVIDER,
},
server: {
@@ -23,6 +25,8 @@ export const getToolsConfig = () => {
CRAWLER_IMPLS: z.string().optional(),
SEARCH_PROVIDERS: z.string().optional(),
SEARXNG_URL: z.string().url().optional(),
+ VISUAL_UNDERSTANDING_MODEL: z.string().optional(),
+ VISUAL_UNDERSTANDING_PROVIDER: z.string().optional(),
},
});
};
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index 2904ec2f1c6..d335daebf91 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -13,7 +13,7 @@ import FileIcon from '@/components/FileIcon';
import RepoIcon from '@/components/LibIcon';
import TipGuide from '@/components/TipGuide';
import { openAttachKnowledgeModal } from '@/features/LibraryModal';
-import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useFileStore } from '@/store/file';
@@ -48,7 +48,7 @@ const FileUpload = memo(() => {
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
- const canUploadImage = useModelSupportVision(model, provider);
+ const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
const [showTip, updateGuideState] = useUserStore((s) => [
preferenceSelectors.showUploadFileInKnowledgeBaseTip(s),
@@ -105,7 +105,10 @@ const FileUpload = memo(() => {
multiple
showUploadList={false}
beforeUpload={async (file) => {
- if (!canUploadImage && (file.type.startsWith('image') || file.type.startsWith('video')))
+ if (
+ (file.type.startsWith('image') && !canUploadImage) ||
+ (file.type.startsWith('video') && !canUploadVideo)
+ )
return false;
// Validate video file size
@@ -139,7 +142,10 @@ const FileUpload = memo(() => {
multiple={true}
showUploadList={false}
beforeUpload={async (file) => {
- if (!canUploadImage && (file.type.startsWith('image') || file.type.startsWith('video')))
+ if (
+ (file.type.startsWith('image') && !canUploadImage) ||
+ (file.type.startsWith('video') && !canUploadVideo)
+ )
return false;
// Validate video file size
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
index d15ac462c77..6a247af23f9 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
@@ -108,6 +108,7 @@ const UNIT_GROUP_MAP: Record<PricingUnitName, PricingGroup> = {
textInput_cacheRead: 'text',
textInput_cacheWrite: 'text',
textOutput: 'text',
+ videoInput: 'video',
videoGeneration: 'video',
};
@@ -139,7 +140,8 @@ const UNIT_SORT_ORDER: Record<PricingUnitName, number> = {
audioInput: 0,
audioOutput: 1,
audioInput_cacheRead: 2,
- videoGeneration: 0,
+ videoInput: 0,
+ videoGeneration: 1,
};
const UNIT_LABEL_MAP: Record<string, string> = {
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index dcb897f2dfa..4f41a39c320 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -59,6 +59,40 @@ vi.mock('@/store/tool', () => ({
} as unknown as ToolManifest,
type: 'builtin' as const,
},
+ {
+ identifier: 'lobe-agent',
+ manifest: {
+ api: [
+ {
+ description: 'Analyze visual media',
+ name: 'analyzeVisualMedia',
+ parameters: {
+ anyOf: [{ required: ['refs'] }, { required: ['urls'] }],
+ properties: {
+ question: { type: 'string' },
+ refs: {
+ items: { type: 'string' },
+ type: 'array',
+ },
+ urls: {
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['question'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: 'lobe-agent',
+ meta: {
+ title: 'Lobe Agent',
+ avatar: 'V',
+ },
+ type: 'builtin',
+ } as unknown as ToolManifest,
+ type: 'builtin' as const,
+ },
],
}),
}));
@@ -218,6 +252,35 @@ describe('toolEngineering', () => {
expect(result.enabledToolIds).toEqual(['search', 'lobe-web-browsing']);
expect(result.enabledToolIds).toHaveLength(2);
});
+
+ it('should enable visual understanding when it is injected into runtime plugin ids', () => {
+ const toolsEngine = createAgentToolsEngine({ model: 'deepseek-chat', provider: 'deepseek' }, [
+ 'lobe-agent',
+ ]);
+
+ const result = toolsEngine.generateToolsDetailed({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [],
+ });
+
+ expect(result.enabledToolIds).toContain('lobe-agent');
+ });
+
+ it('should not enable visual understanding by default', () => {
+ const toolsEngine = createAgentToolsEngine({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ });
+
+ const result = toolsEngine.generateToolsDetailed({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [],
+ });
+
+ expect(result.enabledToolIds).not.toContain('lobe-agent');
+ });
});
describe('isExplicitActivation bypass', () => {
diff --git a/src/hooks/useVisualMediaUploadAbility.test.ts b/src/hooks/useVisualMediaUploadAbility.test.ts
new file mode 100644
index 00000000000..6a0f6d200e6
--- /dev/null
+++ b/src/hooks/useVisualMediaUploadAbility.test.ts
@@ -0,0 +1,160 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
+import { useModelSupportVideo } from '@/hooks/useModelSupportVideo';
+import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import { useVisualMediaUploadAbility } from './useVisualMediaUploadAbility';
+
+vi.mock('@/hooks/useModelSupportToolUse');
+vi.mock('@/hooks/useModelSupportVideo');
+vi.mock('@/hooks/useModelSupportVision');
+vi.mock('@/store/aiInfra', () => ({
+ aiModelSelectors: {
+ getEnabledModelById:
+ (id: string, provider: string) =>
+ (s: {
+ enabledAiModels?: {
+ abilities: { video?: boolean; vision?: boolean };
+ id: string;
+ providerId: string;
+ }[];
+ }) =>
+ s.enabledAiModels?.find((model) => model.id === id && model.providerId === provider),
+ },
+ useAiInfraStore: vi.fn(),
+}));
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: {
+ enableVisualUnderstanding: (s: { enableVisualUnderstanding: boolean }) =>
+ s.enableVisualUnderstanding,
+ visualUnderstanding: (s: { visualUnderstanding?: { model: string; provider: string } }) =>
+ s.visualUnderstanding,
+ },
+ useServerConfigStore: vi.fn(),
+}));
+
+const mockedUseModelSupportToolUse = vi.mocked(useModelSupportToolUse);
+const mockedUseModelSupportVideo = vi.mocked(useModelSupportVideo);
+const mockedUseModelSupportVision = vi.mocked(useModelSupportVision);
+const mockedUseAiInfraStore = vi.mocked(useAiInfraStore);
+const mockedUseServerConfigStore = vi.mocked(useServerConfigStore);
+
+describe('useVisualMediaUploadAbility', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockedUseModelSupportVision.mockReturnValue(false);
+ mockedUseModelSupportVideo.mockReturnValue(false);
+ mockedUseModelSupportToolUse.mockReturnValue(false);
+ mockedUseAiInfraStore.mockImplementation((selector) =>
+ selector({ enabledAiModels: [] } as any),
+ );
+ mockedUseServerConfigStore.mockImplementation((selector) =>
+ selector({ enableVisualUnderstanding: false, visualUnderstanding: undefined } as any),
+ );
+ });
+
+ it('should allow native visual upload without tool use', () => {
+ mockedUseModelSupportVision.mockImplementation((id) => id === 'model');
+
+ const { result } = renderHook(() => useVisualMediaUploadAbility('model', 'provider'));
+
+ expect(result.current.canUploadImage).toBe(true);
+ expect(result.current.canUploadVideo).toBe(false);
+ });
+
+ it('should allow fallback visual upload only when tool use is supported', () => {
+ mockedUseModelSupportToolUse.mockReturnValue(true);
+ mockedUseAiInfraStore.mockImplementation((selector) =>
+ selector({
+ enabledAiModels: [
+ {
+ abilities: { video: true, vision: true },
+ id: 'fallback-model',
+ providerId: 'fallback-provider',
+ },
+ ],
+ } as any),
+ );
+ mockedUseServerConfigStore.mockImplementation((selector) =>
+ selector({
+ enableVisualUnderstanding: true,
+ visualUnderstanding: { model: 'fallback-model', provider: 'fallback-provider' },
+ } as any),
+ );
+
+ const { result } = renderHook(() => useVisualMediaUploadAbility('model', 'provider'));
+
+ expect(result.current.canUploadImage).toBe(true);
+ expect(result.current.canUploadVideo).toBe(true);
+ });
+
+ it('should allow fallback visual upload when fallback model abilities are unknown', () => {
+ mockedUseModelSupportToolUse.mockReturnValue(true);
+ mockedUseServerConfigStore.mockImplementation((selector) =>
+ selector({
+ enableVisualUnderstanding: true,
+ visualUnderstanding: { model: 'server-only-model', provider: 'server-only-provider' },
+ } as any),
+ );
+
+ const { result } = renderHook(() => useVisualMediaUploadAbility('model', 'provider'));
+
+ expect(result.current.canUploadImage).toBe(true);
+ expect(result.current.canUploadVideo).toBe(true);
+ });
+
+ it('should reject fallback visual upload when tool use is unsupported', () => {
+ mockedUseAiInfraStore.mockImplementation((selector) =>
+ selector({
+ enabledAiModels: [
+ {
+ abilities: { video: true, vision: true },
+ id: 'fallback-model',
+ providerId: 'fallback-provider',
+ },
+ ],
+ } as any),
+ );
+ mockedUseServerConfigStore.mockImplementation((selector) =>
+ selector({
+ enableVisualUnderstanding: true,
+ visualUnderstanding: { model: 'fallback-model', provider: 'fallback-provider' },
+ } as any),
+ );
+
+ const { result } = renderHook(() => useVisualMediaUploadAbility('model', 'provider'));
+
+ expect(result.current.canUploadImage).toBe(false);
+ expect(result.current.canUploadVideo).toBe(false);
+ });
+
+ it('should respect fallback model media abilities separately', () => {
+ mockedUseModelSupportToolUse.mockReturnValue(true);
+ mockedUseAiInfraStore.mockImplementation((selector) =>
+ selector({
+ enabledAiModels: [
+ {
+ abilities: { video: false, vision: true },
+ id: 'fallback-model',
+ providerId: 'fallback-provider',
+ },
+ ],
+ } as any),
+ );
+ mockedUseServerConfigStore.mockImplementation((selector) =>
+ selector({
+ enableVisualUnderstanding: true,
+ visualUnderstanding: { model: 'fallback-model', provider: 'fallback-provider' },
+ } as any),
+ );
+
+ const { result } = renderHook(() => useVisualMediaUploadAbility('model', 'provider'));
+
+ expect(result.current.canUploadImage).toBe(true);
+ expect(result.current.canUploadVideo).toBe(false);
+ });
+});
diff --git a/src/hooks/useVisualMediaUploadAbility.ts b/src/hooks/useVisualMediaUploadAbility.ts
new file mode 100644
index 00000000000..ff1a3335a5e
--- /dev/null
+++ b/src/hooks/useVisualMediaUploadAbility.ts
@@ -0,0 +1,30 @@
+import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
+import { useModelSupportVideo } from '@/hooks/useModelSupportVideo';
+import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+export const useVisualMediaUploadAbility = (model: string, provider: string) => {
+ const supportVision = useModelSupportVision(model, provider);
+ const supportVideo = useModelSupportVideo(model, provider);
+ const supportToolUse = useModelSupportToolUse(model, provider);
+ const enableVisualUnderstanding = useServerConfigStore(
+ serverConfigSelectors.enableVisualUnderstanding,
+ );
+ const visualUnderstanding = useServerConfigStore(serverConfigSelectors.visualUnderstanding);
+ const fallbackModel = useAiInfraStore(
+ aiModelSelectors.getEnabledModelById(
+ visualUnderstanding?.model ?? '',
+ visualUnderstanding?.provider ?? '',
+ ),
+ );
+ const fallbackConfigured = !!(visualUnderstanding?.model && visualUnderstanding.provider);
+ const fallbackSupportVision = fallbackConfigured && fallbackModel?.abilities?.vision !== false;
+ const fallbackSupportVideo = fallbackConfigured && fallbackModel?.abilities?.video !== false;
+ const canUseVisualUnderstanding = enableVisualUnderstanding && supportToolUse;
+
+ return {
+ canUploadImage: supportVision || (canUseVisualUnderstanding && fallbackSupportVision),
+ canUploadVideo: supportVideo || (canUseVisualUnderstanding && fallbackSupportVideo),
+ };
+};
diff --git a/src/locales/default/components.ts b/src/locales/default/components.ts
index ea2d102b3ba..f07d3e834cb 100644
--- a/src/locales/default/components.ts
+++ b/src/locales/default/components.ts
@@ -160,6 +160,7 @@ export default {
'ModelSwitchPanel.detail.pricing.unit.textInput_cacheWrite': 'Input (Cache Write)',
'ModelSwitchPanel.detail.pricing.unit.textOutput': 'Output',
'ModelSwitchPanel.detail.pricing.unit.videoGeneration': 'Video Generation',
+ 'ModelSwitchPanel.detail.pricing.unit.videoInput': 'Video Input',
'ModelSwitchPanel.detail.releasedAt': 'Released {{date}}',
'ModelSwitchPanel.emptyModel': 'No enabled model. Please go to settings to enable.',
'ModelSwitchPanel.emptyProvider': 'No enabled providers. Please go to settings to enable one.',
diff --git a/src/server/globalConfig/index.ts b/src/server/globalConfig/index.ts
index 65ce017a762..18e03be9163 100644
--- a/src/server/globalConfig/index.ts
+++ b/src/server/globalConfig/index.ts
@@ -8,6 +8,7 @@ import { fileEnv } from '@/envs/file';
import { imageEnv } from '@/envs/image';
import { knowledgeEnv } from '@/envs/knowledge';
import { langfuseEnv } from '@/envs/langfuse';
+import { toolsEnv } from '@/envs/tools';
import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { parseSystemAgent } from '@/server/globalConfig/parseSystemAgent';
import { type GlobalServerConfig } from '@/types/serverConfig';
@@ -84,6 +85,17 @@ export const getServerGlobalConfig = async () => {
appEnv.MARKET_TRUSTED_CLIENT_SECRET && appEnv.MARKET_TRUSTED_CLIENT_ID
),
enableUploadFileToServer: !!fileEnv.S3_SECRET_ACCESS_KEY,
+ enableVisualUnderstanding: !!(
+ toolsEnv.VISUAL_UNDERSTANDING_PROVIDER && toolsEnv.VISUAL_UNDERSTANDING_MODEL
+ ),
+ ...(toolsEnv.VISUAL_UNDERSTANDING_PROVIDER && toolsEnv.VISUAL_UNDERSTANDING_MODEL
+ ? {
+ visualUnderstanding: {
+ model: toolsEnv.VISUAL_UNDERSTANDING_MODEL,
+ provider: toolsEnv.VISUAL_UNDERSTANDING_PROVIDER,
+ },
+ }
+ : undefined),
// Expose Agent Gateway URL to client when queue-based agent runtime is enabled
...(appEnv.enableQueueAgentRuntime && appEnv.AGENT_GATEWAY_URL
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index dfd6418995c..77e844aef2c 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -524,9 +524,9 @@ export const createRuntimeExecutors = (
return info?.abilities?.functionCall ?? true;
},
isCanUseVideo: (m: string, p: string) => {
- const info = LOBE_DEFAULT_MODEL_LIST.find(
- (item) => item.id === m && item.providerId === p,
- );
+ const info =
+ LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === m && item.providerId === p) ??
+ LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === m);
return info?.abilities?.video ?? false;
},
isCanUseVision: (m: string, p: string) => {
@@ -1541,12 +1541,14 @@ export const createRuntimeExecutors = (
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
documentId: state.metadata?.documentId,
+ groupId: state.metadata?.groupId,
memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
operationId,
scope: state.metadata?.scope,
serverDB: ctx.serverDB,
taskId: state.metadata?.taskId,
+ threadId: state.metadata?.threadId,
toolCallId: chatToolPayload.id,
toolManifestMap: effectiveManifestMap,
toolResultMaxLength,
@@ -1978,12 +1980,14 @@ export const createRuntimeExecutors = (
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
documentId: state.metadata?.documentId,
+ groupId: state.metadata?.groupId,
memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
operationId,
scope: state.metadata?.scope,
serverDB: ctx.serverDB,
taskId: state.metadata?.taskId,
+ threadId: state.metadata?.threadId,
toolCallId: chatToolPayload.id,
toolManifestMap: batchManifestMap,
toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,
diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index b5af32c04bc..96ad15ba315 100644
--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -43,6 +43,11 @@ vi.mock('model-bank', () => ({
id: 'no-tools-model',
providerId: 'test-provider',
},
+ {
+ abilities: { functionCall: true, video: true, vision: true },
+ id: 'gemini-3.1-flash-lite-preview',
+ providerId: 'google',
+ },
],
}));
@@ -1181,8 +1186,11 @@ describe('RuntimeExecutors', () => {
expect(callArgs.capabilities.isCanUseVideo('unknown', 'unknown')).toBe(false);
// Aggregator (e.g. lobehub) routes a known model id under a different
- // provider — vision flag falls back to the upstream model card.
+ // provider — visual capability flags fall back to the upstream model card.
expect(callArgs.capabilities.isCanUseVision('gpt-4', 'lobehub')).toBe(true);
+ expect(
+ callArgs.capabilities.isCanUseVideo('gemini-3.1-flash-lite-preview', 'lobehub'),
+ ).toBe(true);
expect(callArgs.capabilities.isCanUseVision('no-tools-model', 'lobehub')).toBe(false);
});
diff --git a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
index 27e4fc11399..0faea45b093 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
@@ -211,6 +212,40 @@ describe('createServerAgentToolsEngine', () => {
expect(result.enabledToolIds).not.toContain(WebBrowsingManifest.identifier);
});
+ it('should enable VisualUnderstanding when injected into runtime plugins', () => {
+ const context = createMockContext();
+ const engine = createServerAgentToolsEngine(context, {
+ agentConfig: { plugins: [LobeAgentManifest.identifier] },
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ });
+
+ const result = engine.generateToolsDetailed({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [LobeAgentManifest.identifier],
+ });
+
+ expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
+ });
+
+ it('should not enable VisualUnderstanding by default', () => {
+ const context = createMockContext();
+ const engine = createServerAgentToolsEngine(context, {
+ agentConfig: { plugins: [] },
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ });
+
+ const result = engine.generateToolsDetailed({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [],
+ });
+
+ expect(result.enabledToolIds).not.toContain(LobeAgentManifest.identifier);
+ });
+
it('should enable KnowledgeBase when hasEnabledKnowledgeBases is true', () => {
const context = createMockContext();
const engine = createServerAgentToolsEngine(context, {
diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.ts
index f91efc6c7fc..9dec2895ef8 100644
--- a/src/server/modules/Mecha/ContextEngineering/index.ts
+++ b/src/server/modules/Mecha/ContextEngineering/index.ts
@@ -89,8 +89,8 @@ export const serverMessagesEngine = async ({
// Agent configuration
enableHistoryCount,
- // File context configuration (server always includes file URLs)
- fileContext: { enabled: true, includeFileUrl: true },
+ // File context refs must stay stable; media URLs are sent through structured parts.
+ fileContext: { enabled: true, includeFileUrl: false },
// Force finish mode (inject summary prompt when maxSteps exceeded)
forceFinish,
diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index f1e8eab409c..06325020d2e 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -6,14 +6,28 @@ import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
import { AiAgentService } from '../index';
-const { mockCreateOperation, mockGetAgentConfig, mockMessageCreate, mockResolveTask } = vi.hoisted(
- () => ({
- mockCreateOperation: vi.fn(),
- mockGetAgentConfig: vi.fn(),
- mockMessageCreate: vi.fn(),
- mockResolveTask: vi.fn(),
- }),
-);
+const {
+ mockCreateOperation,
+ mockGetAgentConfig,
+ mockMessageCreate,
+ mockMessageQuery,
+ mockResolveTask,
+ mockToolsEnv,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn(),
+ mockResolveTask: vi.fn(),
+ mockToolsEnv: {
+ VISUAL_UNDERSTANDING_MODEL: undefined as string | undefined,
+ VISUAL_UNDERSTANDING_PROVIDER: undefined as string | undefined,
+ },
+}));
+
+vi.mock('@/envs/tools', () => ({
+ toolsEnv: mockToolsEnv,
+}));
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -24,7 +38,7 @@ vi.mock('@/libs/trusted-client', () => ({
vi.mock('@/database/models/message', () => ({
MessageModel: vi.fn().mockImplementation(() => ({
create: mockMessageCreate,
- query: vi.fn().mockResolvedValue([]),
+ query: mockMessageQuery,
update: vi.fn().mockResolvedValue({}),
})),
}));
@@ -88,6 +102,7 @@ vi.mock('@/server/services/klavis', () => ({
vi.mock('@/server/services/file', () => ({
FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: (path: string | null) => Promise.resolve(path || ''),
uploadFromUrl: vi.fn(),
})),
}));
@@ -117,6 +132,16 @@ vi.mock('model-bank', async (importOriginal) => {
id: 'gpt-4',
providerId: 'openai',
},
+ {
+ abilities: { functionCall: true, video: false, vision: false },
+ id: 'text-only',
+ providerId: 'openai',
+ },
+ {
+ abilities: { functionCall: true, video: true, vision: true },
+ id: 'gemini-3.1-flash-lite-preview',
+ providerId: 'google',
+ },
],
};
});
@@ -129,7 +154,10 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
beforeEach(() => {
vi.clearAllMocks();
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageQuery.mockResolvedValue([]);
mockResolveTask.mockResolvedValue(null);
+ mockToolsEnv.VISUAL_UNDERSTANDING_MODEL = 'vision-model';
+ mockToolsEnv.VISUAL_UNDERSTANDING_PROVIDER = 'test-provider';
mockCreateOperation.mockResolvedValue({
autoStarted: true,
messageId: 'queue-msg-1',
@@ -300,4 +328,64 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
'Default Lobe AI agent id: agt_inbox',
);
});
+
+ it('should inject lobe-agent when history has visual media and model lacks vision', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-custom',
+ model: 'text-only',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ });
+ mockMessageQuery.mockResolvedValue([
+ {
+ id: 'history-image',
+ imageList: [{ alt: 'image.png', id: 'file-image', url: 'https://example.com/image.png' }],
+ role: 'user',
+ },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-custom',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'What is in the previous image?',
+ });
+
+ expect(createServerAgentToolsEngine).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ agentConfig: expect.objectContaining({
+ plugins: expect.arrayContaining(['lobe-agent']),
+ }),
+ }),
+ );
+ });
+
+ it('should not inject lobe-agent when the LobeHub routed model supports visual media natively', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-custom',
+ model: 'gemini-3.1-flash-lite-preview',
+ plugins: [],
+ provider: 'lobehub',
+ systemRole: '',
+ });
+ mockMessageQuery.mockResolvedValue([
+ {
+ id: 'history-video',
+ role: 'user',
+ videoList: [{ id: 'file-video', url: 'https://example.com/video.mp4' }],
+ },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-custom',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'What is in the previous video?',
+ });
+
+ const callArgs = vi.mocked(createServerAgentToolsEngine).mock.calls[0][1];
+ expect(callArgs.agentConfig.plugins).not.toContain('lobe-agent');
+ });
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 3bb1e2b6ff8..42a7f02ecc7 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -1,6 +1,7 @@
import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';
import { builtinSkills } from '@lobechat/builtin-skills';
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
@@ -49,6 +50,7 @@ import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
+import { toolsEnv } from '@/envs/tools';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
import {
@@ -100,6 +102,35 @@ function formatErrorForMetadata(error: unknown): Record<string, any> | undefined
return { message: String(error) };
}
+const getVisualAvailabilityFromFileTypes = (fileTypes: string[]) => ({
+ hasImages: fileTypes.some((fileType) => fileType.startsWith('image')),
+ hasVideos: fileTypes.some((fileType) => fileType.startsWith('video')),
+});
+
+interface VisualAvailabilityMessage {
+ imageList?: unknown[];
+ role?: string;
+ videoList?: unknown[];
+}
+
+const getVisualAvailabilityFromMessages = (messages: VisualAvailabilityMessage[]) => ({
+ hasImages: messages.some(
+ (message) => message.role === 'user' && (message.imageList?.length ?? 0) > 0,
+ ),
+ hasVideos: messages.some(
+ (message) => message.role === 'user' && (message.videoList?.length ?? 0) > 0,
+ ),
+});
+
+const isVisualUnderstandingConfigured = () => {
+ try {
+ return !!toolsEnv.VISUAL_UNDERSTANDING_PROVIDER && !!toolsEnv.VISUAL_UNDERSTANDING_MODEL;
+ } catch {
+ // The env proxy rejects server-only keys in client-like runtimes; treat that as disabled.
+ return false;
+ }
+};
+
/**
* Internal params for execAgent with step lifecycle callbacks
* This extends the public ExecAgentParams with server-side only options
@@ -632,6 +663,40 @@ export class AiAgentService {
// model-bank is needed both for tool support check and model metadata
const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');
+ // Resolve S3 keys in imageList/videoList before visual tool activation checks and context build.
+ const fileService = new FileService(this.db, this.userId);
+ const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);
+ let historyMessagesCache: any[] | undefined;
+ const loadHistoryMessages = async () => {
+ if (historyMessagesCache) return historyMessagesCache;
+
+ if (existingMessageIds.length > 0) {
+ const messages = await this.messageModel.query(
+ {
+ sessionId: appContext?.sessionId,
+ threadId: appContext?.threadId,
+ topicId: appContext?.topicId ?? undefined,
+ },
+ { postProcessUrl },
+ );
+ const idSet = new Set(existingMessageIds);
+ historyMessagesCache = messages.filter((msg) => idSet.has(msg.id));
+ } else if (appContext?.topicId) {
+ // Follow-up message in existing topic: load all history for context.
+ historyMessagesCache = await this.messageModel.query(
+ {
+ sessionId: appContext?.sessionId,
+ threadId: appContext?.threadId,
+ topicId: appContext?.topicId,
+ },
+ { postProcessUrl },
+ );
+ } else {
+ historyMessagesCache = [];
+ }
+
+ return historyMessagesCache;
+ };
if (params.disableTools) {
log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');
@@ -698,12 +763,44 @@ export class AiAgentService {
isModelSupportToolUse,
};
- // Dynamically inject topic-reference tool when prompt contains <refer_topic> tags
+ // Dynamically inject turn-scoped builtin tools.
const hasTopicReference = /refer_topic/.test(prompt ?? '');
+ const modelAbilities =
+ LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === model && item.providerId === provider)
+ ?.abilities ?? LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === model)?.abilities;
+ const externalFileTypes = files?.map((file) => file.mimeType ?? '') ?? [];
+ let attachedFileTypes: string[] = [];
+ if (attachedFileIds && attachedFileIds.length > 0) {
+ const fileModel = new FileModel(this.db, this.userId);
+ const fileRecords = await fileModel.findByIds(Array.from(new Set(attachedFileIds)));
+ attachedFileTypes = fileRecords.map((file) => file.fileType || '');
+ }
+ const inputFileTypes = [...externalFileTypes, ...attachedFileTypes];
+ const inputVisualAvailability = getVisualAvailabilityFromFileTypes(inputFileTypes);
+ let historyVisualAvailability = { hasImages: false, hasVideos: false };
+ const visualUnderstandingConfigured = isVisualUnderstandingConfigured();
+
+ if (
+ visualUnderstandingConfigured &&
+ ((!modelAbilities?.vision && !inputVisualAvailability.hasImages) ||
+ (!modelAbilities?.video && !inputVisualAvailability.hasVideos))
+ ) {
+ historyVisualAvailability = getVisualAvailabilityFromMessages(await loadHistoryMessages());
+ }
+
+ const needsImageUnderstanding =
+ (inputVisualAvailability.hasImages || historyVisualAvailability.hasImages) &&
+ !modelAbilities?.vision;
+ const needsVideoUnderstanding =
+ (inputVisualAvailability.hasVideos || historyVisualAvailability.hasVideos) &&
+ !modelAbilities?.video;
+ const shouldEnableVisualUnderstanding =
+ visualUnderstandingConfigured && (needsImageUnderstanding || needsVideoUnderstanding);
agentPlugins = [
...agentPlugins,
...(hasTopicReference ? ['lobe-topic-reference'] : []),
...(isBotConversation ? [MessageToolIdentifier] : []),
+ ...(shouldEnableVisualUnderstanding ? [LobeAgentManifest.identifier] : []),
];
// Derive activeDeviceId from device context:
@@ -744,14 +841,14 @@ export class AiAgentService {
// 5f. Generate tools and manifest map
const pluginIds = [
- ...(agentConfig.plugins || []),
- ...(additionalPluginIds || []),
- LocalSystemManifest.identifier,
- RemoteDeviceManifest.identifier,
- ...(isBotConversation ? [MessageToolIdentifier] : []),
- // Include LobeHub Skills and Klavis tools so they are passed to generateToolsDetailed
- ...lobehubSkillManifests.map((m) => m.identifier),
- ...klavisManifests.map((m) => m.identifier),
+ ...new Set([
+ ...agentPlugins,
+ LocalSystemManifest.identifier,
+ RemoteDeviceManifest.identifier,
+ // Include LobeHub Skills and Klavis tools so they are passed to generateToolsDetailed
+ ...lobehubSkillManifests.map((m) => m.identifier),
+ ...klavisManifests.map((m) => m.identifier),
+ ]),
];
log('execAgent: agent configured plugins: %O', pluginIds);
@@ -1085,35 +1182,8 @@ export class AiAgentService {
}
}
- // 11. Get existing messages if provided
- // Use postProcessUrl to resolve S3 keys in imageList to publicly accessible URLs,
- // matching the frontend flow in aiChatService.getMessagesAndTopics.
- const fileService = new FileService(this.db, this.userId);
- const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);
-
- let historyMessages: any[] = [];
- if (existingMessageIds.length > 0) {
- historyMessages = await this.messageModel.query(
- {
- sessionId: appContext?.sessionId,
- threadId: appContext?.threadId,
- topicId: appContext?.topicId ?? undefined,
- },
- { postProcessUrl },
- );
- const idSet = new Set(existingMessageIds);
- historyMessages = historyMessages.filter((msg) => idSet.has(msg.id));
- } else if (appContext?.topicId) {
- // Follow-up message in existing topic: load all history for context
- historyMessages = await this.messageModel.query(
- {
- sessionId: appContext?.sessionId,
- threadId: appContext?.threadId,
- topicId: appContext?.topicId,
- },
- { postProcessUrl },
- );
- }
+ // 11. Get existing messages if provided.
+ const historyMessages = await loadHistoryMessages();
await throwIfExecutionAborted('message history loading');
diff --git a/src/server/services/file/impls/s3.test.ts b/src/server/services/file/impls/s3.test.ts
index f99f4011a9c..af8003ce00d 100644
--- a/src/server/services/file/impls/s3.test.ts
+++ b/src/server/services/file/impls/s3.test.ts
@@ -4,10 +4,21 @@ import { FileModel } from '@/database/models/file';
import { S3StaticFileImpl } from './s3';
+const redisMocks = vi.hoisted(() => ({
+ getRedisConfig: vi.fn(() => ({ enabled: false, prefix: 'lobechat', tls: false, url: '' })),
+ initializeRedis: vi.fn(),
+ isRedisEnabled: vi.fn(() => false),
+ redis: {
+ get: vi.fn(),
+ set: vi.fn(),
+ },
+}));
+
const config = {
S3_ENABLE_PATH_STYLE: false,
S3_PUBLIC_DOMAIN: 'https://example.com',
S3_BUCKET: 'my-bucket',
+ S3_PREVIEW_URL_EXPIRE_IN: 7200,
S3_SET_ACL: true,
};
@@ -18,6 +29,15 @@ vi.mock('@/envs/file', () => ({
},
}));
+vi.mock('@/envs/redis', () => ({
+ getRedisConfig: redisMocks.getRedisConfig,
+}));
+
+vi.mock('@/libs/redis', () => ({
+ initializeRedis: redisMocks.initializeRedis,
+ isRedisEnabled: redisMocks.isRedisEnabled,
+}));
+
// 模拟 S3 类
vi.mock('@/server/modules/S3', () => ({
FileS3: vi.fn().mockImplementation(() => ({
@@ -42,6 +62,20 @@ describe('S3StaticFileImpl', () => {
let fileService: S3StaticFileImpl;
beforeEach(() => {
+ vi.clearAllMocks();
+ config.S3_ENABLE_PATH_STYLE = false;
+ config.S3_PUBLIC_DOMAIN = 'https://example.com';
+ config.S3_SET_ACL = true;
+ redisMocks.getRedisConfig.mockReturnValue({
+ enabled: false,
+ prefix: 'lobechat',
+ tls: false,
+ url: '',
+ });
+ redisMocks.isRedisEnabled.mockReturnValue(false);
+ redisMocks.initializeRedis.mockResolvedValue(redisMocks.redis as any);
+ redisMocks.redis.get.mockResolvedValue(null);
+ redisMocks.redis.set.mockResolvedValue('OK');
fileService = new S3StaticFileImpl(mockDb);
});
@@ -58,6 +92,61 @@ describe('S3StaticFileImpl', () => {
config.S3_SET_ACL = true;
});
+ it('should reuse cached presigned preview URL for repeated private preview requests', async () => {
+ config.S3_SET_ACL = false;
+ const url = 'path/to/cached-file.jpg';
+ const createPreSignedUrlForPreview = fileService['s3'].createPreSignedUrlForPreview;
+
+ await expect(fileService.getFullFileUrl(url)).resolves.toBe(
+ 'https://presigned.example.com/test.jpg',
+ );
+ await expect(fileService.getFullFileUrl(url)).resolves.toBe(
+ 'https://presigned.example.com/test.jpg',
+ );
+
+ expect(createPreSignedUrlForPreview).toHaveBeenCalledTimes(1);
+ config.S3_SET_ACL = true;
+ });
+
+ it('should reuse Redis cached presigned preview URL across function instances', async () => {
+ config.S3_SET_ACL = false;
+ redisMocks.getRedisConfig.mockReturnValue({
+ enabled: true,
+ prefix: 'lobechat',
+ tls: false,
+ url: 'redis://localhost:6379',
+ });
+ redisMocks.isRedisEnabled.mockReturnValue(true);
+ redisMocks.redis.get.mockResolvedValue('https://redis.example.com/cached.jpg');
+
+ const result = await fileService.getFullFileUrl('path/to/redis-cached-file.jpg');
+
+ expect(result).toBe('https://redis.example.com/cached.jpg');
+ expect(fileService['s3'].createPreSignedUrlForPreview).not.toHaveBeenCalled();
+ });
+
+ it('should write generated presigned preview URL to Redis when available', async () => {
+ config.S3_SET_ACL = false;
+ redisMocks.getRedisConfig.mockReturnValue({
+ enabled: true,
+ prefix: 'lobechat',
+ tls: false,
+ url: 'redis://localhost:6379',
+ });
+ redisMocks.isRedisEnabled.mockReturnValue(true);
+ redisMocks.redis.get.mockResolvedValue(null);
+
+ await expect(fileService.getFullFileUrl('path/to/redis-write-file.jpg')).resolves.toBe(
+ 'https://presigned.example.com/test.jpg',
+ );
+
+ expect(redisMocks.redis.set).toHaveBeenCalledWith(
+ 'file:presigned-preview:7200:path/to/redis-write-file.jpg',
+ 'https://presigned.example.com/test.jpg',
+ { ex: 3600 },
+ );
+ });
+
it('should return correct URL when S3_ENABLE_PATH_STYLE is false', async () => {
const url = 'path/to/file.jpg';
expect(await fileService.getFullFileUrl(url)).toBe('https://example.com/path/to/file.jpg');
diff --git a/src/server/services/file/impls/s3.ts b/src/server/services/file/impls/s3.ts
index 7d8b91e413c..98eeee7656c 100644
--- a/src/server/services/file/impls/s3.ts
+++ b/src/server/services/file/impls/s3.ts
@@ -1,12 +1,37 @@
import { type LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
import urlJoin from 'url-join';
import { FileModel } from '@/database/models/file';
import { fileEnv } from '@/envs/file';
+import { getRedisConfig } from '@/envs/redis';
+import { initializeRedis, isRedisEnabled } from '@/libs/redis';
import { FileS3 } from '@/server/modules/S3';
import { type FileServiceImpl } from './type';
+const log = debug('lobe-file:s3');
+
+const PRESIGNED_PREVIEW_CACHE_SAFETY_SECONDS = 60;
+const PRESIGNED_PREVIEW_CACHE_MAX_SECONDS = 3600;
+const PRESIGNED_PREVIEW_CACHE_KEY_PREFIX = 'file:presigned-preview:';
+
+interface PresignedPreviewCacheEntry {
+ expiresAt: number;
+ url: string;
+}
+
+const presignedPreviewUrlCache = new Map<string, PresignedPreviewCacheEntry>();
+
+const createPresignedPreviewCacheKey = (key: string, expiresIn: number) =>
+ `${PRESIGNED_PREVIEW_CACHE_KEY_PREFIX}${expiresIn}:${key}`;
+
+const getPresignedPreviewCacheTtlSeconds = (expiresInSeconds: number) =>
+ Math.min(
+ Math.max(expiresInSeconds - PRESIGNED_PREVIEW_CACHE_SAFETY_SECONDS, 0),
+ PRESIGNED_PREVIEW_CACHE_MAX_SECONDS,
+ );
+
/**
* S3-based file service implementation
*/
@@ -47,6 +72,56 @@ export class S3StaticFileImpl implements FileServiceImpl {
return this.s3.createPreSignedUrlForPreview(key, expiresIn);
}
+ private async getCachedPreSignedUrlForPreview(key: string, expiresIn?: number): Promise<string> {
+ const expiresInSeconds = expiresIn ?? fileEnv.S3_PREVIEW_URL_EXPIRE_IN;
+ const cacheKey = createPresignedPreviewCacheKey(key, expiresInSeconds);
+ const ttlSeconds = getPresignedPreviewCacheTtlSeconds(expiresInSeconds);
+ const now = Date.now();
+ const cached = presignedPreviewUrlCache.get(cacheKey);
+
+ if (cached && cached.expiresAt > now) {
+ return cached.url;
+ }
+
+ try {
+ const redisConfig = getRedisConfig();
+ const redis = isRedisEnabled(redisConfig) ? await initializeRedis(redisConfig) : null;
+ const cachedUrl = await redis?.get(cacheKey);
+
+ if (cachedUrl) {
+ if (ttlSeconds > 0) {
+ presignedPreviewUrlCache.set(cacheKey, {
+ expiresAt: now + ttlSeconds * 1000,
+ url: cachedUrl,
+ });
+ }
+
+ return cachedUrl;
+ }
+ } catch (error) {
+ log('Failed to read presigned preview URL cache from Redis: %O', error);
+ }
+
+ const url = await this.createPreSignedUrlForPreview(key, expiresIn);
+
+ if (ttlSeconds > 0) {
+ presignedPreviewUrlCache.set(cacheKey, {
+ expiresAt: now + ttlSeconds * 1000,
+ url,
+ });
+
+ try {
+ const redisConfig = getRedisConfig();
+ const redis = isRedisEnabled(redisConfig) ? await initializeRedis(redisConfig) : null;
+ await redis?.set(cacheKey, url, { ex: ttlSeconds });
+ } catch (error) {
+ log('Failed to write presigned preview URL cache to Redis: %O', error);
+ }
+ }
+
+ return url;
+ }
+
async uploadContent(path: string, content: string) {
return this.s3.uploadContent(path, content);
}
@@ -66,9 +141,10 @@ export class S3StaticFileImpl implements FileServiceImpl {
}
// If bucket is not set public read, or S3_PUBLIC_DOMAIN is not configured,
- // the preview address needs to be regenerated each time via presigned URL
+ // reuse the same presigned preview URL briefly so repeated chat turns keep
+ // stable media URLs and can reuse provider-side prefix caches.
if (!fileEnv.S3_SET_ACL || !fileEnv.S3_PUBLIC_DOMAIN) {
- return await this.createPreSignedUrlForPreview(key, expiresIn);
+ return await this.getCachedPreSignedUrlForPreview(key, expiresIn);
}
if (fileEnv.S3_ENABLE_PATH_STYLE) {
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
new file mode 100644
index 00000000000..8871fe2304c
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
@@ -0,0 +1,453 @@
+import { LobeAgentIdentifier, MAX_VISUAL_MEDIA_URLS } from '@lobechat/builtin-tool-lobe-agent';
+import { createVisualFileRef } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ToolExecutionContext } from '../../types';
+
+const mockToolsEnv = vi.hoisted(() => ({
+ VISUAL_UNDERSTANDING_MODEL: undefined as string | undefined,
+ VISUAL_UNDERSTANDING_PROVIDER: undefined as string | undefined,
+}));
+const mockMessageModelQueryByIds = vi.hoisted(() => vi.fn());
+const mockMessageModelQuery = vi.hoisted(() => vi.fn());
+const mockChat = vi.hoisted(() => vi.fn());
+const mockInitModelRuntimeFromDB = vi.hoisted(() => vi.fn());
+const mockConsumeStreamUntilDone = vi.hoisted(() => vi.fn());
+
+vi.mock('@/envs/tools', () => ({
+ toolsEnv: mockToolsEnv,
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ query: (...args: any[]) => mockMessageModelQuery(...args),
+ queryByIds: (...args: any[]) => mockMessageModelQueryByIds(...args),
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: (path: string | null) => Promise.resolve(path || ''),
+ })),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: (...args: any[]) => mockInitModelRuntimeFromDB(...args),
+}));
+
+vi.mock('@lobechat/model-runtime', () => ({
+ consumeStreamUntilDone: (...args: any[]) => mockConsumeStreamUntilDone(...args),
+}));
+
+vi.mock('model-bank', () => ({
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { video: true, vision: true },
+ id: 'vision-model',
+ providerId: 'test-provider',
+ },
+ {
+ abilities: { video: false, vision: true },
+ id: 'image-only-model',
+ providerId: 'test-provider',
+ },
+ ],
+}));
+
+const { lobeAgentRuntime } = await import('../lobeAgent');
+
+describe('lobeAgentRuntime', () => {
+ const baseContext: ToolExecutionContext = {
+ messageId: 'msg-1',
+ serverDB: {} as any,
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageModelQuery.mockResolvedValue([]);
+ mockToolsEnv.VISUAL_UNDERSTANDING_MODEL = 'vision-model';
+ mockToolsEnv.VISUAL_UNDERSTANDING_PROVIDER = 'test-provider';
+ mockChat.mockImplementation(async (_payload, options) => {
+ options?.callback?.onText?.('visual answer');
+ options?.callback?.onCompletion?.({ usage: { totalTokens: 12 } });
+ return new Response('ok');
+ });
+ mockInitModelRuntimeFromDB.mockResolvedValue({ chat: mockChat });
+ mockConsumeStreamUntilDone.mockResolvedValue(undefined);
+ });
+
+ it('should have the correct identifier', () => {
+ expect(lobeAgentRuntime.identifier).toBe(LobeAgentIdentifier);
+ });
+
+ it('should require serverDB, userId and messageId', () => {
+ expect(() => lobeAgentRuntime.factory({ toolManifestMap: {}, userId: 'user-1' })).toThrow(
+ 'serverDB is required for LobeAgent execution',
+ );
+
+ expect(() => lobeAgentRuntime.factory({ serverDB: {} as any, toolManifestMap: {} })).toThrow(
+ 'userId is required for LobeAgent execution',
+ );
+
+ expect(() =>
+ lobeAgentRuntime.factory({
+ serverDB: {} as any,
+ toolManifestMap: {},
+ userId: 'user-1',
+ }),
+ ).toThrow('messageId is required for LobeAgent execution');
+ });
+
+ it('should return a configuration error when visual model env is missing', async () => {
+ mockToolsEnv.VISUAL_UNDERSTANDING_MODEL = undefined;
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: ['image_1'],
+ question: 'what is this?',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error.code).toBe('VISUAL_UNDERSTANDING_NOT_CONFIGURED');
+ });
+
+ it('should return an error when the source message has no visual files', async () => {
+ mockMessageModelQueryByIds.mockResolvedValue([{ id: 'msg-1' }]);
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: ['image_1'],
+ question: 'what is this?',
+ });
+
+ expect(result).toMatchObject({
+ error: { code: 'NO_VISUAL_FILES' },
+ success: false,
+ });
+ });
+
+ it('should validate requested visual file refs', async () => {
+ mockMessageModelQueryByIds.mockResolvedValue([
+ {
+ id: 'msg-1',
+ imageList: [{ alt: 'image.png', id: 'file-image', url: 'https://example.com/image.png' }],
+ role: 'user',
+ },
+ ]);
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: ['image_1'],
+ question: 'what is this?',
+ });
+
+ const stableImageRef = createVisualFileRef({ index: 0, messageId: 'msg-1', type: 'image' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain(`Available refs: ${stableImageRef}`);
+ expect(result.content).not.toContain(`Available refs: ${stableImageRef}, image_1`);
+ });
+
+ it('should require refs or urls', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({ question: 'what is this?' } as any);
+
+ expect(result).toMatchObject({
+ error: { code: 'INVALID_ARGUMENTS' },
+ success: false,
+ });
+ expect(result.content).toContain('Either refs or urls is required');
+ expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
+ });
+
+ it('should analyze direct media urls without querying message refs', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/generated.png'],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
+ expect(result.state).toMatchObject({
+ files: [{ name: 'generated.png', ref: 'url_1', type: 'image' }],
+ });
+ expect(mockChat).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [
+ expect.objectContaining({
+ content: [
+ expect.objectContaining({ type: 'text' }),
+ expect.objectContaining({
+ image_url: { detail: 'auto', url: 'https://example.com/generated.png' },
+ type: 'image_url',
+ }),
+ ],
+ }),
+ ],
+ }),
+ expect.anything(),
+ );
+ });
+
+ it('should reject unsupported direct media url protocols', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ question: 'what is this?',
+ urls: [
+ 'data:text/plain;base64,abcd',
+ 'file:///private/image.png',
+ 'ftp://example.com/image.png',
+ ],
+ });
+
+ expect(result).toMatchObject({
+ error: { code: 'UNSUPPORTED_VISUAL_MEDIA_URLS' },
+ success: false,
+ });
+ expect(result.content).toContain('Only http:, https:, data:image/* and data:video/* URLs');
+ expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
+ expect(mockChat).not.toHaveBeenCalled();
+ });
+
+ it('should reject too many direct media urls before querying message refs', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ question: 'what is this?',
+ urls: Array.from(
+ { length: MAX_VISUAL_MEDIA_URLS + 1 },
+ (_, index) => `https://example.com/${index}.png`,
+ ),
+ });
+
+ expect(result).toMatchObject({
+ error: { code: 'UNSUPPORTED_VISUAL_MEDIA_URLS' },
+ success: false,
+ });
+ expect(result.content).toContain(`At most ${MAX_VISUAL_MEDIA_URLS} URLs are supported`);
+ expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
+ expect(mockChat).not.toHaveBeenCalled();
+ });
+
+ it('should allow http and visual data direct media urls', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeVisualMedia({
+ question: 'what is this?',
+ urls: ['http://example.com/generated.png', 'data:image/png;base64,abcd'],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
+ expect(mockChat).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [
+ expect.objectContaining({
+ content: [
+ expect.objectContaining({ type: 'text' }),
+ expect.objectContaining({
+ image_url: { detail: 'auto', url: 'http://example.com/generated.png' },
+ type: 'image_url',
+ }),
+ expect.objectContaining({
+ image_url: { detail: 'auto', url: 'data:image/png;base64,abcd' },
+ type: 'image_url',
+ }),
+ ],
+ }),
+ ],
+ }),
+ expect.anything(),
+ );
+ });
+
+ it('should resolve stable refs from earlier topic messages', async () => {
+ const previousImageRef = createVisualFileRef({
+ index: 0,
+ messageId: 'msg-previous',
+ type: 'image',
+ });
+ mockMessageModelQueryByIds.mockResolvedValue([
+ {
+ id: 'msg-1',
+ imageList: [
+ { alt: 'current.png', id: 'file-current', url: 'https://example.com/current.png' },
+ ],
+ role: 'user',
+ },
+ ]);
+ mockMessageModelQuery.mockResolvedValue([
+ {
+ id: 'msg-previous',
+ imageList: [
+ { alt: 'previous.png', id: 'file-previous', url: 'https://example.com/previous.png' },
+ ],
+ role: 'user',
+ },
+ {
+ id: 'msg-1',
+ imageList: [
+ { alt: 'current.png', id: 'file-current', url: 'https://example.com/current.png' },
+ ],
+ role: 'user',
+ },
+ ]);
+ const runtime = lobeAgentRuntime.factory({ ...baseContext, topicId: 'topic-1' });
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: [previousImageRef],
+ question: 'what was in the earlier image?',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockMessageModelQuery).toHaveBeenCalledWith(
+ { topicId: 'topic-1' },
+ expect.objectContaining({ postProcessUrl: expect.any(Function) }),
+ );
+ expect(result.state).toMatchObject({
+ files: [{ id: 'file-previous', name: 'previous.png', ref: previousImageRef, type: 'image' }],
+ });
+ expect(mockChat).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [
+ expect.objectContaining({
+ content: [
+ expect.objectContaining({ type: 'text' }),
+ expect.objectContaining({
+ image_url: { detail: 'auto', url: 'https://example.com/previous.png' },
+ type: 'image_url',
+ }),
+ ],
+ }),
+ ],
+ }),
+ expect.anything(),
+ );
+ });
+
+ it('should use the source thread scope when resolving stable refs', async () => {
+ const previousImageRef = createVisualFileRef({
+ index: 0,
+ messageId: 'msg-previous',
+ type: 'image',
+ });
+ mockMessageModelQueryByIds.mockResolvedValue([
+ {
+ id: 'msg-1',
+ role: 'user',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ ]);
+ mockMessageModelQuery.mockResolvedValue([
+ {
+ id: 'msg-previous',
+ imageList: [
+ { alt: 'previous.png', id: 'file-previous', url: 'https://example.com/previous.png' },
+ ],
+ role: 'user',
+ },
+ ]);
+ const runtime = lobeAgentRuntime.factory({ ...baseContext, topicId: 'topic-1' });
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: [previousImageRef],
+ question: 'what was in the earlier image?',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockMessageModelQuery).toHaveBeenCalledWith(
+ { threadId: 'thread-1', topicId: 'topic-1' },
+ expect.objectContaining({ postProcessUrl: expect.any(Function) }),
+ );
+ });
+
+ it('should not fall back to scoped visual messages when refs and urls are omitted', async () => {
+ const runtime = lobeAgentRuntime.factory({ ...baseContext, topicId: 'topic-1' });
+
+ const result = await runtime.analyzeVisualMedia({
+ question: 'Does the person in the first image wear glasses?',
+ } as any);
+
+ expect(result).toMatchObject({
+ error: { code: 'INVALID_ARGUMENTS' },
+ success: false,
+ });
+ expect(mockMessageModelQuery).not.toHaveBeenCalled();
+ });
+
+ it('should use group, agent and legacy session scopes when resolving stable refs', async () => {
+ const cases = [
+ {
+ expectedQuery: { groupId: 'group-1', topicId: 'topic-1' },
+ sourceMessage: { groupId: 'group-1', id: 'msg-1', role: 'user', topicId: 'topic-1' },
+ },
+ {
+ expectedQuery: { agentId: 'agent-1', topicId: 'topic-1' },
+ sourceMessage: { agentId: 'agent-1', id: 'msg-1', role: 'user', topicId: 'topic-1' },
+ },
+ {
+ expectedQuery: { sessionId: 'session-1', topicId: 'topic-1' },
+ sourceMessage: { id: 'msg-1', role: 'user', sessionId: 'session-1', topicId: 'topic-1' },
+ },
+ ];
+
+ for (const { expectedQuery, sourceMessage } of cases) {
+ vi.clearAllMocks();
+ mockMessageModelQueryByIds.mockResolvedValue([sourceMessage]);
+ mockMessageModelQuery.mockResolvedValue([
+ {
+ id: 'msg-previous',
+ imageList: [
+ { alt: 'previous.png', id: 'file-previous', url: 'https://example.com/previous.png' },
+ ],
+ role: 'user',
+ },
+ ]);
+ mockInitModelRuntimeFromDB.mockResolvedValue({ chat: mockChat });
+ mockConsumeStreamUntilDone.mockResolvedValue(undefined);
+
+ const runtime = lobeAgentRuntime.factory({ ...baseContext, topicId: 'topic-1' });
+ const result = await runtime.analyzeVisualMedia({
+ refs: [createVisualFileRef({ index: 0, messageId: 'msg-previous', type: 'image' })],
+ question: 'what was in the earlier image?',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockMessageModelQuery).toHaveBeenCalledWith(
+ expectedQuery,
+ expect.objectContaining({ postProcessUrl: expect.any(Function) }),
+ );
+ }
+ });
+
+ it('should reject video files when the configured model lacks video support', async () => {
+ mockToolsEnv.VISUAL_UNDERSTANDING_MODEL = 'image-only-model';
+ mockMessageModelQueryByIds.mockResolvedValue([
+ {
+ id: 'msg-1',
+ role: 'user',
+ videoList: [{ alt: 'video.mp4', id: 'file-video', url: 'https://example.com/video.mp4' }],
+ },
+ ]);
+ const runtime = lobeAgentRuntime.factory(baseContext);
+ const stableVideoRef = createVisualFileRef({ index: 0, messageId: 'msg-1', type: 'video' });
+
+ const result = await runtime.analyzeVisualMedia({
+ refs: [stableVideoRef],
+ question: 'what is in the video?',
+ });
+
+ expect(result).toMatchObject({
+ error: { code: 'VISUAL_MODEL_VIDEO_UNSUPPORTED' },
+ success: false,
+ });
+ expect(mockChat).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index 10264e9874d..c141698c79b 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -16,6 +16,7 @@ import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
import { cronRuntime } from './cron';
import { gtdRuntime } from './gtd';
+import { lobeAgentRuntime } from './lobeAgent';
import { localSystemRuntime } from './localSystem';
import { memoryRuntime } from './memory';
import { messageRuntime } from './message';
@@ -67,6 +68,7 @@ registerRuntimes([
gtdRuntime,
webOnboardingRuntime,
agentMarketplaceRuntime,
+ lobeAgentRuntime,
]);
// ==================== Registry API ====================
diff --git a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts
new file mode 100644
index 00000000000..a19afd568af
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -0,0 +1,294 @@
+import type { VisualFileItem, VisualSourceMessage } from '@lobechat/builtin-tool-lobe-agent';
+import {
+ buildAnalyzeVisualMediaContent,
+ createUrlVisualFileItems,
+ createVisualFileItems,
+ formatVisualMediaUrlValidationError,
+ hasUserVisualFiles,
+ LobeAgentIdentifier,
+ normalizeAnalyzeVisualMediaInput,
+ selectVisualFileItems,
+ validateVisualMediaUrls,
+} from '@lobechat/builtin-tool-lobe-agent';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ChatStreamPayload } from '@lobechat/model-runtime';
+import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+
+import { MessageModel } from '@/database/models/message';
+import { toolsEnv } from '@/envs/tools';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { FileService } from '@/server/services/file';
+
+import type { ServerRuntimeRegistration } from './types';
+
+interface AnalyzeVisualMediaParams {
+ question: string;
+ refs?: string[];
+ urls?: string[];
+}
+
+interface LobeAgentRuntimeContext {
+ agentId?: string | null;
+ groupId?: string | null;
+ messageId: string;
+ serverDB: LobeChatDatabase;
+ threadId?: string | null;
+ topicId?: string;
+ userId: string;
+}
+
+const buildError = (content: string, code: string): BuiltinServerRuntimeOutput => ({
+ content,
+ error: { code, message: content },
+ success: false,
+});
+
+const getModelAbilities = (model: string, provider: string) => {
+ return (
+ LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === model && item.providerId === provider) ??
+ LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === model)
+ )?.abilities;
+};
+
+interface ServerVisualSourceMessage extends VisualSourceMessage {
+ agentId?: string | null;
+ groupId?: string | null;
+ sessionId?: string | null;
+ threadId?: string | null;
+ topicId?: string | null;
+}
+
+class LobeAgentExecutionRuntime {
+ private agentId?: string | null;
+ private db: LobeChatDatabase;
+ private groupId?: string | null;
+ private userId: string;
+ private messageId: string;
+ private threadId?: string | null;
+ private topicId?: string;
+
+ constructor(context: LobeAgentRuntimeContext) {
+ this.agentId = context.agentId;
+ this.db = context.serverDB;
+ this.groupId = context.groupId;
+ this.messageId = context.messageId;
+ this.threadId = context.threadId;
+ this.topicId = context.topicId;
+ this.userId = context.userId;
+ }
+
+ private queryScopeMessages = (
+ messageModel: MessageModel,
+ sourceMessage: ServerVisualSourceMessage,
+ postProcessUrl: (path: string | null, file: { fileType: string }) => Promise<string>,
+ ) => {
+ const topicId = this.topicId ?? sourceMessage.topicId ?? undefined;
+ const threadId = sourceMessage.threadId ?? this.threadId ?? undefined;
+ const groupId = sourceMessage.groupId ?? this.groupId ?? undefined;
+ const agentId = sourceMessage.agentId ?? this.agentId ?? undefined;
+ const sessionId = sourceMessage.sessionId ?? undefined;
+
+ if (threadId) {
+ return messageModel.query({ threadId, topicId }, { postProcessUrl });
+ }
+
+ if (groupId) {
+ return messageModel.query({ groupId, topicId }, { postProcessUrl });
+ }
+
+ if (agentId) {
+ return messageModel.query({ agentId, topicId }, { postProcessUrl });
+ }
+
+ if (sessionId) {
+ return messageModel.query({ sessionId, topicId }, { postProcessUrl });
+ }
+
+ if (topicId) {
+ return messageModel.query({ topicId }, { postProcessUrl });
+ }
+
+ return Promise.resolve([sourceMessage]);
+ };
+
+ analyzeVisualMedia = async (
+ params: AnalyzeVisualMediaParams,
+ ): Promise<BuiltinServerRuntimeOutput> => {
+ const provider = toolsEnv.VISUAL_UNDERSTANDING_PROVIDER;
+ const model = toolsEnv.VISUAL_UNDERSTANDING_MODEL;
+
+ if (!provider || !model) {
+ return buildError(
+ 'Visual understanding is not configured. Set VISUAL_UNDERSTANDING_PROVIDER and VISUAL_UNDERSTANDING_MODEL.',
+ 'VISUAL_UNDERSTANDING_NOT_CONFIGURED',
+ );
+ }
+
+ if (!params.question || typeof params.question !== 'string') {
+ return buildError('question is required.', 'INVALID_ARGUMENTS');
+ }
+
+ const { requestedRefs, requestedUrls } = normalizeAnalyzeVisualMediaInput(
+ params as unknown as Record<PropertyKey, unknown>,
+ );
+ if (requestedRefs.length === 0 && requestedUrls.length === 0) {
+ return buildError(
+ 'Either refs or urls is required and must include at least one visual file ref or media URL.',
+ 'INVALID_ARGUMENTS',
+ );
+ }
+
+ const urlValidation = validateVisualMediaUrls(requestedUrls);
+ const urlValidationError = formatVisualMediaUrlValidationError(urlValidation);
+ if (urlValidationError) {
+ return buildError(urlValidationError, 'UNSUPPORTED_VISUAL_MEDIA_URLS');
+ }
+
+ const selectedUrlItems = createUrlVisualFileItems(urlValidation.validUrls);
+ let selectedRefItems: VisualFileItem[] = [];
+
+ if (requestedRefs.length > 0) {
+ const fileService = new FileService(this.db, this.userId);
+ const messageModel = new MessageModel(this.db, this.userId);
+ const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);
+ const [sourceMessage] = await messageModel.queryByIds([this.messageId], {
+ postProcessUrl,
+ });
+
+ const visualMessages = sourceMessage
+ ? await this.queryScopeMessages(messageModel, sourceMessage, postProcessUrl)
+ : [];
+ const orderedVisualMessages = [
+ ...(sourceMessage && hasUserVisualFiles(sourceMessage) ? [sourceMessage] : []),
+ ...visualMessages.filter(
+ (message) => message.id !== sourceMessage?.id && hasUserVisualFiles(message),
+ ),
+ ];
+
+ if (!sourceMessage) {
+ return buildError(
+ `Source message not found: ${this.messageId}`,
+ 'SOURCE_MESSAGE_NOT_FOUND',
+ );
+ }
+
+ const visualItems = orderedVisualMessages.flatMap((message) =>
+ createVisualFileItems(message, message.imageList, message.videoList),
+ );
+
+ if (visualItems.length === 0) {
+ return buildError(
+ 'No visual files are attached to the current message.',
+ 'NO_VISUAL_FILES',
+ );
+ }
+
+ const { availableRefs, invalidRefs, selected } = selectVisualFileItems(
+ visualItems,
+ requestedRefs,
+ );
+
+ if (invalidRefs.length > 0) {
+ return buildError(
+ `Unknown visual file refs: ${invalidRefs.join(', ')}. Available refs: ${availableRefs.join(', ')}.`,
+ 'UNKNOWN_VISUAL_FILE_REFS',
+ );
+ }
+
+ selectedRefItems = selected;
+ }
+
+ const selectedItems = [...selectedRefItems, ...selectedUrlItems];
+
+ if (selectedItems.length === 0) {
+ return buildError('No visual files selected.', 'NO_VISUAL_FILES_SELECTED');
+ }
+
+ const abilities = getModelAbilities(model, provider);
+ const hasImages = selectedItems.some((item) => item.type === 'image');
+ const hasVideos = selectedItems.some((item) => item.type === 'video');
+
+ if (hasImages && abilities?.vision === false) {
+ return buildError(
+ `Configured visual understanding model "${provider}/${model}" does not support image vision.`,
+ 'VISUAL_MODEL_IMAGE_UNSUPPORTED',
+ );
+ }
+
+ if (hasVideos && abilities?.video === false) {
+ return buildError(
+ `Configured visual understanding model "${provider}/${model}" does not support video understanding.`,
+ 'VISUAL_MODEL_VIDEO_UNSUPPORTED',
+ );
+ }
+
+ let content = '';
+ let usage: unknown;
+ const runtime = await initModelRuntimeFromDB(this.db, this.userId, provider);
+ const payload = {
+ messages: [
+ {
+ content: buildAnalyzeVisualMediaContent(selectedItems, params.question),
+ role: 'user' as const,
+ },
+ ],
+ model,
+ stream: false,
+ } satisfies ChatStreamPayload;
+
+ const response = await runtime.chat(payload, {
+ callback: {
+ onCompletion: (data) => {
+ usage = data.usage;
+ },
+ onText: (text) => {
+ content += text;
+ },
+ },
+ metadata: {
+ trigger: 'lobe-agent.analyzeVisualMedia',
+ },
+ });
+
+ await consumeStreamUntilDone(response);
+
+ return {
+ content: content.trim(),
+ state: {
+ files: selectedItems.map(({ ref, id, type, name }) => ({ id, name, ref, type })),
+ model,
+ provider,
+ trigger: 'lobe-agent.analyzeVisualMedia',
+ usage,
+ },
+ success: true,
+ };
+ };
+}
+
+export const lobeAgentRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.serverDB) {
+ throw new Error('serverDB is required for LobeAgent execution');
+ }
+ if (!context.userId) {
+ throw new Error('userId is required for LobeAgent execution');
+ }
+ if (!context.messageId) {
+ throw new Error('messageId is required for LobeAgent execution');
+ }
+
+ return new LobeAgentExecutionRuntime({
+ agentId: context.agentId,
+ groupId: context.groupId,
+ messageId: context.messageId,
+ serverDB: context.serverDB,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ userId: context.userId,
+ });
+ },
+ identifier: LobeAgentIdentifier,
+};
diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.ts
index 2481c793121..e225be9e4e1 100644
--- a/src/server/services/toolExecution/types.ts
+++ b/src/server/services/toolExecution/types.ts
@@ -9,6 +9,8 @@ export interface ToolExecutionContext {
agentId?: string;
/** Current page document ID for page-scoped conversations */
documentId?: string | null;
+ /** Current group ID for group chat context */
+ groupId?: string | null;
/** Memory tool permission from agent chat config */
memoryToolPermission?: 'read-only' | 'read-write';
/** Source user message ID used by Agent Signal procedure suppression. */
@@ -21,6 +23,8 @@ export interface ToolExecutionContext {
serverDB?: LobeChatDatabase;
/** Task ID when executing within the Task system */
taskId?: string;
+ /** Current thread ID for thread-scoped conversations */
+ threadId?: string | null;
/** Stable LLM tool call ID for structured tool outcome identity. */
toolCallId?: string;
toolManifestMap: Record<string, LobeToolManifest>;
diff --git a/src/services/agentRuntime/__tests__/index.test.ts b/src/services/agentRuntime/__tests__/index.test.ts
index bed4cac6b2c..687bbe9276e 100644
--- a/src/services/agentRuntime/__tests__/index.test.ts
+++ b/src/services/agentRuntime/__tests__/index.test.ts
@@ -104,4 +104,25 @@ describe('AgentRuntimeService', () => {
}),
);
});
+
+ it('should use current agent plugins when creating operation tools', async () => {
+ getAgentStoreStateMock.mockReturnValue({
+ activeAgentId: 'agent-1',
+ });
+
+ await agentRuntimeService.createOperation({
+ messages: [{ id: 'msg-1', content: 'Hello', role: 'user' }] as UIChatMessage[],
+ userMessageId: 'msg-1',
+ });
+
+ expect(createAgentToolsEngineMock).toHaveBeenCalledWith({
+ model: 'gpt-4o',
+ provider: 'openai',
+ });
+ expect(contextEngineeringMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ plugins: ['plugin-1'],
+ }),
+ );
+ });
});
diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.ts
index 4a37381b3e8..f57a7767d0c 100644
--- a/src/services/agentRuntime/index.ts
+++ b/src/services/agentRuntime/index.ts
@@ -42,10 +42,7 @@ class AgentRuntimeService {
provider: agentConfig.provider!,
};
- const toolsEngine = createAgentToolsEngine({
- model: agentConfig.model,
- provider: agentConfig.provider!,
- });
+ const toolsEngine = createAgentToolsEngine(modelRuntimeConfig);
const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({
model: agentConfig.model,
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 5769f691638..31593762e3e 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -1,9 +1,14 @@
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { type ChatStreamPayload, type LobeTool, type UIChatMessage } from '@lobechat/types';
-import { ChatErrorType } from '@lobechat/types';
+import {
+ ChatErrorType,
+ type ChatStreamPayload,
+ createVisualFileRef,
+ type LobeTool,
+ type UIChatMessage,
+} from '@lobechat/types';
import { act } from '@testing-library/react';
-import { ModelProvider } from 'model-bank';
+import { type EnabledAiModel, ModelProvider } from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
@@ -20,6 +25,28 @@ import { chatService } from './index';
import * as mechaModule from './mecha';
import { type ResolvedAgentConfig } from './mecha';
+vi.hoisted(() => {
+ const storage = new Map<string, string>();
+
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: {
+ clear: () => storage.clear(),
+ getItem: (key: string) => storage.get(key) ?? null,
+ key: (index: number) => Array.from(storage.keys())[index] ?? null,
+ get length() {
+ return storage.size;
+ },
+ removeItem: (key: string) => {
+ storage.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ },
+ });
+});
+
// Helper to compute expected date content from SystemDateProvider
const getCurrentDateContent = () => {
const tz = 'UTC';
@@ -557,7 +584,7 @@ describe('ChatService', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="abc.png" url="http://example.com/image.jpg"></image>
+<image ref="image_1" name="abc.png"></image>
</images>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -609,6 +636,19 @@ describe('ChatService', () => {
});
describe('local image URL conversion', () => {
+ beforeEach(() => {
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ abilities: { vision: true },
+ id: 'gpt-4-vision-preview',
+ providerId: ModelProvider.OpenAI,
+ type: 'chat',
+ } as EnabledAiModel,
+ ],
+ });
+ });
+
it('should convert local image URLs to base64 and call processImageList', async () => {
const { imageUrlToBase64 } = await import('@lobechat/utils/imageToBase64');
const { parseDataUri } = await import('@lobechat/utils/uriParser');
@@ -622,9 +662,6 @@ describe('ChatService', () => {
mimeType: 'image/png',
});
- // Mock aiModelSelectors to return true for vision support
- vi.spyOn(aiModelSelectors, 'isModelSupportVision').mockReturnValue(() => true);
-
const messages = [
{
content: 'Hello',
@@ -649,6 +686,7 @@ describe('ChatService', () => {
await chatService.createAssistantMessage({
messages,
model: 'gpt-4-vision-preview',
+ provider: ModelProvider.OpenAI,
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'gpt-4-vision-preview' },
}),
@@ -661,6 +699,12 @@ describe('ChatService', () => {
);
expect(imageUrlToBase64).toHaveBeenCalledWith('http://127.0.0.1:3000/uploads/image.png');
+ const visualRef = createVisualFileRef({
+ index: 0,
+ messageId: 'test-id',
+ type: 'image',
+ });
+
// Verify the final result contains base64 converted URL
expect(getChatCompletionSpy).toHaveBeenCalledWith(
{
@@ -683,7 +727,7 @@ describe('ChatService', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="local-image.png" url="http://127.0.0.1:3000/uploads/image.png"></image>
+<image ref="${visualRef}" name="local-image.png"></image>
</images>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -701,6 +745,7 @@ describe('ChatService', () => {
},
],
model: 'gpt-4-vision-preview',
+ provider: ModelProvider.OpenAI,
stream: true,
enabledSearch: undefined,
tools: undefined,
@@ -719,9 +764,6 @@ describe('ChatService', () => {
vi.mocked(isDesktopLocalStaticServerUrl).mockReturnValue(false); // This is NOT a local URL
vi.mocked(imageUrlToBase64).mockClear(); // Clear to ensure it's not called
- // Mock aiModelSelectors to return true for vision support
- vi.spyOn(aiModelSelectors, 'isModelSupportVision').mockReturnValue(() => true);
-
const messages = [
{
content: 'Hello',
@@ -745,6 +787,7 @@ describe('ChatService', () => {
await chatService.createAssistantMessage({
messages,
model: 'gpt-4-vision-preview',
+ provider: ModelProvider.OpenAI,
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'gpt-4-vision-preview' },
}),
@@ -757,6 +800,12 @@ describe('ChatService', () => {
);
expect(imageUrlToBase64).not.toHaveBeenCalled(); // Should NOT be called for remote URLs
+ const visualRef = createVisualFileRef({
+ index: 0,
+ messageId: 'test-id-2',
+ type: 'image',
+ });
+
// Verify the final result preserves original URL
expect(getChatCompletionSpy).toHaveBeenCalledWith(
{
@@ -779,7 +828,7 @@ describe('ChatService', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="remote-image.jpg" url="https://example.com/remote-image.jpg"></image>
+<image ref="${visualRef}" name="remote-image.jpg"></image>
</images>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -794,6 +843,7 @@ describe('ChatService', () => {
},
],
model: 'gpt-4-vision-preview',
+ provider: ModelProvider.OpenAI,
stream: true,
enabledSearch: undefined,
tools: undefined,
@@ -821,9 +871,6 @@ describe('ChatService', () => {
mimeType: 'image/jpeg',
});
- // Mock aiModelSelectors to return true for vision support
- vi.spyOn(aiModelSelectors, 'isModelSupportVision').mockReturnValue(() => true);
-
const messages = [
{
content: 'Multiple images',
@@ -856,6 +903,7 @@ describe('ChatService', () => {
await chatService.createAssistantMessage({
messages,
model: 'gpt-4-vision-preview',
+ provider: ModelProvider.OpenAI,
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'gpt-4-vision-preview' },
}),
@@ -1707,23 +1755,21 @@ describe('ChatService', () => {
it('should handle successful chat completion response', async () => {
// Mock getChatCompletion to simulate successful completion
- const getChatCompletionSpy = vi
- .spyOn(chatService, 'getChatCompletion')
- .mockImplementation(async (params, options) => {
- // Simulate successful response
- if (options?.onFinish) {
- options.onFinish('AI response', {
- type: 'done',
- observationId: null,
- toolCalls: undefined,
- traceId: null,
- });
- }
- if (options?.onMessageHandle) {
- options.onMessageHandle({ type: 'text', text: 'AI response' });
- }
- return new Response('');
- });
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (params, options) => {
+ // Simulate successful response
+ if (options?.onFinish) {
+ options.onFinish('AI response', {
+ type: 'done',
+ observationId: null,
+ toolCalls: undefined,
+ traceId: null,
+ });
+ }
+ if (options?.onMessageHandle) {
+ options.onMessageHandle({ type: 'text', text: 'AI response' });
+ }
+ return new Response('');
+ });
const params = {
messages: [{ content: 'Hello', role: 'user' as const }],
@@ -1762,15 +1808,13 @@ describe('ChatService', () => {
it('should handle error in chat completion', async () => {
// Mock getChatCompletion to simulate error
- const getChatCompletionSpy = vi
- .spyOn(chatService, 'getChatCompletion')
- .mockImplementation(async (params, options) => {
- // Simulate error response
- if (options?.onErrorHandle) {
- options.onErrorHandle({ message: 'translated_response.404', type: 404 });
- }
- return new Response('');
- });
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (params, options) => {
+ // Simulate error response
+ if (options?.onErrorHandle) {
+ options.onErrorHandle({ message: 'translated_response.404', type: 404 });
+ }
+ return new Response('');
+ });
const params = {
messages: [{ content: 'Hello', role: 'user' as const }],
diff --git a/src/services/chat/helper.test.ts b/src/services/chat/helper.test.ts
new file mode 100644
index 00000000000..b10e74abdaf
--- /dev/null
+++ b/src/services/chat/helper.test.ts
@@ -0,0 +1,44 @@
+import { type EnabledAiModel, ModelProvider } from 'model-bank';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { useAiInfraStore } from '@/store/aiInfra';
+
+import { isCanUseVideo, isCanUseVision } from './helper';
+
+describe('chat helper', () => {
+ afterEach(() => {
+ useAiInfraStore.setState({ enabledAiModels: [] });
+ });
+
+ it('should resolve LobeHub routed model abilities by model id fallback', () => {
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ abilities: { video: true, vision: true },
+ id: 'gemini-3.1-flash-lite-preview',
+ providerId: ModelProvider.Google,
+ type: 'chat',
+ } as EnabledAiModel,
+ ],
+ });
+
+ expect(isCanUseVision('gemini-3.1-flash-lite-preview', ModelProvider.LobeHub)).toBe(true);
+ expect(isCanUseVideo('gemini-3.1-flash-lite-preview', ModelProvider.LobeHub)).toBe(true);
+ });
+
+ it('should not fallback across non-LobeHub providers', () => {
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ abilities: { video: true, vision: true },
+ id: 'gemini-3.1-flash-lite-preview',
+ providerId: ModelProvider.Google,
+ type: 'chat',
+ } as EnabledAiModel,
+ ],
+ });
+
+ expect(isCanUseVision('gemini-3.1-flash-lite-preview', ModelProvider.OpenAI)).toBe(false);
+ expect(isCanUseVideo('gemini-3.1-flash-lite-preview', ModelProvider.OpenAI)).toBe(false);
+ });
+});
diff --git a/src/services/chat/helper.ts b/src/services/chat/helper.ts
index e6df5919d8a..8712fec269f 100644
--- a/src/services/chat/helper.ts
+++ b/src/services/chat/helper.ts
@@ -1,14 +1,25 @@
import { ModelProvider } from 'model-bank';
import { getAiInfraStoreState } from '@/store/aiInfra';
-import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';
+import { aiProviderSelectors } from '@/store/aiInfra/selectors';
+
+const getModelAbilities = (model: string, provider: string) => {
+ const state = getAiInfraStoreState();
+ const exactModel = state.enabledAiModels?.find(
+ (item) => item.id === model && item.providerId === provider,
+ );
+
+ if (exactModel || provider !== ModelProvider.LobeHub) return exactModel?.abilities;
+
+ return state.enabledAiModels?.find((item) => item.id === model)?.abilities;
+};
export const isCanUseVision = (model: string, provider: string): boolean => {
- return aiModelSelectors.isModelSupportVision(model, provider)(getAiInfraStoreState());
+ return getModelAbilities(model, provider)?.vision || false;
};
export const isCanUseVideo = (model: string, provider: string): boolean => {
- return aiModelSelectors.isModelSupportVideo(model, provider)(getAiInfraStoreState()) || false;
+ return getModelAbilities(model, provider)?.video || false;
};
/**
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index a0460a3f75b..1d1c5b7626a 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -8,6 +8,28 @@ import * as helpers from '../helper';
import { contextEngineering } from './contextEngineering';
import * as memoryManager from './memoryManager';
+vi.hoisted(() => {
+ const storage = new Map<string, string>();
+
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: {
+ clear: () => storage.clear(),
+ getItem: (key: string) => storage.get(key) ?? null,
+ key: (index: number) => Array.from(storage.keys())[index] ?? null,
+ get length() {
+ return storage.size;
+ },
+ removeItem: (key: string) => {
+ storage.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ },
+ });
+});
+
// Mock VARIABLE_GENERATORS
vi.mock('@/helpers/parserPlaceholder', () => ({
VARIABLE_GENERATORS: {
@@ -159,12 +181,12 @@ describe('contextEngineering', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="ttt.png" url="http://example.com/xxx0asd-dsd.png"></image>
+<image ref="image_1" name="ttt.png"></image>
</images>
<files>
<files_docstring>here are user upload files you can refer to</files_docstring>
-<file id="file1" name="abc.png" type="plain/txt" size="100000" url="http://abc.com/abc.txt"></file>
-<file id="file_oKMve9qySLMI" name="2402.16667v1.pdf" type="undefined" size="11256078" url="https://xxx.com/ppp/480497/5826c2b8-fde0-4de1-a54b-a224d5e3d898.pdf"></file>
+<file id="file1" name="abc.png" type="plain/txt" size="100000"></file>
+<file id="file_oKMve9qySLMI" name="2402.16667v1.pdf" type="undefined" size="11256078"></file>
</files>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
@@ -232,7 +254,7 @@ describe('contextEngineering', () => {
<files_info>
<images>
<images_docstring>here are user upload images you can refer to</images_docstring>
-<image name="abc.png" url="http://example.com/image.jpg"></image>
+<image ref="image_1" name="abc.png"></image>
</images>
</files_info>
<!-- END SYSTEM CONTEXT -->`,
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index a8d1f0608f4..5e60628242e 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -17,7 +17,7 @@ import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';
-import { isDesktop, KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
+import { KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
import type {
AgentBuilderContext,
AgentContextDocument,
@@ -694,7 +694,7 @@ export const contextEngineering = async ({
},
// File context configuration
- fileContext: { enabled: true, includeFileUrl: !isDesktop },
+ fileContext: { enabled: true, includeFileUrl: false },
// Knowledge injection
knowledge: {
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index 056a2093062..3f430dedebd 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -1,10 +1,12 @@
import { type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
+import { type EnabledAiModel, ModelProvider } from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as toolEngineering from '@/helpers/toolEngineering';
import { chatService } from '@/services/chat';
import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
+import { useAiInfraStore } from '@/store/aiInfra';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { useChatStore } from '../../../../store';
@@ -18,8 +20,19 @@ import {
} from './fixtures';
import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+const serverConfigMock = vi.hoisted(() => ({ enableVisualUnderstanding: false }));
+
// Keep zustand mock as it's needed globally
vi.mock('zustand/traditional');
+vi.mock('@/store/serverConfig', () => ({
+ getServerConfigStoreState: () => ({
+ serverConfig: { enableVisualUnderstanding: serverConfigMock.enableVisualUnderstanding },
+ }),
+ serverConfigSelectors: {
+ enableVisualUnderstanding: (state: { serverConfig: { enableVisualUnderstanding?: boolean } }) =>
+ !!state.serverConfig.enableVisualUnderstanding,
+ },
+}));
const realExecAgentRuntime = useChatStore.getState().internal_execAgentRuntime;
@@ -27,6 +40,7 @@ beforeEach(() => {
resetTestEnvironment();
setupMockSelectors();
spyOnMessageService();
+ serverConfigMock.enableVisualUnderstanding = false;
act(() => {
useChatStore.setState({
@@ -37,6 +51,7 @@ beforeEach(() => {
});
afterEach(() => {
+ useAiInfraStore.setState({ enabledAiModels: [] });
vi.restoreAllMocks();
});
@@ -705,7 +720,7 @@ describe('StreamingExecutor actions', () => {
expect(capturedInitialContexts.length).toBeGreaterThanOrEqual(1);
// All captured initialContexts should be the same (preserved through steps)
- capturedInitialContexts.forEach((ctx, index) => {
+ capturedInitialContexts.forEach((ctx) => {
expect(ctx).toEqual(mockInitialContext);
});
@@ -959,6 +974,127 @@ describe('StreamingExecutor actions', () => {
);
});
+ it('should enable visual understanding when a previous user message has visual media', () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ serverConfigMock.enableVisualUnderstanding = true;
+
+ const { result } = renderHook(() => useChatStore());
+ const previousVisualMessage = {
+ id: 'msg_with_image',
+ role: 'user',
+ content: 'Please inspect this image',
+ imageList: [{ id: 'image-file', url: 'https://example.com/image.png' }],
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+ const currentTextMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: 'Does the person in the first image wear glasses?',
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ const generateToolsDetailed = vi.fn().mockReturnValue({
+ enabledManifests: [],
+ enabledToolIds: ['lobe-agent'],
+ tools: [],
+ });
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig({ model: 'text-only-model', provider: 'openai' }),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed,
+ } as any);
+
+ result.current.internal_createAgentState({
+ messages: [previousVisualMessage, currentTextMessage],
+ parentMessageId: currentTextMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ });
+
+ expect(generateToolsDetailed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolIds: ['lobe-agent'],
+ }),
+ );
+ });
+
+ it('should not enable visual understanding when the active LobeHub model supports visual media natively', () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ serverConfigMock.enableVisualUnderstanding = true;
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ abilities: { functionCall: true, video: true, vision: true },
+ id: 'gemini-3.1-flash-lite-preview',
+ providerId: ModelProvider.Google,
+ type: 'chat',
+ } as EnabledAiModel,
+ ],
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const previousVisualMessage = {
+ id: 'msg_with_video',
+ role: 'user',
+ content: 'Please inspect this video',
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ videoList: [{ id: 'video-file', url: 'https://example.com/video.mp4' }],
+ } as UIChatMessage;
+ const currentTextMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: 'Summarize the previous video',
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ const generateToolsDetailed = vi.fn().mockReturnValue({
+ enabledManifests: [],
+ enabledToolIds: [],
+ tools: [],
+ });
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig({
+ model: 'gemini-3.1-flash-lite-preview',
+ provider: ModelProvider.LobeHub,
+ }),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed,
+ } as any);
+
+ result.current.internal_createAgentState({
+ messages: [previousVisualMessage, currentTextMessage],
+ parentMessageId: currentTextMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ });
+
+ expect(generateToolsDetailed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolIds: undefined,
+ }),
+ );
+ });
+
it('should use excludeDefaultToolIds (not skipDefaultTools) in manual mode for builtin agents', () => {
act(() => {
useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
diff --git a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
index eefb772c565..e560a78b16f 100644
--- a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
+++ b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
@@ -102,6 +102,7 @@ export class ClientToolExecutionActionImpl {
operationId,
scope: operation?.context?.scope,
signal: operation?.abortController?.signal,
+ sourceMessageId: operation?.context?.messageId,
topicId: operation?.context?.topicId ?? undefined,
};
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 9c26a94d42c..26fec5c6078 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -6,6 +6,7 @@ import {
type Usage,
} from '@lobechat/agent-runtime';
import { AgentRuntime, computeStepContext, GeneralChatAgent } from '@lobechat/agent-runtime';
+import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
@@ -21,6 +22,7 @@ import debug from 'debug';
import { t } from 'i18next';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
+import { isCanUseVideo, isCanUseVision } from '@/services/chat/helper';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';
import { localFileService } from '@/services/electron/localFileService';
@@ -34,6 +36,7 @@ import {
notifyDesktopHumanApprovalRequired,
resolveNotificationNavigatePath,
} from '@/store/chat/utils/desktopNotification';
+import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import { getTaskStoreState } from '@/store/task';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { type StoreSetter } from '@/store/types';
@@ -75,6 +78,11 @@ const hasReferTopicNode = (editorData: Record<string, any> | null | undefined):
return walk(editorData.root);
};
+const getVisualMediaAvailability = (messages: UIChatMessage[]) => ({
+ hasImages: messages.some((message) => message.role === 'user' && !!message.imageList?.length),
+ hasVideos: messages.some((message) => message.role === 'user' && !!message.videoList?.length),
+});
+
/**
* Core streaming execution actions for AI chat
*/
@@ -161,10 +169,6 @@ export class StreamingExecutorActionImpl {
const selectedToolIds = initialContext?.initialContext?.selectedTools?.map(
(tool) => tool.identifier,
);
- const mergedToolIds =
- selectedToolIds && selectedToolIds.length > 0
- ? [...new Set([...(pluginIds || []), ...selectedToolIds])]
- : pluginIds;
if (!agentConfigData || !agentConfigData.model) {
throw new Error(
@@ -172,11 +176,30 @@ export class StreamingExecutorActionImpl {
);
}
- // Dynamically inject topic-reference tool when messages contain refer-topic nodes
+ // Dynamically inject turn-scoped builtin tools.
const hasTopicReference = messages.some((m) => hasReferTopicNode(m.editorData));
- const effectivePluginIds = hasTopicReference
- ? [...(pluginIds || []), 'lobe-topic-reference']
- : pluginIds;
+ const visualMediaAvailability = getVisualMediaAvailability(messages);
+ const serverConfigState = getServerConfigStoreState();
+ const visualUnderstandingConfigured =
+ !!serverConfigState && serverConfigSelectors.enableVisualUnderstanding(serverConfigState);
+ const shouldEnableVisualUnderstanding =
+ visualUnderstandingConfigured &&
+ ((visualMediaAvailability.hasImages &&
+ !isCanUseVision(agentConfigData.model, agentConfigData.provider!)) ||
+ (visualMediaAvailability.hasVideos &&
+ !isCanUseVideo(agentConfigData.model, agentConfigData.provider!)));
+ const runtimePluginIds = [
+ ...new Set([
+ ...(pluginIds || []),
+ ...(hasTopicReference ? ['lobe-topic-reference'] : []),
+ ...(shouldEnableVisualUnderstanding ? [LobeAgentManifest.identifier] : []),
+ ]),
+ ];
+ const effectivePluginIds = runtimePluginIds.length > 0 ? runtimePluginIds : undefined;
+ const mergedToolIds =
+ selectedToolIds && selectedToolIds.length > 0
+ ? [...new Set([...runtimePluginIds, ...selectedToolIds])]
+ : effectivePluginIds;
log(
'[internal_createAgentState] resolved plugins=%o, isSubTask=%s, disableTools=%s, hasTopicReference=%s',
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 55494bfd9c7..0e45e525090 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -156,6 +156,7 @@ export class PluginTypesActionImpl {
registerAfterCompletion,
scope,
signal: operation?.abortController?.signal,
+ sourceMessageId: rootRuntimeOperationContext?.messageId,
stepContext,
taskId,
topicId,
diff --git a/src/store/serverConfig/index.ts b/src/store/serverConfig/index.ts
index 40b3a365ed8..0298a789fe3 100644
--- a/src/store/serverConfig/index.ts
+++ b/src/store/serverConfig/index.ts
@@ -1,2 +1,2 @@
export { featureFlagsSelectors, serverConfigSelectors } from './selectors';
-export { useServerConfigStore } from './store';
+export { getServerConfigStoreState, useServerConfigStore } from './store';
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index b17d39e25a8..6d559727885 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -13,7 +13,10 @@ export const serverConfigSelectors = {
enableMarketTrustedClient: (s: ServerConfigStore) =>
s.serverConfig.enableMarketTrustedClient || false,
enableUploadFileToServer: (s: ServerConfigStore) => s.serverConfig.enableUploadFileToServer,
+ enableVisualUnderstanding: (s: ServerConfigStore) =>
+ s.serverConfig.enableVisualUnderstanding || false,
enabledTelemetryChat: (s: ServerConfigStore) => s.serverConfig.telemetry.langfuse || false,
isMobile: (s: ServerConfigStore) => s.isMobile || false,
oAuthSSOProviders: (s: ServerConfigStore) => s.serverConfig.oAuthSSOProviders,
+ visualUnderstanding: (s: ServerConfigStore) => s.serverConfig.visualUnderstanding,
};
diff --git a/src/store/serverConfig/store.ts b/src/store/serverConfig/store.ts
index d0d633655a1..49a5c00ae3f 100644
--- a/src/store/serverConfig/store.ts
+++ b/src/store/serverConfig/store.ts
@@ -52,7 +52,7 @@ const createStore: CreateStore =
// =============== Implement useStore ============ //
-let store: StoreApi<ServerConfigStore>;
+let store: StoreApi<ServerConfigStore> | undefined;
declare global {
interface Window {
@@ -83,5 +83,7 @@ export const createServerConfigStore = (initState?: Partial<ServerConfigStore>)
return store;
};
+export const getServerConfigStoreState = () => store?.getState();
+
export const { useStore: useServerConfigStore, Provider } =
createContext<StoreApiWithSelector<ServerConfigStore>>();
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
index 3228e5b5782..44181144732 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
@@ -71,7 +71,7 @@ describe('lobe-activator executor discovery allowlist', () => {
expect(activatedIds).toContain('web-browsing');
expect(activatedIds).not.toContain('internal-admin');
- });
+ }, 10_000);
it('should reject all identifiers when none are discoverable', async () => {
const hiddenTool = makeBuiltinTool('secret-tool', false);
diff --git a/src/store/tool/slices/builtin/executors/index.test.ts b/src/store/tool/slices/builtin/executors/index.test.ts
index f7214434081..76772e3d57f 100644
--- a/src/store/tool/slices/builtin/executors/index.test.ts
+++ b/src/store/tool/slices/builtin/executors/index.test.ts
@@ -1,11 +1,34 @@
+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
import {
WebOnboardingApiName,
WebOnboardingIdentifier,
} from '@lobechat/builtin-tool-web-onboarding';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { getApiNamesForIdentifier, hasExecutor } from './index';
+vi.hoisted(() => {
+ const storage = new Map<string, string>();
+
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: {
+ clear: () => storage.clear(),
+ getItem: (key: string) => storage.get(key) ?? null,
+ key: (index: number) => Array.from(storage.keys())[index] ?? null,
+ get length() {
+ return storage.size;
+ },
+ removeItem: (key: string) => {
+ storage.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ },
+ });
+});
+
describe('builtin executor registry', () => {
it('registers web onboarding executor APIs', () => {
expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion)).toBe(true);
@@ -14,4 +37,8 @@ describe('builtin executor registry', () => {
Object.values(WebOnboardingApiName),
);
});
+
+ it('registers visual understanding executor APIs', () => {
+ expect(hasExecutor(LobeAgentIdentifier, LobeAgentApiName.analyzeVisualMedia)).toBe(true);
+ });
});
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index 8388c774b44..533244ee213 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -14,6 +14,7 @@ import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-bu
import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';
import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/executor';
+import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/executor';
import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/executor';
import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
import { taskExecutor } from '@lobechat/builtin-tool-task/executor';
@@ -157,6 +158,7 @@ registerExecutors([
activatorExecutor,
topicReferenceExecutor,
userInteractionExecutor,
+ lobeAgentExecutor,
webOnboardingExecutor,
webBrowsing,
]);