Skip to content

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

feat(app): refine realtime voice UX and response lifecycle (#3180)

qbc22d042ab1e00
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 069bade70..91b971ab1 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -848,6 +848,7 @@ export interface RealtimeModelCard {
label: string;
status: 'active' | 'deprecated' | 'sunset';
deprecated_at: string | null;
+ release_date: string | null;
input_types: string[];
output_types: string[];
input_sample_rate: number;
diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
index 1afbb8761..d226b7624 100644
--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
@@ -107,7 +107,7 @@ interface FieldProps {
function BooleanField({ id, label, prop, value, onChange }: FieldProps) {
return (
<>
- <Label htmlFor={id} className="whitespace-nowrap">
+ <Label htmlFor={id} className="min-w-0 whitespace-normal leading-tight">
{label}
</Label>
<Switch
@@ -136,13 +136,17 @@ function EnumField({
return (
<>
- <Label htmlFor={id} className="whitespace-nowrap">
+ <Label htmlFor={id} className="min-w-0 whitespace-normal leading-tight">
{label}
{required && <span className="text-destructive ml-0.5">*</span>}
</Label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button id={id} variant="outline" className="w-full justify-between gap-1">
+ <Button
+ id={id}
+ variant="outline"
+ className="min-w-0 w-full justify-between gap-1"
+ >
<span className="truncate">{displayValue}</span>
<ChevronDown className="size-3.5 opacity-50 shrink-0" />
</Button>
@@ -170,7 +174,7 @@ function NumberField({ id, label, required, prop, value, onChange }: FieldProps)
return (
<>
- <Label htmlFor={id} className="whitespace-nowrap">
+ <Label htmlFor={id} className="min-w-0 whitespace-normal leading-tight">
{label}
{required && <span className="text-destructive ml-0.5">*</span>}
</Label>
@@ -209,7 +213,7 @@ function NumberField({ id, label, required, prop, value, onChange }: FieldProps)
function StringField({ id, label, required, prop, value, onChange }: FieldProps) {
return (
<>
- <Label htmlFor={id} className="whitespace-nowrap">
+ <Label htmlFor={id} className="min-w-0 whitespace-normal leading-tight">
{label}
{required && <span className="text-destructive ml-0.5">*</span>}
</Label>
@@ -260,13 +264,14 @@ interface Props {
}
/**
- * A unified settings dropdown for the active chat model. Exposes two
- * sub-menus:
+ * A unified settings dropdown for the active chat model. Exposes these
+ * sections when configured:
* - "Fallback model": pick a backup model invoked when the primary fails.
* - "Parameters": edit the primary model's inference parameters inline.
+ * - "TTS": select and configure a speech model.
*
- * The trigger is disabled until a primary model is selected, since both
- * sub-menus are meaningless without one.
+ * When parameters are the only section, they are rendered directly in the
+ * dropdown. The trigger is disabled until a primary model is selected.
*/
export function ModelParametersPopover({
selectedModel,
@@ -335,6 +340,67 @@ export function ModelParametersPopover({
.map(([type, items]) => [type, items.filter((i) => i.models.length > 0)] as const)
.filter(([, usable]) => usable.length > 0);
const hasFallbackOptions = fallbackGroups.length > 0;
+ const parametersOnly = onFallbackChange === undefined && onTTSChange === undefined;
+ const parameterEditor = (
+ <>
+ <div className="mb-3">
+ <p className="text-sm font-medium">{t('model-parameters.title')}</p>
+ <p className="text-muted-foreground text-xs">{t('model-parameters.description')}</p>
+ </div>
+ {entries.length === 0 ? (
+ <p className="text-muted-foreground text-xs">{t('model-parameters.empty')}</p>
+ ) : (
+ <div
+ className="grid grid-cols-[minmax(0,1fr)_minmax(7.5rem,10rem)] items-center gap-x-3 gap-y-3"
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ {entries.map(([key, prop]) => {
+ const { type: effectiveType, enumValues } = resolveType(prop);
+ const label = prop.title ?? key;
+ const isRequired = required.includes(key);
+ const fieldProps: FieldProps = {
+ id: `param-${idPrefix}-${key}`,
+ label,
+ required: isRequired,
+ prop,
+ value: values[key],
+ onChange: (v) => handleChange(key, v),
+ };
+
+ let field: React.ReactNode;
+ if (effectiveType === 'boolean') {
+ field = <BooleanField {...fieldProps} />;
+ } else if (enumValues) {
+ field = (
+ <EnumField
+ {...fieldProps}
+ excludedValues={excludedEnumValues?.[key]}
+ />
+ );
+ } else if (effectiveType === 'number' || effectiveType === 'integer') {
+ field = <NumberField {...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>
+ )}
+ </>
+ );
// Legacy configs use the first matching implementation, as the backend does.
const selectedFallbackCard = selectedFallbackModel
? groups[selectedFallbackModel.type]
@@ -360,7 +426,14 @@ export function ModelParametersPopover({
<SlidersHorizontal />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-40">
+ <DropdownMenuContent
+ align="start"
+ className={cn(
+ parametersOnly
+ ? 'w-80 max-w-(--radix-dropdown-menu-content-available-width) max-h-(--radix-dropdown-menu-content-available-height) overflow-x-hidden overflow-y-auto p-3'
+ : 'min-w-40',
+ )}
+ >
{/* ----- Fallback model selection ----- */}
{onFallbackChange !== undefined && (
<DropdownMenuSub>
@@ -473,81 +546,20 @@ export function ModelParametersPopover({
)}
{/* ----- Primary model parameters ----- */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- {t('model-parameters.parametersLabel')}
- </DropdownMenuSubTrigger>
- <DropdownMenuPortal>
- <DropdownMenuSubContent className="w-80 max-h-(--radix-dropdown-menu-content-available-height) overflow-x-hidden overflow-y-auto p-3">
- <div className="mb-3">
- <p className="text-sm font-medium">{t('model-parameters.title')}</p>
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.description')}
- </p>
- </div>
- {entries.length === 0 ? (
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.empty')}
- </p>
- ) : (
- <div
- className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3"
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- >
- {entries.map(([key, prop]) => {
- const { type: effectiveType, enumValues } =
- resolveType(prop);
- const label = prop.title ?? key;
- const isRequired = required.includes(key);
- const fieldProps: FieldProps = {
- id: `param-${idPrefix}-${key}`,
- label,
- required: isRequired,
- prop,
- value: values[key],
- onChange: (v) => handleChange(key, v),
- };
-
- let field: React.ReactNode;
- if (effectiveType === 'boolean') {
- field = <BooleanField {...fieldProps} />;
- } else if (enumValues) {
- field = (
- <EnumField
- {...fieldProps}
- excludedValues={excludedEnumValues?.[key]}
- />
- );
- } else if (
- effectiveType === 'number' ||
- effectiveType === 'integer'
- ) {
- field = <NumberField {...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>
- </DropdownMenuPortal>
- </DropdownMenuSub>
+ {parametersOnly ? (
+ parameterEditor
+ ) : (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ {t('model-parameters.parametersLabel')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent className="w-80 max-h-(--radix-dropdown-menu-content-available-height) overflow-x-hidden overflow-y-auto p-3">
+ {parameterEditor}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ )}
{/* ----- TTS ----- */}
{onTTSChange !== undefined && (
diff --git a/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
index 407f54310..0e366e178 100644
--- a/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
+++ b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
@@ -46,7 +46,7 @@ export function RealtimeModelSelect({
}: Props) {
const { groups, loading } = useAvailableRealtimeModels();
const { t } = useTranslation();
- const entries = Object.entries(groups);
+ const entries = Object.entries(groups).sort(([left], [right]) => left.localeCompare(right));
const handleSelect = (credentialId: string, model: RealtimeModelCard) => {
onChange?.({
@@ -93,7 +93,7 @@ export function RealtimeModelSelect({
handleSelect(items[0].credential.id, model)
}
>
- {model.label}
+ {model.name}
</DropdownMenuItem>
))
: items.map(({ credential, models }) => (
@@ -110,7 +110,7 @@ export function RealtimeModelSelect({
handleSelect(credential.id, model)
}
>
- {model.label}
+ {model.name}
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts
index 4853592fa..d1a6974ce 100644
--- a/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts
+++ b/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts
@@ -24,9 +24,14 @@ async function fetchGroups(): Promise<Record<string, CredentialWithRealtimeModel
try {
const { models } = await realtimeModelApi.list(provider);
if (models.length === 0) return;
- const sortedModels = [...models].sort((a, b) =>
- b.name.localeCompare(a.name, undefined, { numeric: true }),
- );
+ const sortedModels = [...models].sort((a, b) => {
+ const byReleaseDate = (b.release_date ?? '').localeCompare(
+ a.release_date ?? '',
+ );
+ return (
+ byReleaseDate || b.name.localeCompare(a.name, undefined, { numeric: true })
+ );
+ });
result[provider] = providerCredentials.map((credential) => ({
credential,
models: sortedModels,
diff --git a/src/agentscope/agent/_realtime/_agent.py b/src/agentscope/agent/_realtime/_agent.py
index 65b19d6d8..9fa8fcc5e 100644
--- a/src/agentscope/agent/_realtime/_agent.py
+++ b/src/agentscope/agent/_realtime/_agent.py
@@ -81,6 +81,16 @@ class _Reply:
audio_started: bool = False
+@dataclass
+class _UserTurn:
+ """One user reply, retained until its transcription settles."""
+
+ reply_id: str
+ item_id: str = ""
+ open: bool = True
+ speech_ended: bool = False
+
+
@dataclass
class _QueuedEvent:
"""One outward event and its state at a persistence boundary."""
@@ -179,13 +189,12 @@ class RealtimeAgent:
self._reply: _Reply | None = None
self._audio_pending = False
self._finished_item = ""
- # The agent's open reply, and whether the next response continues
- # it (after tool results) rather than starting a new one.
+ # The agent's open logical reply. Multiple provider responses may
+ # belong to it when tools are involved.
self._reply_id = ""
- self._continuing = False
# The user's turn in flight, reported as a reply of its own.
- self._user_turn = ""
- self._user_turn_open = False
+ self._user_turn: _UserTurn | None = None
+ self._pending_user_turns: dict[str, _UserTurn] = {}
self._metrics = TurnMetrics()
self._pending_tools: dict[str, ToolCallBlock] = {}
self._confirmations: dict[str, asyncio.Future[ConfirmResult]] = {}
@@ -223,8 +232,7 @@ class RealtimeAgent:
if self._connection_generation:
async with self._barge_lock:
- self._end_user_turn()
- self._user_turn = ""
+ self._reset_user_turns()
self._finish_reply(ReplyFinishedReason.ERROR)
self._connection_generation += 1
@@ -452,6 +460,9 @@ class RealtimeAgent:
# events that produced (the interrupted ReplyEnd) before the
# stream ends rather than leaking them into the next run.
await self._barge_in()
+ for turn in list(self._pending_user_turns.values()):
+ self._end_user_turn(turn)
+ self._end_user_turn()
while not self._out.empty():
queued = self._out.get_nowait()
self._yielded_checkpoint = (
@@ -588,6 +599,8 @@ class RealtimeAgent:
self._start_user_turn()
await self._barge_in()
elif speech is SpeechTransition.ENDED:
+ if self._user_turn is not None:
+ self._user_turn.speech_ended = True
if not self.model.input_transcription_enabled:
self._end_user_turn()
now = time.monotonic()
@@ -664,8 +677,7 @@ class RealtimeAgent:
if generation != self._connection_generation:
continue
self._mark_disconnected()
- self._end_user_turn()
- self._user_turn = ""
+ self._reset_user_turns()
self._finish_reply(ReplyFinishedReason.ERROR)
logger.info(
"RealtimeAgent: model session ended; keep talking and it "
@@ -681,8 +693,16 @@ class RealtimeAgent:
await self._barge_in()
case me.SpeechEndedEvent():
- if not self.model.input_transcription_enabled:
- self._end_user_turn()
+ turn = (
+ self._find_user_turn(event.item_id)
+ if event.item_id
+ else self._user_turn
+ )
+ if turn is not None:
+ turn.speech_ended = True
+ turn.item_id = turn.item_id or event.item_id
+ if not self.model.input_transcription_enabled:
+ self._end_user_turn(turn)
# With provider turn detection this is also its commit.
now = time.monotonic()
self._metrics.user_speech_end_at = now
@@ -693,8 +713,9 @@ class RealtimeAgent:
self._on_transcription(event)
case me.InputTranscriptionFailedEvent():
- self._end_user_turn()
- self._user_turn = ""
+ self._finish_transcription(
+ self._find_user_turn(event.item_id),
+ )
case me.ResponseCreatedEvent():
self._start_reply(event.item_id)
@@ -722,7 +743,10 @@ class RealtimeAgent:
case me.ToolCallEvent():
if self._start_reply(event.item_id) is not None:
self._pending_tools[event.tool_call.id] = event.tool_call
- self.state.append_context(self.name, [event.tool_call])
+ self._append_reply_block(
+ self._reply_id,
+ event.tool_call,
+ )
case me.ResponseDoneEvent():
async with self._barge_lock:
@@ -731,11 +755,9 @@ class RealtimeAgent:
return
self._metrics.input_tokens = event.input_tokens
self._metrics.output_tokens = event.output_tokens
- tail = (
- self.state.context[-1] if self.state.context else None
- )
- if tail is not None and tail.id == self._reply_id:
- tail.append_usage(
+ message = self._find_reply_message(self._reply_id)
+ if message is not None:
+ message.append_usage(
Usage(
input_tokens=event.input_tokens,
output_tokens=event.output_tokens,
@@ -746,7 +768,6 @@ class RealtimeAgent:
# response answers with their results.
reply_id = reply.reply_id
self._finish_response()
- self._continuing = True
self._schedule_tools(reply_id)
else:
self._finish_reply(ReplyFinishedReason.COMPLETED)
@@ -758,8 +779,7 @@ class RealtimeAgent:
event.message,
)
async with self._barge_lock:
- self._end_user_turn()
- self._user_turn = ""
+ self._reset_user_turns()
self._finish_reply(ReplyFinishedReason.ERROR)
case me.SessionEndedEvent():
@@ -772,47 +792,101 @@ class RealtimeAgent:
def _start_user_turn(self, item_id: str = "") -> None:
"""Open the user's turn as a reply of its own. A local VAD sees it
before the provider creates an item, hence the generated id."""
- if self._user_turn_open:
- return # providers repeat speech_started; one turn, one reply
- self._user_turn = item_id or uuid.uuid4().hex
- self._user_turn_open = True
+ if item_id and any(
+ turn.item_id == item_id
+ for turn in self._pending_user_turns.values()
+ ):
+ return # Providers can repeat speech_started for a pending item.
+ current = self._user_turn
+ if (
+ current is not None
+ and current.open
+ and not current.speech_ended
+ and (not item_id or not current.item_id)
+ ):
+ current.item_id = current.item_id or item_id
+ return
+ # Keep the start replayable until its transcript is settled.
+ if not self.model.input_transcription_enabled:
+ self._end_user_turn()
+ self._user_turn = self._new_user_turn(item_id)
+
+ def _new_user_turn(self, item_id: str) -> _UserTurn:
+ """Create a reply without changing another turn's identity."""
+ turn = _UserTurn(reply_id=item_id or uuid.uuid4().hex, item_id=item_id)
+ self._pending_user_turns[turn.reply_id] = turn
self._emit(
ReplyStartEvent(
session_id=self.state.session_id,
- reply_id=self._user_turn,
+ reply_id=turn.reply_id,
name="user",
role="user",
),
)
+ return turn
- def _end_user_turn(self) -> None:
- """Close the user reply once no transcript remains pending."""
- if not self._user_turn_open:
+ def _end_user_turn(self, turn: _UserTurn | None = None) -> None:
+ """Close a reply while retaining its pending transcription ID."""
+ turn = turn or self._user_turn
+ if turn is None or not turn.open:
return
- self._user_turn_open = False
+ turn.open = False
self._emit(
ReplyEndEvent(
session_id=self.state.session_id,
- reply_id=self._user_turn,
+ reply_id=turn.reply_id,
finished_reason=ReplyFinishedReason.COMPLETED,
),
)
+ if not self.model.input_transcription_enabled:
+ self._pending_user_turns.pop(turn.reply_id, None)
+
+ def _find_user_turn(self, item_id: str) -> _UserTurn | None:
+ """Match provider IDs first, then unbound local turns in order."""
+ turns = list(self._pending_user_turns.values())
+ if self._user_turn is not None and self._user_turn not in turns:
+ turns.append(self._user_turn)
+ if item_id:
+ for turn in turns:
+ if turn.item_id == item_id:
+ return turn
+ return next(
+ (turn for turn in turns if not item_id or not turn.item_id),
+ None,
+ )
+
+ def _finish_transcription(self, turn: _UserTurn | None) -> None:
+ """Retire only the turn whose transcript succeeded or failed."""
+ if turn is None:
+ return
+ self._end_user_turn(turn)
+ self._pending_user_turns.pop(turn.reply_id, None)
+ if self._user_turn is turn:
+ self._user_turn = None
+
+ def _reset_user_turns(self) -> None:
+ """Discard pending identities when their model session ends."""
+ for turn in list(self._pending_user_turns.values()):
+ self._end_user_turn(turn)
+ self._end_user_turn()
+ self._pending_user_turns.clear()
+ self._user_turn = None
def _on_transcription(self, event: me.InputTranscriptionEvent) -> None:
"""Record a settled user turn, merging a split one back together,
and report its text on the user's reply."""
turn = self.aggregator.take(event.text)
+ user_turn = self._find_user_turn(event.item_id)
if turn is None:
logger.debug("RealtimeAgent: dropping %r", event.text)
- self._end_user_turn()
- self._user_turn = ""
+ self._finish_transcription(user_turn)
return
# A transcript with no detected speech, e.g. after a reconnect,
# gets a turn of its own.
- if not self._user_turn:
- self._start_user_turn(event.item_id)
- reply_id, block_id = self._user_turn, uuid.uuid4().hex
+ if user_turn is None:
+ user_turn = self._new_user_turn(event.item_id)
+ reply_id, block_id = user_turn.reply_id, uuid.uuid4().hex
self._emit(TextBlockStartEvent(reply_id=reply_id, block_id=block_id))
self._emit(
TextBlockDeltaEvent(
@@ -829,8 +903,7 @@ class RealtimeAgent:
self.state.context.append(
UserMsg(name="user", content=turn, id=reply_id),
)
- self._end_user_turn()
- self._user_turn = ""
+ self._finish_transcription(user_turn)
def _merge_user(self, text: str) -> bool:
"""Append *text* to the previous user turn that endpointing split.
@@ -866,7 +939,7 @@ class RealtimeAgent:
if self._reply is not None:
self._finish_response()
- if not self._continuing:
+ if not self._reply_id:
# The agent takes the turn; the reply is named by its first
# response so that every event of the turn shares one id.
self._reply_id = item_id
@@ -882,7 +955,6 @@ class RealtimeAgent:
name=self.name,
),
)
- self._continuing = False
self._reply = _Reply(item_id=item_id, reply_id=self._reply_id)
self._emit(
ModelCallStartEvent(
@@ -937,13 +1009,43 @@ class RealtimeAgent:
reply_id=self._reply_id,
finished_reason=reason,
)
- for message in reversed(self.state.context):
- if message.id == self._reply_id:
- message.append_event(event)
- break
+ message = self._find_reply_message(self._reply_id)
+ if message is not None:
+ message.append_event(event)
self._emit(event)
self._reply_id = ""
- self._continuing = False
+
+ def _find_reply_message(self, reply_id: str) -> Msg | None:
+ """Find a logical reply even after user transcription was appended."""
+ return next(
+ (
+ message
+ for message in reversed(self.state.context)
+ if message.id == reply_id
+ and message.role == "assistant"
+ and message.name == self.name
+ ),
+ None,
+ )
+
+ def _append_reply_block(
+ self,
+ reply_id: str,
+ block: TextBlock | ToolCallBlock | ToolResultBlock,
+ ) -> None:
+ """Keep all blocks of a logical reply in one assistant message."""
+ message = self._find_reply_message(reply_id)
+ if message is None:
+ self.state.context.append(
+ Msg(
+ id=reply_id,
+ role="assistant",
+ name=self.name,
+ content=[block],
+ ),
+ )
+ else:
+ message.content.append(block)
def _emit_text(self, reply: _Reply, delta: str) -> None:
"""Emit a transcript delta, opening the block on first use."""
@@ -957,12 +1059,8 @@ class RealtimeAgent:
)
# Grow the tail text block rather than appending one per delta,
# or the context ends up as dozens of one-word blocks.
- tail = self.state.context[-1] if self.state.context else None
- blocks = (
- tail.content
- if tail is not None and tail.id == reply.reply_id
- else None
- )
+ message = self._find_reply_message(reply.reply_id)
+ blocks = message.content if message is not None else None
if (
isinstance(blocks, list)
and blocks
@@ -970,9 +1068,9 @@ class RealtimeAgent:
):
blocks[-1].text += delta
else:
- self.state.append_context(
- self.name,
- [TextBlock(id=reply.text_block_id, text=delta)],
+ self._append_reply_block(
+ reply.reply_id,
+ TextBlock(id=reply.text_block_id, text=delta),
)
self._emit(
TextBlockDeltaEvent(
@@ -1236,12 +1334,7 @@ class RealtimeAgent:
)
# The result belongs to the reply that made the call, which may no
# longer be the current one if the user interrupted a slow tool.
- for msg in reversed(self.state.context):
- if msg.id == reply_id:
- msg.content.append(block)
- break
- else:
- self.state.append_context(self.name, [block])
+ self._append_reply_block(reply_id, block)
self._emit(
ToolResultEndEvent(
reply_id=reply_id,
diff --git a/src/agentscope/realtime/_dashscope/_audio_model.py b/src/agentscope/realtime/_dashscope/_audio_model.py
index 68c0445c9..8a4bd4487 100644
--- a/src/agentscope/realtime/_dashscope/_audio_model.py
+++ b/src/agentscope/realtime/_dashscope/_audio_model.py
@@ -24,20 +24,52 @@ class DashScopeAudioRealtimeModel(DashScopeRealtimeModel):
class Parameters(RealtimeModelBase.Parameters):
"""Tuneables surfaced to the UI."""
- voice: str = Field(default="longanqian", title="Voice")
+ voice: str = Field(
+ default="longanqian",
+ title="Voice",
+ description="The voice used for spoken model responses.",
+ )
turn_detection: Literal["server_vad", "smart_turn", "none"] = Field(
default="server_vad",
title="Turn Detection",
- description="``none`` hands endpointing to the caller.",
+ description=(
+ "How the model detects when the user has finished speaking."
+ ),
+ )
+ vad_threshold: float = Field(
+ default=0.5,
+ ge=-1.0,
+ le=1.0,
+ description=(
+ "Speech detection sensitivity. Lower values detect quieter "
+ "speech."
+ ),
+ )
+ vad_silence_duration_ms: int = Field(
+ default=800,
+ ge=200,
+ le=6000,
+ description=(
+ "Silence required before the model considers the user's "
+ "turn complete."
+ ),
)
- vad_threshold: float = Field(default=0.5, ge=-1.0, le=1.0)
- vad_silence_duration_ms: int = Field(default=800, ge=200, le=6000)
voiceprint_audio_urls: list[str] = Field(
default_factory=list,
title="Voiceprint Audio URLs",
- description="Speaker references, used by ``smart_turn`` only.",
+ description=(
+ "Reference audio URLs used by smart_turn to identify the "
+ "intended speaker."
+ ),
+ )
+ max_history_turns: int = Field(
+ default=20,
+ ge=1,
+ le=50,
+ description=(
+ "Maximum number of conversation turns retained by the model."
+ ),
)
- max_history_turns: int = Field(default=20, ge=1, le=50)
type = "dashscope_audio_realtime"
supports_text_input = True
diff --git a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-flash.yaml b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-flash.yaml
index cabece70f..a0ae71229 100644
--- a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-flash.yaml
+++ b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-flash.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen-audio-3.0-realtime-flash
label: Qwen-Audio-3.0-Realtime-Flash
status: active
+release_date: 2026-07-14
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-plus.yaml b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-plus.yaml
index ef6df29fb..2de7d81ea 100644
--- a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-plus.yaml
+++ b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.0-realtime-plus.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen-audio-3.0-realtime-plus
label: Qwen-Audio-3.0-Realtime-Plus
status: active
+release_date: 2026-07-14
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml
index 87b2d357d..f697a80e6 100644
--- a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml
+++ b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen-audio-3.1-realtime-plus
label: Qwen-Audio-3.1-Realtime-Plus
status: active
+release_date: 2026-09-20
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_model.py b/src/agentscope/realtime/_dashscope/_model.py
index 54f757cb3..df4a4c5ea 100644
--- a/src/agentscope/realtime/_dashscope/_model.py
+++ b/src/agentscope/realtime/_dashscope/_model.py
@@ -40,18 +40,39 @@ class DashScopeRealtimeModel(RealtimeModelBase):
class Parameters(RealtimeModelBase.Parameters):
"""Tuneables surfaced to the UI."""
- voice: str = Field(default="Cherry", title="Voice")
+ voice: str = Field(
+ default="Cherry",
+ title="Voice",
+ description="The voice used for spoken model responses.",
+ )
turn_detection: Literal["server_vad", "semantic_vad", "none"] = Field(
default="server_vad",
title="Turn Detection",
- description="``none`` hands endpointing to the caller.",
+ description=(
+ "How the model detects when the user has finished speaking."
+ ),
+ )
+ vad_threshold: float = Field(
+ default=0.5,
+ ge=0.0,
+ le=1.0,
+ description=(
+ "Speech detection sensitivity. Lower values detect quieter "
+ "speech."
+ ),
+ )
+ vad_silence_duration_ms: int = Field(
+ default=800,
+ ge=0,
+ description=(
+ "Silence required before the model considers the user's "
+ "turn complete."
+ ),
)
- vad_threshold: float = Field(default=0.5, ge=0.0, le=1.0)
- vad_silence_duration_ms: int = Field(default=800, ge=0)
input_audio_transcription: bool = Field(
default=True,
title="Transcribe Input",
- description="Whether to transcribe the user's speech.",
+ description=("Whether to show a transcript of the user's speech."),
)
type = "dashscope_omni_realtime"
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
index 5721e873d..ef9251ecc 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen-omni-turbo-realtime
label: Qwen-Omni-Turbo Realtime
status: active
+release_date: 2025-05-08
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
index 722ed0773..373e0f936 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen3-omni-flash-realtime
label: Qwen3-Omni-Flash Realtime
status: active
+release_date: 2025-12-04
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
index c5f9a8509..b51e73b39 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen3.5-omni-flash-realtime
label: Qwen3.5-Omni-Flash Realtime
status: active
+release_date: 2026-03-30
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
index 81b070b3c..dfeb750cf 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
@@ -2,6 +2,7 @@ type: realtime_model
name: qwen3.5-omni-plus-realtime
label: Qwen3.5-Omni-Plus Realtime
status: active
+release_date: 2026-03-30
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3.8-omni-flash-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3.8-omni-flash-realtime.yaml
index ef2b2a63b..432778780 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3.8-omni-flash-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3.8-omni-flash-realtime.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: qwen3.8-omni-flash-realtime
label: Qwen3.8-Omni-Flash Realtime
status: active
+# Release date: https://help.aliyun.com/zh/model-studio/newly-released-models
+release_date: 2026-09-21
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml b/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml
index 1c4e36b00..2646f7c3f 100644
--- a/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml
+++ b/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gemini-2.5-flash-native-audio-preview-12-2025
label: Gemini 2.5 Flash Native Audio
status: active
+# Release date: https://ai.google.dev/gemini-api/docs/changelog
+release_date: 2025-12-12
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml b/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml
index 7041df507..e5a51b3f7 100644
--- a/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml
+++ b/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gemini-3.1-flash-live-preview
label: Gemini 3.1 Flash Live
status: active
+# Release date: https://ai.google.dev/gemini-api/docs/changelog
+release_date: 2026-03-26
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_gemini/_models/gemini-3.8-live.yaml b/src/agentscope/realtime/_gemini/_models/gemini-3.8-live.yaml
index 892f9927a..c6f1a914d 100644
--- a/src/agentscope/realtime/_gemini/_models/gemini-3.8-live.yaml
+++ b/src/agentscope/realtime/_gemini/_models/gemini-3.8-live.yaml
@@ -3,6 +3,8 @@ type: realtime_model
name: gemini-3.8-live
label: Gemini 3.8 Live
status: active
+# Release date: https://ai.google.dev/gemini-api/docs/changelog
+release_date: 2026-09-15
# Image input is not implemented by the current realtime adapter.
input_types:
diff --git a/src/agentscope/realtime/_model_card.py b/src/agentscope/realtime/_model_card.py
index 575356658..d7189c4e6 100644
--- a/src/agentscope/realtime/_model_card.py
+++ b/src/agentscope/realtime/_model_card.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""The realtime model card."""
import copy
-from datetime import datetime
+from datetime import date, datetime
from pathlib import Path
from typing import Literal, Self, Type
@@ -35,6 +35,10 @@ class RealtimeModelCard(BaseModel):
default=None,
description="When the model was deprecated, if applicable.",
)
+ release_date: date | None = Field(
+ default=None,
+ description="The model release date, if known.",
+ )
input_types: list[str] = Field(
default_factory=lambda: ["audio/pcm"],
diff --git a/src/agentscope/realtime/_openai/_models/gpt-realtime-1.5.yaml b/src/agentscope/realtime/_openai/_models/gpt-realtime-1.5.yaml
index f1db38ce1..9567709f7 100644
--- a/src/agentscope/realtime/_openai/_models/gpt-realtime-1.5.yaml
+++ b/src/agentscope/realtime/_openai/_models/gpt-realtime-1.5.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gpt-realtime-1.5
label: GPT Realtime 1.5
status: active
+# Release date: https://developers.openai.com/api/docs/changelog
+release_date: 2026-02-23
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1-mini.yaml b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1-mini.yaml
index fc495be47..81a1603d0 100644
--- a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1-mini.yaml
+++ b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1-mini.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gpt-realtime-2.1-mini
label: GPT Realtime 2.1 Mini
status: active
+# Release date: https://developers.openai.com/api/docs/changelog
+release_date: 2026-07-06
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1.yaml b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1.yaml
index 06e529a54..ae3ce18ae 100644
--- a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1.yaml
+++ b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.1.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gpt-realtime-2.1
label: GPT Realtime 2.1
status: active
+# Release date: https://developers.openai.com/api/docs/changelog
+release_date: 2026-07-06
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.yaml b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.yaml
index cf2ab3aad..d17870883 100644
--- a/src/agentscope/realtime/_openai/_models/gpt-realtime-2.yaml
+++ b/src/agentscope/realtime/_openai/_models/gpt-realtime-2.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: gpt-realtime-2
label: GPT Realtime 2
status: active
+# Release date: https://developers.openai.com/api/docs/changelog
+release_date: 2026-05-07
input_types:
- audio/pcm
diff --git a/src/agentscope/realtime/_xai/_models/grok-voice-think-fast-2.0.yaml b/src/agentscope/realtime/_xai/_models/grok-voice-think-fast-2.0.yaml
index 2be32523a..89ed503a6 100644
--- a/src/agentscope/realtime/_xai/_models/grok-voice-think-fast-2.0.yaml
+++ b/src/agentscope/realtime/_xai/_models/grok-voice-think-fast-2.0.yaml
@@ -2,6 +2,8 @@ type: realtime_model
name: grok-voice-think-fast-2.0
label: Grok Voice Think Fast 2.0
status: active
+# Release date: https://x.ai/news/grok-voice-think-fast-2
+release_date: 2026-07-29
input_types:
- audio/pcm
diff --git a/tests/realtime_agent_test.py b/tests/realtime_agent_test.py
index 209d6d1e5..241c7d97c 100644
--- a/tests/realtime_agent_test.py
+++ b/tests/realtime_agent_test.py
@@ -3,8 +3,11 @@
transport — no network, no sound card."""
# pylint: disable=protected-access, unused-argument
import asyncio
+from itertools import count
+from types import SimpleNamespace
from typing import Any, AsyncIterator, Sequence
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
from utils import AnyString, MockModel
from agentscope.agent import (
@@ -21,7 +24,7 @@ from agentscope.event import (
TextBlockDeltaEvent,
TextBlockEndEvent,
)
-from agentscope.message import AssistantMsg, Msg, UserMsg
+from agentscope.message import AssistantMsg, Msg, Usage, UserMsg
from agentscope.model import ChatResponse
from agentscope.realtime import (
AudioFrame,
@@ -540,6 +543,7 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
"monk.",
("user_start", "u2"),
("reply_end", "interrupted"),
+ ("reply_end", "completed"),
],
)
self.assertEqual(
@@ -801,6 +805,12 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
async def test_provider_timeout_reconnects_on_next_audio(self) -> None:
"""When the provider closes the session, nothing reconnects until
the next user audio, which reconnects with the current context."""
+ self.enterContext(
+ patch(
+ "agentscope.agent._realtime._aggregator.time",
+ SimpleNamespace(monotonic=count(step=1.0).__next__),
+ ),
+ )
model = ScriptedModel(
[
REPLY_R1 + [me.SessionEndedEvent(reason="idle")],
@@ -811,7 +821,6 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
"Friday",
"be brief",
model,
- aggregator=TurnAggregator(merge_window_ms=0),
)
async with agent:
@@ -1082,7 +1091,9 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
"connection_generation": agent._connection_generation,
"sessions": model.sessions,
"reply_open": agent._reply is not None,
- "user_turn_open": agent._user_turn_open,
+ "user_turn_open": (
+ agent._user_turn is not None and agent._user_turn.open
+ ),
"iterator_started": [
event.is_set() for event in model.iterator_started
],
@@ -1289,6 +1300,328 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
class RealtimeAgentTranscriptionTest(IsolatedAsyncioTestCase):
"""Verify user reply boundaries around delayed transcription."""
+ @staticmethod
+ def _drain(agent: RealtimeAgent) -> list[tuple]:
+ """Read all queued user lifecycle and text events."""
+ events: list[tuple] = []
+ while not agent._out.empty():
+ event = agent._out.get_nowait().event
+ if isinstance(event, ReplyStartEvent):
+ events.append(("start", event.reply_id))
+ elif isinstance(event, ReplyEndEvent):
+ events.append(("end", event.reply_id))
+ elif isinstance(event, TextBlockDeltaEvent):
+ events.append(("text", event.reply_id, event.delta))
+ return events
+
+ def _make_agent(self) -> RealtimeAgent:
+ """Build an agent with independent, provider-transcribed user turns."""
+ # Space transcripts beyond the merge window without changing asyncio.
+ self.enterContext(
+ patch(
+ "agentscope.agent._realtime._aggregator.time",
+ SimpleNamespace(monotonic=count(step=1.0).__next__),
+ ),
+ )
+ return RealtimeAgent(
+ "Friday",
+ "be brief",
+ ScriptedModel([[]], input_audio_transcription=True),
+ )
+
+ async def test_text_and_usage_after_transcript_update_existing_reply(
+ self,
+ ) -> None:
+ """Even deltas within one response can follow user transcription."""
+ agent = self._make_agent()
+ for event in [
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.TranscriptDeltaEvent(item_id="r1", delta="Hello"),
+ me.InputTranscriptionEvent(item_id="u1", text="Hi"),
+ me.TranscriptDeltaEvent(item_id="r1", delta=" there"),
+ me.ResponseDoneEvent(
+ item_id="r1",
+ input_tokens=7,
+ output_tokens=3,
+ ),
+ ]:
+ await agent._on_model_event(event)
+ self.assertEqual(
+ [(msg.id, msg.get_text_content()) for msg in agent.state.context],
+ [("r1", "Hello there"), ("u1", "Hi")],
+ )
+ self.assertEqual(
+ agent.state.context[0].usage,
+ Usage(input_tokens=7, output_tokens=3),
+ )
+
+ async def test_old_transcript_after_resume_does_not_end_new_turn(
+ self,
+ ) -> None:
+ """Exercise success, failure and dropped text after a disconnect."""
+ for old_event, old_text in [
+ (me.InputTranscriptionEvent(item_id="u1", text="first"), "first"),
+ (me.InputTranscriptionFailedEvent(item_id="u1"), None),
+ (me.InputTranscriptionEvent(item_id="u1", text=""), None),
+ ]:
+ with self.subTest(event=old_event):
+ agent = self._make_agent()
+ await agent._on_model_event(
+ me.SpeechStartedEvent(item_id="u1"),
+ )
+ await agent._on_model_event(
+ me.SpeechEndedEvent(item_id="u1"),
+ )
+ _ = [
+ event
+ async for event in agent.reply_stream(FakeTransport(0))
+ ]
+ await agent._on_model_event(
+ me.SpeechStartedEvent(item_id="u2"),
+ )
+ self._drain(agent)
+ await agent._on_model_event(old_event)
+ old_events = self._drain(agent)
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id="u2", text="second"),
+ )
+ self.assertEqual(
+ {
+ "old_events": old_events,
+ "new_events": self._drain(agent),
+ "context": [
+ (msg.id, msg.get_text_content())
+ for msg in agent.state.context
+ ],
+ },
+ {
+ "old_events": (
+ [("text", "u1", "first")] if old_text else []
+ ),
+ "new_events": [
+ ("text", "u2", "second"),
+ ("end", "u2"),
+ ],
+ "context": ([("u1", "first")] if old_text else [])
+ + [("u2", "second")],
+ },
+ )
+
+ async def test_transcripts_can_arrive_in_reverse_order(self) -> None:
+ """Provider IDs disambiguate two pending turns without reconnect."""
+ agent = self._make_agent()
+ for item_id in ["u1", "u2"]:
+ await agent._on_model_event(
+ me.SpeechStartedEvent(item_id=item_id),
+ )
+ await agent._on_model_event(
+ me.SpeechEndedEvent(item_id=item_id),
+ )
+ self._drain(agent)
+ for item_id in ["u2", "u1"]:
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id=item_id, text=item_id),
+ )
+ self.assertEqual(
+ self._drain(agent),
+ [
+ ("text", "u2", "u2"),
+ ("end", "u2"),
+ ("text", "u1", "u1"),
+ ("end", "u1"),
+ ],
+ )
+ self.assertEqual(
+ [(msg.id, msg.get_text_content()) for msg in agent.state.context],
+ [("u2", "u2"), ("u1", "u1")],
+ )
+
+ async def test_overlapping_turns_close_on_transport_end_or_reset(
+ self,
+ ) -> None:
+ """Close all pending replies while keeping only reusable IDs."""
+ for reset in [False, True]:
+ with self.subTest(reset=reset):
+ agent = self._make_agent()
+ for item_id in ["u1", "u2"]:
+ await agent._on_model_event(
+ me.SpeechStartedEvent(item_id=item_id),
+ )
+ await agent._on_model_event(
+ me.SpeechEndedEvent(item_id=item_id),
+ )
+ self.assertEqual(
+ self._drain(agent),
+ [("start", "u1"), ("start", "u2")],
+ )
+ if reset:
+ agent._reset_user_turns()
+ ended = self._drain(agent)
+ else:
+ ended = [
+ ("end", event.reply_id)
+ async for event in agent.reply_stream(
+ FakeTransport(0),
+ )
+ if isinstance(event, ReplyEndEvent)
+ ]
+ self.assertEqual(
+ {
+ "ended": ended,
+ "pending": list(agent._pending_user_turns),
+ "open": [
+ turn.reply_id
+ for turn in agent._pending_user_turns.values()
+ if turn.open
+ ],
+ },
+ {
+ "ended": [("end", "u1"), ("end", "u2")],
+ "pending": [] if reset else ["u1", "u2"],
+ "open": [],
+ },
+ )
+
+ async def test_local_vad_turns_keep_their_generated_reply_ids(
+ self,
+ ) -> None:
+ """Unbound local turns match settled transcripts in commit order."""
+ agent = self._make_agent()
+ agent._connected = True
+ ids = []
+ for _ in range(2):
+ await agent._forward_audio(b"", SpeechTransition.STARTED)
+ ids.append(
+ next(
+ event[1]
+ for event in self._drain(agent)
+ if event[0] == "start"
+ ),
+ )
+ await agent._forward_audio(b"", SpeechTransition.ENDED)
+ self._drain(agent)
+ for item_id, text in [("u1", "first"), ("u2", "second")]:
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id=item_id, text=text),
+ )
+ self.assertEqual(
+ [(msg.id, msg.get_text_content()) for msg in agent.state.context],
+ [(ids[0], "first"), (ids[1], "second")],
+ )
+
+ async def test_provider_id_binds_to_local_turn(self) -> None:
+ """Provider speech events preserve the reply opened by local VAD."""
+ agent = self._make_agent()
+ agent._connected = True
+ await agent._forward_audio(b"", SpeechTransition.STARTED)
+ reply_id = self._drain(agent)[0][1]
+ for event in [
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechEndedEvent(item_id="u1"),
+ me.InputTranscriptionEvent(item_id="u1", text="hello"),
+ ]:
+ await agent._on_model_event(event)
+ self.assertEqual(
+ self._drain(agent),
+ [("text", reply_id, "hello"), ("end", reply_id)],
+ )
+
+ async def test_unmatched_transcript_does_not_end_active_turn(self) -> None:
+ """A transcript without a speech event gets an independent reply."""
+ agent = self._make_agent()
+ await agent._on_model_event(me.SpeechStartedEvent(item_id="u2"))
+ self._drain(agent)
+ for item_id in ["u1", "u2"]:
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id=item_id, text=item_id),
+ )
+ self.assertEqual(
+ self._drain(agent),
+ [
+ ("start", "u1"),
+ ("text", "u1", "u1"),
+ ("end", "u1"),
+ ("text", "u2", "u2"),
+ ("end", "u2"),
+ ],
+ )
+
+ async def test_model_error_clears_pending_local_turns(self) -> None:
+ """A model error retires the old unbound transcript identities."""
+ agent = self._make_agent()
+ async with agent:
+ await agent._forward_audio(b"", SpeechTransition.STARTED)
+ old_id = self._drain(agent)[0][1]
+ await agent._on_model_event(
+ me.ModelErrorEvent(code="failed", message="failed"),
+ )
+ self.assertEqual(self._drain(agent), [("end", old_id)])
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id="u2", text="new"),
+ )
+ self.assertEqual(
+ [(msg.id, msg.get_text_content()) for msg in agent.state.context],
+ [("u2", "new")],
+ )
+
+ async def test_transcription_after_transport_end_keeps_turn(self) -> None:
+ """A late transcript stays in the user reply already closed."""
+ model = ScriptedModel(
+ [
+ [
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechEndedEvent(item_id="u1"),
+ ],
+ ],
+ input_audio_transcription=True,
+ )
+ agent = RealtimeAgent("Friday", "be brief", model)
+
+ async def _collect() -> list[tuple[Any, ...]]:
+ transport = FakeTransport(frames=1)
+ async with transport:
+ return [
+ (
+ event.type,
+ getattr(event, "role", None),
+ getattr(event, "delta", None),
+ getattr(event, "finished_reason", None),
+ )
+ async for event in agent.reply_stream(transport)
+ if getattr(event, "reply_id", None) == "u1"
+ ]
+
+ async with agent:
+ first_events = await _collect()
+ await agent._on_model_event(
+ me.InputTranscriptionEvent(item_id="u1", text="hello"),
+ )
+ next_events = await _collect()
+
+ self.assertEqual(
+ {
+ "first_events": first_events,
+ "next_events": next_events,
+ "context": [
+ (message.role, message.id, message.get_text_content())
+ for message in agent.state.context
+ ],
+ },
+ {
+ "first_events": [
+ ("REPLY_START", "user", None, None),
+ ("REPLY_END", None, None, "completed"),
+ ],
+ "next_events": [
+ ("TEXT_BLOCK_START", None, None, None),
+ ("TEXT_BLOCK_DELTA", None, "hello", None),
+ ("TEXT_BLOCK_END", None, None, None),
+ ],
+ "context": [("user", "u1", "hello")],
+ },
+ )
+
async def test_user_reply_ends_after_transcription_result(self) -> None:
"""Success and failure both close their delayed user replies."""
model = ScriptedModel(
@@ -1743,8 +2076,9 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
pcm=b"\x01\x00",
sample_rate=24000,
),
+ me.ResponseCreatedEvent(item_id="r2"),
me.ToolCallEvent(
- item_id="r1",
+ item_id="r2",
tool_call=ToolCallBlock(
id="c1",
name="stream_tool",
@@ -1752,23 +2086,23 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
),
),
me.ResponseDoneEvent(
- item_id="r1",
+ item_id="r2",
input_tokens=5,
output_tokens=2,
),
"WAIT",
- me.ResponseCreatedEvent(item_id="r2"),
+ me.ResponseCreatedEvent(item_id="r3"),
me.TranscriptDeltaEvent(
- item_id="r2",
+ item_id="r3",
delta="It is sunny.",
),
me.AudioDeltaEvent(
- item_id="r2",
+ item_id="r3",
pcm=b"\x01\x00",
sample_rate=24000,
),
me.ResponseDoneEvent(
- item_id="r2",
+ item_id="r3",
input_tokens=9,
output_tokens=3,
),
@@ -1828,6 +2162,8 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
("TEXT_BLOCK_END", "r1", None, None, None, None),
("DATA_BLOCK_END", "r1", None, None, None, None),
("MODEL_CALL_END", "r1", None, None, None, "completed"),
+ ("MODEL_CALL_START", "r1", None, None, None, None),
+ ("MODEL_CALL_END", "r1", None, None, None, "completed"),
("TOOL_CALL_START", "r1", None, None, "c1", None),
(
"TOOL_CALL_DELTA",
diff --git a/tests/realtime_dashscope_test.py b/tests/realtime_dashscope_test.py
index a56cf1a1b..e6e7f8719 100644
--- a/tests/realtime_dashscope_test.py
+++ b/tests/realtime_dashscope_test.py
@@ -77,6 +77,7 @@ class DashScopeCardsTest(unittest.TestCase):
c.model_type,
c.supports_tools,
c.max_audio_turns,
+ c.release_date.isoformat() if c.release_date else None,
)
for c in DashScopeRealtimeModel.list_models()
],
@@ -86,30 +87,35 @@ class DashScopeCardsTest(unittest.TestCase):
"dashscope_omni_realtime",
False,
None,
+ "2025-05-08",
),
(
"qwen3-omni-flash-realtime",
"dashscope_omni_realtime",
False,
8,
+ "2025-12-04",
),
(
"qwen3.5-omni-flash-realtime",
"dashscope_omni_realtime",
True,
80,
+ "2026-03-30",
),
(
"qwen3.5-omni-plus-realtime",
"dashscope_omni_realtime",
True,
100,
+ "2026-03-30",
),
(
"qwen3.8-omni-flash-realtime",
"dashscope_omni_realtime",
True,
100,
+ "2026-09-21",
),
],
)
@@ -160,6 +166,7 @@ class DashScopeCardsTest(unittest.TestCase):
c.model_type,
c.max_audio_turns,
c.max_audio_duration_s,
+ c.release_date.isoformat() if c.release_date else None,
)
for c in DashScopeAudioRealtimeModel.list_models()
],
@@ -169,18 +176,21 @@ class DashScopeCardsTest(unittest.TestCase):
"dashscope_audio_realtime",
50,
300,
+ "2026-07-14",
),
(
"qwen-audio-3.0-realtime-plus",
"dashscope_audio_realtime",
50,
300,
+ "2026-07-14",
),
(
"qwen-audio-3.1-realtime-plus",
"dashscope_audio_realtime",
50,
300,
+ "2026-09-20",
),
],
)
@@ -207,6 +217,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen-omni-turbo-realtime": {
"schema": {
"default": "Chelsie",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": ["Cherry", "Serena", "Ethan", "Chelsie"],
"title": "Voice",
"type": "string",
@@ -216,6 +229,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen3-omni-flash-realtime": {
"schema": {
"default": "Cherry",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": ["Cherry", "Serena", "Ethan", "Chelsie"],
"title": "Voice",
"type": "string",
@@ -225,6 +241,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen3.5-omni-flash-realtime": {
"schema": {
"default": "Tina",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": ["Tina", "Serena", "Ethan"],
"title": "Voice",
"type": "string",
@@ -234,6 +253,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen3.5-omni-plus-realtime": {
"schema": {
"default": "Tina",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": ["Tina", "Serena", "Ethan"],
"title": "Voice",
"type": "string",
@@ -243,6 +265,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen3.8-omni-flash-realtime": {
"schema": {
"default": "Tina",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": [
"Tina",
"Serena",
@@ -288,6 +313,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen-audio-3.0-realtime-flash": {
"schema": {
"default": "longanqian",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": [
"longanqian",
"longanlingxin",
@@ -303,6 +331,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen-audio-3.0-realtime-plus": {
"schema": {
"default": "longanqian",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": [
"longanqian",
"longanlingxin",
@@ -318,6 +349,9 @@ class DashScopeCardsTest(unittest.TestCase):
"qwen-audio-3.1-realtime-plus": {
"schema": {
"default": "longanqian_v3.1",
+ "description": (
+ "The voice used for spoken model responses."
+ ),
"enum": [
"longanqian",
"longanlingxin",
diff --git a/tests/webrtc_audio_transport_test.py b/tests/webrtc_audio_transport_test.py
index 4d1dd8eb7..46bd99726 100644
--- a/tests/webrtc_audio_transport_test.py
+++ b/tests/webrtc_audio_transport_test.py
@@ -8,6 +8,7 @@ import unittest
from collections.abc import Callable
from contextlib import asynccontextmanager
from fractions import Fraction
+from itertools import count
from types import SimpleNamespace
from typing import Any, AsyncIterator, cast
from unittest.mock import AsyncMock, MagicMock, patch
@@ -18,6 +19,7 @@ from aiortc.mediastreams import MediaStreamError
from av import AudioFrame as AVAudioFrame
from fastapi import HTTPException
+from agentscope.agent import RealtimeAgent
from agentscope.app._router._realtime import _create_realtime_offer
from agentscope.app._router._schema import (
RealtimeOfferRequest,
@@ -42,8 +44,14 @@ from agentscope.event import (
TextBlockStartEvent,
ToolResultEndEvent,
)
-from agentscope.message import ToolCallBlock, ToolResultState
-from agentscope.realtime import AudioFrame, DashScopeAudioRealtimeModel
+from agentscope.message import ToolCallBlock, ToolResultState, UserMsg
+from agentscope.realtime import (
+ AudioFrame,
+ DashScopeAudioRealtimeModel,
+ RealtimeModelBase,
+)
+from agentscope.realtime import _events as me
+from agentscope.tool import FunctionTool, Toolkit
class _FakeDataChannel:
@@ -958,6 +966,91 @@ class RealtimeOfferTest(unittest.IsolatedAsyncioTestCase):
class WebRTCSessionTest(unittest.IsolatedAsyncioTestCase):
"""Verify that a WebRTC run keeps the normal session contract."""
+ async def test_transcript_between_responses_preserves_full_reply(
+ self,
+ ) -> None:
+ """Persist opening text, tools and the final answer under one ID."""
+
+ def stream_tool(q: str) -> str:
+ """Return a deterministic tool result for persistence."""
+ return f"{q}-final"
+
+ model = MagicMock(
+ spec=RealtimeModelBase,
+ model="scripted",
+ output_sample_rate=24000,
+ input_transcription_enabled=True,
+ )
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ toolkit=Toolkit(
+ tools=[FunctionTool(stream_tool, is_read_only=True)],
+ ),
+ )
+ storage = _FakeStorage()
+ session = _make_session(
+ agent_factory=AsyncMock(),
+ storage=storage,
+ message_bus=_FakeMessageBus(),
+ on_closed=lambda _: None,
+ )
+ session.agent = agent
+ for event in [
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechEndedEvent(item_id="u1"),
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.TranscriptDeltaEvent(item_id="r1", delta="Let me check."),
+ me.InputTranscriptionEvent(item_id="u1", text="Weather?"),
+ me.ResponseCreatedEvent(item_id="r2"),
+ me.ToolCallEvent(
+ item_id="r2",
+ tool_call=ToolCallBlock(
+ id="c1",
+ name="stream_tool",
+ input='{"q": "x"}',
+ ),
+ ),
+ me.ResponseDoneEvent(item_id="r2"),
+ ]:
+ await agent._on_model_event(event)
+ await asyncio.gather(*agent._tasks)
+ for event in [
+ me.ResponseCreatedEvent(item_id="r3"),
+ me.TranscriptDeltaEvent(item_id="r3", delta="It is sunny."),
+ me.ResponseDoneEvent(item_id="r3"),
+ ]:
+ await agent._on_model_event(event)
+
+ while not agent._out.empty():
+ queued = agent._out.get_nowait()
+ if queued.checkpoint is not None:
+ await session._persist_state(queued.checkpoint)
+ await session._persist_state()
+ self.assertEqual(
+ {
+ "context_ids": [msg.id for msg in agent.state.context],
+ "saved": {
+ key: value.model_dump(mode="json")
+ for key, value in storage.messages.items()
+ },
+ "blocks": [
+ block.type for block in agent.state.context[0].content
+ ],
+ "text": agent.state.context[0].get_text_content(),
+ },
+ {
+ "context_ids": ["r1", "u1"],
+ "saved": {
+ msg.id: msg.model_dump(mode="json")
+ for msg in agent.state.context
+ },
+ "blocks": ["text", "tool_call", "tool_result", "text"],
+ "text": "Let me check.\nIt is sunny.",
+ },
+ )
+
async def test_request_close_owns_and_deduplicates_the_task(self) -> None:
"""Synchronous callbacks share one retained asynchronous close."""
transport = _FakeTransport()
@@ -1199,6 +1292,155 @@ class WebRTCSessionTest(unittest.IsolatedAsyncioTestCase):
["6-0"],
)
+ async def test_overlapping_transcripts_remain_replayable(self) -> None:
+ """A new page can replay an older turn after a newer one settles."""
+ for old_event, old_text in [
+ (me.InputTranscriptionEvent(item_id="u1", text="first"), "first"),
+ (me.InputTranscriptionFailedEvent(item_id="u1"), None),
+ (me.InputTranscriptionEvent(item_id="u1", text=""), None),
+ ]:
+ with self.subTest(event=old_event):
+ await self._check_transcript_replay(old_event, old_text)
+
+ async def _check_transcript_replay(
+ self,
+ old_event: me.ModelEvent,
+ old_text: str | None,
+ ) -> None:
+ """Check replay and persistence for one delayed transcript result."""
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ MagicMock(
+ spec=RealtimeModelBase,
+ output_sample_rate=24000,
+ input_transcription_enabled=True,
+ ),
+ )
+ storage = _FakeStorage()
+ message_bus = _FakeMessageBus(sequence_entries=True)
+ closed = asyncio.Event()
+ emitted = {}
+ reload_messages = {}
+ reload_cursor = 0
+ boundaries = []
+
+ async def stream(transport: object) -> AsyncIterator[Any]:
+ """Drive real agent events through the session runner."""
+ nonlocal reload_cursor
+ del transport
+ events = [
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechEndedEvent(item_id="u1"),
+ me.SpeechStartedEvent(item_id="u2"),
+ me.SpeechEndedEvent(item_id="u2"),
+ me.InputTranscriptionEvent(
+ item_id="u2",
+ text="second",
+ ),
+ old_event,
+ ]
+ for index, model_event in enumerate(events):
+ if index in (3, 5):
+ cursors = [
+ call["value"]
+ for call in message_bus.calls
+ if call["method"] == "registry_set"
+ ]
+ boundaries.append(
+ {
+ "cursors": cursors,
+ "messages": list(storage.messages),
+ },
+ )
+ reload_cursor = (
+ int(cursors[-1].split("-")[0]) if cursors else 0
+ )
+ reload_messages.update(storage.messages)
+ await agent._on_model_event(model_event)
+ while not agent._out.empty():
+ queued = agent._out.get_nowait()
+ event = queued.event
+ emitted[event.id] = event
+ agent._yielded_checkpoint = (
+ (event.id, queued.checkpoint)
+ if queued.checkpoint is not None
+ else None
+ )
+ try:
+ yield event
+ finally:
+ agent._yielded_checkpoint = None
+
+ session = _make_session(
+ agent_factory=AsyncMock(return_value=agent),
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=lambda _: closed.set(),
+ )
+ with (
+ patch(
+ "agentscope.agent._realtime._aggregator.time",
+ SimpleNamespace(monotonic=count(step=1.0).__next__),
+ ),
+ patch.object(agent, "connect", new=AsyncMock()),
+ patch.object(agent, "reply_stream", new=stream),
+ ):
+ session.start()
+ await asyncio.wait_for(closed.wait(), timeout=1)
+
+ # Replay at page load, then apply live events by reply ID.
+ for call in message_bus.calls:
+ if call["method"] != "publish":
+ continue
+ payload = call["event"]
+ if int(payload["_entry_id"].split("-")[0]) <= (reload_cursor):
+ continue
+ event = emitted[payload["id"]]
+ if isinstance(event, ReplyStartEvent):
+ reload_messages.setdefault(
+ event.reply_id,
+ UserMsg(
+ id=event.reply_id,
+ name="user",
+ content=[],
+ ),
+ )
+ elif event.reply_id in reload_messages:
+ reload_messages[event.reply_id].append_event(event)
+
+ final_cursor = "10-0" if old_text else "7-0"
+ self.assertEqual(
+ {
+ "boundaries": boundaries,
+ "replayed": {
+ key: msg.get_text_content()
+ for key, msg in reload_messages.items()
+ },
+ "saved": {
+ key: msg.get_text_content()
+ for key, msg in storage.messages.items()
+ },
+ "cursors": [
+ call["value"]
+ for call in message_bus.calls
+ if call["method"] == "registry_set"
+ ],
+ "pending": list(agent._pending_user_turns),
+ },
+ {
+ "boundaries": [
+ {"cursors": [], "messages": []},
+ {"cursors": [], "messages": []},
+ ],
+ "replayed": {"u1": old_text, "u2": "second"},
+ "saved": {"u2": "second"}
+ | ({"u1": old_text} if old_text else {}),
+ "cursors": [final_cursor],
+ "pending": [],
+ },
+ )
+
async def test_checkpoint_deletes_message_removed_from_context(
self,
) -> None: