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(agent): pass audio (mp3) attachments to audio-capable models like Gemini (#15988)

Arvin Xu7624ce635e91
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index f6aafbdce1f..d3eb5765ce9 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -1249,6 +1249,12 @@ export const createRuntimeExecutors = (
},
userTimezone: ctx.userTimezone,
capabilities: {
+ isCanUseAudio: (m: string, p: string) => {
+ const info =
+ builtinModels.find((item) => item.id === m && item.providerId === p) ??
+ builtinModels.find((item) => item.id === m);
+ return info?.abilities?.audio ?? false;
+ },
isCanUseFC: (m: string, p: string) => {
const info = builtinModels.find((item) => item.id === m && item.providerId === p);
return info?.abilities?.functionCall ?? true;
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
index 606b5f1ca8c..57104059e3a 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
@@ -83,6 +83,7 @@ export const serverMessagesEngine = async ({
const engine = new MessagesEngine({
// Capability injection
capabilities: {
+ isCanUseAudio: capabilities?.isCanUseAudio,
isCanUseFC: capabilities?.isCanUseFC,
isCanUseVideo: capabilities?.isCanUseVideo,
isCanUseVision: capabilities?.isCanUseVision,
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
index 755125166ae..164cdd6a3cf 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
@@ -23,6 +23,8 @@ import type { RuntimeInitialContext, UIChatMessage } from '@lobechat/types';
* Model capability checker functions for server-side
*/
export interface ServerModelCapabilities {
+ /** Check if audio input is supported */
+ isCanUseAudio?: (model: string, provider: string) => boolean;
/** Check if function calling is supported */
isCanUseFC?: (model: string, provider: string) => boolean;
/** Check if video is supported */
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 44e6b9a56de..d3ebe401e9f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -27,6 +27,7 @@ import type { LobeChatDatabase } from '@lobechat/database';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';
import type {
+ ChatAudioItem,
ChatFileItem,
ChatTopicBotContext,
ChatVideoItem,
@@ -476,6 +477,7 @@ export class AiAgentService {
files?: InternalExecAgentParams['files'];
throwIfAborted: (stage: string) => Promise<void>;
}): Promise<{
+ audioList?: ChatAudioItem[];
fileIds?: string[];
fileList?: ChatFileItem[];
imageList?: Array<{ alt: string; id: string; url: string }>;
@@ -486,13 +488,15 @@ export class AiAgentService {
let fileIds: string[] | undefined;
let imageList: Array<{ alt: string; id: string; url: string }> | undefined;
let videoList: ChatVideoItem[] | undefined;
+ let audioList: ChatAudioItem[] | undefined;
let fileList: ChatFileItem[] | undefined;
- // Upload raw bot/IM files to S3 and classify them (image / video / document).
+ // Upload raw bot/IM files to S3 and classify them (image / video / audio / document).
if (files && files.length > 0) {
fileIds = [];
imageList = [];
videoList = [];
+ audioList = [];
fileList = [];
const fileService = new FileService(this.db, this.userId, this.workspaceId);
const documentService = new DocumentService(this.db, this.userId, this.workspaceId);
@@ -522,7 +526,16 @@ export class AiAgentService {
continue;
}
- // Non-image / non-video: parse file content into the documents table so
+ if (result.isAudio) {
+ audioList.push({
+ alt: file.name || 'audio',
+ id: result.fileId,
+ url: result.resolvedUrl,
+ });
+ continue;
+ }
+
+ // Non-image / non-video / non-audio: parse file content into the documents table so
// the MessageContentProcessor can inject it via filesPrompts(). Mirrors
// what the web upload path does, ensuring bot-uploaded PDFs / text /
// JSON / .skill files are actually visible to the LLM (instead of
@@ -559,15 +572,17 @@ export class AiAgentService {
if (fileIds.length > 0) {
log(
- 'execAgent: uploaded %d files to S3 (%d images, %d videos, %d documents)',
+ 'execAgent: uploaded %d files to S3 (%d images, %d videos, %d audios, %d documents)',
fileIds.length,
imageList.length,
videoList.length,
+ audioList.length,
fileList.length,
);
}
if (imageList.length === 0) imageList = undefined;
if (videoList.length === 0) videoList = undefined;
+ if (audioList.length === 0) audioList = undefined;
if (fileList.length === 0) fileList = undefined;
}
@@ -597,6 +612,9 @@ export class AiAgentService {
if (resolved.videoList.length > 0) {
videoList = [...(videoList ?? []), ...resolved.videoList];
}
+ if (resolved.audioList.length > 0) {
+ audioList = [...(audioList ?? []), ...resolved.audioList];
+ }
if (resolved.fileList.length > 0) {
fileList = [...(fileList ?? []), ...resolved.fileList];
}
@@ -614,7 +632,7 @@ export class AiAgentService {
// an empty messagesFiles relation.
if (fileIds && fileIds.length === 0) fileIds = undefined;
- return { fileIds, fileList, imageList, videoList, warnings };
+ return { audioList, fileIds, fileList, imageList, videoList, warnings };
}
/**
@@ -2424,8 +2442,10 @@ export class AiAgentService {
// row created above).
// - imageList: vision models render these as image_url parts
// - videoList: video-capable models render these as video parts
+ // - audioList: audio-capable models render these as audio parts
// - fileList: MessageContentProcessor injects content via filesPrompts() XML
const userMessage = {
+ audioList: runAttachments.audioList,
content: ephemeralUserMessage ?? prompt,
fileList: runAttachments.fileList,
id: userMessageRecord?.id,
diff --git a/apps/server/src/services/aiAgent/ingestAttachment.ts b/apps/server/src/services/aiAgent/ingestAttachment.ts
index b5a8edfca38..0cc7f2b5c74 100644
--- a/apps/server/src/services/aiAgent/ingestAttachment.ts
+++ b/apps/server/src/services/aiAgent/ingestAttachment.ts
@@ -33,6 +33,7 @@ export interface AttachmentSource {
export interface IngestResult {
fileId: string;
+ isAudio: boolean;
isImage: boolean;
isVideo: boolean;
key: string;
@@ -149,12 +150,17 @@ export async function ingestAttachment(
// MessageContentProcessor can pass the video to vision/video-capable models.
const isVideo = !isImage && mimeType.startsWith('video/');
+ // Audio is passed through untouched; audio-capable models (e.g. Gemini) receive
+ // it as an inline/file media part instead of being parsed into document text.
+ const isAudio = !isImage && !isVideo && mimeType.startsWith('audio/');
+
log(
- 'ingestAttachment: classified name=%s, finalMimeType=%s, isImage=%s, isVideo=%s, bufferSize=%d',
+ 'ingestAttachment: classified name=%s, finalMimeType=%s, isImage=%s, isVideo=%s, isAudio=%s, bufferSize=%d',
source.name,
mimeType,
isImage,
isVideo,
+ isAudio,
buffer.length,
);
@@ -164,9 +170,11 @@ export async function ingestAttachment(
const pathname = `files/${userId}/${nanoid()}/${source.name || `file.${ext}`}`;
const { fileId, key } = await fileService.uploadFromBuffer(buffer, mimeType, pathname);
- // 5. Resolve access URL for images and videos.
+ // 5. Resolve access URL for images, videos and audio.
const resolvedUrl =
- isImage || isVideo ? await fileService.getFileAccessUrl({ id: fileId, url: key }) : '';
+ isImage || isVideo || isAudio
+ ? await fileService.getFileAccessUrl({ id: fileId, url: key })
+ : '';
log(
'ingestAttachment: uploaded fileId=%s, key=%s, resolvedUrl=%s',
@@ -175,5 +183,5 @@ export async function ingestAttachment(
resolvedUrl ? 'set' : '(empty)',
);
- return { fileId, isImage, isVideo, key, resolvedUrl };
+ return { fileId, isAudio, isImage, isVideo, key, resolvedUrl };
}
diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.ts
index 4f638a6bf77..3401da1b242 100644
--- a/apps/server/src/services/file/resolveAttachments.ts
+++ b/apps/server/src/services/file/resolveAttachments.ts
@@ -1,5 +1,5 @@
import type { LobeChatDatabase } from '@lobechat/database';
-import type { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
import debug from 'debug';
import { FileModel } from '@/database/models/file';
@@ -9,6 +9,7 @@ import { FileService } from '@/server/services/file';
const log = debug('lobe-server:resolveAttachments');
export interface ResolvedAttachments {
+ audioList: ChatAudioItem[];
fileList: ChatFileItem[];
imageList: ChatImageItem[];
/**
@@ -45,6 +46,7 @@ export const resolveAttachmentsByFileIds = async ({
workspaceId,
}: ResolveArgs): Promise<ResolvedAttachments> => {
const result: ResolvedAttachments = {
+ audioList: [],
fileList: [],
imageList: [],
orderedFileIds: [],
@@ -76,7 +78,11 @@ export const resolveAttachmentsByFileIds = async ({
}
const resolvedUrl = (await fileService.getFullFileUrl(file.url)) || file.url;
const fileType = file.fileType || '';
- if (fileType.startsWith('image') || fileType.startsWith('video')) {
+ if (
+ fileType.startsWith('image') ||
+ fileType.startsWith('video') ||
+ fileType.startsWith('audio')
+ ) {
return { file, fileType, id, resolvedUrl };
}
let content: string | undefined;
@@ -106,6 +112,10 @@ export const resolveAttachmentsByFileIds = async ({
result.videoList.push({ alt: file.name || 'video', id: file.id, url: resolvedUrl });
continue;
}
+ if (fileType.startsWith('audio')) {
+ result.audioList.push({ alt: file.name || 'audio', id: file.id, url: resolvedUrl });
+ continue;
+ }
if (entry.parseError) {
log('parseFile failed for %s (id=%s): %O', file.name, file.id, entry.parseError);
result.warnings.push(
@@ -123,10 +133,11 @@ export const resolveAttachmentsByFileIds = async ({
}
log(
- 'resolved %d attachment(s) (%d images, %d videos, %d documents)',
+ 'resolved %d attachment(s) (%d images, %d videos, %d audios, %d documents)',
fileRecords.length,
result.imageList.length,
result.videoList.length,
+ result.audioList.length,
result.fileList.length,
);
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 6a3fdde6729..105160f2049 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -101,6 +101,7 @@
"LocalFile.action.open": "Open",
"LocalFile.action.showInFolder": "Show in Folder",
"MaxTokenSlider.unlimited": "Unlimited",
+ "ModelSelect.featureTag.audio": "This model supports audio input recognition.",
"ModelSelect.featureTag.custom": "Custom model, by default, supports both tool calls and visual recognition. Please verify the availability of the above capabilities based on actual situations.",
"ModelSelect.featureTag.file": "This model supports file upload for reading and recognition.",
"ModelSelect.featureTag.functionCall": "This model supports tool calls.",
@@ -114,6 +115,7 @@
"ModelSwitchPanel.byModel": "By Model",
"ModelSwitchPanel.byProvider": "By Provider",
"ModelSwitchPanel.detail.abilities": "Abilities",
+ "ModelSwitchPanel.detail.abilities.audio": "Audio",
"ModelSwitchPanel.detail.abilities.files": "Files",
"ModelSwitchPanel.detail.abilities.functionCall": "Tool Calling",
"ModelSwitchPanel.detail.abilities.imageOutput": "Image Output",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index 193bd0a8731..b62dd7b34fd 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -101,6 +101,7 @@
"LocalFile.action.open": "打开",
"LocalFile.action.showInFolder": "在文件夹中显示",
"MaxTokenSlider.unlimited": "无限制",
+ "ModelSelect.featureTag.audio": "该模型支持音频输入识别",
"ModelSelect.featureTag.custom": "自定义模型,默认支持函数调用和视觉识别。请根据实际情况确认上述功能是否可用。",
"ModelSelect.featureTag.file": "该模型支持上传文件读取与识别",
"ModelSelect.featureTag.functionCall": "该模型支持工具调用(Tool Calling)",
@@ -114,6 +115,7 @@
"ModelSwitchPanel.byModel": "按模型",
"ModelSwitchPanel.byProvider": "按提供商",
"ModelSwitchPanel.detail.abilities": "能力",
+ "ModelSwitchPanel.detail.abilities.audio": "音频识别",
"ModelSwitchPanel.detail.abilities.files": "文件上传",
"ModelSwitchPanel.detail.abilities.functionCall": "工具调用",
"ModelSwitchPanel.detail.abilities.imageOutput": "图片生成",
diff --git a/packages/const/src/visualRef.ts b/packages/const/src/visualRef.ts
index 2d8aefb18c6..907790cec8c 100644
--- a/packages/const/src/visualRef.ts
+++ b/packages/const/src/visualRef.ts
@@ -1,4 +1,4 @@
-export type VisualFileType = 'image' | 'video';
+export type VisualFileType = 'audio' | 'image' | 'video';
interface CreateVisualFileRefOptions {
index: number;
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 373d72aea90..77b77a341d3 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -453,6 +453,7 @@ export class MessagesEngine {
// Message content processing (image encoding, multimodal)
new MessageContentProcessor({
fileContext: fileContext || { enabled: true, includeFileUrl: true },
+ isCanUseAudio: capabilities?.isCanUseAudio || (() => false),
isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
isCanUseVision: capabilities?.isCanUseVision || (() => true),
model,
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index be6dc96ba09..b0d0ec4e2eb 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -32,6 +32,8 @@ import type { LobeToolManifest } from '../tools/types';
* Injected by caller to check if model supports specific capabilities
*/
export interface ModelCapabilityChecker {
+ /** Check if audio input is supported */
+ isCanUseAudio?: (model: string, provider: string) => boolean;
/** Check if function calling is supported */
isCanUseFC?: (model: string, provider: string) => boolean;
/** Check if video is supported */
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index e7f0343f9b4..dee9d270373 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -54,6 +54,8 @@ export interface FileContextConfig {
export interface MessageContentConfig {
/** File context configuration */
fileContext?: FileContextConfig;
+ /** Function to check if audio input is supported */
+ isCanUseAudio?: (model: string, provider: string) => boolean | undefined;
/** Function to check if video is supported */
isCanUseVideo?: (model: string, provider: string) => boolean | undefined;
/** Function to check if vision is supported */
@@ -65,6 +67,9 @@ export interface MessageContentConfig {
}
export interface UserMessageContentPart {
+ audio_url?: {
+ url: string;
+ };
googleThoughtSignature?: string;
image_url?: {
detail?: string;
@@ -73,7 +78,7 @@ export interface UserMessageContentPart {
signature?: string;
text?: string;
thinking?: string;
- type: 'text' | 'image_url' | 'thinking' | 'video_url';
+ type: 'text' | 'image_url' | 'thinking' | 'video_url' | 'audio_url';
video_url?: {
url: string;
};
@@ -150,10 +155,12 @@ export class MessageContentProcessor extends BaseProcessor {
// Check if images, videos or files need processing
const hasImages = message.imageList && message.imageList.length > 0;
const hasVideos = message.videoList && message.videoList.length > 0;
+ const hasAudios = message.audioList && message.audioList.length > 0;
const hasFiles = message.fileList && message.fileList.length > 0;
const canUseVision = !!this.config.isCanUseVision?.(this.config.model, this.config.provider);
const canUseVideo = !!this.config.isCanUseVideo?.(this.config.model, this.config.provider);
+ const canUseAudio = !!this.config.isCanUseAudio?.(this.config.model, this.config.provider);
// Historical messages may already be stored in multimodal parts form
// (content is an array of {type, text|image_url|video_url}). Those parts
@@ -166,7 +173,7 @@ export class MessageContentProcessor extends BaseProcessor {
const needsArrayRewrite = contentIsArray && arrayImageUrlCount > 0 && !canUseVision;
// Fast path: nothing to transform — plain text content passes through.
- if (!hasImages && !hasVideos && !hasFiles && !needsArrayRewrite) {
+ if (!hasImages && !hasVideos && !hasAudios && !hasFiles && !needsArrayRewrite) {
return {
...message,
content: message.content,
@@ -209,12 +216,13 @@ export class MessageContentProcessor extends BaseProcessor {
textContent = textContent ? `${textContent}\n\n${placeholders}` : placeholders;
}
- // Add file context (if file context is enabled and has files, images or videos)
- if ((hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled) {
+ // Add file context (if file context is enabled and has files, images, videos or audios)
+ if ((hasFiles || hasImages || hasVideos || hasAudios) && this.config.fileContext?.enabled) {
const filesContext = filesPrompts({
// File access URLs are needed by sandbox/code tools that fetch attachments from text.
// Call sites can still disable them for environments such as desktop local files.
addUrl: this.config.fileContext.includeFileUrl ?? true,
+ audioList: message.audioList || [],
fileList: message.fileList,
imageList: message.imageList || [],
messageId: message.id,
@@ -253,18 +261,27 @@ export class MessageContentProcessor extends BaseProcessor {
contentParts.push(...videoContentParts);
}
+ // Process audio content
+ if (hasAudios && canUseAudio) {
+ const audioContentParts = await this.processAudioList(message.audioList || []);
+ contentParts.push(...audioContentParts);
+ }
+
// Explicitly return fields, keeping only necessary message fields
- const hasFileContext = (hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled;
+ const hasFileContext =
+ (hasFiles || hasImages || hasVideos || hasAudios) && this.config.fileContext?.enabled;
const hasVisionContent = (hasImages || arrayImageUrlCount > 0) && canUseVision;
const hasVideoContent = hasVideos && canUseVideo;
+ const hasAudioContent = hasAudios && canUseAudio;
- // If only text content and no file context added and no vision/video content, return plain text
+ // If only text content and no file context added and no vision/video/audio content, return plain text
if (
contentParts.length === 1 &&
contentParts[0].type === 'text' &&
!hasFileContext &&
!hasVisionContent &&
- !hasVideoContent
+ !hasVideoContent &&
+ !hasAudioContent
) {
return {
content: contentParts[0].text,
@@ -502,6 +519,22 @@ export class MessageContentProcessor extends BaseProcessor {
});
}
+ /**
+ * Process audio list
+ */
+ private async processAudioList(audioList: any[]): Promise<UserMessageContentPart[]> {
+ if (!audioList || audioList.length === 0) {
+ return [];
+ }
+
+ return audioList.map((audio) => {
+ return {
+ audio_url: { url: audio.url },
+ type: 'audio_url',
+ } as UserMessageContentPart;
+ });
+ }
+
/**
* Validate content part format
*/
@@ -521,6 +554,9 @@ export class MessageContentProcessor extends BaseProcessor {
case 'video_url': {
return !!(part.video_url && part.video_url.url);
}
+ case 'audio_url': {
+ return !!(part.audio_url && part.audio_url.url);
+ }
default: {
return false;
}
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 490b42efd39..13ff685f6e1 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -1,4 +1,4 @@
-import type { ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/types';
+import type { ChatAudioItem, ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import type { PipelineContext } from '../../types';
@@ -24,6 +24,7 @@ const createContext = (messages: UIChatMessage[]): PipelineContext => ({
const mockIsCanUseVision = vi.fn();
const mockIsCanUseVideo = vi.fn();
+const mockIsCanUseAudio = vi.fn();
describe('MessageContentProcessor', () => {
describe('Image processing functionality', () => {
@@ -750,6 +751,106 @@ describe('MessageContentProcessor', () => {
});
});
+ describe('Audio processing functionality', () => {
+ it('should return plain text if model cannot use audio', async () => {
+ mockIsCanUseAudio.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'text-model',
+ provider: 'openai',
+ isCanUseAudio: mockIsCanUseAudio,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: 'Transcribe this',
+ audioList: [{ url: 'audio_url', alt: 'test audio', id: 'test' } as ChatAudioItem],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ // Should return plain text when audio is not supported
+ expect(result.messages[0].content).toBe('Transcribe this');
+ });
+
+ it('should process audios as audio_url parts if model can use audio', async () => {
+ mockIsCanUseAudio.mockReturnValue(true);
+
+ const processor = new MessageContentProcessor({
+ model: 'gemini-3-flash',
+ provider: 'google',
+ isCanUseAudio: mockIsCanUseAudio,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: 'Listen',
+ audioList: [
+ { url: 'http://example.com/a.mp3', alt: 'a1', id: 'a1' },
+ { url: 'http://example.com/b.mp3', alt: 'a2', id: 'a2' },
+ ] as ChatAudioItem[],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ const content = result.messages[0].content as any[];
+ expect(content).toHaveLength(3); // text + 2 audios
+ expect(content[0].type).toBe('text');
+ expect(content[0].text).toBe('Listen');
+ expect(content[1].type).toBe('audio_url');
+ expect(content[1].audio_url.url).toBe('http://example.com/a.mp3');
+ expect(content[2].type).toBe('audio_url');
+ expect(content[2].audio_url.url).toBe('http://example.com/b.mp3');
+ });
+
+ it('should include audios in file context when enabled even if audio not supported', async () => {
+ mockIsCanUseAudio.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'gpt-4',
+ provider: 'openai',
+ isCanUseAudio: mockIsCanUseAudio,
+ fileContext: { enabled: true, includeFileUrl: true },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: 'Hello',
+ audioList: [
+ { id: 'audio1', url: 'http://example.com/a.mp3', alt: 'Test audio' },
+ ] as ChatAudioItem[],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ expect(Array.isArray(result.messages[0].content)).toBe(true);
+ const content = result.messages[0].content as any[];
+ expect(content).toHaveLength(1);
+ expect(content[0].type).toBe('text');
+ expect(content[0].text).toContain('SYSTEM CONTEXT');
+ expect(content[0].text).toContain('<audios>');
+ // No raw audio_url part when audio understanding is unsupported
+ expect(content.some((p) => p.type === 'audio_url')).toBe(false);
+ });
+ });
+
describe('Multimodal message content processing', () => {
it('should convert assistant message with metadata.isMultimodal to OpenAI format', async () => {
mockIsCanUseVision.mockReturnValue(true);
diff --git a/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts
index 595ca362850..f45b92eb791 100644
--- a/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts
+++ b/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts
@@ -48,34 +48,38 @@ describe('attachment token buckets', () => {
url: 'https://example.com/note.txt',
},
],
+ audioList: [{ alt: 'audio.mp3', id: 'audio-id', url: 'https://example.com/audio.mp3' }],
imageList: [{ alt: 'image.png', id: 'image-id', url: 'https://example.com/image.png' }],
role: 'user',
videoList: [{ alt: 'video.mp4', id: 'video-id', url: 'https://example.com/video.mp4' }],
}),
],
- { canUseVideo: true, canUseVision: true },
+ { canUseAudio: true, canUseVideo: true, canUseVision: true },
);
expect(result.textTokens).toBeGreaterThan(0);
expect(result.imageTokens).toBe(1000);
expect(result.videoTokens).toBe(1000);
+ expect(result.audioTokens).toBe(1000);
});
it('keeps file context but skips visual buckets when the model cannot consume them', () => {
const result = estimateSentMessageAttachmentTokenBuckets(
[
mkMsg({
+ audioList: [{ alt: 'audio.mp3', id: 'audio-id', url: 'https://example.com/audio.mp3' }],
imageList: [{ alt: 'image.png', id: 'image-id', url: 'https://example.com/image.png' }],
role: 'user',
videoList: [{ alt: 'video.mp4', id: 'video-id', url: 'https://example.com/video.mp4' }],
}),
],
- { canUseVideo: false, canUseVision: false },
+ { canUseAudio: false, canUseVideo: false, canUseVision: false },
);
expect(result.textTokens).toBeGreaterThan(0);
expect(result.imageTokens).toBe(0);
expect(result.videoTokens).toBe(0);
+ expect(result.audioTokens).toBe(0);
});
it('estimates pending upload buckets with text fallback and loaded text content', () => {
@@ -83,16 +87,17 @@ describe('attachment token buckets', () => {
mkUploadFile({ id: 'text-file', name: 'note.txt', size: 40, type: 'text/plain' }),
mkUploadFile({ id: 'image-file', name: 'image.png', size: 100, type: 'image/png' }),
mkUploadFile({ id: 'video-file', name: 'video.mp4', size: 200, type: 'video/mp4' }),
+ mkUploadFile({ id: 'audio-file', name: 'audio.mp3', size: 300, type: 'audio/mpeg' }),
];
const fallbackResult = estimatePendingUploadTokenBuckets(
files,
- { canUseVideo: true, canUseVision: true },
+ { canUseAudio: true, canUseVideo: true, canUseVision: true },
{},
);
const loadedResult = estimatePendingUploadTokenBuckets(
files,
- { canUseVideo: true, canUseVision: true },
+ { canUseAudio: true, canUseVideo: true, canUseVision: true },
{ 'text-file': 'loaded text content' },
);
@@ -100,8 +105,10 @@ describe('attachment token buckets', () => {
expect(loadedResult.textTokens).toBeGreaterThan(0);
expect(fallbackResult.imageTokens).toBe(1000);
expect(fallbackResult.videoTokens).toBe(1000);
+ expect(fallbackResult.audioTokens).toBe(1000);
expect(loadedResult.imageTokens).toBe(1000);
expect(loadedResult.videoTokens).toBe(1000);
+ expect(loadedResult.audioTokens).toBe(1000);
});
it('detects text-like upload files by mime type and extension', () => {
diff --git a/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts
index 392884244bc..a9f70e34a2a 100644
--- a/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts
+++ b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts
@@ -1,6 +1,7 @@
// cspell:ignore tokenx
import { filesPrompts } from '@lobechat/prompts';
import type {
+ ChatAudioItem,
ChatFileItem,
ChatImageItem,
ChatVideoItem,
@@ -12,6 +13,10 @@ import { estimateTokenCount } from 'tokenx';
const ESTIMATE_INPUT_MESSAGE_ID = '__cost_estimate_input__';
const VISUAL_INPUT_TOKEN_ESTIMATE = 1000;
+// Per-attachment flat estimate for audio media parts. Audio token usage scales
+// with duration (Gemini bills ~32 tokens/sec), but duration isn't available at
+// preflight, so we mirror the visual flat-per-item heuristic as a lower bound.
+const AUDIO_INPUT_TOKEN_ESTIMATE = 1000;
const BYTES_PER_TEXT_TOKEN_ESTIMATE = 4;
const TEXT_UPLOAD_MIME_TYPES = new Set([
'application/javascript',
@@ -31,17 +36,20 @@ const TEXT_UPLOAD_MIME_TYPES = new Set([
const TEXT_UPLOAD_EXTENSION_OVERRIDES = new Set(['.cs', '.jsonl', '.ts', '.tsx']);
export interface InputTokenBuckets {
+ audioTokens: number;
imageTokens: number;
textTokens: number;
videoTokens: number;
}
interface AttachmentTokenOptions {
+ canUseAudio: boolean;
canUseVideo: boolean;
canUseVision: boolean;
}
export const EMPTY_TOKEN_BUCKETS: InputTokenBuckets = {
+ audioTokens: 0,
imageTokens: 0,
textTokens: 0,
videoTokens: 0,
@@ -54,11 +62,13 @@ const countPromptTextTokens = (content: string) => {
};
const countFileContextTokens = ({
+ audioList,
fileList,
imageList,
messageId,
videoList,
}: {
+ audioList?: ChatAudioItem[];
fileList?: ChatFileItem[];
imageList?: ChatImageItem[];
messageId: string;
@@ -66,6 +76,7 @@ const countFileContextTokens = ({
}) => {
const prompt = filesPrompts({
addUrl: false,
+ audioList,
fileList,
imageList,
messageId,
@@ -77,11 +88,12 @@ const countFileContextTokens = ({
export const estimateSentMessageAttachmentTokenBuckets = (
messages: UIChatMessage[],
- { canUseVideo, canUseVision }: AttachmentTokenOptions,
+ { canUseAudio, canUseVideo, canUseVision }: AttachmentTokenOptions,
): InputTokenBuckets => {
let textTokens = 0;
let imageTokens = 0;
let videoTokens = 0;
+ let audioTokens = 0;
for (const message of messages) {
if (message.role !== 'user') continue;
@@ -89,10 +101,18 @@ export const estimateSentMessageAttachmentTokenBuckets = (
const fileList = message.fileList ?? [];
const imageList = message.imageList ?? [];
const videoList = message.videoList ?? [];
-
- if (fileList.length === 0 && imageList.length === 0 && videoList.length === 0) continue;
+ const audioList = message.audioList ?? [];
+
+ if (
+ fileList.length === 0 &&
+ imageList.length === 0 &&
+ videoList.length === 0 &&
+ audioList.length === 0
+ )
+ continue;
textTokens += countFileContextTokens({
+ audioList,
fileList,
imageList,
messageId: message.id,
@@ -106,9 +126,14 @@ export const estimateSentMessageAttachmentTokenBuckets = (
if (canUseVideo) {
videoTokens += videoList.length * VISUAL_INPUT_TOKEN_ESTIMATE;
}
+
+ if (canUseAudio) {
+ audioTokens += audioList.length * AUDIO_INPUT_TOKEN_ESTIMATE;
+ }
}
return {
+ audioTokens,
imageTokens,
textTokens,
videoTokens,
@@ -144,7 +169,7 @@ const estimateTextFileTokensBySize = (size: number) =>
export const estimatePendingUploadTokenBuckets = (
files: UploadFileItem[],
- { canUseVideo, canUseVision }: AttachmentTokenOptions,
+ { canUseAudio, canUseVideo, canUseVision }: AttachmentTokenOptions,
textFileContents: Record<string, string>,
): InputTokenBuckets => {
if (files.length === 0) return EMPTY_TOKEN_BUCKETS;
@@ -152,6 +177,7 @@ export const estimatePendingUploadTokenBuckets = (
const fileList: ChatFileItem[] = [];
const imageList: ChatImageItem[] = [];
const videoList: ChatVideoItem[] = [];
+ const audioList: ChatAudioItem[] = [];
let pendingTextFallbackTokens = 0;
for (const item of files) {
@@ -176,6 +202,15 @@ export const estimatePendingUploadTokenBuckets = (
continue;
}
+ if (type.startsWith('audio')) {
+ audioList.push({
+ alt: item.file.name || item.id,
+ id: item.id,
+ url,
+ });
+ continue;
+ }
+
const textContent = textFileContents[item.id];
if (isTextLikeUploadFile(item) && textContent === undefined) {
pendingTextFallbackTokens += estimateTextFileTokensBySize(item.file.size || 0);
@@ -192,9 +227,11 @@ export const estimatePendingUploadTokenBuckets = (
}
return {
+ audioTokens: canUseAudio ? audioList.length * AUDIO_INPUT_TOKEN_ESTIMATE : 0,
imageTokens: canUseVision ? imageList.length * VISUAL_INPUT_TOKEN_ESTIMATE : 0,
textTokens:
countFileContextTokens({
+ audioList,
fileList,
imageList,
messageId: ESTIMATE_INPUT_MESSAGE_ID,
@@ -207,6 +244,7 @@ export const estimatePendingUploadTokenBuckets = (
export const addTokenBuckets = (...buckets: InputTokenBuckets[]): InputTokenBuckets =>
buckets.reduce<InputTokenBuckets>(
(sum, bucket) => ({
+ audioTokens: sum.audioTokens + bucket.audioTokens,
imageTokens: sum.imageTokens + bucket.imageTokens,
textTokens: sum.textTokens + bucket.textTokens,
videoTokens: sum.videoTokens + bucket.videoTokens,
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 4d11d830910..b551fab0eb4 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1,6 +1,7 @@
import { INBOX_SESSION_ID } from '@lobechat/const';
import { parse } from '@lobechat/conversation-flow';
import type {
+ ChatAudioItem,
ChatFileItem,
ChatImageItem,
ChatToolPayload,
@@ -476,8 +477,12 @@ export class MessageModel {
const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));
const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));
+ const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));
const fileList = relatedFileList.filter(
- (i) => !(i.fileType || '').startsWith('image') && !(i.fileType || '').startsWith('video'),
+ (i) =>
+ !(i.fileType || '').startsWith('image') &&
+ !(i.fileType || '').startsWith('video') &&
+ !(i.fileType || '').startsWith('audio'),
);
const threadMap = this.createThreadMap(threadData);
@@ -544,6 +549,10 @@ export class MessageModel {
.filter((relation) => relation.messageId === item.id)
.map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),
+ audioList: audioList
+ .filter((relation) => relation.messageId === item.id)
+
+ .map<ChatAudioItem>(({ id, url, name }) => ({ alt: name!, id, url })),
} as unknown as UIChatMessage;
},
),
@@ -1013,8 +1022,12 @@ export class MessageModel {
const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));
const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));
+ const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));
const fileList = relatedFileList.filter(
- (i) => !(i.fileType || '').startsWith('image') && !(i.fileType || '').startsWith('video'),
+ (i) =>
+ !(i.fileType || '').startsWith('image') &&
+ !(i.fileType || '').startsWith('video') &&
+ !(i.fileType || '').startsWith('audio'),
);
// 4. Build thread map
@@ -1091,6 +1104,9 @@ export class MessageModel {
videoList: videoList
.filter((relation) => relation.messageId === item.id)
.map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),
+ audioList: audioList
+ .filter((relation) => relation.messageId === item.id)
+ .map<ChatAudioItem>(({ id, url, name }) => ({ alt: name!, id, url })),
} as unknown as UIChatMessage;
},
);
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index 8579f1efb95..1d0a8a46d3b 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -117,6 +117,7 @@ export default {
'LocalFile.action.open': 'Open',
'LocalFile.action.showInFolder': 'Show in Folder',
'MaxTokenSlider.unlimited': 'Unlimited',
+ 'ModelSelect.featureTag.audio': 'This model supports audio input recognition.',
'ModelSelect.featureTag.custom':
'Custom model, by default, supports both tool calls and visual recognition. Please verify the availability of the above capabilities based on actual situations.',
'ModelSelect.featureTag.file': 'This model supports file upload for reading and recognition.',
@@ -133,6 +134,7 @@ export default {
'ModelSwitchPanel.byModel': 'By Model',
'ModelSwitchPanel.byProvider': 'By Provider',
'ModelSwitchPanel.detail.abilities': 'Abilities',
+ 'ModelSwitchPanel.detail.abilities.audio': 'Audio',
'ModelSwitchPanel.detail.abilities.files': 'Files',
'ModelSwitchPanel.detail.abilities.functionCall': 'Tool Calling',
'ModelSwitchPanel.detail.abilities.imageOutput': 'Image Output',
diff --git a/packages/model-bank/src/aiModels/aihubmix.ts b/packages/model-bank/src/aiModels/aihubmix.ts
index 7b616b785f0..673687969c5 100644
--- a/packages/model-bank/src/aiModels/aihubmix.ts
+++ b/packages/model-bank/src/aiModels/aihubmix.ts
@@ -1562,6 +1562,7 @@ const aihubmixChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -1626,6 +1627,7 @@ const aihubmixChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -1659,6 +1661,7 @@ const aihubmixChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -1721,6 +1724,7 @@ const aihubmixChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
diff --git a/packages/model-bank/src/aiModels/google.ts b/packages/model-bank/src/aiModels/google.ts
index 778fe0acd70..25f23215344 100644
--- a/packages/model-bank/src/aiModels/google.ts
+++ b/packages/model-bank/src/aiModels/google.ts
@@ -14,6 +14,7 @@ import type { AIChatModelCard, AIImageModelCard, AIVideoModelCard } from '../typ
const googleChatModels: AIChatModelCard[] = [
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -68,6 +69,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -97,6 +99,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -126,6 +129,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -203,6 +207,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -294,6 +299,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -333,6 +339,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -369,6 +376,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -499,6 +507,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -588,6 +597,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -651,6 +661,7 @@ const googleChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
diff --git a/packages/model-bank/src/aiModels/vertexai.ts b/packages/model-bank/src/aiModels/vertexai.ts
index 2c8f899eb46..b623e56dcaf 100644
--- a/packages/model-bank/src/aiModels/vertexai.ts
+++ b/packages/model-bank/src/aiModels/vertexai.ts
@@ -6,6 +6,7 @@ import { imagenGenParameters } from './google';
const vertexaiChatModels: AIChatModelCard[] = [
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -83,6 +84,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -174,6 +176,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -213,6 +216,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -249,6 +253,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
@@ -308,6 +313,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
{
abilities: {
+ audio: true,
functionCall: true,
reasoning: true,
search: true,
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index ddb80aedb85..ed9a9f83fef 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -26,6 +26,10 @@ export const AiModelTypeSchema = z.enum([
export type AiModelType = z.infer<typeof AiModelTypeSchema>;
export interface ModelAbilities {
+ /**
+ * whether model supports audio input understanding
+ */
+ audio?: boolean;
/**
* whether model supports file upload
*/
@@ -61,6 +65,7 @@ export interface ModelAbilities {
}
const AiModelAbilitiesSchema = z.object({
+ audio: z.boolean().optional(),
// files: z.boolean().optional(),
functionCall: z.boolean().optional(),
imageOutput: z.boolean().optional(),
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index ac92476d557..607071fb50c 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -383,6 +383,94 @@ describe('google contextBuilders', () => {
expect(imageToBase64Spy).not.toHaveBeenCalled();
});
+ it('should handle base64 audio', async () => {
+ const base64Audio = 'data:audio/mp3;base64,mockAudioBase64Data';
+
+ vi.mocked(parseDataUri).mockReturnValueOnce({
+ base64: 'mockAudioBase64Data',
+ mimeType: 'audio/mp3',
+ type: 'base64',
+ });
+
+ const content: UserMessageContentPart = {
+ audio_url: { url: base64Audio },
+ type: 'audio_url',
+ };
+
+ const result = await buildGooglePart(content);
+
+ expect(result).toEqual({
+ inlineData: {
+ data: 'mockAudioBase64Data',
+ mimeType: 'audio/mp3',
+ },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ });
+ });
+
+ it('should default mimeType to audio/mp3 when base64 audio has no mime', async () => {
+ vi.mocked(parseDataUri).mockReturnValueOnce({
+ base64: 'mockAudioBase64Data',
+ mimeType: null,
+ type: 'base64',
+ });
+
+ const content: UserMessageContentPart = {
+ audio_url: { url: 'data:;base64,mockAudioBase64Data' },
+ type: 'audio_url',
+ };
+
+ const result = await buildGooglePart(content);
+
+ expect(result).toEqual({
+ inlineData: {
+ data: 'mockAudioBase64Data',
+ mimeType: 'audio/mp3',
+ },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ });
+ });
+
+ it('should use fileData for external URL audio on gemini-3+', async () => {
+ const audioUrl = 'https://example.com/audio.mp3';
+
+ vi.mocked(parseDataUri).mockReturnValueOnce({
+ base64: null,
+ mimeType: null,
+ type: 'url',
+ });
+
+ vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
+ vi.mocked(validateExternalUrl).mockResolvedValueOnce({
+ contentLength: 1024,
+ contentType: 'audio/mpeg',
+ isValid: true,
+ });
+
+ const imageToBase64Spy = vi
+ .spyOn(imageToBase64Module, 'imageUrlToBase64')
+ .mockResolvedValueOnce({
+ base64: 'mockAudioBase64Data',
+ mimeType: 'audio/mpeg',
+ });
+
+ const content: UserMessageContentPart = {
+ audio_url: { url: audioUrl },
+ type: 'audio_url',
+ };
+
+ const result = await buildGooglePart(content, { model: 'gemini-3-flash-preview' });
+
+ expect(result).toEqual({
+ fileData: {
+ fileUri: audioUrl,
+ mimeType: 'audio/mpeg',
+ },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ });
+ expect(imageToBase64Spy).not.toHaveBeenCalled();
+ });
+
it('should return undefined for unsupported SVG image (base64)', async () => {
const svgBase64 =
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==';
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 1706e290b25..77ff6c7364e 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -176,6 +176,40 @@ export const buildGooglePart = async (
throw new TypeError(`currently we don't support video url: ${content.video_url.url}`);
}
+
+ case 'audio_url': {
+ const { mimeType, base64, type } = parseDataUri(content.audio_url.url);
+
+ if (type === 'base64') {
+ if (!base64) {
+ throw new TypeError("Audio URL doesn't contain base64 data");
+ }
+
+ return {
+ inlineData: { data: base64, mimeType: mimeType || 'audio/mp3' },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ };
+ }
+
+ if (type === 'url') {
+ const url = content.audio_url.url;
+
+ const externalUrlPart = await buildExternalUrlFileDataPart(url, options);
+ if (externalUrlPart) return externalUrlPart;
+
+ // Fallback: convert URL to base64 (for private/local URLs or earlier model
+ // generations that don't support external fileData URIs).
+ // imageUrlToBase64 provides SSRF protection and works for any binary data.
+ const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(url);
+
+ return {
+ inlineData: { data: urlBase64, mimeType: urlMimeType || 'audio/mp3' },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ };
+ }
+
+ throw new TypeError(`currently we don't support audio url: ${content.audio_url.url}`);
+ }
}
};
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index e5197abfe8d..9d3ba984204 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -37,11 +37,16 @@ interface UserMessageContentPartVideo {
type: 'video_url';
video_url: { url: string };
}
+interface UserMessageContentPartAudio {
+ audio_url: { url: string };
+ type: 'audio_url';
+}
export type UserMessageContentPart =
| UserMessageContentPartText
| UserMessageContentPartImage
| UserMessageContentPartVideo
+ | UserMessageContentPartAudio
| UserMessageContentPartThinking;
export interface OpenAIChatMessage {
diff --git a/packages/model-runtime/src/utils/uriParser.test.ts b/packages/model-runtime/src/utils/uriParser.test.ts
index 993a1f7316a..826857d0642 100644
--- a/packages/model-runtime/src/utils/uriParser.test.ts
+++ b/packages/model-runtime/src/utils/uriParser.test.ts
@@ -114,6 +114,34 @@ describe('validateExternalUrl', () => {
});
});
+ it('should accept supported external audio URLs', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValueOnce(
+ mockHeadResponse({ 'content-length': '1024', 'content-type': 'audio/wav' }),
+ );
+
+ const result = await validateExternalUrl('https://example.com/audio.wav');
+
+ expect(result).toEqual({
+ contentLength: 1024,
+ contentType: 'audio/wav',
+ isValid: true,
+ });
+ });
+
+ it('should normalize audio/mpeg to audio/mp3 so mp3 URLs hand off as fileData', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValueOnce(
+ mockHeadResponse({ 'content-length': '1024', 'content-type': 'audio/mpeg' }),
+ );
+
+ const result = await validateExternalUrl('https://example.com/audio.mp3');
+
+ expect(result).toEqual({
+ contentLength: 1024,
+ contentType: 'audio/mp3',
+ isValid: true,
+ });
+ });
+
it('should reject supported MIME types when Content-Length is missing', async () => {
vi.mocked(ssrfSafeFetch).mockResolvedValueOnce(
mockHeadResponse({ 'content-type': 'image/png' }),
diff --git a/packages/model-runtime/src/utils/uriParser.ts b/packages/model-runtime/src/utils/uriParser.ts
index 2119f70ca79..e9ae8ce0901 100644
--- a/packages/model-runtime/src/utils/uriParser.ts
+++ b/packages/model-runtime/src/utils/uriParser.ts
@@ -63,6 +63,13 @@ const GOOGLE_EXTERNAL_URL_SUPPORTED_TYPES = new Set([
'video/webm',
'video/wmv',
'video/x-flv',
+ // Audio file types
+ 'audio/aac',
+ 'audio/aiff',
+ 'audio/flac',
+ 'audio/mp3',
+ 'audio/ogg',
+ 'audio/wav',
]);
const normalizeExternalContentType = (contentType: string): string => {
@@ -70,6 +77,11 @@ const normalizeExternalContentType = (contentType: string): string => {
// Normalize it to the standard type to avoid unnecessary fallback to inline base64.
if (contentType === 'image/jpg') return 'image/jpeg';
+ // MP3 is commonly served as `audio/mpeg` / `audio/mpg`, but Gemini's external
+ // URL feature expects `audio/mp3`. Normalize so audio URLs are handed off as
+ // fileData instead of falling back to downloading + inlining the whole file.
+ if (contentType === 'audio/mpeg' || contentType === 'audio/mpg') return 'audio/mp3';
+
return contentType;
};
diff --git a/packages/prompts/src/prompts/files/audio.ts b/packages/prompts/src/prompts/files/audio.ts
new file mode 100644
index 00000000000..0a06bfb8da1
--- /dev/null
+++ b/packages/prompts/src/prompts/files/audio.ts
@@ -0,0 +1,30 @@
+import { createVisualFileRef } from '@lobechat/const/visualRef';
+import type { ChatAudioItem } from '@lobechat/types';
+
+const audioPrompt = (
+ item: ChatAudioItem,
+ attachUrl: boolean,
+ index: number,
+ messageId?: string,
+) => {
+ const ref = createVisualFileRef({ index, messageId, type: 'audio' });
+
+ return attachUrl
+ ? `<audio ref="${ref}" name="${item.alt}" url="${item.url}"></audio>`
+ : `<audio ref="${ref}" name="${item.alt}"></audio>`;
+};
+
+export const audiosPrompts = (
+ audioList: ChatAudioItem[],
+ addUrl: boolean = true,
+ messageId?: string,
+) => {
+ if (audioList.length === 0) return '';
+
+ const prompt = `<audios>
+<audios_docstring>here are user upload audios you can refer to</audios_docstring>
+${audioList.map((item, index) => audioPrompt(item, addUrl, index, messageId)).join('\n')}
+</audios>`;
+
+ return prompt.trim();
+};
diff --git a/packages/prompts/src/prompts/files/index.test.ts b/packages/prompts/src/prompts/files/index.test.ts
index fe8faf8a35a..faf6f49f214 100644
--- a/packages/prompts/src/prompts/files/index.test.ts
+++ b/packages/prompts/src/prompts/files/index.test.ts
@@ -1,5 +1,5 @@
import { createVisualFileRef } from '@lobechat/const/visualRef';
-import type { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { filesPrompts } from './index';
@@ -26,6 +26,12 @@ describe('filesPrompts', () => {
url: 'https://example.com/video.mp4',
};
+ const mockAudio: ChatAudioItem = {
+ id: 'audio-1',
+ alt: 'test audio',
+ url: 'https://example.com/audio.mp3',
+ };
+
it('should generate prompt with only images', () => {
const result = filesPrompts({
imageList: [mockImage],
@@ -209,6 +215,34 @@ describe('filesPrompts', () => {
);
});
+ describe('Audio functionality', () => {
+ it('should generate prompt with only audios', () => {
+ const result = filesPrompts({
+ audioList: [mockAudio],
+ });
+
+ expect(result).toEqual(
+ `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<files_info>
+<audios>
+<audios_docstring>here are user upload audios you can refer to</audios_docstring>
+<audio ref="audio_1" name="test audio" url="https://example.com/audio.mp3"></audio>
+</audios>
+</files_info>
+<!-- END SYSTEM CONTEXT -->`,
+ );
+ });
+
+ it('should return empty string for empty audio list', () => {
+ expect(filesPrompts({ audioList: [] })).toBe('');
+ });
+ });
+
describe('Video functionality', () => {
it('should generate prompt with only videos', () => {
const result = filesPrompts({
diff --git a/packages/prompts/src/prompts/files/index.ts b/packages/prompts/src/prompts/files/index.ts
index d7d4d05c006..146b12a66cc 100644
--- a/packages/prompts/src/prompts/files/index.ts
+++ b/packages/prompts/src/prompts/files/index.ts
@@ -1,5 +1,6 @@
-import type { ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import { audiosPrompts } from './audio';
import { filePrompts } from './file';
import { imagesPrompts } from './image';
import { videosPrompts } from './video';
@@ -11,10 +12,12 @@ export const filesPrompts = ({
imageList,
fileList,
videoList,
+ audioList,
addUrl = true,
messageId,
}: {
addUrl?: boolean;
+ audioList?: ChatAudioItem[];
fileList?: ChatFileItem[];
imageList?: ChatImageItem[];
messageId?: string;
@@ -23,13 +26,15 @@ export const filesPrompts = ({
const hasImages = (imageList || []).length > 0;
const hasFiles = (fileList || []).length > 0;
const hasVideos = (videoList || []).length > 0;
+ const hasAudios = (audioList || []).length > 0;
- if (!hasImages && !hasFiles && !hasVideos) return '';
+ if (!hasImages && !hasFiles && !hasVideos && !hasAudios) return '';
const contentParts = [
hasImages ? imagesPrompts(imageList!, addUrl, messageId) : '',
hasFiles ? filePrompts(fileList!, addUrl) : '',
hasVideos ? videosPrompts(videoList!, addUrl, messageId) : '',
+ hasAudios ? audiosPrompts(audioList!, addUrl, messageId) : '',
].filter(Boolean);
const prompt = `<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
diff --git a/packages/types/src/message/ui/audio.ts b/packages/types/src/message/ui/audio.ts
new file mode 100644
index 00000000000..0c50db7754b
--- /dev/null
+++ b/packages/types/src/message/ui/audio.ts
@@ -0,0 +1,5 @@
+export interface ChatAudioItem {
+ alt: string;
+ id: string;
+ url: string;
+}
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index ba3459e599c..2a4a83b477b 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -14,6 +14,7 @@ import type {
ChatToolPayloadWithResult,
ToolIntervention,
} from '../common/tools';
+import type { ChatAudioItem } from './audio';
import type { ChatMessageExtra } from './extra';
import type { ChatFileChunk } from './rag';
import type { ChatVideoItem } from './video';
@@ -173,6 +174,7 @@ export interface TaskDetail {
export interface UIChatMessage {
// Group chat fields (alphabetically before other fields)
agentId?: string | 'supervisor';
+ audioList?: ChatAudioItem[];
/**
* Branch information for user messages with multiple children
*/
diff --git a/packages/types/src/message/ui/index.ts b/packages/types/src/message/ui/index.ts
index 6c36fb48a4e..b5bbe1de3be 100644
--- a/packages/types/src/message/ui/index.ts
+++ b/packages/types/src/message/ui/index.ts
@@ -1,3 +1,4 @@
+export * from './audio';
export * from './chat';
export * from './extra';
export * from './params';
diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.ts
index f736aae3a3a..d981e02a8f2 100644
--- a/packages/types/src/openai/chat.ts
+++ b/packages/types/src/openai/chat.ts
@@ -37,11 +37,16 @@ interface UserMessageContentPartVideo {
type: 'video_url';
video_url: { url: string };
}
+interface UserMessageContentPartAudio {
+ audio_url: { url: string };
+ type: 'audio_url';
+}
export type UserMessageContentPart =
| UserMessageContentPartText
| UserMessageContentPartImage
- | UserMessageContentPartVideo;
+ | UserMessageContentPartVideo
+ | UserMessageContentPartAudio;
export interface OpenAIChatMessage {
/**
diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.ts
index e98a9e8ce40..5085ec1dbfd 100644
--- a/src/components/DragUploadZone/useUploadFiles.ts
+++ b/src/components/DragUploadZone/useUploadFiles.ts
@@ -21,7 +21,10 @@ interface UseUploadFilesOptions {
export const useUploadFiles = (options: UseUploadFilesOptions) => {
const { agentId, model = '', provider = '' } = options;
- const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
+ const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(
+ model,
+ provider,
+ );
const uploadFiles = useFileStore((s) => s.uploadChatFiles);
const { allowed: canUpload } = usePermission('create_content');
@@ -29,10 +32,11 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {
async (files: File[]) => {
if (!canUpload) return;
- // Filter out visual files if the model cannot receive them directly or via fallback.
+ // Filter out media files if the model cannot receive them directly or via fallback.
const filteredFiles = files.filter((file) => {
if (file.type.startsWith('image')) return canUploadImage;
if (file.type.startsWith('video')) return canUploadVideo;
+ if (file.type.startsWith('audio')) return canUploadAudio;
return true;
});
@@ -40,8 +44,8 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {
uploadFiles(filteredFiles, agentId);
}
},
- [agentId, canUpload, canUploadImage, canUploadVideo, uploadFiles],
+ [agentId, canUpload, canUploadImage, canUploadVideo, canUploadAudio, uploadFiles],
);
- return { canUploadImage, canUploadVideo, handleUploadFiles };
+ return { canUploadImage, canUploadVideo, canUploadAudio, handleUploadFiles };
};
diff --git a/src/components/ModelSelect/index.tsx b/src/components/ModelSelect/index.tsx
index 1972ff7d73c..0e4dbe06c5f 100644
--- a/src/components/ModelSelect/index.tsx
+++ b/src/components/ModelSelect/index.tsx
@@ -5,6 +5,7 @@ import { type FlexboxProps } from '@lobehub/ui';
import { Avatar, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, useResponsive } from 'antd-style';
import {
+ AudioLines,
Infinity as InfinityIcon,
LucideEye,
LucideImage,
@@ -63,7 +64,7 @@ interface ModelInfoTagsProps extends ModelAbilities {
interface FeatureTagsProps extends Pick<
ModelAbilities,
- 'files' | 'imageOutput' | 'vision' | 'video' | 'functionCall'
+ 'files' | 'imageOutput' | 'vision' | 'video' | 'audio' | 'functionCall'
> {
disableTooltip?: boolean;
placement: 'top' | 'right';
@@ -102,6 +103,7 @@ const FeatureTagItem = memo<FeatureTagItemProps>(
const FeatureTags = memo<FeatureTagsProps>(
({
+ audio,
disableTooltip,
files,
functionCall,
@@ -151,6 +153,15 @@ const FeatureTags = memo<FeatureTagsProps>(
placement={placement}
title={t('ModelSelect.featureTag.video')}
/>
+ <FeatureTagItem
+ className={tagClassName}
+ color={'gold'}
+ disableTooltip={disableTooltip}
+ enabled={audio}
+ icon={AudioLines}
+ placement={placement}
+ title={t('ModelSelect.featureTag.audio')}
+ />
<FeatureTagItem
className={tagClassName}
color={'info'}
@@ -212,6 +223,7 @@ export const ModelInfoTags = memo<ModelInfoTagsProps>(
width={'fit-content'}
>
<FeatureTags
+ audio={model.audio}
disableTooltip={disableTooltip}
files={model.files}
functionCall={model.functionCall}
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 73132bc8d96..a20423d9edd 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -323,7 +323,10 @@ const PlusAction = memo(() => {
const isMemoryEnabled = useMemoryEnabled(agentId);
const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
const editor = useChatInputStore((s) => s.editor);
- const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
+ const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(
+ model,
+ provider,
+ );
const enableFC = useModelSupportToolUse(model, provider);
const handleOpenKnowledge = useCallback(() => {
setDropdownOpen(false);
@@ -473,6 +476,7 @@ const PlusAction = memo(() => {
beforeUpload={async (file) => {
if (file.type.startsWith('image') && !canUploadImage) return false;
if (file.type.startsWith('video') && !canUploadVideo) return false;
+ if (file.type.startsWith('audio') && !canUploadAudio) return false;
const validation = validateVideoFileSize(file);
if (!validation.isValid) {
message.error(
@@ -666,6 +670,7 @@ const PlusAction = memo(() => {
activeSearchOption,
canUploadImage,
canUploadVideo,
+ canUploadAudio,
editor,
enableFC,
enableGatewayMode,
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index 604463aaf3a..233c43f6d41 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -56,7 +56,10 @@ const FileUpload = memo(() => {
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
- const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
+ const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(
+ model,
+ provider,
+ );
const [showTip, updateGuideState] = useUserStore((s) => [
preferenceSelectors.showUploadFileInKnowledgeBaseTip(s),
@@ -130,7 +133,8 @@ const FileUpload = memo(() => {
beforeUpload={async (file) => {
if (
(file.type.startsWith('image') && !canUploadImage) ||
- (file.type.startsWith('video') && !canUploadVideo)
+ (file.type.startsWith('video') && !canUploadVideo) ||
+ (file.type.startsWith('audio') && !canUploadAudio)
)
return false;
@@ -169,7 +173,8 @@ const FileUpload = memo(() => {
beforeUpload={async (file) => {
if (
(file.type.startsWith('image') && !canUploadImage) ||
- (file.type.startsWith('video') && !canUploadVideo)
+ (file.type.startsWith('video') && !canUploadVideo) ||
+ (file.type.startsWith('audio') && !canUploadAudio)
)
return false;
diff --git a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx
new file mode 100644
index 00000000000..47e8c47a36b
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx
@@ -0,0 +1,23 @@
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { type ChatAudioItem } from '@/types/index';
+
+interface AudioFileListViewerProps {
+ items: ChatAudioItem[];
+}
+
+const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items }) => {
+ return (
+ <Flexbox gap={8}>
+ {items.map((item) => (
+ <audio controls key={item.id} style={{ maxWidth: '100%', width: 360 }}>
+ <source src={item.url} />
+ {item.alt}
+ </audio>
+ ))}
+ </Flexbox>
+ );
+});
+
+export default AudioFileListViewer;
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx
index 2c44b747007..c57acd7ae11 100644
--- a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx
+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx
@@ -29,6 +29,9 @@ vi.mock('./PageSelections', () => ({
vi.mock('./VideoFileListViewer', () => ({
default: () => null,
}));
+vi.mock('./AudioFileListViewer', () => ({
+ default: ({ items }: any) => <div data-testid="audio-viewer">{items.length}</div>,
+}));
describe('User MessageContent', () => {
it('should prefer rich text rendering when editorData exists', () => {
@@ -61,4 +64,19 @@ describe('User MessageContent', () => {
expect(screen.getByTestId('markdown-message')).toBeInTheDocument();
expect(screen.queryByTestId('rich-message')).not.toBeInTheDocument();
});
+
+ it('should render the audio viewer when audioList has items', () => {
+ render(
+ <MessageContent
+ audioList={[{ alt: 'audio.mp3', id: 'a1', url: 'https://example.com/a.mp3' }]}
+ content={''}
+ createdAt={Date.now()}
+ id={'msg-3'}
+ role={'user'}
+ updatedAt={Date.now()}
+ />,
+ );
+
+ expect(screen.getByTestId('audio-viewer')).toHaveTextContent('1');
+ });
});
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsx
index 1e12bd98bc7..0977ede1a83 100644
--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx
@@ -6,6 +6,7 @@ import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';
import { type UIChatMessage } from '@/types/index';
import { useMarkdown } from '../useMarkdown';
+import AudioFileListViewer from './AudioFileListViewer';
import CollapsibleContent from './CollapsibleContent';
import FileListViewer from './FileListViewer';
import ImageFileListViewer from './ImageFileListViewer';
@@ -14,7 +15,7 @@ import RichTextMessage from './RichTextMessage';
import VideoFileListViewer from './VideoFileListViewer';
const UserMessageContent = memo<UIChatMessage>(
- ({ id, content, editorData, imageList, videoList, fileList, metadata }) => {
+ ({ id, content, editorData, imageList, videoList, audioList, fileList, metadata }) => {
const markdownProps = useMarkdown(id);
const pageSelections = metadata?.pageSelections;
const displayContent = useMemo(() => (content ? cleanSpeakerTag(content) : content), [content]);
@@ -36,6 +37,7 @@ const UserMessageContent = memo<UIChatMessage>(
{textBody && <CollapsibleContent>{textBody}</CollapsibleContent>}
{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}
{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}
+ {audioList && audioList?.length > 0 && <AudioFileListViewer items={audioList} />}
{fileList && fileList?.length > 0 && <FileListViewer items={fileList} />}
</Flexbox>
);
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
index a196c7d8346..86f5844426e 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
@@ -7,6 +7,7 @@ import {
ArrowDownToDot,
ArrowUpFromDot,
AtomIcon,
+ AudioLinesIcon,
CircleFadingArrowUp,
EyeIcon,
GlobeIcon,
@@ -301,6 +302,7 @@ const ABILITY_CONFIG: AbilityItem[] = [
{ color: 'success', icon: PaperclipIcon, key: 'files' },
{ color: 'success', icon: ImageIcon, key: 'imageOutput' },
{ color: 'magenta', icon: VideoIcon, key: 'video' },
+ { color: 'gold', icon: AudioLinesIcon, key: 'audio' },
{ color: 'info', icon: WrenchIcon, key: 'functionCall' },
{ color: 'purple', icon: AtomIcon, key: 'reasoning' },
{ color: 'cyan', icon: GlobeIcon, key: 'search' },
diff --git a/src/hooks/useModelSupportAudio.ts b/src/hooks/useModelSupportAudio.ts
new file mode 100644
index 00000000000..a0d00c134fa
--- /dev/null
+++ b/src/hooks/useModelSupportAudio.ts
@@ -0,0 +1,10 @@
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiModelSelectors } from '@/store/aiInfra/selectors';
+
+export const useModelSupportAudio = (id?: string, provider?: string) => {
+ return useAiInfraStore((s) => {
+ if (!id || !provider) return false;
+
+ return aiModelSelectors.isModelSupportAudio(id, provider)(s);
+ });
+};
diff --git a/src/hooks/useVisualMediaUploadAbility.ts b/src/hooks/useVisualMediaUploadAbility.ts
index ff1a3335a5e..6cc63e7a8b2 100644
--- a/src/hooks/useVisualMediaUploadAbility.ts
+++ b/src/hooks/useVisualMediaUploadAbility.ts
@@ -1,3 +1,4 @@
+import { useModelSupportAudio } from '@/hooks/useModelSupportAudio';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useModelSupportVideo } from '@/hooks/useModelSupportVideo';
import { useModelSupportVision } from '@/hooks/useModelSupportVision';
@@ -7,6 +8,7 @@ import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfi
export const useVisualMediaUploadAbility = (model: string, provider: string) => {
const supportVision = useModelSupportVision(model, provider);
const supportVideo = useModelSupportVideo(model, provider);
+ const supportAudio = useModelSupportAudio(model, provider);
const supportToolUse = useModelSupportToolUse(model, provider);
const enableVisualUnderstanding = useServerConfigStore(
serverConfigSelectors.enableVisualUnderstanding,
@@ -24,6 +26,7 @@ export const useVisualMediaUploadAbility = (model: string, provider: string) =>
const canUseVisualUnderstanding = enableVisualUnderstanding && supportToolUse;
return {
+ canUploadAudio: supportAudio,
canUploadImage: supportVision || (canUseVisualUnderstanding && fallbackSupportVision),
canUploadVideo: supportVideo || (canUseVisualUnderstanding && fallbackSupportVideo),
};
diff --git a/src/services/chat/helper.test.ts b/src/services/chat/helper.test.ts
index b10e74abdaf..0531ae5bb07 100644
--- a/src/services/chat/helper.test.ts
+++ b/src/services/chat/helper.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import { useAiInfraStore } from '@/store/aiInfra';
-import { isCanUseVideo, isCanUseVision } from './helper';
+import { isCanUseAudio, isCanUseVideo, isCanUseVision } from './helper';
describe('chat helper', () => {
afterEach(() => {
@@ -14,7 +14,7 @@ describe('chat helper', () => {
useAiInfraStore.setState({
enabledAiModels: [
{
- abilities: { video: true, vision: true },
+ abilities: { audio: true, video: true, vision: true },
id: 'gemini-3.1-flash-lite-preview',
providerId: ModelProvider.Google,
type: 'chat',
@@ -24,13 +24,14 @@ describe('chat helper', () => {
expect(isCanUseVision('gemini-3.1-flash-lite-preview', ModelProvider.LobeHub)).toBe(true);
expect(isCanUseVideo('gemini-3.1-flash-lite-preview', ModelProvider.LobeHub)).toBe(true);
+ expect(isCanUseAudio('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 },
+ abilities: { audio: true, video: true, vision: true },
id: 'gemini-3.1-flash-lite-preview',
providerId: ModelProvider.Google,
type: 'chat',
@@ -40,5 +41,6 @@ describe('chat helper', () => {
expect(isCanUseVision('gemini-3.1-flash-lite-preview', ModelProvider.OpenAI)).toBe(false);
expect(isCanUseVideo('gemini-3.1-flash-lite-preview', ModelProvider.OpenAI)).toBe(false);
+ expect(isCanUseAudio('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 8712fec269f..27bfe082664 100644
--- a/src/services/chat/helper.ts
+++ b/src/services/chat/helper.ts
@@ -22,6 +22,10 @@ export const isCanUseVideo = (model: string, provider: string): boolean => {
return getModelAbilities(model, provider)?.video || false;
};
+export const isCanUseAudio = (model: string, provider: string): boolean => {
+ return getModelAbilities(model, provider)?.audio || false;
+};
+
/**
* TODO: we need to update this function to auto find deploymentName with provider setting config
*/
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index a5dba35f9e7..698283fe245 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -69,7 +69,7 @@ import {
} from '@/store/tool/selectors';
import { ComposioServerStatus } from '@/store/tool/slices/composioStore';
-import { isCanUseVideo, isCanUseVision } from '../helper';
+import { isCanUseAudio, isCanUseVideo, isCanUseVision } from '../helper';
import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';
import { resolveClientSkills } from './skillEngineering';
@@ -670,6 +670,7 @@ export const contextEngineering = async ({
// Capability injection
capabilities: {
+ isCanUseAudio,
isCanUseFC,
isCanUseVideo,
isCanUseVision,
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index 8cc18ec8d28..3d41cb5974c 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -68,6 +68,12 @@ const isModelSupportVideo = (id: string, provider: string) => (s: AIProviderStor
return model?.abilities?.video;
};
+const isModelSupportAudio = (id: string, provider: string) => (s: AIProviderStoreState) => {
+ const model = getEnabledModelById(id, provider)(s);
+
+ return model?.abilities?.audio || false;
+};
+
const isModelSupportImageOutput = (id: string, provider: string) => (s: AIProviderStoreState) => {
const model = getEnabledModelById(id, provider)(s);
@@ -160,6 +166,7 @@ export const aiModelSelectors = {
isModelHasContextWindowToken,
isModelHasExtendParams,
isModelLoading,
+ isModelSupportAudio,
isModelSupportFiles,
isModelSupportImageOutput,
isModelSupportReasoning,
diff --git a/src/store/file/slices/chat/uploadGuard.test.ts b/src/store/file/slices/chat/uploadGuard.test.ts
index f4a2e96fc2a..6aed85ca1c1 100644
--- a/src/store/file/slices/chat/uploadGuard.test.ts
+++ b/src/store/file/slices/chat/uploadGuard.test.ts
@@ -37,6 +37,17 @@ describe('isSupportedChatUploadFile', () => {
isSupportedChatUploadFile(new File(['zip'], 'archive.zip', { type: 'application/zip' })),
).toBe(false);
});
+
+ it('accepts audio formats (model-level gating happens in the upload UI)', () => {
+ expect(isSupportedChatUploadFile(new File(['a'], 'voice.mp3', { type: 'audio/mpeg' }))).toBe(
+ true,
+ );
+ // .m4a often reports a non-audio or empty mime — fall back to the extension.
+ expect(isSupportedChatUploadFile(new File(['a'], 'voice.m4a', { type: '' }))).toBe(true);
+ expect(isSupportedChatUploadFile(new File(['a'], 'voice.wav', { type: 'audio/wav' }))).toBe(
+ true,
+ );
+ });
});
describe('filterSupportedChatUploadFiles', () => {
diff --git a/src/store/file/slices/chat/uploadGuard.ts b/src/store/file/slices/chat/uploadGuard.ts
index c110d742909..6502770bc6c 100644
--- a/src/store/file/slices/chat/uploadGuard.ts
+++ b/src/store/file/slices/chat/uploadGuard.ts
@@ -8,6 +8,18 @@ const SUPPORTED_CHAT_IMAGE_TYPES = new Set([
const SUPPORTED_CHAT_IMAGE_EXTENSIONS = new Set(['gif', 'jpeg', 'jpg', 'png', 'webp']);
+const SUPPORTED_CHAT_AUDIO_EXTENSIONS = new Set([
+ 'aac',
+ 'flac',
+ 'm4a',
+ 'mp3',
+ 'oga',
+ 'ogg',
+ 'opus',
+ 'wav',
+ 'weba',
+]);
+
const SUPPORTED_CHAT_DOCUMENT_EXTENSIONS = new Set([
'bat',
'bash',
@@ -103,7 +115,11 @@ export const isSupportedChatUploadFile = (file: File) => {
if (fileType.startsWith('video/')) return true;
- if (fileType.startsWith('audio/')) return false;
+ if (fileType.startsWith('audio/')) return true;
+
+ // Some audio containers (e.g. .m4a) report an empty or non-audio mime in the
+ // browser, so fall back to the extension before the document checks below.
+ if (SUPPORTED_CHAT_AUDIO_EXTENSIONS.has(extension)) return true;
if (extension) return SUPPORTED_CHAT_DOCUMENT_EXTENSIONS.has(extension);