Skip to content

Build and run agents you can see, understand and trust.

feat(asr): add browser speech input and DashScope models (#3298)

qbc9c006f3865c5
diff --git a/examples/web_ui/frontend/public/pcm-recorder-worklet.js b/examples/web_ui/frontend/public/pcm-recorder-worklet.js
new file mode 100644
index 000000000..c8dd51a9a
--- /dev/null
+++ b/examples/web_ui/frontend/public/pcm-recorder-worklet.js
@@ -0,0 +1,37 @@
+class PCMRecorderProcessor extends AudioWorkletProcessor {
+ constructor() {
+ super();
+ this.buffer = new Int16Array(1024);
+ this.offset = 0;
+ this.port.onmessage = (event) => {
+ if (event.data?.type !== 'flush') return;
+ this.flush();
+ this.port.postMessage({ type: 'flushed' });
+ };
+ }
+
+ flush() {
+ if (this.offset === 0) return;
+ const tail = this.buffer.slice(0, this.offset);
+ this.port.postMessage(tail.buffer, [tail.buffer]);
+ this.buffer = new Int16Array(1024);
+ this.offset = 0;
+ }
+
+ process(inputs) {
+ const input = inputs[0]?.[0];
+ if (!input || input.length === 0) return true;
+
+ for (let index = 0; index < input.length; index += 1) {
+ const sample = Math.max(-1, Math.min(1, input[index]));
+ this.buffer[this.offset] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
+ this.offset += 1;
+ if (this.offset === this.buffer.length) {
+ this.flush();
+ }
+ }
+ return true;
+ }
+}
+
+registerProcessor('pcm-recorder', PCMRecorderProcessor);
diff --git a/examples/web_ui/frontend/src/api/asr.ts b/examples/web_ui/frontend/src/api/asr.ts
new file mode 100644
index 000000000..0d271238c
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/asr.ts
@@ -0,0 +1,29 @@
+import { client } from './client';
+import type { RealtimeASRTokenResponse, TranscriptionResponse } from './types';
+
+interface TranscriptionRequest {
+ file: File;
+ credentialId: string;
+ model: string;
+ parameters: Record<string, unknown>;
+}
+
+export const asrApi = {
+ createRealtimeToken: (credentialId: string, model: string) =>
+ client.post<RealtimeASRTokenResponse>(
+ '/asr/realtime/token',
+ { credential_id: credentialId, model },
+ undefined,
+ { silent: true },
+ ),
+ transcribe: ({ file, credentialId, model, parameters }: TranscriptionRequest) => {
+ const body = new FormData();
+ body.append('file', file);
+ body.append('credential_id', credentialId);
+ body.append('model', model);
+ body.append('parameters', JSON.stringify(parameters));
+ return client.post<TranscriptionResponse>('/asr/transcriptions', body, undefined, {
+ silent: true,
+ });
+ },
+};
diff --git a/examples/web_ui/frontend/src/api/client.ts b/examples/web_ui/frontend/src/api/client.ts
index 66a1c0b8e..47252d0ee 100644
--- a/examples/web_ui/frontend/src/api/client.ts
+++ b/examples/web_ui/frontend/src/api/client.ts
@@ -37,9 +37,9 @@ interface RequestOptions {
/** Reported when `timeoutMs` elapses. Real 408s come from a server, so either way the request did not complete in time. */
export const TIMEOUT_STATUS = 408;
-function buildHeaders(hasBody: boolean, userId?: string): Record<string, string> {
+function buildHeaders(hasJsonBody: boolean, userId?: string): Record<string, string> {
const headers: Record<string, string> = { 'X-User-ID': userId ?? getUserId() };
- if (hasBody) headers['Content-Type'] = 'application/json';
+ if (hasJsonBody) headers['Content-Type'] = 'application/json';
return headers;
}
@@ -80,10 +80,11 @@ async function streamRequest(path: string, options: RequestOptions = {}): Promis
let res: Response;
try {
+ const isFormData = body instanceof FormData;
res = await fetch(url.toString(), {
method,
- headers: buildHeaders(body !== undefined, userId),
- body: body ? JSON.stringify(body) : undefined,
+ headers: buildHeaders(body !== undefined && !isFormData, userId),
+ body: isFormData ? body : body !== undefined ? JSON.stringify(body) : undefined,
signal: combined,
});
} catch (e) {
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 0ecb3712c..478592bde 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -8,7 +8,8 @@ export { hubApi } from './hub';
export { mcpApi } from './mcp';
export { skillApi } from './skill';
export { scheduleApi } from './schedule';
-export { embeddingModelApi, modelApi, realtimeModelApi, ttsModelApi } from './model';
+export { asrApi } from './asr';
+export { asrModelApi, embeddingModelApi, modelApi, realtimeModelApi, ttsModelApi } from './model';
export { realtimeApi } from './realtime';
export { knowledgeBaseApi } from './knowledgeBase';
export { voiceProfileApi } from './voiceProfile';
diff --git a/examples/web_ui/frontend/src/api/model.ts b/examples/web_ui/frontend/src/api/model.ts
index 8c1bf1fbb..78bf543ec 100644
--- a/examples/web_ui/frontend/src/api/model.ts
+++ b/examples/web_ui/frontend/src/api/model.ts
@@ -1,11 +1,16 @@
import { client } from './client';
import type {
+ ListASRModelResponse,
ListEmbeddingModelResponse,
ListModelResponse,
ListRealtimeModelResponse,
ListTTSModelResponse,
} from './types';
+export const asrModelApi = {
+ list: (provider: string) => client.get<ListASRModelResponse>('/asr-model/', { provider }),
+};
+
export const modelApi = {
list: (provider: string) => client.get<ListModelResponse>('/model/', { provider }),
};
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index d145171d3..c3e876b5f 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -22,6 +22,13 @@ export interface TTSModelConfig {
parameters: Record<string, unknown>;
}
+export interface ASRModelConfig {
+ type: string;
+ credential_id: string;
+ model: string;
+ parameters: Record<string, unknown>;
+}
+
export interface RealtimeModelConfig {
type: string;
credential_id: string;
@@ -159,6 +166,8 @@ export interface SessionConfig {
fallback_chat_model_config: ChatModelConfig | null;
/** TTS model configuration. null means TTS is not enabled. */
tts_model_config: TTSModelConfig | null;
+ /** ASR model configuration. null means speech input is not enabled. */
+ asr_model_config: ASRModelConfig | null;
/** Realtime voice model configuration. null disables voice mode. */
realtime_model_config: RealtimeModelConfig | null;
/** Knowledge bases attached to this session + KB middleware parameters. */
@@ -198,6 +207,8 @@ export interface CreateSessionRequest {
fallback_chat_model_config?: ChatModelConfig | null;
/** Optional TTS model. Omit (or pass null) for no TTS. */
tts_model_config?: TTSModelConfig | null;
+ /** Optional ASR model. Omit (or pass null) for no speech input. */
+ asr_model_config?: ASRModelConfig | null;
/** Optional realtime voice model. Omit (or pass null) for none. */
realtime_model_config?: RealtimeModelConfig | null;
/** Optional knowledge base attachment. Omit (or null) for none. */
@@ -229,6 +240,8 @@ export interface UpdateSessionRequest {
* - set to a value → replace the existing TTS config
*/
tts_model_config?: TTSModelConfig | null;
+ /** New ASR model, or null to disable speech input. */
+ asr_model_config?: ASRModelConfig | null;
/** New realtime voice model, or null to disable voice mode. */
realtime_model_config?: RealtimeModelConfig | null;
/**
@@ -1309,6 +1322,33 @@ export interface ChannelChatIdsResponse {
chats: { chat_id: string; name: string; source: string }[];
}
+// ─── ASR ──────────────────────────────────────────────────────────────────────
+
+export interface ASRModelCard {
+ type: 'asr_model';
+ name: string;
+ label: string;
+ input_types: string[];
+ output_types: string[];
+ realtime: boolean;
+ parameter_schema: Record<string, unknown>;
+ parameters_overrides: Record<string, Record<string, unknown>>;
+}
+
+export interface ListASRModelResponse {
+ models: ASRModelCard[];
+ total: number;
+}
+
+export interface TranscriptionResponse {
+ text: string;
+}
+
+export interface RealtimeASRTokenResponse {
+ token: string;
+ expires_at: number;
+}
+
// ─── TTS ──────────────────────────────────────────────────────────────────────
export interface TTSModelCard {
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 560434776..9cd39663b 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -32,6 +32,7 @@ import {
import { Spinner } from '@/components/ui/spinner';
import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n';
+import type { RealtimeASRConfig } from '@/lib/browserRealtimeASRTransport';
import type { RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
import { cn } from '@/lib/utils';
@@ -101,6 +102,18 @@ interface ChatContentProps {
voiceState?: RealtimeConnectionState;
onVoiceToggle?: () => void;
voiceDisabled?: boolean;
+ /** Audio media types accepted by the selected ASR model. */
+ asrInputTypes?: string[];
+ /** Transcribes one completed browser recording. */
+ onTranscribe?: (file: File) => Promise<string>;
+ /** Whether the selected model uses streaming recognition. */
+ asrRealtime?: boolean;
+ /** Configuration for the realtime ASR browser transport. */
+ realtimeASRConfig?: RealtimeASRConfig | null;
+ /** Whether speech-to-text recording is unavailable. */
+ asrDisabled?: boolean;
+ /** Identity used to discard recording state after context changes. */
+ asrResetKey?: string;
/**
* Optional content pinned at the bottom of the chat — between the
* message scroll area and the text input (e.g. pending subagent HITL
@@ -149,6 +162,12 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
voiceState,
onVoiceToggle,
voiceDisabled,
+ asrInputTypes,
+ onTranscribe,
+ asrRealtime,
+ realtimeASRConfig,
+ asrDisabled,
+ asrResetKey,
footerSlot,
allowedInputTypes,
fileProcessor,
@@ -372,6 +391,12 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
voiceState={voiceState}
onVoiceToggle={onVoiceToggle}
voiceDisabled={voiceDisabled}
+ asrInputTypes={asrInputTypes}
+ onTranscribe={onTranscribe}
+ asrRealtime={asrRealtime}
+ realtimeASRConfig={realtimeASRConfig}
+ asrDisabled={asrDisabled}
+ asrResetKey={asrResetKey}
headerSlot={
<div className="flex w-full items-center justify-between px-2 py-1 text-sm text-muted-foreground">
<WorkingDirectoryDialog
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index b40fd0b39..0e673600d 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -3,6 +3,8 @@ import {
AudioLines,
ArrowUp,
FileText,
+ Mic,
+ MicOff,
Loader2,
Paperclip,
Square,
@@ -13,12 +15,14 @@ import mime from 'mime';
import React, {
useState,
useRef,
+ useEffect,
useMemo,
useLayoutEffect,
type KeyboardEvent,
useImperativeHandle,
forwardRef,
} from 'react';
+import { toast } from 'sonner';
import { Button } from '../ui/button';
import { Kbd } from '../ui/kbd';
@@ -33,8 +37,11 @@ import {
AttachmentTitle,
} from '@/components/ui/attachment.tsx';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useAudioRecorder } from '@/hooks/useAudioRecorder';
import type { ReplyPhase } from '@/hooks/useMessages';
+import { useRealtimeAudioRecorder } from '@/hooks/useRealtimeAudioRecorder';
import { useTranslation } from '@/i18n/useI18n.ts';
+import type { RealtimeASRConfig } from '@/lib/browserRealtimeASRTransport';
import type { RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
import { cn } from '@/lib/utils';
@@ -92,6 +99,18 @@ interface TextInputProps {
onVoiceToggle?: () => void;
/** Prevents voice start when no realtime model is configured. */
voiceDisabled?: boolean;
+ /** Audio formats accepted by the selected ASR model. */
+ asrInputTypes?: string[];
+ /** Upload one completed recording and return its transcription. */
+ onTranscribe?: (file: File) => Promise<string>;
+ /** Whether the selected ASR model consumes live PCM audio. */
+ asrRealtime?: boolean;
+ /** Credential and model used by server-proxied realtime ASR. */
+ realtimeASRConfig?: RealtimeASRConfig | null;
+ /** Prevents recording when the active credential has no ASR model. */
+ asrDisabled?: boolean;
+ /** Restarts recorder state when its session, credential, or model changes. */
+ asrResetKey?: string;
/**
* Content rendered directly above the input pill, inside the outer
* wrapper that {@link className} styles (e.g. the working directory
@@ -153,6 +172,12 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
voiceState = 'idle',
onVoiceToggle,
voiceDisabled = false,
+ asrInputTypes = [],
+ onTranscribe,
+ asrRealtime = false,
+ realtimeASRConfig = null,
+ asrDisabled = false,
+ asrResetKey = '',
headerSlot,
},
ref,
@@ -175,6 +200,94 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
const measureRef = useRef<HTMLSpanElement>(null);
/** ``true`` — textarea takes the full width, buttons drop to their own row. */
const [isStacked, setIsStacked] = useState(false);
+ const asrContextRef = useRef({ key: asrResetKey, mounted: true });
+
+ useEffect(() => {
+ asrContextRef.current = { key: asrResetKey, mounted: true };
+ return () => {
+ asrContextRef.current.mounted = false;
+ };
+ }, [asrResetKey]);
+
+ const handleRecorded = async (file: File) => {
+ if (!onTranscribe) return;
+ const requestKey = asrResetKey;
+ const transcript = (await onTranscribe(file)).trim();
+ if (!asrContextRef.current.mounted || asrContextRef.current.key !== requestKey) return;
+ if (!transcript) {
+ toast.info(t('textInput.transcriptionEmpty'));
+ return;
+ }
+ setValue((current) =>
+ current.trimEnd() ? `${current.trimEnd()} ${transcript}` : transcript,
+ );
+ requestAnimationFrame(() => textareaRef.current?.focus());
+ };
+
+ const handleRecordingError = (error: unknown) => {
+ const permissionDenied =
+ error instanceof DOMException &&
+ (error.name === 'NotAllowedError' || error.name === 'SecurityError');
+ toast.error(
+ permissionDenied
+ ? t('textInput.microphonePermissionDenied')
+ : t('textInput.transcriptionFailed'),
+ );
+ };
+
+ const audioRecorder = useAudioRecorder({
+ acceptedTypes: asrInputTypes,
+ resetKey: asrResetKey,
+ onRecorded: handleRecorded,
+ onError: handleRecordingError,
+ });
+ const realtimeBaseRef = useRef('');
+ const realtimeAudioRecorder = useRealtimeAudioRecorder({
+ config: realtimeASRConfig,
+ resetKey: asrResetKey,
+ onStart: () => {
+ realtimeBaseRef.current = value.trimEnd();
+ },
+ onTranscript: (text, isLast) => {
+ const transcript = text.trim();
+ const base = realtimeBaseRef.current;
+ setValue(base && transcript ? `${base} ${transcript}` : base || transcript);
+ if (isLast) {
+ if (!transcript) toast.info(t('textInput.transcriptionEmpty'));
+ requestAnimationFrame(() => textareaRef.current?.focus());
+ }
+ },
+ onError: handleRecordingError,
+ });
+ const speechRecorder = asrRealtime ? realtimeAudioRecorder : audioRecorder;
+ const speechInputBusy = speechRecorder.state !== 'idle';
+ const speechHandlerUnavailable = asrRealtime ? !realtimeASRConfig : !onTranscribe;
+ const speechInputDisabled =
+ speechRecorder.state !== 'recording' &&
+ (disabled ||
+ phase !== 'idle' ||
+ asrDisabled ||
+ speechHandlerUnavailable ||
+ !speechRecorder.supported ||
+ speechRecorder.state !== 'idle');
+ const speechInputTooltip = (() => {
+ if (speechRecorder.state === 'requesting') {
+ return t('textInput.requestingMicrophone');
+ }
+ if (speechRecorder.state === 'recording') {
+ return t('textInput.stopRecording');
+ }
+ if (speechRecorder.state === 'transcribing') {
+ return t('textInput.transcribing');
+ }
+ if (asrDisabled || speechHandlerUnavailable) {
+ return t('textInput.asrUnavailable');
+ }
+ if (!speechRecorder.supported) {
+ return t('textInput.recordingUnsupported');
+ }
+ return t('textInput.startRecording');
+ })();
// Derive the accept attribute for the hidden file input
const acceptAttr =
@@ -247,7 +360,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
};
const handleSend = async () => {
- if (!hasContent || disabled || hasProcessing || submitting) return;
+ if (!hasContent || disabled || hasProcessing || submitting || speechInputBusy) return;
const blocks: ContentBlock[] = [];
@@ -327,7 +440,8 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
return {
icon: submitting ? Loader2 : ArrowUp,
tooltip: replyActive ? t('textInput.queue') : t('textInput.send'),
- disabled: disabled || !hasContent || hasProcessing || submitting,
+ disabled:
+ disabled || !hasContent || hasProcessing || submitting || speechInputBusy,
variant: 'default',
onClick: handleSend,
};
@@ -335,7 +449,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
return {
icon: AudioLines,
tooltip: voiceDisabled ? t('realtime.selectFirst') : t('realtime.start'),
- disabled: voiceDisabled,
+ disabled: voiceDisabled || speechInputBusy,
variant: 'ghost',
onClick: onVoiceToggle,
};
@@ -477,7 +591,8 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
<div className="flex shrink-0 gap-2">
<div className="size-9" />
<div className="size-9" />
- {replyActive && <div className="size-9" />}
+ <div className="size-9" />
+ {replyActive && !voiceActive && <div className="size-9" />}
</div>
</div>
@@ -497,6 +612,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
onBlur={() => setIsFocused(false)}
placeholder={defaultPlaceholder}
disabled={disabled}
+ readOnly={asrRealtime && speechInputBusy}
rows={1}
className="block w-full resize-none rounded-md border-0 bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
style={{
@@ -562,6 +678,40 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
</TooltipContent>
</Tooltip>
+ {/* Speech-to-text recording */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ className="inline-flex shrink-0"
+ tabIndex={speechInputDisabled ? 0 : undefined}
+ >
+ <Button
+ type="button"
+ aria-label={speechInputTooltip}
+ variant="ghost"
+ size="icon-lg"
+ onClick={speechRecorder.toggle}
+ disabled={speechInputDisabled}
+ className={cn(
+ 'relative shrink-0 rounded-full transition-colors',
+ speechRecorder.state === 'recording' &&
+ 'bg-destructive/10 text-destructive hover:bg-destructive/15 hover:text-destructive',
+ )}
+ >
+ {speechRecorder.state === 'requesting' ||
+ speechRecorder.state === 'transcribing' ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : speechRecorder.state === 'recording' ? (
+ <MicOff className="size-4" />
+ ) : (
+ <Mic className="size-4" />
+ )}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{speechInputTooltip}</TooltipContent>
+ </Tooltip>
+
{/* Keep Stop and Send separate while a reply is active:
users can enqueue another turn without losing the
ability to interrupt the current generation. */}
@@ -590,26 +740,32 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
{/* Voice or Send — driven by ``actionButton`` config. */}
<Tooltip>
<TooltipTrigger asChild>
- <Button
- type="button"
- variant={actionButton.variant}
- onClick={actionButton.onClick}
- disabled={actionButton.disabled}
- size="icon-lg"
- className={cn(
- 'relative shrink-0 rounded-full transition-colors',
- voiceState === 'active' &&
- 'before:absolute before:inset-[-4px] before:rounded-full before:border before:border-primary/30 before:animate-pulse',
- )}
+ <span
+ className="inline-flex shrink-0"
+ tabIndex={actionButton.disabled ? 0 : undefined}
>
- <actionButton.icon
+ <Button
+ type="button"
+ aria-label={actionButton.tooltip}
+ variant={actionButton.variant}
+ onClick={actionButton.onClick}
+ disabled={actionButton.disabled}
+ size="icon-lg"
className={cn(
- 'h-4 w-4',
- (voiceState === 'connecting' || submitting) &&
- 'animate-spin',
+ 'relative shrink-0 rounded-full transition-colors',
+ voiceState === 'active' &&
+ 'before:absolute before:inset-[-4px] before:rounded-full before:border before:border-primary/30 before:animate-pulse',
)}
- />
- </Button>
+ >
+ <actionButton.icon
+ className={cn(
+ 'h-4 w-4',
+ (voiceState === 'connecting' || submitting) &&
+ 'animate-spin',
+ )}
+ />
+ </Button>
+ </span>
</TooltipTrigger>
<TooltipContent>{actionButton.tooltip}</TooltipContent>
</Tooltip>
diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
index e0a64a6bd..da10c9ccb 100644
--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
@@ -2,6 +2,8 @@ import { Check, ChevronDown, SlidersHorizontal } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import type {
+ ASRModelCard,
+ ASRModelConfig,
ChatModelConfig,
CredentialView,
ModelCard,
@@ -33,6 +35,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { type CredentialWithASRModels, useAvailableASRModels } from '@/hooks/useAvailableASRModels';
import { useAvailableModels } from '@/hooks/useAvailableModels';
import { useAvailableTTSModels } from '@/hooks/useAvailableTTSModels';
import { useVoiceEngines } from '@/hooks/useVoiceEngines';
@@ -307,6 +310,262 @@ function StringField({ id, label, required, prop, value, onChange }: FieldProps)
);
}
+function JsonField({ id, label, required, prop, value, onChange }: FieldProps) {
+ const [draft, setDraft] = useState(value === undefined ? '' : JSON.stringify(value));
+ const [invalid, setInvalid] = useState(false);
+
+ useEffect(() => {
+ setDraft(value === undefined ? '' : JSON.stringify(value));
+ setInvalid(false);
+ }, [value]);
+
+ return (
+ <>
+ <Label htmlFor={id} className="whitespace-nowrap">
+ {label}
+ {required && <span className="text-destructive ml-0.5">*</span>}
+ </Label>
+ <Input
+ id={id}
+ type="text"
+ value={draft}
+ aria-invalid={invalid}
+ placeholder={prop.default === undefined ? undefined : JSON.stringify(prop.default)}
+ onChange={(event) => {
+ setDraft(event.target.value);
+ setInvalid(false);
+ }}
+ onBlur={() => {
+ if (draft.trim() === '') {
+ onChange(undefined);
+ return;
+ }
+ try {
+ const parsed = JSON.parse(draft) as unknown;
+ const expected = resolveType(prop).type;
+ const matches =
+ (expected === 'array' && Array.isArray(parsed)) ||
+ (expected === 'object' &&
+ typeof parsed === 'object' &&
+ parsed !== null &&
+ !Array.isArray(parsed));
+ if (!matches) {
+ setInvalid(true);
+ return;
+ }
+ onChange(parsed);
+ } catch {
+ setInvalid(true);
+ }
+ }}
+ />
+ </>
+ );
+}
+
+interface ASRModelMenuProps {
+ groups: Record<string, CredentialWithASRModels[]>;
+ selectedASRModel: ASRModelConfig | null;
+ onASRChange: (config: ASRModelConfig | null) => void;
+}
+
+function ASRModelMenu({ groups, selectedASRModel, onASRChange }: ASRModelMenuProps) {
+ const { t } = useTranslation();
+ const groupEntries = Object.entries(groups)
+ .map(([type, items]) => [type, items.filter((item) => item.models.length > 0)] as const)
+ .filter(([, items]) => items.length > 0);
+
+ let selectedCard: ASRModelCard | undefined;
+ if (selectedASRModel) {
+ for (const item of groups[selectedASRModel.type] ?? []) {
+ if (item.credential.id !== selectedASRModel.credential_id) continue;
+ selectedCard = item.models.find((model) => model.name === selectedASRModel.model);
+ if (selectedCard) break;
+ }
+ }
+
+ const renderModels = (type: string, credential: CredentialView, models: ASRModelCard[]) =>
+ models.map((model) => {
+ const selected =
+ selectedASRModel?.credential_id === credential.id &&
+ selectedASRModel.model === model.name;
+ return (
+ <DropdownMenuCheckboxItem
+ key={`${credential.id}-${model.name}`}
+ checked={selected}
+ onSelect={(event) => event.preventDefault()}
+ onCheckedChange={(checked) => {
+ if (!checked) return;
+ onASRChange({
+ type,
+ credential_id: credential.id,
+ model: model.name,
+ parameters: extractDefaults(
+ model.parameter_schema as ParameterSchema | undefined,
+ ),
+ });
+ }}
+ >
+ <span className="min-w-0 flex-1 whitespace-normal wrap-anywhere">
+ {model.label}
+ </span>
+ {model.realtime && (
+ <Badge variant="outline" className="ml-1.5 shrink-0 px-1 py-0 text-[10px]">
+ Realtime
+ </Badge>
+ )}
+ </DropdownMenuCheckboxItem>
+ );
+ });
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="truncate">{t('model-parameters.asrLabel')}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-96 w-max max-w-[calc(100vw-2rem)] overflow-y-auto">
+ {groupEntries.length === 0 ? (
+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">
+ <p>{t('model-parameters.asrEmpty')}</p>
+ </div>
+ ) : (
+ groupEntries.map(([type, items], index) => {
+ const singleCredential = items.length === 1;
+ return (
+ <DropdownMenuGroup key={type}>
+ {index > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuLabel>
+ {type.replace(/_credential$/, '')}
+ </DropdownMenuLabel>
+ {singleCredential
+ ? renderModels(type, items[0].credential, items[0].models)
+ : items.map(({ credential, models }) => {
+ const selected = models.some(
+ (model) =>
+ selectedASRModel?.credential_id ===
+ credential.id &&
+ selectedASRModel.model === model.name,
+ );
+ return (
+ <DropdownMenuSub key={credential.id}>
+ <DropdownMenuSubTrigger>
+ <Check
+ className={cn(
+ 'size-4 mr-1.5 shrink-0',
+ !selected && 'invisible',
+ )}
+ />
+ {credentialLabel(credential)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent className="max-h-60 w-max max-w-[calc(100vw-2rem)] overflow-y-auto">
+ {renderModels(type, credential, models)}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ );
+ })}
+ </DropdownMenuGroup>
+ );
+ })
+ )}
+
+ {selectedASRModel && selectedCard && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ {t('model-parameters.asrParameters')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-80 max-h-96 overflow-y-auto p-3">
+ <p className="mb-3 text-xs text-muted-foreground">
+ {t('model-parameters.asrParametersDescription')}
+ </p>
+ {(() => {
+ const schema = selectedCard.parameter_schema as
+ | ParameterSchema
+ | undefined;
+ const entries = Object.entries(schema?.properties ?? {});
+ if (entries.length === 0) {
+ return (
+ <p className="text-xs text-muted-foreground">
+ {t('model-parameters.empty')}
+ </p>
+ );
+ }
+ const required = schema?.required ?? [];
+ const values = selectedASRModel.parameters ?? {};
+ return (
+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3">
+ {entries.map(([key, prop]) => {
+ const fieldProps: FieldProps = {
+ id: `asr-${selectedCard.name}-${key}`,
+ label: prop.title ?? key,
+ required: required.includes(key),
+ prop,
+ value: values[key],
+ onChange: (value) => {
+ const parameters = {
+ ...values,
+ [key]: value,
+ };
+ if (value === '' || value === undefined)
+ delete parameters[key];
+ onASRChange({
+ ...selectedASRModel,
+ parameters,
+ });
+ },
+ };
+ const { type, enumValues } = resolveType(prop);
+ let field: React.ReactNode;
+ if (type === 'boolean')
+ field = <BooleanField {...fieldProps} />;
+ else if (enumValues)
+ field = <EnumField {...fieldProps} />;
+ else if (type === 'number' || type === 'integer')
+ field = <NumberField {...fieldProps} />;
+ else if (type === 'array' || type === 'object')
+ field = <JsonField {...fieldProps} />;
+ else field = <StringField {...fieldProps} />;
+ return (
+ <Tooltip key={key}>
+ <TooltipTrigger asChild>
+ <div className="col-span-2 grid grid-cols-subgrid items-center">
+ {field}
+ </div>
+ </TooltipTrigger>
+ {prop.description && (
+ <TooltipContent side="left">
+ {prop.description}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+ })()}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </>
+ )}
+
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ checked={!selectedASRModel}
+ onSelect={(event) => event.preventDefault()}
+ onCheckedChange={(checked) => {
+ if (checked) onASRChange(null);
+ }}
+ >
+ {t('model-parameters.noAsr')}
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
@@ -326,6 +585,10 @@ interface Props {
selectedTTSModel?: TTSModelConfig | null;
/** Called when the user picks a TTS model+voice or disables TTS. */
onTTSChange?: (config: TTSModelConfig | null) => void;
+ /** Currently selected ASR model. `null` means speech input is disabled. */
+ selectedASRModel?: ASRModelConfig | null;
+ /** Called when the user picks an ASR model or disables speech input. */
+ onASRChange?: (config: ASRModelConfig | null) => void;
/**
* Locks the trigger while a session config write is in flight, so a
* second edit cannot race the first. The trigger is also locked
@@ -360,6 +623,8 @@ export function ModelParametersPopover({
onFallbackChange,
selectedTTSModel,
onTTSChange,
+ selectedASRModel,
+ onASRChange,
disabled: locked = false,
idPrefix = 'model',
triggerLabel,
@@ -370,6 +635,7 @@ export function ModelParametersPopover({
const { t } = useTranslation();
const { groups } = useAvailableModels();
const { groups: ttsGroups } = useAvailableTTSModels();
+ const { groups: asrGroups } = useAvailableASRModels();
const { profiles: voiceProfiles } = useVoiceProfiles();
const { engineDetails } = useVoiceEngines(selectedTTSModel !== undefined);
@@ -528,8 +794,8 @@ export function ModelParametersPopover({
variant="ghost"
size="icon-sm"
disabled={disabled}
- aria-label={triggerLabel}
- title={triggerLabel}
+ aria-label={triggerLabel ?? t('model-parameters.settings')}
+ tooltip={triggerLabel ?? t('model-parameters.settings')}
>
<SlidersHorizontal />
</Button>
@@ -995,6 +1261,15 @@ export function ModelParametersPopover({
</DropdownMenuSubContent>
</DropdownMenuSub>
)}
+
+ {/* ----- ASR ----- */}
+ {onASRChange !== undefined && (
+ <ASRModelMenu
+ groups={asrGroups}
+ selectedASRModel={selectedASRModel ?? null}
+ onASRChange={onASRChange}
+ />
+ )}
</DropdownMenuContent>
</DropdownMenu>
);
diff --git a/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
index 0e366e178..39ae794fa 100644
--- a/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
+++ b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
@@ -63,6 +63,8 @@ export function RealtimeModelSelect({
<Button
variant="ghost"
size="sm"
+ aria-label={t('realtime.selectModel')}
+ tooltip={t('realtime.selectModel')}
className={cn('max-w-52 justify-between gap-1 font-mono', className)}
{...props}
>
diff --git a/examples/web_ui/frontend/src/hooks/useAudioRecorder.ts b/examples/web_ui/frontend/src/hooks/useAudioRecorder.ts
new file mode 100644
index 000000000..5096f15ff
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useAudioRecorder.ts
@@ -0,0 +1,163 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+export type AudioRecorderState = 'idle' | 'requesting' | 'recording' | 'transcribing';
+
+interface UseAudioRecorderOptions {
+ acceptedTypes: string[];
+ resetKey: string;
+ onRecorded: (file: File) => Promise<void>;
+ onError: (error: unknown) => void;
+}
+
+const MIME_CANDIDATES: Record<string, string[]> = {
+ 'audio/webm': ['audio/webm;codecs=opus', 'audio/webm'],
+ 'audio/ogg': ['audio/ogg;codecs=opus', 'audio/ogg'],
+ 'audio/mp4': ['audio/mp4'],
+ 'audio/mpeg': ['audio/mpeg'],
+ 'audio/wav': ['audio/wav'],
+};
+
+const FILE_EXTENSIONS: Record<string, string> = {
+ 'audio/webm': 'webm',
+ 'audio/ogg': 'ogg',
+ 'audio/mp4': 'mp4',
+ 'audio/mpeg': 'mp3',
+ 'audio/wav': 'wav',
+};
+
+/** Pick a MediaRecorder format accepted by both the browser and ASR model. */
+function selectMimeType(acceptedTypes: string[]): string | null {
+ if (typeof MediaRecorder === 'undefined') return null;
+ for (const [baseType, candidates] of Object.entries(MIME_CANDIDATES)) {
+ if (!acceptedTypes.includes(baseType) && !acceptedTypes.includes('audio/*')) {
+ continue;
+ }
+ for (const candidate of candidates) {
+ if (MediaRecorder.isTypeSupported(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
+/** Record one microphone clip and hand it to an asynchronous consumer. */
+export function useAudioRecorder({
+ acceptedTypes,
+ resetKey,
+ onRecorded,
+ onError,
+}: UseAudioRecorderOptions) {
+ const [state, setState] = useState<AudioRecorderState>('idle');
+ const recorderRef = useRef<MediaRecorder | null>(null);
+ const streamRef = useRef<MediaStream | null>(null);
+ const chunksRef = useRef<Blob[]>([]);
+ const generationRef = useRef(0);
+ const onRecordedRef = useRef(onRecorded);
+ const onErrorRef = useRef(onError);
+
+ useEffect(() => {
+ onRecordedRef.current = onRecorded;
+ onErrorRef.current = onError;
+ }, [onRecorded, onError]);
+
+ const mimeType = useMemo(() => selectMimeType(acceptedTypes), [acceptedTypes]);
+ const supported =
+ typeof navigator !== 'undefined' &&
+ !!navigator.mediaDevices?.getUserMedia &&
+ mimeType !== null;
+
+ const stopTracks = useCallback(() => {
+ streamRef.current?.getTracks().forEach((track) => track.stop());
+ streamRef.current = null;
+ }, []);
+
+ const reset = useCallback(() => {
+ generationRef.current += 1;
+ const recorder = recorderRef.current;
+ recorderRef.current = null;
+ if (recorder && recorder.state !== 'inactive') {
+ recorder.onstop = null;
+ recorder.stop();
+ }
+ chunksRef.current = [];
+ stopTracks();
+ setState('idle');
+ }, [stopTracks]);
+
+ useEffect(() => {
+ reset();
+ return reset;
+ }, [mimeType, reset, resetKey]);
+
+ const start = useCallback(async () => {
+ if (!supported || !mimeType || state !== 'idle') return;
+ const generation = ++generationRef.current;
+ setState('requesting');
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ if (generation !== generationRef.current) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+
+ streamRef.current = stream;
+ chunksRef.current = [];
+ const recorder = new MediaRecorder(stream, { mimeType });
+ recorderRef.current = recorder;
+ recorder.ondataavailable = (event) => {
+ if (event.data.size > 0) chunksRef.current.push(event.data);
+ };
+ recorder.onstop = () => {
+ const chunks = chunksRef.current;
+ chunksRef.current = [];
+ recorderRef.current = null;
+ stopTracks();
+
+ if (generation !== generationRef.current || chunks.length === 0) {
+ setState('idle');
+ return;
+ }
+
+ const baseType = recorder.mimeType.split(';')[0];
+ const extension = FILE_EXTENSIONS[baseType] ?? 'webm';
+ const file = new File(chunks, `recording.${extension}`, {
+ type: recorder.mimeType,
+ });
+ setState('transcribing');
+ void onRecordedRef
+ .current(file)
+ .catch((error) => {
+ if (generation === generationRef.current) {
+ onErrorRef.current(error);
+ }
+ })
+ .finally(() => {
+ if (generation === generationRef.current) setState('idle');
+ });
+ };
+ recorder.start();
+ setState('recording');
+ } catch (error) {
+ if (generation === generationRef.current) {
+ stopTracks();
+ setState('idle');
+ onErrorRef.current(error);
+ }
+ }
+ }, [mimeType, state, stopTracks, supported]);
+
+ const stop = useCallback(() => {
+ if (state !== 'recording') return;
+ const recorder = recorderRef.current;
+ if (recorder?.state === 'recording') recorder.stop();
+ }, [state]);
+
+ const toggle = useCallback(() => {
+ if (state === 'recording') {
+ stop();
+ return;
+ }
+ if (state === 'idle') void start();
+ }, [start, state, stop]);
+
+ return { state, supported, toggle };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableASRModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableASRModels.ts
new file mode 100644
index 000000000..419a89256
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useAvailableASRModels.ts
@@ -0,0 +1,54 @@
+import { useQuery } from '@tanstack/react-query';
+
+import { asrModelApi, credentialApi } from '@/api';
+import type { ASRModelCard, CredentialView } from '@/api';
+
+export interface CredentialWithASRModels {
+ credential: CredentialView;
+ models: ASRModelCard[];
+}
+
+async function fetchGroups(): Promise<Record<string, CredentialWithASRModels[]>> {
+ const { credentials } = await credentialApi.list();
+ const result: Record<string, CredentialWithASRModels[]> = {};
+ const credentialsByProvider: Record<string, CredentialView[]> = {};
+
+ for (const credential of credentials) {
+ const provider = credential.data.type as string | undefined;
+ if (!provider) continue;
+ (credentialsByProvider[provider] ??= []).push(credential);
+ }
+
+ await Promise.all(
+ Object.entries(credentialsByProvider).map(async ([provider, providerCredentials]) => {
+ try {
+ const response = await asrModelApi.list(provider);
+ const models = response.models;
+ if (models.length === 0) return;
+ result[provider] = providerCredentials.map((credential) => ({
+ credential,
+ models,
+ }));
+ } catch {
+ // A provider without ASR support is not an error here.
+ }
+ }),
+ );
+
+ return result;
+}
+
+export const AVAILABLE_ASR_MODELS_KEY = ['available-asr-models'];
+
+/** Fetch batch and realtime ASR models for every configured credential. */
+export function useAvailableASRModels() {
+ const { data, isPending, error } = useQuery({
+ queryKey: AVAILABLE_ASR_MODELS_KEY,
+ queryFn: fetchGroups,
+ });
+ return {
+ groups: data ?? {},
+ loading: isPending,
+ error: error as Error | null,
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useCredentials.ts b/examples/web_ui/frontend/src/hooks/useCredentials.ts
index ee2c50d76..aec609c5d 100644
--- a/examples/web_ui/frontend/src/hooks/useCredentials.ts
+++ b/examples/web_ui/frontend/src/hooks/useCredentials.ts
@@ -3,6 +3,7 @@ import { useState, useEffect, useCallback } from 'react';
import { credentialApi } from '../api';
import type { CredentialView, CreateCredentialRequest, UpdateCredentialRequest } from '../api';
+import { AVAILABLE_ASR_MODELS_KEY } from './useAvailableASRModels';
import { AVAILABLE_MODELS_KEY } from './useAvailableModels';
import { AVAILABLE_REALTIME_MODELS_KEY } from './useAvailableRealtimeModels';
@@ -38,6 +39,7 @@ export function useCredentials() {
const refresh = useCallback(async () => {
await refetch();
await Promise.all([
+ queryClient.invalidateQueries({ queryKey: AVAILABLE_ASR_MODELS_KEY }),
queryClient.invalidateQueries({ queryKey: AVAILABLE_MODELS_KEY }),
queryClient.invalidateQueries({ queryKey: AVAILABLE_REALTIME_MODELS_KEY }),
]);
diff --git a/examples/web_ui/frontend/src/hooks/useRealtimeAudioRecorder.ts b/examples/web_ui/frontend/src/hooks/useRealtimeAudioRecorder.ts
new file mode 100644
index 000000000..b23ef7875
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useRealtimeAudioRecorder.ts
@@ -0,0 +1,187 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import {
+ BrowserRealtimeASRTransport,
+ type RealtimeASRConfig,
+} from '@/lib/browserRealtimeASRTransport';
+
+export type RealtimeAudioRecorderState = 'idle' | 'requesting' | 'recording' | 'transcribing';
+
+interface UseRealtimeAudioRecorderOptions {
+ config: RealtimeASRConfig | null;
+ resetKey: string;
+ onStart: () => void;
+ onTranscript: (text: string, isLast: boolean) => void;
+ onError: (error: unknown) => void;
+}
+
+/** Capture mono PCM16 and stream it to the selected realtime ASR model. */
+export function useRealtimeAudioRecorder({
+ config,
+ resetKey,
+ onStart,
+ onTranscript,
+ onError,
+}: UseRealtimeAudioRecorderOptions) {
+ const [state, setState] = useState<RealtimeAudioRecorderState>('idle');
+ const generationRef = useRef(0);
+ const streamRef = useRef<MediaStream | null>(null);
+ const contextRef = useRef<AudioContext | null>(null);
+ const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
+ const workletRef = useRef<AudioWorkletNode | null>(null);
+ const flushResolveRef = useRef<(() => void) | null>(null);
+ const transportRef = useRef<BrowserRealtimeASRTransport | null>(null);
+ const callbacksRef = useRef({ onStart, onTranscript, onError });
+
+ useEffect(() => {
+ callbacksRef.current = { onStart, onTranscript, onError };
+ }, [onStart, onTranscript, onError]);
+
+ const supported =
+ typeof navigator !== 'undefined' &&
+ !!navigator.mediaDevices?.getUserMedia &&
+ typeof AudioContext !== 'undefined' &&
+ 'audioWorklet' in AudioContext.prototype;
+
+ const stopCapture = useCallback(() => {
+ workletRef.current?.disconnect();
+ workletRef.current = null;
+ sourceRef.current?.disconnect();
+ sourceRef.current = null;
+ streamRef.current?.getTracks().forEach((track) => track.stop());
+ streamRef.current = null;
+ const context = contextRef.current;
+ contextRef.current = null;
+ if (context && context.state !== 'closed') void context.close();
+ }, []);
+
+ const reset = useCallback(() => {
+ generationRef.current += 1;
+ flushResolveRef.current?.();
+ flushResolveRef.current = null;
+ stopCapture();
+ transportRef.current?.close();
+ transportRef.current = null;
+ setState('idle');
+ }, [stopCapture]);
+
+ useEffect(() => {
+ reset();
+ return reset;
+ }, [reset, resetKey]);
+
+ const start = useCallback(async () => {
+ if (!supported || !config || state !== 'idle') return;
+ const generation = ++generationRef.current;
+ setState('requesting');
+ callbacksRef.current.onStart();
+ let stream: MediaStream | null = null;
+ let context: AudioContext | null = null;
+ let transport: BrowserRealtimeASRTransport | null = null;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
+ });
+ if (generation !== generationRef.current) return;
+ streamRef.current = stream;
+
+ context = new AudioContext();
+ contextRef.current = context;
+ await context.audioWorklet.addModule(
+ `${import.meta.env.BASE_URL}pcm-recorder-worklet.js`,
+ );
+ if (generation !== generationRef.current) return;
+ transport = new BrowserRealtimeASRTransport({
+ config,
+ onTranscript: (text, isLast) => {
+ if (generation === generationRef.current) {
+ callbacksRef.current.onTranscript(text, isLast);
+ }
+ },
+ onError: (error) => {
+ if (generation === generationRef.current) {
+ reset();
+ callbacksRef.current.onError(error);
+ }
+ },
+ });
+ transportRef.current = transport;
+ await transport.connect(context.sampleRate);
+ if (generation !== generationRef.current) return;
+
+ const source = context.createMediaStreamSource(stream);
+ const worklet = new AudioWorkletNode(context, 'pcm-recorder');
+ const silentOutput = context.createGain();
+ silentOutput.gain.value = 0;
+ worklet.port.onmessage = (event: MessageEvent<ArrayBuffer | { type: string }>) => {
+ if (generation !== generationRef.current) return;
+ if (event.data instanceof ArrayBuffer) {
+ transport?.sendAudio(event.data);
+ } else if (event.data.type === 'flushed') {
+ flushResolveRef.current?.();
+ flushResolveRef.current = null;
+ }
+ };
+ source.connect(worklet);
+ worklet.connect(silentOutput).connect(context.destination);
+ sourceRef.current = source;
+ workletRef.current = worklet;
+ await context.resume();
+ if (generation !== generationRef.current) return;
+ setState('recording');
+ } catch (error) {
+ if (generation === generationRef.current) {
+ reset();
+ callbacksRef.current.onError(error);
+ }
+ } finally {
+ // A cancelled start must only release its own resources.
+ if (generation !== generationRef.current) {
+ stream?.getTracks().forEach((track) => track.stop());
+ if (context && context.state !== 'closed') void context.close();
+ transport?.close();
+ }
+ }
+ }, [config, state, reset, supported]);
+
+ const stop = useCallback(async () => {
+ if (state !== 'recording') return;
+ const generation = generationRef.current;
+ const transport = transportRef.current;
+ setState('transcribing');
+ const worklet = workletRef.current;
+ if (worklet) {
+ await new Promise<void>((resolve) => {
+ const timeout = window.setTimeout(resolve, 100);
+ flushResolveRef.current = () => {
+ window.clearTimeout(timeout);
+ resolve();
+ };
+ worklet.port.postMessage({ type: 'flush' });
+ });
+ }
+ if (generation !== generationRef.current) return;
+ flushResolveRef.current = null;
+ stopCapture();
+ try {
+ await transport?.stop();
+ } catch (error) {
+ if (generation === generationRef.current) {
+ callbacksRef.current.onError(error);
+ }
+ } finally {
+ transport?.close();
+ if (generation === generationRef.current) {
+ transportRef.current = null;
+ setState('idle');
+ }
+ }
+ }, [state, stopCapture]);
+
+ const toggle = useCallback(() => {
+ if (state === 'recording') void stop();
+ else if (state === 'idle') void start();
+ }, [start, state, stop]);
+
+ return { state, supported, toggle };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index 0bdc57bc1..b147bf1cb 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -104,7 +104,16 @@
"queued_one": "{{count}} message queued",
"queued_other": "{{count}} messages queued",
"stop": "Stop current reply",
- "stopping": "Stopping current reply ..."
+ "stopping": "Stopping current reply ...",
+ "startRecording": "Start voice input",
+ "stopRecording": "Stop and transcribe",
+ "requestingMicrophone": "Requesting microphone access…",
+ "transcribing": "Transcribing…",
+ "asrUnavailable": "Speech recognition is off. Open Model settings next to the chat model at the top, then select a model under Speech recognition.",
+ "recordingUnsupported": "This browser cannot record a supported audio format",
+ "microphonePermissionDenied": "Microphone access was denied",
+ "transcriptionFailed": "Voice transcription failed",
+ "transcriptionEmpty": "No speech was detected"
},
"chatQueue": {
"title_one": "Pending message ({{count}})",
@@ -475,7 +484,7 @@
"parameters": "Realtime voice parameters",
"noModels": "No realtime voice models are available.",
"disable": "Disable voice model",
- "selectFirst": "Select a voice model first",
+ "selectFirst": "Realtime voice is off. Select a model from Voice model (the waveform icon) at the top.",
"start": "Start voice conversation",
"stop": "End voice conversation"
},
@@ -583,6 +592,7 @@
"wednesday": "Wed"
},
"model-parameters": {
+ "settings": "Model settings",
"title": "Model Parameters",
"booleanDefault": "Default",
"booleanEnabled": "On",
@@ -598,7 +608,12 @@
"ttsParametersDescription": "Adjust parameters for the selected TTS model.",
"voiceProfiles": "Voice Profiles",
"voiceProfileUnavailable": "The bound credential or model is unavailable.",
- "noTts": "No TTS"
+ "noTts": "No TTS",
+ "asrLabel": "Speech recognition",
+ "asrEmpty": "No speech recognition models available.",
+ "asrParameters": "Parameters",
+ "asrParametersDescription": "Adjust parameters for the selected speech recognition model. Arrays and objects use JSON.",
+ "noAsr": "No speech recognition"
},
"setup": {
"title": "Connect to Service",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index a0625bff3..b54b362d0 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -104,7 +104,16 @@
"queued_one": "{{count}} 条消息正在排队",
"queued_other": "{{count}} 条消息正在排队",
"stop": "停止当前回复",
- "stopping": "正在停止当前回复 ..."
+ "stopping": "正在停止当前回复 ...",
+ "startRecording": "开始语音输入",
+ "stopRecording": "停止并转写",
+ "requestingMicrophone": "正在请求麦克风权限…",
+ "transcribing": "正在转写…",
+ "asrUnavailable": "语音识别未开启。请在顶部聊天模型旁的「模型设置」→「语音识别」中选择模型。",
+ "recordingUnsupported": "当前浏览器无法录制受支持的音频格式",
+ "microphonePermissionDenied": "麦克风权限已被拒绝",
+ "transcriptionFailed": "语音转写失败",
+ "transcriptionEmpty": "未检测到语音"
},
"chatQueue": {
"title_one": "待发送消息({{count}} 条)",
@@ -475,7 +484,7 @@
"parameters": "实时语音参数",
"noModels": "暂无可用的实时语音模型。",
"disable": "停用语音模型",
- "selectFirst": "请先选择语音模型",
+ "selectFirst": "实时语音未开启。请在顶部的「语音模型」(声波图标)中选择模型。",
"start": "开始语音对话",
"stop": "结束语音对话"
},
@@ -583,6 +592,7 @@
"wednesday": "周三"
},
"model-parameters": {
+ "settings": "模型设置",
"title": "模型参数",
"booleanDefault": "默认",
"booleanEnabled": "开启",
@@ -598,7 +608,12 @@
"ttsParametersDescription": "调整所选语音合成模型的参数。",
"voiceProfiles": "语音配置",
"voiceProfileUnavailable": "绑定的凭证或模型不可用。",
- "noTts": "不使用语音合成"
+ "noTts": "不使用语音合成",
+ "asrLabel": "语音识别",
+ "asrEmpty": "暂无可用的语音识别模型。",
+ "asrParameters": "参数",
+ "asrParametersDescription": "调整所选语音识别模型的参数,数组和对象请使用 JSON。",
+ "noAsr": "不使用语音识别"
},
"setup": {
"title": "连接到服务器",
diff --git a/examples/web_ui/frontend/src/lib/browserRealtimeASRTransport.ts b/examples/web_ui/frontend/src/lib/browserRealtimeASRTransport.ts
new file mode 100644
index 000000000..dcc747c01
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/browserRealtimeASRTransport.ts
@@ -0,0 +1,151 @@
+import { asrApi } from '@/api/asr';
+import { getBaseUrl } from '@/api/client';
+
+export interface RealtimeASRConfig {
+ credentialId: string;
+ model: string;
+ parameters: Record<string, unknown>;
+}
+
+interface RealtimeASRTransportOptions {
+ config: RealtimeASRConfig;
+ onTranscript: (text: string, isLast: boolean) => void;
+ onError: (error: Error) => void;
+}
+
+interface ServerEvent {
+ type: 'ready' | 'transcript' | 'error';
+ text?: string;
+ is_last?: boolean;
+ detail?: string;
+}
+
+/** Browser WebSocket transport for server-proxied realtime ASR. */
+export class BrowserRealtimeASRTransport {
+ private readonly options: RealtimeASRTransportOptions;
+ private socket: WebSocket | null = null;
+ private readyResolve: (() => void) | null = null;
+ private readyReject: ((error: Error) => void) | null = null;
+ private finalResolve: (() => void) | null = null;
+ private finalReject: ((error: Error) => void) | null = null;
+ private closedByClient = false;
+
+ constructor(options: RealtimeASRTransportOptions) {
+ this.options = options;
+ }
+
+ async connect(sampleRate: number): Promise<void> {
+ const { token } = await asrApi.createRealtimeToken(
+ this.options.config.credentialId,
+ this.options.config.model,
+ );
+ if (this.closedByClient) {
+ throw new Error('Realtime ASR connection was cancelled.');
+ }
+ const baseUrl = getBaseUrl() || window.location.origin;
+ const url = new URL('/asr/realtime', baseUrl);
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
+ url.searchParams.set('token', token);
+
+ const socket = new WebSocket(url);
+ this.socket = socket;
+ const ready = new Promise<void>((resolve, reject) => {
+ this.readyResolve = resolve;
+ this.readyReject = reject;
+ });
+
+ socket.onopen = () => {
+ socket.send(
+ JSON.stringify({
+ type: 'start',
+ credential_id: this.options.config.credentialId,
+ model: this.options.config.model,
+ parameters: this.options.config.parameters,
+ sample_rate: sampleRate,
+ }),
+ );
+ };
+ socket.onmessage = (event) => this.handleMessage(event.data);
+ socket.onerror = () => this.fail(new Error('Realtime ASR connection failed.'));
+ socket.onclose = () => {
+ if (!this.closedByClient) {
+ this.fail(new Error('Realtime ASR connection closed unexpectedly.'));
+ }
+ };
+
+ return ready;
+ }
+
+ sendAudio(audio: ArrayBuffer): void {
+ if (this.socket?.readyState !== WebSocket.OPEN) return;
+ this.socket.send(audio);
+ }
+
+ async stop(): Promise<void> {
+ if (this.socket?.readyState !== WebSocket.OPEN) {
+ throw new Error('Realtime ASR connection is not open.');
+ }
+ const final = new Promise<void>((resolve, reject) => {
+ this.finalResolve = resolve;
+ this.finalReject = reject;
+ });
+ this.socket.send(JSON.stringify({ type: 'stop' }));
+ return final;
+ }
+
+ close(): void {
+ this.closedByClient = true;
+ this.readyReject?.(new Error('Realtime ASR connection was cancelled.'));
+ this.finalReject?.(new Error('Realtime ASR connection was cancelled.'));
+ this.clearPending();
+ this.socket?.close();
+ this.socket = null;
+ }
+
+ private handleMessage(data: unknown): void {
+ if (this.closedByClient || typeof data !== 'string') return;
+ let event: ServerEvent;
+ try {
+ event = JSON.parse(data) as ServerEvent;
+ } catch {
+ this.fail(new Error('Realtime ASR returned an invalid event.'));
+ return;
+ }
+ if (event.type === 'ready') {
+ this.readyResolve?.();
+ this.readyResolve = null;
+ this.readyReject = null;
+ return;
+ }
+ if (event.type === 'error') {
+ this.fail(new Error(event.detail || 'Realtime ASR failed.'));
+ return;
+ }
+ if (event.type === 'transcript') {
+ this.options.onTranscript(event.text ?? '', !!event.is_last);
+ if (event.is_last) {
+ this.finalResolve?.();
+ this.finalResolve = null;
+ this.finalReject = null;
+ }
+ }
+ }
+
+ private fail(error: Error): void {
+ if (this.closedByClient) return;
+ this.closedByClient = true;
+ this.readyReject?.(error);
+ this.finalReject?.(error);
+ this.clearPending();
+ this.socket?.close();
+ this.socket = null;
+ this.options.onError(error);
+ }
+
+ private clearPending(): void {
+ this.readyResolve = null;
+ this.readyReject = null;
+ this.finalResolve = null;
+ this.finalReject = null;
+ }
+}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index ecf0738ca..5045597a1 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -12,6 +12,7 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type {
+ ASRModelConfig,
ChatModelConfig,
PermissionMode,
RealtimeModelConfig,
@@ -19,7 +20,7 @@ import type {
TTSModelConfig,
UpdateSessionRequest,
} from '@/api';
-import { sessionApi } from '@/api';
+import { asrApi, sessionApi } from '@/api';
import MCPSvg from '@/assets/images/mcp.svg?react';
import { ChatContent } from '@/components/chat/ChatContent.tsx';
import { SubagentHitlCard } from '@/components/chat/SubagentHitlCard';
@@ -50,6 +51,7 @@ import {
ResizablePanelGroup,
} from '@/components/ui/resizable.tsx';
import { SidebarTrigger } from '@/components/ui/sidebar';
+import { useAvailableASRModels } from '@/hooks/useAvailableASRModels';
import { useAvailableModels } from '@/hooks/useAvailableModels';
import { useAvailableRealtimeModels } from '@/hooks/useAvailableRealtimeModels';
import { useKnowledgeBaseMiddlewareSchema } from '@/hooks/useKnowledgeBaseMiddlewareSchema';
@@ -181,12 +183,14 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
const { sessions, refetch: refetchSessions } = useSessions(agentId);
const { groups } = useAvailableModels();
const { groups: realtimeGroups } = useAvailableRealtimeModels();
+ const { groups: asrGroups, loading: asrModelsLoading } = useAvailableASRModels();
const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);
const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(
null,
);
const [selectedTTSModel, setSelectedTTSModel] = useState<TTSModelConfig | null>(null);
+ const [selectedASRModel, setSelectedASRModel] = useState<ASRModelConfig | null>(null);
const [selectedRealtimeModel, setSelectedRealtimeModel] = useState<RealtimeModelConfig | null>(
null,
);
@@ -535,6 +539,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
setSelectedModel(null);
setSelectedFallbackModel(null);
setSelectedTTSModel(null);
+ setSelectedASRModel(null);
setSelectedRealtimeModel(null);
setSelectedKnowledgeConfig(null);
}, [sessionId]);
@@ -570,6 +575,16 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
return null;
}, [realtimeGroups, selectedRealtimeModel]);
+ const selectedASRModelCard = useMemo(() => {
+ if (!selectedASRModel) return null;
+ for (const item of asrGroups[selectedASRModel.type] ?? []) {
+ if (item.credential.id !== selectedASRModel.credential_id) continue;
+ const card = item.models.find((model) => model.name === selectedASRModel.model);
+ if (card) return card;
+ }
+ return null;
+ }, [asrGroups, selectedASRModel]);
+
/**
* Pick the first model the available-models endpoint surfaces, used
* as a sensible default when the current session has no model
@@ -662,6 +677,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
setSelectedFallbackModel(view.session.config.fallback_chat_model_config ?? null);
setSelectedTTSModel(view.session.config.tts_model_config ?? null);
+ setSelectedASRModel(view.session.config.asr_model_config ?? null);
setSelectedRealtimeModel(view.session.config.realtime_model_config ?? null);
setSelectedKnowledgeConfig(view.session.config.knowledge_config ?? null);
}, [view, groups, sessionId, agentId]);
@@ -719,6 +735,11 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
await patchConfig({ tts_model_config: config }, () => setSelectedTTSModel(config));
};
+ /** Persist an ASR model change. `null` disables speech input. */
+ const handleASRChange = async (config: ASRModelConfig | null) => {
+ await patchConfig({ asr_model_config: config }, () => setSelectedASRModel(config));
+ };
+
/** Persist the model used by browser realtime voice mode. */
const handleRealtimeModelChange = async (config: RealtimeModelConfig | null) => {
await patchConfig({ realtime_model_config: config }, () =>
@@ -735,6 +756,21 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
);
};
+ /** Transcribe one browser recording with the configured batch ASR model. */
+ const handleTranscribe = useCallback(
+ async (file: File) => {
+ if (!selectedASRModel || selectedASRModelCard?.realtime) return '';
+ const response = await asrApi.transcribe({
+ file,
+ credentialId: selectedASRModel.credential_id,
+ model: selectedASRModel.model,
+ parameters: selectedASRModel.parameters,
+ });
+ return response.text;
+ },
+ [selectedASRModel, selectedASRModelCard],
+ );
+
/**
* Persist a permission-mode change.
*
@@ -840,6 +876,8 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
onFallbackChange={handleFallbackChange}
selectedTTSModel={selectedTTSModel}
onTTSChange={handleTTSChange}
+ selectedASRModel={selectedASRModel}
+ onASRChange={handleASRChange}
disabled={configPending}
/>
<PermissionModeSelect
@@ -942,6 +980,27 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
voiceState={realtimeVoice.state}
onVoiceToggle={() => void realtimeVoice.toggle()}
voiceDisabled={!selectedRealtimeModel || !agentId || !sessionId}
+ asrInputTypes={selectedASRModelCard?.input_types ?? []}
+ onTranscribe={handleTranscribe}
+ asrRealtime={!!selectedASRModelCard?.realtime}
+ realtimeASRConfig={
+ selectedASRModel && selectedASRModelCard?.realtime
+ ? {
+ credentialId: selectedASRModel.credential_id,
+ model: selectedASRModel.model,
+ parameters: selectedASRModel.parameters,
+ }
+ : null
+ }
+ asrDisabled={
+ asrModelsLoading ||
+ !selectedASRModel ||
+ !selectedASRModelCard ||
+ !agentId ||
+ !sessionId ||
+ voiceBusy
+ }
+ asrResetKey={`${agentId ?? ''}:${sessionId ?? ''}:${selectedASRModel?.credential_id ?? ''}:${selectedASRModel?.model ?? ''}`}
footerSlot={
subagentHitl.length > 0 ? (
<SubagentHitlCard
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 6e79097f6..7f004ac08 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -15,6 +15,7 @@ from .rag.blob_store import BlobStoreBase, LocalBlobStore
from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .workspace_manager import WorkspaceManagerBase
from ._router import (
+ asr_router,
agent_router,
channel_router,
chat_router,
@@ -436,6 +437,7 @@ def create_app(
# Built-in routers
for router in (
+ asr_router,
agent_router,
chat_router,
credential_router,
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index 9c05e276b..02aaa2eec 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""App routers."""
+from ._asr import asr_router
from ._agent import agent_router
from ._channel import channel_router
from ._chat import chat_router
@@ -20,6 +21,7 @@ from ._voice_profile import voice_profile_router
from ._workspace import workspace_router
__all__ = [
+ "asr_router",
"agent_router",
"channel_router",
"model_router",
diff --git a/src/agentscope/app/_router/_asr.py b/src/agentscope/app/_router/_asr.py
new file mode 100644
index 000000000..a83fd7a33
--- /dev/null
+++ b/src/agentscope/app/_router/_asr.py
@@ -0,0 +1,353 @@
+# -*- coding: utf-8 -*-
+"""Speech recognition endpoints for browser-recorded audio."""
+
+import json
+from urllib.parse import quote
+
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ Form,
+ HTTPException,
+ UploadFile,
+ WebSocket,
+ WebSocketDisconnect,
+)
+from fastapi import status
+from pydantic import ValidationError
+
+from ..deps import (
+ get_current_user_id,
+ get_download_secret,
+ get_resource_access_service,
+)
+from .._service import (
+ ResourceAccessService,
+ get_asr_model,
+ sign_download_token,
+ verify_download_token,
+)
+from ._schema import (
+ ListASRModelsRequest,
+ ListASRModelsResponse,
+ RealtimeASRStartRequest,
+ RealtimeASRTokenRequest,
+ RealtimeASRTokenResponse,
+ TranscriptionResponse,
+)
+from ...credential import CredentialFactory
+
+
+asr_router = APIRouter(
+ tags=["asr"],
+ responses={404: {"description": "Not found"}},
+)
+
+_MAX_AUDIO_UPLOAD_BYTES = 25 * 1024 * 1024
+_REALTIME_TOKEN_TTL_SECONDS = 60
+
+
+def _realtime_token_scope(credential_id: str, model: str) -> str:
+ """Return the capability scope for one realtime ASR configuration."""
+ encoded_credential = quote(credential_id, safe="")
+ encoded_model = quote(model, safe="")
+ return f"/asr/realtime/{encoded_credential}/{encoded_model}"
+
+
+@asr_router.get(
+ "/asr-model/",
+ response_model=ListASRModelsResponse,
+ summary="List ASR models under a credential provider",
+)
+async def list_asr_models(
+ body: ListASRModelsRequest = Depends(),
+) -> ListASRModelsResponse:
+ """Return batch and realtime ASR cards for a credential provider.
+
+ Args:
+ body (`ListASRModelsRequest`):
+ The provider whose ASR models should be listed.
+
+ Returns:
+ `ListASRModelsResponse`:
+ The available ASR model cards and their total count.
+
+ Raises:
+ `HTTPException`:
+ If the requested credential provider is not registered.
+ """
+ credential_cls = CredentialFactory.get_credential_class(body.provider)
+ if credential_cls is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Provider {body.provider!r} not found.",
+ )
+
+ models = credential_cls.list_asr_models()
+ return ListASRModelsResponse(models=models, total=len(models))
+
+
+@asr_router.post(
+ "/asr/transcriptions",
+ response_model=TranscriptionResponse,
+ summary="Transcribe an uploaded audio recording",
+)
+async def transcribe_audio(
+ file: UploadFile = File(),
+ credential_id: str = Form(),
+ model: str = Form(),
+ parameters: str = Form(default="{}"),
+ user_id: str = Depends(get_current_user_id),
+ access: ResourceAccessService = Depends(get_resource_access_service),
+) -> TranscriptionResponse:
+ """Transcribe one complete browser recording with a batch ASR model.
+
+ Args:
+ file (`UploadFile`):
+ The uploaded audio recording. Files larger than 25 MiB are
+ rejected.
+ credential_id (`str`):
+ The stored credential used to call the ASR provider.
+ model (`str`):
+ The batch ASR model name.
+ parameters (`str`):
+ Provider-specific parameters encoded as a JSON object.
+ user_id (`str`):
+ The authenticated viewer's user ID.
+ access (`ResourceAccessService`):
+ The service used to authorize and resolve the credential.
+
+ Returns:
+ `TranscriptionResponse`:
+ The recognized text.
+
+ Raises:
+ `HTTPException`:
+ If the upload is empty or too large, the parameters are invalid,
+ or the credential and model cannot be used by the viewer.
+ """
+ if file.size is not None and file.size > _MAX_AUDIO_UPLOAD_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,
+ detail="Audio file exceeds the 25 MiB upload limit.",
+ )
+ audio = await file.read(_MAX_AUDIO_UPLOAD_BYTES + 1)
+ if len(audio) > _MAX_AUDIO_UPLOAD_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,
+ detail="Audio file exceeds the 25 MiB upload limit.",
+ )
+ if not audio:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Audio file must not be empty.",
+ )
+ try:
+ parsed_parameters = json.loads(parameters)
+ except json.JSONDecodeError as error:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="ASR parameters must be valid JSON.",
+ ) from error
+ if not isinstance(parsed_parameters, dict):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="ASR parameters must be a JSON object.",
+ )
+
+ try:
+ asr_model = await get_asr_model(
+ user_id=user_id,
+ credential_id=credential_id,
+ model=model,
+ access=access,
+ parameters=parsed_parameters,
+ )
+ except ValidationError as error:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=str(error),
+ ) from error
+ result = await asr_model.transcribe(
+ audio=audio,
+ filename=file.filename or "audio.webm",
+ )
+ return TranscriptionResponse(
+ text=result.content.text if result.content is not None else "",
+ )
+
+
+@asr_router.post(
+ "/asr/realtime/token",
+ response_model=RealtimeASRTokenResponse,
+ summary="Mint a short-lived realtime ASR WebSocket token",
+)
+async def create_realtime_asr_token(
+ body: RealtimeASRTokenRequest,
+ user_id: str = Depends(get_current_user_id),
+ access: ResourceAccessService = Depends(get_resource_access_service),
+ download_secret: str = Depends(get_download_secret),
+) -> RealtimeASRTokenResponse:
+ """Authorize one credential and model before opening a WebSocket.
+
+ The returned token is scoped to the requested credential and model and
+ expires after a short interval.
+
+ Args:
+ body (`RealtimeASRTokenRequest`):
+ The credential and realtime ASR model to authorize.
+ user_id (`str`):
+ The authenticated viewer's user ID.
+ access (`ResourceAccessService`):
+ The service used to authorize and resolve the credential.
+ download_secret (`str`):
+ The server secret used to sign the capability token.
+
+ Returns:
+ `RealtimeASRTokenResponse`:
+ The signed token and its expiration timestamp.
+
+ Raises:
+ `HTTPException`:
+ If the credential is unavailable to the viewer or does not
+ support the requested realtime model.
+ """
+ await get_asr_model(
+ user_id=user_id,
+ credential_id=body.credential_id,
+ model=body.model,
+ access=access,
+ realtime=True,
+ )
+ token, expires_at = sign_download_token(
+ download_secret,
+ user_id,
+ _realtime_token_scope(body.credential_id, body.model),
+ ttl=_REALTIME_TOKEN_TTL_SECONDS,
+ )
+ return RealtimeASRTokenResponse(
+ token=token,
+ expires_at=expires_at,
+ )
+
+
+@asr_router.websocket("/asr/realtime")
+async def transcribe_realtime(websocket: WebSocket) -> None:
+ """Proxy browser PCM audio to a server-side realtime ASR model.
+
+ The connection requires a signed ``token`` query parameter. The first
+ client frame must contain :class:`RealtimeASRStartRequest` JSON, followed
+ by binary PCM16 audio frames and a final ``{"type": "stop"}`` control
+ frame. The server emits ``ready``, ``transcript``, or ``error`` JSON
+ frames and closes the connection after the final transcript.
+
+ Args:
+ websocket (`WebSocket`):
+ The browser WebSocket connection carrying control and audio
+ frames.
+ """
+ await websocket.accept()
+ try:
+ start = RealtimeASRStartRequest.model_validate(
+ await websocket.receive_json(),
+ )
+ token = websocket.query_params.get("token")
+ if token is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Realtime ASR token is required.",
+ )
+ try:
+ user_id = verify_download_token(
+ websocket.app.state.download_secret,
+ token,
+ _realtime_token_scope(start.credential_id, start.model),
+ )
+ except ValueError as error:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or expired realtime ASR token.",
+ ) from error
+ access = websocket.app.state.resource_access_service
+ parameters = {**start.parameters, "sample_rate": start.sample_rate}
+ asr_model = await get_asr_model(
+ user_id=user_id,
+ credential_id=start.credential_id,
+ model=start.model,
+ access=access,
+ parameters=parameters,
+ realtime=True,
+ )
+ async with asr_model:
+ await websocket.send_json({"type": "ready"})
+ while True:
+ message = await websocket.receive()
+ if message["type"] == "websocket.disconnect":
+ return
+ audio = message.get("bytes")
+ if audio is not None:
+ response = await asr_model.push(audio)
+ await _send_transcript(websocket, response)
+ continue
+ text = message.get("text")
+ if text is None:
+ continue
+ control = json.loads(text)
+ if control.get("type") != "stop":
+ raise ValueError("Unsupported realtime ASR control frame.")
+ response = await asr_model.transcribe()
+ await _send_transcript(websocket, response)
+ await websocket.close(code=status.WS_1000_NORMAL_CLOSURE)
+ return
+ except WebSocketDisconnect:
+ return
+ except ValidationError as error:
+ await _send_realtime_error(websocket, str(error))
+ except HTTPException as error:
+ close_code = (
+ status.WS_1008_POLICY_VIOLATION
+ if error.status_code
+ in {
+ status.HTTP_401_UNAUTHORIZED,
+ status.HTTP_403_FORBIDDEN,
+ }
+ else status.WS_1011_INTERNAL_ERROR
+ )
+ await _send_realtime_error(
+ websocket,
+ str(error.detail),
+ close_code=close_code,
+ )
+ except (json.JSONDecodeError, ValueError) as error:
+ await _send_realtime_error(websocket, str(error))
+ except Exception as error: # pylint: disable=broad-exception-caught
+ await _send_realtime_error(websocket, str(error))
+
+
+async def _send_transcript(websocket: WebSocket, response: object) -> None:
+ """Send one non-empty ASR response to the browser."""
+ content = getattr(response, "content", None)
+ is_last = bool(getattr(response, "is_last", False))
+ text = content.text if content is not None else ""
+ if text or is_last:
+ await websocket.send_json(
+ {
+ "type": "transcript",
+ "text": text,
+ "is_last": is_last,
+ },
+ )
+
+
+async def _send_realtime_error(
+ websocket: WebSocket,
+ detail: str,
+ close_code: int = status.WS_1011_INTERNAL_ERROR,
+) -> None:
+ """Report a realtime failure and close the browser connection."""
+ try:
+ await websocket.send_json({"type": "error", "detail": detail})
+ await websocket.close(code=close_code)
+ except RuntimeError:
+ return
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 1ceb3e62b..e6057fdfb 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -20,6 +20,14 @@ from ._chat import (
SteerChatQueueItemRequest,
UpdateChatQueueItemRequest,
)
+from ._asr import (
+ ListASRModelsRequest,
+ ListASRModelsResponse,
+ RealtimeASRStartRequest,
+ RealtimeASRTokenRequest,
+ RealtimeASRTokenResponse,
+ TranscriptionResponse,
+)
from ._health import ComponentStatus, HealthResponse
from ._hub import HubInfo
from ._hub_mcp import InstallMCPRequest, MCPView, UpdateMCPRequest
@@ -179,6 +187,13 @@ __all__ = [
"ReorderChatQueueRequest",
"SteerChatQueueItemRequest",
"UpdateChatQueueItemRequest",
+ # ASR
+ "ListASRModelsRequest",
+ "ListASRModelsResponse",
+ "RealtimeASRStartRequest",
+ "RealtimeASRTokenRequest",
+ "RealtimeASRTokenResponse",
+ "TranscriptionResponse",
# Credential
"CreateCredentialRequest",
"CreateCredentialResponse",
diff --git a/src/agentscope/app/_router/_schema/_asr.py b/src/agentscope/app/_router/_schema/_asr.py
new file mode 100644
index 000000000..10495ec5d
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_asr.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+"""Speech recognition request and response schemas."""
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from ....asr import ASRModelCard
+
+
+class ListASRModelsResponse(BaseModel):
+ """List the candidate ASR models response."""
+
+ models: list[ASRModelCard] = Field(
+ description="The candidate ASR models.",
+ )
+ total: int = Field(description="The total number of candidates.")
+
+
+class ListASRModelsRequest(BaseModel):
+ """List the candidate ASR models request."""
+
+ provider: str = Field(
+ description="The credential provider type.",
+ )
+
+
+class TranscriptionResponse(BaseModel):
+ """Text returned after transcribing an uploaded audio file."""
+
+ text: str = Field(description="The transcribed text.")
+
+
+class RealtimeASRTokenRequest(BaseModel):
+ """Request a capability for one realtime ASR configuration."""
+
+ credential_id: str = Field(min_length=1)
+ model: str = Field(min_length=1)
+
+
+class RealtimeASRTokenResponse(BaseModel):
+ """Short-lived capability accepted by the realtime ASR socket."""
+
+ token: str = Field(description="Pass as the WebSocket token query.")
+ expires_at: int = Field(
+ description="Unix timestamp after which the token is refused.",
+ )
+
+
+class RealtimeASRStartRequest(BaseModel):
+ """First browser frame for a realtime ASR connection."""
+
+ type: Literal["start"]
+ credential_id: str = Field(min_length=1)
+ model: str = Field(min_length=1)
+ parameters: dict = Field(default_factory=dict)
+ sample_rate: int = Field(gt=0)
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index 4f54cc63f..aa89908f3 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -4,6 +4,7 @@ from pydantic import BaseModel, Field
from ....permission import PermissionMode
from ...storage import (
+ ASRModelConfig,
ChatModelConfig,
RealtimeModelConfig,
SessionKnowledgeConfig,
@@ -87,6 +88,10 @@ class CreateSessionRequest(BaseModel):
default=None,
description="TTS model configuration. Can be set later via PATCH.",
)
+ asr_model_config: ASRModelConfig | None = Field(
+ default=None,
+ description="ASR model configuration. Can be set later via PATCH.",
+ )
realtime_model_config: RealtimeModelConfig | None = Field(
default=None,
description=(
@@ -135,6 +140,11 @@ class UpdateSessionRequest(BaseModel):
description="New TTS model configuration. "
"Pass null to clear; omit to leave unchanged.",
)
+ asr_model_config: ASRModelConfig | None = Field(
+ default=None,
+ description="New ASR model configuration. "
+ "Pass null to clear; omit to leave unchanged.",
+ )
realtime_model_config: RealtimeModelConfig | None = Field(
default=None,
description="New realtime voice model configuration. "
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index c1f27c5bb..2273de0ce 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -42,6 +42,7 @@ from .._service import (
validate_tts_model_config,
)
from ..storage import (
+ ASRModelConfig,
ChatModelConfig,
RealtimeModelConfig,
SessionKnowledgeConfig,
@@ -132,7 +133,13 @@ session_router = APIRouter(
async def _ensure_credential_exists(
access: ResourceAccessService,
user_id: str,
- config: ChatModelConfig | RealtimeModelConfig | TTSModelConfig | None,
+ config: (
+ ASRModelConfig
+ | ChatModelConfig
+ | RealtimeModelConfig
+ | TTSModelConfig
+ | None
+ ),
) -> None:
"""Validate that the credential referenced by ``config`` is visible to
the given user (own or shared). No-op when ``config`` is ``None``.
@@ -140,8 +147,9 @@ async def _ensure_credential_exists(
Args:
access (`ResourceAccessService`): Injected access service.
user_id (`str`): The authenticated user ID.
- config (`ChatModelConfig | RealtimeModelConfig | TTSModelConfig | \
- None`): Model config to validate. Pass ``None`` to skip the check.
+ config (`ASRModelConfig | ChatModelConfig | RealtimeModelConfig | \
+ TTSModelConfig | None`): Model config to validate. Pass ``None`` \
+ to skip the check.
Raises:
`HTTPException`: 404 if the credential does not exist or is not
@@ -337,6 +345,7 @@ async def create_session(
access,
storage,
)
+ await _ensure_credential_exists(access, user_id, body.asr_model_config)
await _ensure_credential_exists(
access,
user_id,
@@ -368,6 +377,7 @@ async def create_session(
chat_model_config=body.chat_model_config,
fallback_chat_model_config=body.fallback_chat_model_config,
tts_model_config=body.tts_model_config,
+ asr_model_config=body.asr_model_config,
realtime_model_config=body.realtime_model_config,
knowledge_config=body.knowledge_config,
# A caller that named the session owns that name; anything
@@ -532,6 +542,7 @@ async def update_session(
access,
storage,
)
+ await _ensure_credential_exists(access, user_id, body.asr_model_config)
await _ensure_credential_exists(
access,
user_id,
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index fdceb6800..f2cc62f56 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -13,6 +13,7 @@ from ._credential_binding import (
CredentialBindingService,
)
from ._chat import ChatService
+from ._asr_model import get_asr_model
from ._embedding import get_embedding_model
from ._index_sweeper import IndexSweeper
from ._index_task_consumer import IndexTaskConsumer
@@ -62,6 +63,7 @@ __all__ = [
"verify_download_token",
"WorkspaceStatus",
"get_embedding_model",
+ "get_asr_model",
"get_model",
"get_realtime_model",
"get_tts_model",
diff --git a/src/agentscope/app/_service/_asr_model.py b/src/agentscope/app/_service/_asr_model.py
new file mode 100644
index 000000000..9946983be
--- /dev/null
+++ b/src/agentscope/app/_service/_asr_model.py
@@ -0,0 +1,117 @@
+# -*- coding: utf-8 -*-
+"""ASR model construction from a stored credential."""
+
+from typing import Type
+
+from fastapi import HTTPException, status
+
+from ..storage import CredentialRecord
+from ._access import ResourceAccessService
+from ...asr import ASRModelBase
+from ...credential import CredentialFactory
+
+
+async def get_asr_model(
+ user_id: str,
+ credential_id: str,
+ model: str,
+ access: ResourceAccessService,
+ parameters: dict | None = None,
+ realtime: bool = False,
+) -> ASRModelBase:
+ """Build an ASR model from a visible stored credential.
+
+ Args:
+ user_id (`str`):
+ The viewer's user id.
+ credential_id (`str`):
+ The stored credential to use.
+ model (`str`):
+ The requested ASR model name.
+ access (`ResourceAccessService`):
+ Resource access service used to resolve shared credentials.
+ parameters (`dict | None`, defaults to `None`):
+ Provider-specific speech recognition parameters.
+ realtime (`bool`, defaults to `False`):
+ Whether to resolve a realtime rather than batch implementation.
+
+ Returns:
+ `ASRModelBase`:
+ An ASR model matching the requested input mode.
+
+ Raises:
+ `HTTPException`:
+ If the credential has no matching ASR implementation or the model
+ name is not available for it.
+ `pydantic.ValidationError`:
+ If the provider-specific parameters are invalid.
+ """
+ credential_record = await access.resolve_credential(
+ user_id,
+ credential_id,
+ )
+ return _build_asr_model(
+ credential_record,
+ model,
+ parameters,
+ realtime,
+ )
+
+
+def _build_asr_model(
+ credential_record: CredentialRecord,
+ model: str,
+ parameters: dict | None = None,
+ realtime: bool = False,
+) -> ASRModelBase:
+ """Construct the requested ASR model from a credential record.
+
+ Args:
+ credential_record (`CredentialRecord`):
+ The unmasked stored credential record.
+ model (`str`):
+ The requested ASR model name.
+ parameters (`dict | None`, defaults to `None`):
+ Provider-specific speech recognition parameters.
+ realtime (`bool`, defaults to `False`):
+ Whether to select a realtime implementation.
+
+ Returns:
+ `ASRModelBase`:
+ The configured ASR model.
+
+ Raises:
+ `HTTPException`:
+ If no implementation advertises the requested model.
+ `pydantic.ValidationError`:
+ If the credential or provider-specific parameters are invalid.
+ """
+ credential = CredentialFactory.from_dict(credential_record.data)
+ asr_classes = [
+ asr_cls
+ for asr_cls in credential.get_asr_model_classes()
+ if asr_cls.realtime is realtime
+ ]
+ asr_cls = _resolve_asr_class(asr_classes, model)
+ parsed_parameters = (
+ asr_cls.Parameters(**parameters) if parameters is not None else None
+ )
+ return asr_cls(
+ credential=credential,
+ model=model,
+ parameters=parsed_parameters,
+ )
+
+
+def _resolve_asr_class(
+ classes: list[Type[ASRModelBase]],
+ model: str,
+) -> Type[ASRModelBase]:
+ """Find the ASR implementation that advertises a model name."""
+ for asr_cls in classes:
+ if any(card.name == model for card in asr_cls.list_models()):
+ return asr_cls
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"ASR model {model!r} is not available for this credential.",
+ )
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index 85a70e36a..b85546807 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -45,6 +45,7 @@ from ._model import (
SOPWorkspaceGrain,
SkillRecord,
ChatModelConfig,
+ ASRModelConfig,
RealtimeModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
@@ -129,6 +130,7 @@ __all__ = [
"SOPWorkspaceGrain",
"SkillRecord",
"ChatModelConfig",
+ "ASRModelConfig",
"RealtimeModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index 007d00b87..320303879 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -28,6 +28,7 @@ from ._session import (
SessionNaming,
SessionKnowledgeConfig,
ChatModelConfig,
+ ASRModelConfig,
RealtimeModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
@@ -101,6 +102,7 @@ __all__ = [
"SOPVerifier",
"SOPWorkspaceGrain",
"ChatModelConfig",
+ "ASRModelConfig",
"RealtimeModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index 73e2db43b..f40955aaa 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -152,6 +152,22 @@ class TTSModelConfig(BaseModel):
"""TTS parameters (voice, language, etc.)."""
+class ASRModelConfig(BaseModel):
+ """The ASR model configuration class."""
+
+ type: str
+ """The provider type."""
+
+ credential_id: str
+ """The credential id."""
+
+ model: str
+ """The ASR model name."""
+
+ parameters: dict
+ """Provider-specific speech recognition parameters."""
+
+
class RealtimeModelConfig(BaseModel):
"""The realtime voice model configuration class."""
@@ -315,6 +331,9 @@ class SessionConfig(BaseModel):
tts_model_config: TTSModelConfig | None = None
"""The TTS model config. None means TTS is not enabled."""
+ asr_model_config: ASRModelConfig | None = None
+ """The ASR model config. None means speech input is not enabled."""
+
realtime_model_config: RealtimeModelConfig | None = None
"""The realtime voice model config. None disables voice mode."""
diff --git a/src/agentscope/asr/__init__.py b/src/agentscope/asr/__init__.py
index 5da4cdfd7..0f05bc881 100644
--- a/src/agentscope/asr/__init__.py
+++ b/src/agentscope/asr/__init__.py
@@ -4,11 +4,14 @@
from ._asr_base import ASRModelBase
from ._asr_model_card import ASRModelCard
from ._asr_response import ASRResponse
+from ._dashscope import DashScopeASRModel, DashScopeRealtimeASRModel
from ._openai import OpenAIASRModel
__all__ = [
"ASRModelBase",
"ASRModelCard",
"ASRResponse",
+ "DashScopeASRModel",
+ "DashScopeRealtimeASRModel",
"OpenAIASRModel",
]
diff --git a/src/agentscope/asr/_asr_model_card.py b/src/agentscope/asr/_asr_model_card.py
index 8cb3f6adc..dcf8791eb 100644
--- a/src/agentscope/asr/_asr_model_card.py
+++ b/src/agentscope/asr/_asr_model_card.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""Model metadata for speech recognition implementations."""
+import copy
from typing import Literal, Self, Type
from pydantic import BaseModel, Field
@@ -44,20 +45,67 @@ class ASRModelCard(BaseModel):
)
"""The JSON schema for provider-specific parameters."""
+ parameters_overrides: dict[str, dict] = Field(
+ default_factory=dict,
+ description="Per-model overrides applied to the parameter schema.",
+ )
+ """The YAML overrides used to tailor frontend-visible parameters."""
+
@classmethod
def from_yaml(
cls,
yaml_path: str,
parameter_class: Type[BaseModel],
) -> Self:
- """Load a card and the implementation's parameter schema."""
+ """Load a model card and its frontend-visible parameter schema.
+
+ Args:
+ yaml_path (`str`):
+ The path to the model-card YAML file.
+ parameter_class (`Type[BaseModel]`):
+ The provider parameter model used to generate the base JSON
+ schema.
+
+ Returns:
+ `ASRModelCard`:
+ The validated model card with per-model parameter overrides
+ applied.
+
+ Raises:
+ `OSError`:
+ If the YAML file cannot be read.
+ `yaml.YAMLError`:
+ If the YAML content is malformed.
+ `KeyError`:
+ If a required model-card field is missing.
+ `pydantic.ValidationError`:
+ If the resulting model card is invalid.
+ """
with open(yaml_path, "r", encoding="utf-8") as file:
config = yaml.safe_load(file)
+
+ schema = copy.deepcopy(parameter_class.model_json_schema())
+ properties = schema.get("properties", {})
+ overrides = config.get("parameter_overrides", {})
+ for parameter_name, override in overrides.items():
+ if override is None or override.get("hidden"):
+ properties.pop(parameter_name, None)
+ elif parameter_name in properties:
+ properties[parameter_name] = {
+ **properties[parameter_name],
+ **override,
+ }
+
+ if "required" in schema:
+ schema["required"] = [
+ name for name in schema["required"] if name in properties
+ ]
return cls(
name=config["name"],
label=config["label"],
input_types=config.get("input_types", []),
output_types=config.get("output_types", ["text/plain"]),
realtime=config.get("realtime", False),
- parameter_schema=parameter_class.model_json_schema(),
+ parameter_schema=schema,
+ parameters_overrides=overrides,
)
diff --git a/src/agentscope/asr/_dashscope/__init__.py b/src/agentscope/asr/_dashscope/__init__.py
new file mode 100644
index 000000000..4b898d0fd
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/__init__.py
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+"""DashScope speech recognition models."""
+
+from ._model import DashScopeASRModel
+from ._realtime_model import DashScopeRealtimeASRModel
+
+__all__ = ["DashScopeASRModel", "DashScopeRealtimeASRModel"]
diff --git a/src/agentscope/asr/_dashscope/_model.py b/src/agentscope/asr/_dashscope/_model.py
new file mode 100644
index 000000000..00b9ebce4
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/_model.py
@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+"""DashScope non-realtime speech recognition implementation."""
+
+import asyncio
+import base64
+from pathlib import Path
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+from ...credential import DashScopeCredential
+from ...message import TextBlock
+from .._asr_base import ASRModelBase
+from .._asr_response import ASRResponse
+
+
+_AUDIO_FORMATS = {
+ ".aac": ("aac", "audio/aac"),
+ ".amr": ("amr", "audio/amr"),
+ ".flac": ("flac", "audio/flac"),
+ ".m4a": ("m4a", "audio/mp4"),
+ ".mp3": ("mp3", "audio/mpeg"),
+ ".mp4": ("mp4", "audio/mp4"),
+ ".mpeg": ("mpeg", "audio/mpeg"),
+ ".ogg": ("ogg", "audio/ogg"),
+ ".opus": ("opus", "audio/opus"),
+ ".wav": ("wav", "audio/wav"),
+ ".webm": ("webm", "audio/webm"),
+}
+
+_UNSUPPORTED_PARAMETERS = {
+ "qwen-audio-3.0-asr-flash": {
+ "keep_dialect",
+ "speaker_diarization_enabled",
+ },
+}
+
+
+class DashScopeASRModel(ASRModelBase):
+ """Batch ASR through DashScope's native multimodal API."""
+
+ class Parameters(BaseModel):
+ """Options supported by Qwen Audio ASR Flash models."""
+
+ language_hints: list[str] | None = Field(
+ default=None,
+ max_length=4,
+ description=(
+ "Optional language codes. Up to four languages are supported."
+ ),
+ )
+ keep_dialect: bool = Field(
+ default=False,
+ description="Preserve dialect expressions in the transcript.",
+ )
+ speaker_diarization_enabled: bool = Field(
+ default=False,
+ description="Identify different speakers in the recording.",
+ )
+ vocabulary: dict[str, int] | None = Field(
+ default=None,
+ description="Inline hotwords mapped to their recognition weights.",
+ )
+ sample_rate: int | None = Field(
+ default=None,
+ gt=0,
+ description="Optional audio sample rate in Hz.",
+ )
+
+ type: Literal["dashscope_asr"] = "dashscope_asr"
+ realtime: bool = False
+
+ def __init__(
+ self,
+ credential: DashScopeCredential,
+ model: str = "qwen-audio-3.1-asr-flash",
+ parameters: "DashScopeASRModel.Parameters | None" = None,
+ ) -> None:
+ """Initialize a DashScope batch ASR model.
+
+ Args:
+ credential (`DashScopeCredential`):
+ The credential used to authenticate with DashScope.
+ model (`str`, defaults to
+ ``"qwen-audio-3.1-asr-flash"``):
+ The DashScope batch ASR model name.
+ parameters (`DashScopeASRModel.Parameters | None`, defaults to
+ `None`):
+ Provider-specific transcription parameters. Default
+ parameters are used when omitted.
+ """
+ super().__init__(credential, model, parameters)
+ self.api_key = credential.api_key.get_secret_value()
+ self.base_address = self._resolve_base_address(credential.base_url)
+
+ async def transcribe(
+ self,
+ audio: bytes | None = None,
+ filename: str = "audio.wav",
+ **kwargs: Any,
+ ) -> ASRResponse:
+ """Transcribe a complete audio recording without streaming.
+
+ Args:
+ audio (`bytes | None`, defaults to `None`):
+ The complete encoded audio recording.
+ filename (`str`, defaults to ``"audio.wav"``):
+ The filename used to determine the audio format and MIME
+ type.
+ **kwargs (`Any`):
+ Additional options passed to the DashScope API.
+
+ Returns:
+ `ASRResponse`:
+ The final recognized text.
+
+ Raises:
+ `ValueError`:
+ If the audio is empty or its filename has an unsupported
+ extension.
+ `RuntimeError`:
+ If DashScope rejects the request or omits the transcript.
+ """
+ if not audio:
+ raise ValueError("audio must not be empty")
+ if not filename:
+ raise ValueError("filename must not be empty")
+
+ audio_format, media_type = self._resolve_audio_format(filename)
+ encoded_audio = base64.b64encode(audio).decode("ascii")
+ data_uri = f"data:{media_type};base64,{encoded_audio}"
+ options = self.parameters.model_dump(exclude_none=True)
+ options.update(kwargs)
+ for parameter in _UNSUPPORTED_PARAMETERS.get(self.model, set()):
+ options.pop(parameter, None)
+ options["format"] = options.get("format", audio_format)
+
+ import dashscope
+
+ response = await asyncio.to_thread(
+ dashscope.MultiModalConversation.call,
+ api_key=self.api_key,
+ base_address=self.base_address,
+ model=self.model,
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_audio",
+ "input_audio": {"data": data_uri},
+ },
+ ],
+ },
+ ],
+ stream=False,
+ **options,
+ )
+ if response.status_code != 200:
+ raise RuntimeError(f"DashScope ASR API error: {response}")
+
+ output = response.output
+ text = (
+ output.get("text")
+ if isinstance(output, dict)
+ else getattr(output, "text", None)
+ )
+ if not isinstance(text, str):
+ raise RuntimeError("DashScope ASR response did not contain text")
+ return ASRResponse(content=TextBlock(text=text))
+
+ @staticmethod
+ def _resolve_audio_format(filename: str) -> tuple[str, str]:
+ """Return the DashScope format and MIME type for a filename."""
+ suffix = Path(filename).suffix.lower()
+ result = _AUDIO_FORMATS.get(suffix)
+ if result is None:
+ raise ValueError(
+ f"Unsupported audio file format: {suffix or filename}",
+ )
+ return result
+
+ @staticmethod
+ def _resolve_base_address(base_url: str) -> str:
+ """Convert a compatible endpoint into its native API counterpart."""
+ normalized = base_url.rstrip("/")
+ compatible_suffix = "/compatible-mode/v1"
+ if normalized.endswith(compatible_suffix):
+ return f"{normalized[:-len(compatible_suffix)]}/api/v1"
+ return normalized
diff --git a/src/agentscope/asr/_dashscope/_models/qwen-audio-3.0-asr-flash.yaml b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.0-asr-flash.yaml
new file mode 100644
index 000000000..bf5414cc2
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.0-asr-flash.yaml
@@ -0,0 +1,28 @@
+name: qwen-audio-3.0-asr-flash
+label: Qwen Audio 3.0 ASR Flash
+input_types:
+ - audio/aac
+ - audio/flac
+ - audio/mpeg
+ - audio/mp4
+ - audio/ogg
+ - audio/opus
+ - audio/wav
+ - audio/webm
+output_types:
+ - text/plain
+realtime: false
+
+parameter_overrides:
+ # The 3.0 synchronous model does not support the two user-facing 3.1
+ # switches. The remaining fields are inferred or require dedicated UX.
+ language_hints:
+ hidden: true
+ keep_dialect:
+ hidden: true
+ speaker_diarization_enabled:
+ hidden: true
+ vocabulary:
+ hidden: true
+ sample_rate:
+ hidden: true
diff --git a/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash-streaming.yaml b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash-streaming.yaml
new file mode 100644
index 000000000..bc77d4d81
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash-streaming.yaml
@@ -0,0 +1,21 @@
+name: qwen-audio-3.1-asr-flash-streaming
+label: Qwen Audio 3.1 ASR Flash Streaming
+input_types:
+ - audio/pcm
+output_types:
+ - text/plain
+realtime: true
+
+parameter_overrides:
+ # Browser capture supplies the sample rate. Language is auto-detected;
+ # VAD and hotwords stay internal until they have purpose-built controls.
+ sample_rate:
+ hidden: true
+ language_hints:
+ hidden: true
+ vad_model:
+ hidden: true
+ vocabulary_id:
+ hidden: true
+ vocabulary:
+ hidden: true
diff --git a/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash.yaml b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash.yaml
new file mode 100644
index 000000000..eee464b8d
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/_models/qwen-audio-3.1-asr-flash.yaml
@@ -0,0 +1,24 @@
+name: qwen-audio-3.1-asr-flash
+label: Qwen Audio 3.1 ASR Flash
+input_types:
+ - audio/aac
+ - audio/flac
+ - audio/mpeg
+ - audio/mp4
+ - audio/ogg
+ - audio/opus
+ - audio/wav
+ - audio/webm
+output_types:
+ - text/plain
+realtime: false
+
+parameter_overrides:
+ # Language is detected automatically. Hotwords need a dedicated editor,
+ # and sample rate is inferred from the uploaded recording.
+ language_hints:
+ hidden: true
+ vocabulary:
+ hidden: true
+ sample_rate:
+ hidden: true
diff --git a/src/agentscope/asr/_dashscope/_realtime_model.py b/src/agentscope/asr/_dashscope/_realtime_model.py
new file mode 100644
index 000000000..f95e8a94c
--- /dev/null
+++ b/src/agentscope/asr/_dashscope/_realtime_model.py
@@ -0,0 +1,391 @@
+# -*- coding: utf-8 -*-
+"""DashScope realtime speech recognition implementation."""
+
+import asyncio
+import json
+from typing import Any, Literal
+from urllib.parse import urlsplit
+from uuid import uuid4
+
+from pydantic import BaseModel, Field
+
+from ...credential import DashScopeCredential
+from ...message import TextBlock
+from .._asr_base import ASRModelBase
+from .._asr_response import ASRResponse
+
+
+_CONNECT_TIMEOUT_SECONDS = 15.0
+_FINISH_TIMEOUT_SECONDS = 30.0
+_REALTIME_PATH = "/api-ws/v1/inference"
+
+
+def _realtime_url(base_url: str) -> str:
+ """Build the native DashScope inference WebSocket endpoint."""
+ parsed = urlsplit(base_url)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise ValueError(f"Invalid DashScope base_url: {base_url!r}.")
+ scheme = "wss" if parsed.scheme == "https" else "ws"
+ return f"{scheme}://{parsed.netloc}{_REALTIME_PATH}"
+
+
+class DashScopeRealtimeASRModel(ASRModelBase):
+ """Realtime ASR through DashScope's native streaming protocol."""
+
+ class Parameters(BaseModel):
+ """Options supported by Qwen Audio streaming ASR models."""
+
+ sample_rate: int = Field(
+ default=16000,
+ gt=0,
+ description=(
+ "PCM input sample rate in Hz. Browser sessions set this "
+ "from their AudioContext."
+ ),
+ )
+ language_hints: list[str] | None = Field(
+ default=None,
+ max_length=4,
+ description=(
+ "Optional language codes. Up to four languages are supported."
+ ),
+ )
+ keep_dialect: bool = Field(
+ default=False,
+ description="Preserve dialect expressions in the transcript.",
+ )
+ vad_model: Literal[
+ "near_meeting_16k",
+ "far_field_meeting_16k",
+ ] = Field(
+ default="far_field_meeting_16k",
+ description="Voice activity detection profile.",
+ )
+ vocabulary_id: str | None = Field(
+ default=None,
+ description="DashScope hotword vocabulary identifier.",
+ )
+ vocabulary: dict[str, int] | None = Field(
+ default=None,
+ description="Inline hotwords mapped to recognition weights.",
+ )
+ semantic_punctuation_enabled: bool = Field(
+ default=True,
+ description="Use semantic punctuation in recognition results.",
+ )
+
+ type: Literal["dashscope_realtime_asr"] = "dashscope_realtime_asr"
+ realtime: bool = True
+
+ def __init__(
+ self,
+ credential: DashScopeCredential,
+ model: str = "qwen-audio-3.1-asr-flash-streaming",
+ parameters: "DashScopeRealtimeASRModel.Parameters | None" = None,
+ ) -> None:
+ """Initialize a DashScope realtime ASR model.
+
+ Args:
+ credential (`DashScopeCredential`):
+ The credential used to authenticate with DashScope.
+ model (`str`, defaults to
+ ``"qwen-audio-3.1-asr-flash-streaming"``):
+ The DashScope realtime ASR model name.
+ parameters (`DashScopeRealtimeASRModel.Parameters | None`,
+ defaults to `None`):
+ Streaming recognition parameters, including the PCM sample
+ rate. Default parameters are used when omitted.
+ """
+ super().__init__(credential, model, parameters)
+ self._url = _realtime_url(credential.base_url)
+ self._api_key = credential.api_key.get_secret_value()
+ self._websocket: Any = None
+ self._reader: asyncio.Task | None = None
+ self._started = asyncio.Event()
+ self._finished = asyncio.Event()
+ self._error: Exception | None = None
+ self._responses: asyncio.Queue[ASRResponse] = asyncio.Queue()
+ self._task_id = ""
+ self._committed_sentences: list[str] = []
+ self._current_sentence = ""
+
+ async def connect(self) -> None:
+ """Connect to DashScope and start one recognition task.
+
+ Calling this method resets any previous task state and waits until
+ DashScope confirms that the new task has started.
+
+ Raises:
+ RuntimeError:
+ If DashScope rejects the task or does not start it before the
+ timeout.
+ """
+ from websockets.asyncio.client import connect
+
+ await self.close()
+ self._started.clear()
+ self._finished.clear()
+ self._error = None
+ self._responses = asyncio.Queue()
+ self._task_id = uuid4().hex
+ self._committed_sentences = []
+ self._current_sentence = ""
+ self._websocket = await connect(
+ self._url,
+ additional_headers={
+ "Authorization": f"Bearer {self._api_key}",
+ "X-DashScope-DataInspection": "disable",
+ },
+ )
+ try:
+ websocket = self._websocket
+ self._reader = asyncio.create_task(
+ self._read_events(websocket),
+ name="dashscope-asr",
+ )
+ await self._send_json(self._run_task_event())
+ try:
+ await asyncio.wait_for(
+ self._started.wait(),
+ timeout=_CONNECT_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError as error:
+ raise RuntimeError(
+ "Timed out waiting for DashScope ASR task startup.",
+ ) from error
+ self._raise_provider_error()
+ except BaseException:
+ # Context entry can fail or be cancelled before __aexit__ runs.
+ await self.close()
+ raise
+
+ async def close(self) -> None:
+ """Cancel the provider reader and close the active WebSocket."""
+ reader = self._reader
+ self._reader = None
+ if reader is not None:
+ reader.cancel()
+ await asyncio.gather(reader, return_exceptions=True)
+
+ websocket = self._websocket
+ self._websocket = None
+ if websocket is not None:
+ await websocket.close()
+
+ async def push(
+ self,
+ audio: bytes,
+ **kwargs: Any,
+ ) -> ASRResponse:
+ """Send one PCM16 chunk and return the latest available text.
+
+ The audio sample rate must match :attr:`Parameters.sample_rate`.
+
+ Args:
+ audio (`bytes`):
+ An incremental mono PCM16 audio chunk.
+ **kwargs (`Any`):
+ Reserved for interface compatibility and currently ignored.
+
+ Returns:
+ `ASRResponse`:
+ The newest cumulative partial transcript, or an empty
+ non-final response when no new text is available.
+
+ Raises:
+ `RuntimeError`:
+ If the model is not connected or the provider task failed.
+ """
+ del kwargs
+ if not audio:
+ return ASRResponse(content=None, is_last=False)
+ if self._websocket is None:
+ raise RuntimeError("DashScope ASR model is not connected.")
+ self._raise_provider_error()
+ await self._websocket.send(audio)
+ await asyncio.sleep(0)
+ self._raise_provider_error()
+ return self._drain_latest_response()
+
+ async def transcribe(
+ self,
+ audio: bytes | None = None,
+ filename: str = "audio.pcm",
+ **kwargs: Any,
+ ) -> ASRResponse:
+ """Finish the current stream and return its final transcription.
+
+ Args:
+ audio (`bytes | None`, defaults to `None`):
+ An optional final mono PCM16 audio chunk.
+ filename (`str`, defaults to ``"audio.pcm"``):
+ Reserved for interface compatibility and currently ignored.
+ **kwargs (`Any`):
+ Reserved for interface compatibility and currently ignored.
+
+ Returns:
+ `ASRResponse`:
+ The final cumulative transcript with ``is_last=True``.
+
+ Raises:
+ `RuntimeError`:
+ If the model is not connected, the provider task failed, or
+ the final result does not arrive before the timeout.
+ """
+ del filename, kwargs
+ if audio:
+ await self.push(audio)
+ if self._websocket is None:
+ raise RuntimeError("DashScope ASR model is not connected.")
+ self._raise_provider_error()
+ await self._send_json(
+ {
+ "header": {
+ "action": "finish-task",
+ "task_id": self._task_id,
+ "streaming": "duplex",
+ },
+ "payload": {"input": {}},
+ },
+ )
+ try:
+ await asyncio.wait_for(
+ self._finished.wait(),
+ timeout=_FINISH_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError as error:
+ raise RuntimeError(
+ "Timed out waiting for DashScope ASR final result.",
+ ) from error
+ self._raise_provider_error()
+ text = self._complete_text()
+ return ASRResponse(
+ content=TextBlock(text=text) if text else None,
+ is_last=True,
+ )
+
+ def _run_task_event(self) -> dict[str, Any]:
+ """Build DashScope's initial run-task event."""
+ parameters = self.parameters.model_dump(exclude_none=True)
+ parameters["format"] = "pcm"
+ return {
+ "header": {
+ "action": "run-task",
+ "task_id": self._task_id,
+ "streaming": "duplex",
+ },
+ "payload": {
+ "task_group": "audio",
+ "task": "asr",
+ "function": "recognition",
+ "model": self.model,
+ "parameters": parameters,
+ "input": {},
+ },
+ }
+
+ async def _send_json(self, event: dict[str, Any]) -> None:
+ """Send one JSON protocol event."""
+ if self._websocket is None:
+ raise RuntimeError("DashScope ASR model is not connected.")
+ await self._websocket.send(json.dumps(event, ensure_ascii=False))
+
+ async def _read_events(self, websocket: Any) -> None:
+ """Read provider events until the task finishes or fails."""
+ try:
+ async for raw_event in websocket:
+ if not isinstance(raw_event, str):
+ continue
+ event = json.loads(raw_event)
+ header = event.get("header", {})
+ event_type = header.get("event")
+ if event_type == "task-started":
+ self._started.set()
+ elif event_type == "result-generated":
+ self._handle_result(event)
+ elif event_type == "task-finished":
+ self._finished.set()
+ return
+ elif event_type == "task-failed":
+ self._error = RuntimeError(
+ self._provider_error_message(header),
+ )
+ self._started.set()
+ self._finished.set()
+ return
+ except Exception as error:
+ self._error = RuntimeError(
+ f"DashScope ASR connection failed: {error}",
+ )
+ self._started.set()
+ self._finished.set()
+ finally:
+ if not self._finished.is_set() and self._error is None:
+ self._error = RuntimeError(
+ "DashScope ASR connection closed unexpectedly.",
+ )
+ self._started.set()
+ self._finished.set()
+
+ def _handle_result(self, event: dict[str, Any]) -> None:
+ """Accumulate one partial or completed sentence."""
+ sentence = (
+ event.get("payload", {})
+ .get("output", {})
+ .get(
+ "sentence",
+ {},
+ )
+ )
+ text = sentence.get("text")
+ if not isinstance(text, str):
+ return
+ text = text.strip()
+ self._current_sentence = text
+ transcript = self._complete_text()
+ if transcript:
+ self._responses.put_nowait(
+ ASRResponse(
+ content=TextBlock(text=transcript),
+ is_last=False,
+ ),
+ )
+ if sentence.get("sentence_end") and text:
+ self._committed_sentences.append(text)
+ self._current_sentence = ""
+
+ def _complete_text(self) -> str:
+ """Return committed sentences plus the active partial sentence."""
+ parts = [*self._committed_sentences]
+ if self._current_sentence:
+ parts.append(self._current_sentence)
+ result = ""
+ for part in parts:
+ if result and result[-1].isalnum() and part[0].isalnum():
+ result = f"{result} {part}"
+ else:
+ result = f"{result}{part}"
+ return result
+
+ def _drain_latest_response(self) -> ASRResponse:
+ """Return the newest queued partial response without blocking."""
+ latest: ASRResponse | None = None
+ while not self._responses.empty():
+ latest = self._responses.get_nowait()
+ return latest or ASRResponse(content=None, is_last=False)
+
+ def _raise_provider_error(self) -> None:
+ """Raise a provider failure captured by the reader task."""
+ if self._error is not None:
+ raise self._error
+
+ @staticmethod
+ def _provider_error_message(header: dict[str, Any]) -> str:
+ """Build a readable provider failure message."""
+ code = header.get("error_code") or header.get("code") or "unknown"
+ message = (
+ header.get("error_message")
+ or header.get("message")
+ or "Unknown provider error"
+ )
+ return f"DashScope ASR task failed ({code}): {message}"
diff --git a/src/agentscope/credential/_dashscope.py b/src/agentscope/credential/_dashscope.py
index dcdd479bf..a8a7857fe 100644
--- a/src/agentscope/credential/_dashscope.py
+++ b/src/agentscope/credential/_dashscope.py
@@ -13,6 +13,7 @@ from pydantic import (
from ._base import CredentialBase
if TYPE_CHECKING:
+ from ..asr import ASRModelBase
from ..embedding import EmbeddingModelBase
from ..model import ChatModelBase
from ..realtime import RealtimeModelBase
@@ -96,6 +97,13 @@ class DashScopeCredential(CredentialBase):
DashScopeCosyVoiceTTSModel,
]
+ @classmethod
+ def get_asr_model_classes(cls) -> list[Type["ASRModelBase"]]:
+ """Return the DashScope ASR model classes."""
+ from ..asr import DashScopeASRModel, DashScopeRealtimeASRModel
+
+ return [DashScopeASRModel, DashScopeRealtimeASRModel]
+
@classmethod
def get_realtime_model_classes(
cls,
diff --git a/tests/asr_dashscope_test.py b/tests/asr_dashscope_test.py
new file mode 100644
index 000000000..a7c82788a
--- /dev/null
+++ b/tests/asr_dashscope_test.py
@@ -0,0 +1,591 @@
+# -*- coding: utf-8 -*-
+"""DashScope batch and realtime ASR model tests."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest import IsolatedAsyncioTestCase, TestCase
+from unittest.mock import AsyncMock, patch
+
+from websockets.asyncio.server import ServerConnection, serve
+
+from agentscope.asr import DashScopeASRModel, DashScopeRealtimeASRModel
+from agentscope.credential import DashScopeCredential
+
+
+class DashScopeASRModelTest(IsolatedAsyncioTestCase):
+ """Verify DashScope request mapping and response parsing."""
+
+ async def test_transcribes_browser_audio(self) -> None:
+ """Encode the recording and call the non-streaming native API."""
+ model = DashScopeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ parameters=DashScopeASRModel.Parameters(
+ language_hints=["zh", "en"],
+ keep_dialect=True,
+ sample_rate=48000,
+ ),
+ )
+ response = SimpleNamespace(
+ status_code=200,
+ output={"text": "你好,AgentScope。"},
+ )
+
+ with patch(
+ "dashscope.MultiModalConversation.call",
+ return_value=response,
+ ) as call:
+ result = await model.transcribe(
+ audio=b"browser audio",
+ filename="recording.webm",
+ )
+
+ self.assertEqual(result.content.text, "你好,AgentScope。")
+ call.assert_called_once_with(
+ api_key="test-key",
+ base_address="https://dashscope.aliyuncs.com/api/v1",
+ model="qwen-audio-3.1-asr-flash",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": (
+ "data:audio/webm;base64,"
+ "YnJvd3NlciBhdWRpbw=="
+ ),
+ },
+ },
+ ],
+ },
+ ],
+ stream=False,
+ language_hints=["zh", "en"],
+ keep_dialect=True,
+ speaker_diarization_enabled=False,
+ sample_rate=48000,
+ format="webm",
+ )
+
+ async def test_rejects_invalid_audio(self) -> None:
+ """Validate content and filename before contacting DashScope."""
+ model = DashScopeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+
+ with self.assertRaisesRegex(ValueError, "audio must not be empty"):
+ await model.transcribe(audio=b"", filename="recording.wav")
+ with self.assertRaisesRegex(ValueError, "Unsupported audio"):
+ await model.transcribe(audio=b"audio", filename="recording.txt")
+
+ async def test_omits_parameters_unsupported_by_qwen_audio_3_0(
+ self,
+ ) -> None:
+ """Do not send the user-facing 3.1 switches to the 3.0 model."""
+ model = DashScopeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ model="qwen-audio-3.0-asr-flash",
+ parameters=DashScopeASRModel.Parameters(
+ keep_dialect=True,
+ speaker_diarization_enabled=True,
+ ),
+ )
+ response = SimpleNamespace(status_code=200, output={"text": "text"})
+
+ with patch(
+ "dashscope.MultiModalConversation.call",
+ return_value=response,
+ ) as call:
+ await model.transcribe(audio=b"audio", filename="audio.wav")
+
+ call.assert_called_once_with(
+ api_key="test-key",
+ base_address="https://dashscope.aliyuncs.com/api/v1",
+ model="qwen-audio-3.0-asr-flash",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": "data:audio/wav;base64,YXVkaW8=",
+ },
+ },
+ ],
+ },
+ ],
+ stream=False,
+ format="wav",
+ )
+
+ async def test_surfaces_provider_error(self) -> None:
+ """Raise a useful error when the provider rejects the request."""
+ model = DashScopeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+ response = SimpleNamespace(
+ status_code=400,
+ output=None,
+ message="bad request",
+ )
+
+ with patch(
+ "dashscope.MultiModalConversation.call",
+ return_value=response,
+ ):
+ with self.assertRaisesRegex(RuntimeError, "DashScope ASR API"):
+ await model.transcribe(audio=b"audio", filename="audio.wav")
+
+
+class DashScopeASRModelCardTest(TestCase):
+ """Verify credential discovery for supported ASR models."""
+
+ def test_lists_latest_model(self) -> None:
+ """Expose Qwen Audio 3.0, 3.1, and streaming models."""
+ cards = DashScopeCredential.list_asr_models()
+
+ self.assertEqual(
+ [card.model_dump(exclude={"parameter_schema"}) for card in cards],
+ [
+ {
+ "type": "asr_model",
+ "name": "qwen-audio-3.0-asr-flash",
+ "label": "Qwen Audio 3.0 ASR Flash",
+ "input_types": [
+ "audio/aac",
+ "audio/flac",
+ "audio/mpeg",
+ "audio/mp4",
+ "audio/ogg",
+ "audio/opus",
+ "audio/wav",
+ "audio/webm",
+ ],
+ "output_types": ["text/plain"],
+ "realtime": False,
+ "parameters_overrides": {
+ "language_hints": {"hidden": True},
+ "keep_dialect": {"hidden": True},
+ "speaker_diarization_enabled": {"hidden": True},
+ "vocabulary": {"hidden": True},
+ "sample_rate": {"hidden": True},
+ },
+ },
+ {
+ "type": "asr_model",
+ "name": "qwen-audio-3.1-asr-flash",
+ "label": "Qwen Audio 3.1 ASR Flash",
+ "input_types": [
+ "audio/aac",
+ "audio/flac",
+ "audio/mpeg",
+ "audio/mp4",
+ "audio/ogg",
+ "audio/opus",
+ "audio/wav",
+ "audio/webm",
+ ],
+ "output_types": ["text/plain"],
+ "realtime": False,
+ "parameters_overrides": {
+ "language_hints": {"hidden": True},
+ "vocabulary": {"hidden": True},
+ "sample_rate": {"hidden": True},
+ },
+ },
+ {
+ "type": "asr_model",
+ "name": "qwen-audio-3.1-asr-flash-streaming",
+ "label": "Qwen Audio 3.1 ASR Flash Streaming",
+ "input_types": ["audio/pcm"],
+ "output_types": ["text/plain"],
+ "realtime": True,
+ "parameters_overrides": {
+ "sample_rate": {"hidden": True},
+ "language_hints": {"hidden": True},
+ "vad_model": {"hidden": True},
+ "vocabulary_id": {"hidden": True},
+ "vocabulary": {"hidden": True},
+ },
+ },
+ ],
+ )
+ self.assertEqual(
+ [list(card.parameter_schema["properties"]) for card in cards[:2]],
+ [[], ["keep_dialect", "speaker_diarization_enabled"]],
+ )
+ self.assertEqual(
+ list(cards[2].parameter_schema["properties"]),
+ [
+ "keep_dialect",
+ "semantic_punctuation_enabled",
+ ],
+ )
+
+
+class _FakeDashScopeWebSocket:
+ """Queue-backed provider socket for realtime protocol tests."""
+
+ def __init__(self, fail_start: bool = False) -> None:
+ self.fail_start = fail_start
+ self.sent: list[str | bytes] = []
+ self.events: asyncio.Queue[str | None] = asyncio.Queue()
+ self.close = AsyncMock(side_effect=self._close)
+
+ def __aiter__(self) -> "_FakeDashScopeWebSocket":
+ return self
+
+ async def __anext__(self) -> str:
+ event = await self.events.get()
+ if event is None:
+ raise StopAsyncIteration
+ return event
+
+ async def send(self, value: str | bytes) -> None:
+ """Record outgoing frames and enqueue matching provider events."""
+ self.sent.append(value)
+ if isinstance(value, bytes):
+ await self._put_event(
+ "result-generated",
+ {
+ "output": {
+ "sentence": {
+ "text": "hello",
+ "sentence_end": False,
+ },
+ },
+ },
+ )
+ else:
+ action = json.loads(value)["header"]["action"]
+ if action == "run-task":
+ if self.fail_start:
+ await self._put_event(
+ "task-failed",
+ header={
+ "error_code": "InvalidParameter",
+ "error_message": "bad input",
+ },
+ )
+ else:
+ await self._put_event("task-started")
+ elif action == "finish-task":
+ await self._put_event(
+ "result-generated",
+ {
+ "output": {
+ "sentence": {
+ "text": "hello world",
+ "sentence_end": True,
+ },
+ },
+ },
+ )
+ await self._put_event("task-finished")
+ await asyncio.sleep(0)
+
+ async def _put_event(
+ self,
+ event: str,
+ payload: dict | None = None,
+ header: dict | None = None,
+ ) -> None:
+ await self.events.put(
+ json.dumps(
+ {
+ "header": {"event": event, **(header or {})},
+ "payload": payload or {},
+ },
+ ),
+ )
+
+ async def _close(self) -> None:
+ await self.events.put(None)
+
+
+class DashScopeRealtimeASRModelTest(IsolatedAsyncioTestCase):
+ """Verify the native streaming protocol and failure mapping."""
+
+ async def test_connect_sends_headers_with_real_client(self) -> None:
+ """Exercise the installed client API against a local WebSocket."""
+ received = {}
+
+ async def handle_connection(websocket: ServerConnection) -> None:
+ """Accept the recognition task and record handshake headers."""
+ request = websocket.request
+ event = json.loads(await websocket.recv())
+ received.update(
+ {
+ "path": request.path,
+ "authorization": request.headers["Authorization"],
+ "inspection": request.headers[
+ "X-DashScope-DataInspection"
+ ],
+ "action": event["header"]["action"],
+ },
+ )
+ await websocket.send(
+ json.dumps({"header": {"event": "task-started"}}),
+ )
+ await websocket.wait_closed()
+
+ async with serve(handle_connection, "127.0.0.1", 0) as server:
+ port = server.sockets[0].getsockname()[1]
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(
+ api_key="test-key",
+ base_url=f"http://127.0.0.1:{port}",
+ ),
+ )
+ async with asyncio.timeout(5):
+ async with model:
+ self.assertEqual(
+ received,
+ {
+ "path": "/api-ws/v1/inference",
+ "authorization": "Bearer test-key",
+ "inspection": "disable",
+ "action": "run-task",
+ },
+ )
+
+ async def test_streams_pcm_and_returns_partial_and_final_text(
+ self,
+ ) -> None:
+ """Map the complete realtime task lifecycle to ASR responses."""
+ socket = _FakeDashScopeWebSocket()
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ parameters=DashScopeRealtimeASRModel.Parameters(
+ sample_rate=48000,
+ language_hints=["en"],
+ ),
+ )
+
+ with patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ) as connect:
+ async with model:
+ partial = await model.push(b"pcm")
+ final = await model.transcribe()
+
+ connect.assert_awaited_once_with(
+ "wss://dashscope.aliyuncs.com/api-ws/v1/inference",
+ additional_headers={
+ "Authorization": "Bearer test-key",
+ "X-DashScope-DataInspection": "disable",
+ },
+ )
+ run_task = json.loads(socket.sent[0])
+ self.assertEqual(
+ run_task["payload"],
+ {
+ "task_group": "audio",
+ "task": "asr",
+ "function": "recognition",
+ "model": "qwen-audio-3.1-asr-flash-streaming",
+ "parameters": {
+ "sample_rate": 48000,
+ "language_hints": ["en"],
+ "keep_dialect": False,
+ "vad_model": "far_field_meeting_16k",
+ "semantic_punctuation_enabled": True,
+ "format": "pcm",
+ },
+ "input": {},
+ },
+ )
+ self.assertEqual(socket.sent[1], b"pcm")
+ self.assertEqual(partial.content.text, "hello")
+ self.assertFalse(partial.is_last)
+ self.assertEqual(final.content.text, "hello world")
+ self.assertTrue(final.is_last)
+ self.assertEqual(
+ json.loads(socket.sent[2])["header"]["action"],
+ "finish-task",
+ )
+ socket.close.assert_awaited_once()
+
+ async def test_surfaces_task_start_failure(self) -> None:
+ """Raise the provider's task-failed detail during connection."""
+ socket = _FakeDashScopeWebSocket(fail_start=True)
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+
+ with patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ):
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "InvalidParameter.*bad input",
+ ):
+ await model.connect()
+
+ socket.close.assert_awaited_once()
+
+ async def test_cleans_up_when_initial_send_fails(self) -> None:
+ """Failed context entry releases resources and preserves the error."""
+ # pylint: disable=protected-access
+ # Each callback completes before the next subtest starts.
+ # pylint: disable=cell-var-from-loop
+ for error in (OSError("send failed"), TimeoutError("send timed out")):
+ with self.subTest(error=type(error).__name__):
+ socket = _FakeDashScopeWebSocket()
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+ reader = None
+
+ async def fail_send(_: str) -> None:
+ """Capture the background task before failing the send."""
+ nonlocal reader
+ reader = model._reader
+ raise error
+
+ self.addAsyncCleanup(model.close)
+ with (
+ patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ),
+ patch.object(socket, "send", side_effect=fail_send),
+ ):
+ with self.assertRaises(type(error)) as raised:
+ async with model:
+ self.fail("Context entry must fail")
+
+ self.assertIs(raised.exception, error)
+ self.assertEqual(
+ {
+ "websocket": model._websocket,
+ "reader": model._reader,
+ "reader_done": reader.done(),
+ "close_calls": socket.close.await_count,
+ },
+ {
+ "websocket": None,
+ "reader": None,
+ "reader_done": True,
+ "close_calls": 1,
+ },
+ )
+
+ async def test_cleans_up_when_initialization_is_cancelled(self) -> None:
+ """Cancellation during sending or startup still releases resources."""
+ # pylint: disable=protected-access
+ # Each callback completes before the next subtest starts.
+ # pylint: disable=cell-var-from-loop
+ for phase in ("send", "startup"):
+ with self.subTest(phase=phase):
+ socket = _FakeDashScopeWebSocket()
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+ reached = asyncio.Event()
+ pending = asyncio.Event()
+
+ async def send_without_response(_: str) -> None:
+ """Keep the provider silent until initialization ends."""
+ if phase == "send":
+ reached.set()
+ await pending.wait()
+
+ async def wait_for_startup() -> None:
+ """Signal that connection setup is waiting for startup."""
+ reached.set()
+ await pending.wait()
+
+ self.addAsyncCleanup(model.close)
+ with (
+ patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ),
+ patch.object(
+ socket,
+ "send",
+ side_effect=send_without_response,
+ ),
+ patch.object(
+ model._started,
+ "wait",
+ side_effect=wait_for_startup,
+ ),
+ ):
+ entering = asyncio.create_task(model.connect())
+ try:
+ await asyncio.wait_for(reached.wait(), timeout=5)
+ reader = model._reader
+ entering.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await entering
+ finally:
+ entering.cancel()
+ await asyncio.gather(entering, return_exceptions=True)
+
+ self.assertEqual(
+ {
+ "websocket": model._websocket,
+ "reader": model._reader,
+ "reader_done": reader.done(),
+ "close_calls": socket.close.await_count,
+ "cancelled": entering.cancelled(),
+ },
+ {
+ "websocket": None,
+ "reader": None,
+ "reader_done": True,
+ "close_calls": 1,
+ "cancelled": True,
+ },
+ )
+
+ async def test_cleans_up_when_startup_times_out(self) -> None:
+ """Keep the startup timeout message while closing the connection."""
+ socket = _FakeDashScopeWebSocket()
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+ self.addAsyncCleanup(model.close)
+ with (
+ patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ),
+ patch.object(socket, "send", new=AsyncMock()),
+ patch(
+ "agentscope.asr._dashscope._realtime_model."
+ "_CONNECT_TIMEOUT_SECONDS",
+ 0,
+ ),
+ ):
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "Timed out waiting for DashScope ASR task startup",
+ ):
+ await model.connect()
+
+ socket.close.assert_awaited_once()
+
+ async def test_push_after_close_reports_not_connected(self) -> None:
+ """Prefer the local connection state after an intentional close."""
+ socket = _FakeDashScopeWebSocket()
+ model = DashScopeRealtimeASRModel(
+ credential=DashScopeCredential(api_key="test-key"),
+ )
+
+ with patch(
+ "websockets.asyncio.client.connect",
+ new=AsyncMock(return_value=socket),
+ ):
+ await model.connect()
+ await model.close()
+
+ with self.assertRaisesRegex(RuntimeError, "not connected"):
+ await model.push(b"pcm")
diff --git a/tests/asr_openai_test.py b/tests/asr_openai_test.py
index e56ef159e..951aba8f7 100644
--- a/tests/asr_openai_test.py
+++ b/tests/asr_openai_test.py
@@ -1,11 +1,19 @@
# -*- coding: utf-8 -*-
"""Unit tests for batch and realtime ASR model behavior."""
+from enum import Enum
from typing import Any
-from unittest import IsolatedAsyncioTestCase
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest import IsolatedAsyncioTestCase, TestCase
+from unittest.mock import AsyncMock, MagicMock, mock_open, patch
-from agentscope.asr import ASRModelBase, ASRResponse, OpenAIASRModel
+from pydantic import BaseModel, ConfigDict
+
+from agentscope.asr import (
+ ASRModelBase,
+ ASRModelCard,
+ ASRResponse,
+ OpenAIASRModel,
+)
from agentscope.credential import OpenAICredential
from agentscope.message import TextBlock
@@ -486,6 +494,7 @@ class TestOpenAIASRModel(IsolatedAsyncioTestCase):
"output_types": ["text/plain"],
"realtime": False,
"parameter_schema": parameter_schema,
+ "parameters_overrides": {},
},
{
"type": "asr_model",
@@ -502,6 +511,92 @@ class TestOpenAIASRModel(IsolatedAsyncioTestCase):
"output_types": ["text/plain"],
"realtime": False,
"parameter_schema": parameter_schema,
+ "parameters_overrides": {},
},
],
)
+
+
+class _Language(str, Enum):
+ """Languages advertised by the custom ASR model."""
+
+ EN = "en"
+ ZH = "zh"
+
+
+class _Options(BaseModel):
+ """Nested recognition settings."""
+
+ language: _Language
+
+
+class _Parameters(BaseModel):
+ """Custom parameters with references and strict field validation."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ options: _Options
+ language: _Language
+ internal: str
+
+
+class ASRModelCardTest(TestCase):
+ """Preserve complete schemas when applying model-specific overrides."""
+
+ def test_preserves_full_schema_without_overrides(self) -> None:
+ """Keep nested and enum definitions plus root-level constraints."""
+ with patch(
+ "builtins.open",
+ mock_open(read_data="name: custom\nlabel: Custom\n"),
+ ):
+ card = ASRModelCard.from_yaml("model.yaml", _Parameters)
+
+ self.assertEqual(
+ card.parameter_schema,
+ _Parameters.model_json_schema(),
+ )
+
+ def test_overrides_preserve_schema_and_do_not_mutate_source(self) -> None:
+ """Hide required fields and override labels without losing metadata."""
+ original = _Parameters.model_json_schema()
+ expected = _Parameters.model_json_schema()
+ del expected["properties"]["internal"]
+ expected["properties"]["language"]["title"] = "Language choice"
+ expected["required"] = ["options", "language"]
+ yaml_text = (
+ "name: custom\n"
+ "label: Custom\n"
+ "parameter_overrides:\n"
+ " internal:\n"
+ " hidden: true\n"
+ " language:\n"
+ " title: Language choice\n"
+ )
+ with (
+ patch("builtins.open", mock_open(read_data=yaml_text)),
+ patch.object(
+ _Parameters,
+ "model_json_schema",
+ return_value=original,
+ ),
+ ):
+ card = ASRModelCard.from_yaml("model.yaml", _Parameters)
+
+ self.assertEqual(card.parameter_schema, expected)
+ self.assertEqual(original, _Parameters.model_json_schema())
+
+ def test_preserves_schema_without_required_fields(self) -> None:
+ """Do not introduce fields absent from the original schema."""
+
+ class Parameters(BaseModel):
+ """Recognition settings with only optional parameters."""
+
+ language: _Language = _Language.EN
+
+ with patch(
+ "builtins.open",
+ mock_open(read_data="name: custom\nlabel: Custom\n"),
+ ):
+ card = ASRModelCard.from_yaml("model.yaml", Parameters)
+
+ self.assertEqual(card.parameter_schema, Parameters.model_json_schema())
diff --git a/tests/asr_router_test.py b/tests/asr_router_test.py
new file mode 100644
index 000000000..13bf3cd41
--- /dev/null
+++ b/tests/asr_router_test.py
@@ -0,0 +1,525 @@
+# -*- coding: utf-8 -*-
+"""ASR Web App route and model-construction tests."""
+
+from types import SimpleNamespace
+from unittest import IsolatedAsyncioTestCase, TestCase
+from unittest.mock import AsyncMock, call, patch
+
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+
+from agentscope.app._router import asr_router
+from agentscope.app._service import get_asr_model
+from agentscope.app.deps import (
+ get_current_user_id,
+ get_resource_access_service,
+)
+from agentscope.asr import ASRResponse, DashScopeASRModel
+from agentscope.credential import DashScopeCredential, OpenAICredential
+from agentscope.message import TextBlock
+
+
+class ASRRouterTest(TestCase):
+ """Exercise model discovery and multipart transcription."""
+
+ def setUp(self) -> None:
+ """Mount the ASR router with lightweight dependency overrides."""
+ app = FastAPI()
+ app.include_router(asr_router)
+ self.access = object()
+ app.dependency_overrides[get_current_user_id] = lambda: "alice"
+ app.dependency_overrides[
+ get_resource_access_service
+ ] = lambda: self.access
+ app.state.resource_access_service = self.access
+ app.state.download_secret = "test-secret"
+ self.client = self.enterContext(TestClient(app))
+
+ def test_lists_batch_models(self) -> None:
+ """Return every ASR card advertised by the provider."""
+ response = self.client.get(
+ "/asr-model/",
+ params={"provider": "openai_credential"},
+ )
+
+ expected = [
+ card.model_dump(mode="json")
+ for card in OpenAICredential.list_asr_models()
+ ]
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {"models": expected, "total": len(expected)},
+ )
+
+ def test_lists_dashscope_batch_and_realtime_models(self) -> None:
+ """Expose both DashScope transcription modes in one selector."""
+ response = self.client.get(
+ "/asr-model/",
+ params={"provider": "dashscope_credential"},
+ )
+
+ expected = [
+ card.model_dump(mode="json")
+ for card in DashScopeCredential.list_asr_models()
+ ]
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {"models": expected, "total": len(expected)},
+ )
+
+ def test_unknown_provider_is_not_found(self) -> None:
+ """Reject a provider discriminator that is not registered."""
+ response = self.client.get(
+ "/asr-model/",
+ params={"provider": "missing_credential"},
+ )
+
+ self.assertEqual(response.status_code, 404)
+ self.assertEqual(
+ response.json(),
+ {"detail": "Provider 'missing_credential' not found."},
+ )
+
+ def test_transcribes_multipart_audio(self) -> None:
+ """Pass uploaded bytes and filename to the resolved ASR model."""
+ model = SimpleNamespace(
+ transcribe=AsyncMock(
+ return_value=ASRResponse(
+ content=TextBlock(text="hello from audio"),
+ ),
+ ),
+ )
+
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(return_value=model),
+ ) as factory:
+ response = self.client.post(
+ "/asr/transcriptions",
+ data={
+ "credential_id": "credential-1",
+ "model": "asr-1",
+ "parameters": '{"language":"en"}',
+ },
+ files={
+ "file": (
+ "speech.webm",
+ b"audio bytes",
+ "audio/webm",
+ ),
+ },
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json(), {"text": "hello from audio"})
+ factory.assert_awaited_once_with(
+ user_id="alice",
+ credential_id="credential-1",
+ model="asr-1",
+ access=self.access,
+ parameters={"language": "en"},
+ )
+ model.transcribe.assert_awaited_once_with(
+ audio=b"audio bytes",
+ filename="speech.webm",
+ )
+
+ def test_rejects_empty_audio(self) -> None:
+ """Reject an empty recording before constructing an ASR model."""
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(),
+ ) as factory:
+ response = self.client.post(
+ "/asr/transcriptions",
+ data={"credential_id": "credential-1", "model": "asr-1"},
+ files={"file": ("speech.webm", b"", "audio/webm")},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(
+ response.json(),
+ {"detail": "Audio file must not be empty."},
+ )
+ factory.assert_not_awaited()
+
+ def test_rejects_oversized_audio(self) -> None:
+ """Reject a recording before reading beyond the service limit."""
+ with (
+ patch(
+ "agentscope.app._router._asr._MAX_AUDIO_UPLOAD_BYTES",
+ 4,
+ ),
+ patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(),
+ ) as factory,
+ ):
+ response = self.client.post(
+ "/asr/transcriptions",
+ data={"credential_id": "credential-1", "model": "asr-1"},
+ files={"file": ("speech.webm", b"audio", "audio/webm")},
+ )
+
+ self.assertEqual(response.status_code, 413)
+ self.assertEqual(
+ response.json(),
+ {"detail": "Audio file exceeds the 25 MiB upload limit."},
+ )
+ factory.assert_not_awaited()
+
+ def test_rejects_invalid_model_parameters(self) -> None:
+ """Map provider parameter validation failures to a bad request."""
+ with self.assertRaises(ValueError) as context:
+ DashScopeASRModel.Parameters(sample_rate=-5)
+
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(side_effect=context.exception),
+ ):
+ response = self.client.post(
+ "/asr/transcriptions",
+ data={
+ "credential_id": "credential-1",
+ "model": "asr-1",
+ "parameters": '{"sample_rate":-5}',
+ },
+ files={"file": ("speech.webm", b"audio", "audio/webm")},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("sample_rate", response.json()["detail"])
+
+ def test_streams_realtime_audio(self) -> None:
+ """Resolve a realtime model and proxy partial plus final text."""
+
+ class _RealtimeModel:
+ def __init__(self) -> None:
+ self.audio = b""
+
+ async def __aenter__(self) -> "_RealtimeModel":
+ return self
+
+ async def __aexit__(self, *args: object) -> None:
+ return None
+
+ async def push(self, audio: bytes) -> ASRResponse:
+ """Capture one browser audio frame."""
+ self.audio = audio
+ return ASRResponse(
+ content=TextBlock(text="partial"),
+ is_last=False,
+ )
+
+ async def transcribe(self) -> ASRResponse:
+ """Return the final provider text."""
+ return ASRResponse(
+ content=TextBlock(text="final text"),
+ is_last=True,
+ )
+
+ model = _RealtimeModel()
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(return_value=model),
+ ) as factory:
+ token_response = self.client.post(
+ "/asr/realtime/token",
+ json={
+ "credential_id": "credential-1",
+ "model": "streaming-asr",
+ },
+ )
+ token = token_response.json()["token"]
+ with self.client.websocket_connect(
+ f"/asr/realtime?token={token}",
+ ) as websocket:
+ websocket.send_json(
+ {
+ "type": "start",
+ "credential_id": "credential-1",
+ "model": "streaming-asr",
+ "parameters": {"language_hints": ["en"]},
+ "sample_rate": 48000,
+ },
+ )
+ self.assertEqual(websocket.receive_json(), {"type": "ready"})
+ websocket.send_bytes(b"pcm")
+ self.assertEqual(
+ websocket.receive_json(),
+ {
+ "type": "transcript",
+ "text": "partial",
+ "is_last": False,
+ },
+ )
+ websocket.send_json({"type": "stop"})
+ self.assertEqual(
+ websocket.receive_json(),
+ {
+ "type": "transcript",
+ "text": "final text",
+ "is_last": True,
+ },
+ )
+
+ self.assertEqual(model.audio, b"pcm")
+ self.assertEqual(token_response.status_code, 200)
+ self.assertIsInstance(token_response.json()["expires_at"], int)
+ factory.assert_has_awaits(
+ [
+ call(
+ user_id="alice",
+ credential_id="credential-1",
+ model="streaming-asr",
+ access=self.access,
+ realtime=True,
+ ),
+ call(
+ user_id="alice",
+ credential_id="credential-1",
+ model="streaming-asr",
+ access=self.access,
+ parameters={
+ "language_hints": ["en"],
+ "sample_rate": 48000,
+ },
+ realtime=True,
+ ),
+ ],
+ )
+
+ def test_realtime_token_is_required_and_bound_to_config(self) -> None:
+ """Reject missing tokens and tokens minted for another model."""
+ start = {
+ "type": "start",
+ "credential_id": "credential-1",
+ "model": "other-asr",
+ "parameters": {},
+ "sample_rate": 16000,
+ }
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(return_value=object()),
+ ) as factory:
+ token_response = self.client.post(
+ "/asr/realtime/token",
+ json={
+ "credential_id": "credential-1",
+ "model": "streaming-asr",
+ },
+ )
+ with self.client.websocket_connect(
+ "/asr/realtime",
+ ) as websocket:
+ websocket.send_json(start)
+ missing_token = websocket.receive_json()
+ with self.client.websocket_connect(
+ f"/asr/realtime?token={token_response.json()['token']}",
+ ) as websocket:
+ websocket.send_json(start)
+ wrong_config = websocket.receive_json()
+
+ self.assertEqual(
+ missing_token,
+ {"type": "error", "detail": "Realtime ASR token is required."},
+ )
+ self.assertEqual(
+ wrong_config,
+ {
+ "type": "error",
+ "detail": "Invalid or expired realtime ASR token.",
+ },
+ )
+ factory.assert_awaited_once_with(
+ user_id="alice",
+ credential_id="credential-1",
+ model="streaming-asr",
+ access=self.access,
+ realtime=True,
+ )
+
+ def test_rejects_invalid_realtime_start(self) -> None:
+ """Close the realtime connection after an invalid start frame."""
+ with self.client.websocket_connect("/asr/realtime") as websocket:
+ websocket.send_json({"type": "start"})
+ event = websocket.receive_json()
+
+ self.assertEqual(event["type"], "error")
+ self.assertIn("validation error", event["detail"])
+
+ def test_rejects_invalid_parameters(self) -> None:
+ """Reject non-object ASR parameters before model construction."""
+ with patch(
+ "agentscope.app._router._asr.get_asr_model",
+ new=AsyncMock(),
+ ) as factory:
+ response = self.client.post(
+ "/asr/transcriptions",
+ data={
+ "credential_id": "credential-1",
+ "model": "asr-1",
+ "parameters": "[]",
+ },
+ files={"file": ("speech.webm", b"audio", "audio/webm")},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(
+ response.json(),
+ {"detail": "ASR parameters must be a JSON object."},
+ )
+ factory.assert_not_awaited()
+
+
+class ASRModelServiceTest(IsolatedAsyncioTestCase):
+ """Resolve an exact ASR model against a visible credential."""
+
+ async def test_builds_requested_model(self) -> None:
+ """Use resource access and instantiate the advertising class."""
+
+ class _Model:
+ realtime = False
+
+ @classmethod
+ def list_models(cls) -> list:
+ """Advertise one batch model for the service test."""
+ return [SimpleNamespace(name="asr-1")]
+
+ class Parameters:
+ """Capture provider parameters for this service test."""
+
+ def __init__(self, **values: object) -> None:
+ self.values = values
+
+ def __init__(
+ self,
+ credential: object,
+ model: str,
+ parameters: object,
+ ) -> None:
+ self.credential = credential
+ self.model = model
+ self.parameters = parameters
+
+ credential = SimpleNamespace(
+ get_asr_model_classes=lambda: [_Model],
+ )
+ access = SimpleNamespace(
+ resolve_credential=AsyncMock(
+ return_value=SimpleNamespace(data={"type": "fake"}),
+ ),
+ )
+
+ with patch(
+ "agentscope.app._service._asr_model."
+ "CredentialFactory.from_dict",
+ return_value=credential,
+ ):
+ result = await get_asr_model(
+ user_id="alice",
+ credential_id="credential-1",
+ model="asr-1",
+ access=access,
+ parameters={"language": "en"},
+ )
+
+ self.assertEqual(result.credential, credential)
+ self.assertEqual(result.model, "asr-1")
+ self.assertEqual(result.parameters.values, {"language": "en"})
+ access.resolve_credential.assert_awaited_once_with(
+ "alice",
+ "credential-1",
+ )
+
+ async def test_builds_requested_realtime_model(self) -> None:
+ """Select the realtime implementation only when requested."""
+
+ class _RealtimeModel:
+ realtime = True
+
+ @classmethod
+ def list_models(cls) -> list:
+ """Advertise one realtime model for the service test."""
+ return [SimpleNamespace(name="asr-stream")]
+
+ class Parameters:
+ """Capture realtime provider parameters."""
+
+ def __init__(self, **values: object) -> None:
+ self.values = values
+
+ def __init__(
+ self,
+ credential: object,
+ model: str,
+ parameters: object,
+ ) -> None:
+ self.credential = credential
+ self.model = model
+ self.parameters = parameters
+
+ credential = SimpleNamespace(
+ get_asr_model_classes=lambda: [_RealtimeModel],
+ )
+ access = SimpleNamespace(
+ resolve_credential=AsyncMock(
+ return_value=SimpleNamespace(data={"type": "fake"}),
+ ),
+ )
+
+ with patch(
+ "agentscope.app._service._asr_model."
+ "CredentialFactory.from_dict",
+ return_value=credential,
+ ):
+ result = await get_asr_model(
+ user_id="alice",
+ credential_id="credential-1",
+ model="asr-stream",
+ access=access,
+ parameters={"sample_rate": 48000},
+ realtime=True,
+ )
+
+ self.assertEqual(result.credential, credential)
+ self.assertEqual(result.model, "asr-stream")
+ self.assertEqual(result.parameters.values, {"sample_rate": 48000})
+
+ async def test_rejects_unadvertised_model(self) -> None:
+ """Do not silently substitute another model name."""
+
+ class _Model:
+ realtime = False
+
+ @classmethod
+ def list_models(cls) -> list:
+ """Advertise a model different from the requested one."""
+ return [SimpleNamespace(name="asr-1")]
+
+ credential = SimpleNamespace(
+ get_asr_model_classes=lambda: [_Model],
+ )
+ access = SimpleNamespace(
+ resolve_credential=AsyncMock(
+ return_value=SimpleNamespace(data={"type": "fake"}),
+ ),
+ )
+
+ with patch(
+ "agentscope.app._service._asr_model."
+ "CredentialFactory.from_dict",
+ return_value=credential,
+ ):
+ with self.assertRaisesRegex(
+ HTTPException,
+ "ASR model 'missing' is not available",
+ ):
+ await get_asr_model(
+ user_id="alice",
+ credential_id="credential-1",
+ model="missing",
+ access=access,
+ )
diff --git a/tests/session_auto_naming_test.py b/tests/session_auto_naming_test.py
index 051eae3aa..79512638f 100644
--- a/tests/session_auto_naming_test.py
+++ b/tests/session_auto_naming_test.py
@@ -137,6 +137,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
@@ -158,6 +159,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
@@ -185,6 +187,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
@@ -212,6 +215,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
@@ -238,6 +242,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
@@ -362,6 +367,7 @@ class AutoNameSessionTest(IsolatedAsyncioTestCase):
},
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "asr_model_config": None,
"realtime_model_config": None,
"knowledge_config": None,
},
diff --git a/tests/session_config_patch_test.py b/tests/session_config_patch_test.py
index cd7b8566e..0e3cd928e 100644
--- a/tests/session_config_patch_test.py
+++ b/tests/session_config_patch_test.py
@@ -24,6 +24,7 @@ from agentscope.app.message_bus import MessageBusKeys, RedisMessageBus
from agentscope.app.storage import (
AgentData,
AgentRecord,
+ ASRModelConfig,
RealtimeModelConfig,
RedisStorage,
VoiceProfileData,
@@ -211,6 +212,49 @@ class SessionConfigPatchTest(IsolatedAsyncioTestCase):
},
)
+ async def test_asr_config_omission_and_explicit_null(self) -> None:
+ """Omission keeps ASR config while null disables speech input."""
+ record = await self.storage.get_session(
+ "alice",
+ self.agent_id,
+ self.session_id,
+ )
+ asr_config = ASRModelConfig(
+ type="dashscope_credential",
+ credential_id="credential-1",
+ model="qwen-audio-3.1-asr-flash",
+ parameters={"language_hints": ["zh"]},
+ )
+ await self.storage.upsert_session(
+ user_id="alice",
+ agent_id=self.agent_id,
+ config=record.config.model_copy(
+ update={"asr_model_config": asr_config},
+ ),
+ session_id=self.session_id,
+ )
+ self.recorded_states.clear()
+
+ omitted = self._patch({"name": "after"})
+ cleared = self._patch({"asr_model_config": None})
+
+ self.assertDictEqual(
+ {
+ "omitted_status": omitted.status_code,
+ "omitted_config": omitted.json()["config"]["asr_model_config"],
+ "cleared_status": cleared.status_code,
+ "cleared_config": cleared.json()["config"]["asr_model_config"],
+ "written_states": self.recorded_states,
+ },
+ {
+ "omitted_status": 200,
+ "omitted_config": asr_config.model_dump(mode="json"),
+ "cleared_status": 200,
+ "cleared_config": None,
+ "written_states": [None, None],
+ },
+ )
+
async def test_voice_profile_and_realtime_configs_coexist(self) -> None:
"""Create and update keep both voice configs and validate ownership."""
credential_id = await self.storage.upsert_credential(