Skip to content

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

feat(agent): support agent interruption with graceful context and tool state handling (#1995)

DiegoCluv790019025753d
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.json
index b7ae216c3..a865f74c1 100644
--- a/examples/web_ui/frontend/package.json
+++ b/examples/web_ui/frontend/package.json
@@ -11,7 +11,7 @@
"preview": "vite preview"
},
"dependencies": {
- "@agentscope-ai/agentscope": "^0.0.12",
+ "@agentscope-ai/agentscope": "^0.0.13",
"@fontsource-variable/geist": "^5.2.8",
"@tailwindcss/vite": "^4.3.0",
"class-variance-authority": "^0.7.1",
diff --git a/examples/web_ui/frontend/src/api/session.ts b/examples/web_ui/frontend/src/api/session.ts
index 2d679aacb..15dc5feec 100644
--- a/examples/web_ui/frontend/src/api/session.ts
+++ b/examples/web_ui/frontend/src/api/session.ts
@@ -3,6 +3,7 @@ import type {
AgentEvent,
CreateSessionRequest,
CreateSessionResponse,
+ InterruptSessionResponse,
SessionListResponse,
SessionRecord,
UpdateSessionRequest,
@@ -25,6 +26,21 @@ export const sessionApi = {
delete: (sessionId: string, agentId: string) =>
client.delete(`/sessions/${sessionId}`, { agent_id: agentId }),
+ /**
+ * Request interruption of an in-progress reply (running or parked).
+ *
+ * Backend contract:
+ * - 202 Accepted → returns `InterruptSessionResponse`; the cancel
+ * signal was broadcast (running) or a wakeup-interrupt was
+ * enqueued (parked). Idempotent: an idle target is a silent
+ * no-op at the agent layer.
+ * - 404 Not Found → the session does not exist.
+ */
+ interrupt: (sessionId: string, agentId: string) =>
+ client.post<InterruptSessionResponse>(`/sessions/${sessionId}/interrupt`, null, {
+ agent_id: agentId,
+ }),
+
messages: (sessionId: string, agentId: string, offset = 0, limit = 50) =>
client.get<MessagesResponse>(`/sessions/${sessionId}/messages`, {
agent_id: agentId,
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 2d66f6100..6c539df5e 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -155,6 +155,10 @@ export interface CreateSessionResponse {
session_id: string;
}
+export interface InterruptSessionResponse {
+ session_id: string;
+}
+
export interface UpdateSessionRequest {
name?: string;
chat_model_config?: ChatModelConfig;
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 0a76b76b1..16aa0b046 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -5,11 +5,17 @@ import { useRef, useEffect } from 'react';
import { EmptyMessage } from './Empty';
import { MessageBubble } from '@/components/chat/MessageBubble';
import { TextInput } from '@/components/chat/TextInput.tsx';
+import type { ReplyPhase } from '@/hooks/useMessages';
import { cn } from '@/lib/utils';
interface ChatContentProps {
msgs: Msg[];
- sending: boolean;
+ /**
+ * Reply lifecycle phase from ``useMessages`` — forwarded to
+ * ``TextInput`` so the single send / stop button can pick its
+ * icon, tooltip, disabled state and click handler from one source.
+ */
+ phase: ReplyPhase;
disabled: boolean;
onSend: (content: ContentBlock[]) => void;
onUserConfirm: (
@@ -20,6 +26,8 @@ interface ChatContentProps {
) => void;
autoComplete?: (input: string) => string | null;
className?: string;
+ /** Called when the user clicks the stop button. */
+ onInterrupt?: () => void;
/**
* Optional content pinned at the bottom of the chat — between the
* message scroll area and the text input (e.g. pending subagent HITL
@@ -36,12 +44,13 @@ interface ChatContentProps {
const ChatContentComponent: React.FC<ChatContentProps> = ({
msgs,
- sending,
+ phase,
disabled,
onSend,
onUserConfirm,
autoComplete,
className,
+ onInterrupt,
footerSlot,
allowedInputTypes,
fileProcessor,
@@ -55,8 +64,9 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
const currentCount = msgs.length;
const prevCount = prevMsgCountRef.current;
+ const isActive = phase !== 'idle';
const shouldCheck =
- (currentCount > prevCount && prevCount > 0) || (sending && prevCount > 0);
+ (currentCount > prevCount && prevCount > 0) || (isActive && prevCount > 0);
if (shouldCheck && scrollAreaRef.current) {
const { scrollHeight } = scrollAreaRef.current;
@@ -73,7 +83,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
}
prevMsgCountRef.current = currentCount;
- }, [msgs, sending]);
+ }, [msgs, phase]);
// Track if user is near bottom whenever they scroll
useEffect(() => {
@@ -117,6 +127,8 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
autoComplete={autoComplete}
allowedInputTypes={allowedInputTypes}
fileProcessor={fileProcessor}
+ phase={phase}
+ onInterrupt={onInterrupt}
/>
</div>
);
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index bd4fa0d60..eac1f77f0 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -1,5 +1,5 @@
import type { ContentBlock, TextBlock } from '@agentscope-ai/agentscope/message';
-import { Paperclip, Send, Loader2, X } from 'lucide-react';
+import { Paperclip, Send, Loader2, Square, X, type LucideIcon } from 'lucide-react';
import React, {
useState,
useRef,
@@ -12,6 +12,7 @@ import React, {
import { Button } from '../ui/button';
import { Kbd } from '../ui/kbd';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n.ts';
import { cn } from '@/lib/utils';
import { isMac } from '@/utils/platform';
@@ -55,6 +56,15 @@ interface TextInputProps {
* Runs concurrently for all selected files; the UI shows a loading state per file while processing.
*/
fileProcessor: (file: File) => Promise<ContentBlock | null>;
+ /**
+ * The current reply lifecycle phase from ``useMessages``. Drives the
+ * send / stop button in one shot:
+ * - ``idle`` — Send (enabled when there is content to send)
+ * - ``streaming`` — Stop (click to interrupt)
+ * - ``interrupting`` — Stop (disabled while the interrupt is in flight)
+ */
+ phase?: ReplyPhase;
+ onInterrupt?: () => void;
}
export interface TextInputRef {
@@ -82,6 +92,8 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
className,
allowedInputTypes,
fileProcessor,
+ phase = 'idle',
+ onInterrupt,
},
ref,
) => {
@@ -166,6 +178,40 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
setFiles([]);
};
+ /**
+ * Send / stop button configuration derived from the current reply
+ * phase. One struct = one branch of rendering, so the JSX stays flat.
+ */
+ const sendButton: {
+ icon: LucideIcon;
+ tooltip: string;
+ disabled: boolean;
+ onClick: (() => void) | undefined;
+ } = (() => {
+ if (phase === 'streaming') {
+ return {
+ icon: Square,
+ tooltip: t('textInput.stop'),
+ disabled: false,
+ onClick: onInterrupt,
+ };
+ }
+ if (phase === 'interrupting') {
+ return {
+ icon: Square,
+ tooltip: t('textInput.stopping'),
+ disabled: true,
+ onClick: onInterrupt,
+ };
+ }
+ return {
+ icon: Send,
+ tooltip: t('textInput.send'),
+ disabled: disabled || !value.trim() || hasProcessing,
+ onClick: handleSend,
+ };
+ })();
+
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
const selected = Array.from(e.target.files);
@@ -330,20 +376,20 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
</TooltipContent>
</Tooltip>
- {/* Send button */}
+ {/* Send / Stop button — driven by ``sendButton`` config */}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
- onClick={handleSend}
- disabled={disabled || !value.trim() || hasProcessing}
+ onClick={sendButton.onClick}
+ disabled={sendButton.disabled}
size="icon"
className="shrink-0 rounded-full"
>
- <Send className="h-4 w-4" />
+ <sendButton.icon className="h-4 w-4" />
</Button>
</TooltipTrigger>
- <TooltipContent>{t('textInput.send')}</TooltipContent>
+ <TooltipContent>{sendButton.tooltip}</TooltipContent>
</Tooltip>
{/* Hidden file input */}
diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.ts
index 08d8822bd..29467317b 100644
--- a/examples/web_ui/frontend/src/hooks/useMessages.ts
+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts
@@ -35,9 +35,46 @@ export type SubagentHitlEntry = {
created_at: string;
};
+/**
+ * Return true if ``msg`` is an assistant reply currently parked on a
+ * pending tool_call (awaiting user confirmation or an external
+ * execution result). Used both to detect the "in-flight reply on page
+ * load" case and as the SDK-gap workaround that hides the confirm
+ * card once the paired tool_result lands.
+ */
+const hasPendingToolCall = (msg: Msg | undefined): boolean => {
+ if (!msg || msg.role !== 'assistant') return false;
+ for (const block of msg.content) {
+ if (block.type !== 'tool_call') continue;
+ const state = (block as ToolCallBlock).state;
+ if (state === 'asking' || state === 'submitted') return true;
+ }
+ return false;
+};
+
const hitlKey = (e: { worker_session_id: string; reply_id: string }) =>
`${e.worker_session_id}:${e.reply_id}`;
+/**
+ * Lifecycle phase of the reply currently owned by this session.
+ *
+ * - ``idle`` — no in-flight reply; the send button is enabled.
+ * - ``streaming`` — a reply is in progress (either actively producing
+ * events or parked awaiting HITL). The send button is replaced by a
+ * Stop button. The parked-vs-generating distinction is not tracked
+ * here; HITL cards render themselves from message content when a
+ * ``RequireUserConfirmEvent`` block is present.
+ * - ``interrupting`` — the user has requested a stop and we are
+ * waiting for the backend's terminating ``ReplyEndEvent``. Stop
+ * button is shown but disabled so users cannot spam it. Falls back
+ * to ``idle`` after a 10s safety timeout in case the terminating
+ * event never arrives (dropped SSE frame, backend bug, etc.).
+ */
+export type ReplyPhase = 'idle' | 'streaming' | 'interrupting';
+
+/** Safety fallback: force phase back to idle if REPLY_END is not seen. */
+const INTERRUPT_TIMEOUT_MS = 10_000;
+
/**
* Manages messages for a single ``(agentId, sessionId)`` pair.
*
@@ -55,14 +92,16 @@ const hitlKey = (e: { worker_session_id: string; reply_id: string }) =>
* via ``POST /chat/`` (fire-and-forget); the resulting events arrive
* through the already-open SSE connection.
*
- * ``streaming`` is driven by event content, not HTTP lifecycle:
- * ``true`` after receiving ``ReplyStartEvent``, ``false`` after
- * ``ReplyEndEvent``.
+ * ``phase`` is driven by event content, not HTTP lifecycle: it moves
+ * to ``streaming`` on ``ReplyStartEvent`` and back to ``idle`` on
+ * ``ReplyEndEvent``. Calling ``interrupt()`` moves it to
+ * ``interrupting`` until the terminating ``ReplyEndEvent`` arrives (or
+ * a 10s safety timeout fires).
*
* @param agentId - The agent whose session to subscribe. ``null`` to
* skip.
* @param sessionId - The session to subscribe. ``null`` to skip.
- * @returns Object with ``msgs``, ``loading``, ``streaming``, ``error``,
+ * @returns Object with ``msgs``, ``loading``, ``phase``, ``error``,
* ``send``, ``onUserConfirm``, and ``abort``.
*/
export function useMessages(
@@ -87,7 +126,7 @@ export function useMessages(
) {
const [msgs, setMsgs] = useState<Msg[]>([]);
const [loading, setLoading] = useState(false);
- const [streaming, setStreaming] = useState(false);
+ const [phase, setPhase] = useState<ReplyPhase>('idle');
const [error, setError] = useState<Error | null>(null);
// Pending subagent HITL cards projected onto this (leader) session.
const [subagentHitl, setSubagentHitl] = useState<SubagentHitlEntry[]>([]);
@@ -96,6 +135,16 @@ export function useMessages(
const currentReplyRef = useRef<Msg | null>(null);
const abortRef = useRef<AbortController | null>(null);
const rafRef = useRef<number | null>(null);
+ // Timer that reverts ``interrupting`` back to ``idle`` if the
+ // terminating REPLY_END never arrives (dropped SSE frame, etc.).
+ const interruptTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clearInterruptTimer = useCallback(() => {
+ if (interruptTimerRef.current !== null) {
+ clearTimeout(interruptTimerRef.current);
+ interruptTimerRef.current = null;
+ }
+ }, []);
const audioManager = useAudioManager();
@@ -144,12 +193,14 @@ export function useMessages(
const msg = AssistantMsg({ id: e.reply_id, name: e.name, content: [] });
msgsRef.current = [...msgsRef.current, msg];
currentReplyRef.current = msg;
- setStreaming(true);
+ clearInterruptTimer();
+ setPhase('streaming');
} else if (event.type === EventType.REPLY_END) {
if (currentReplyRef.current) {
appendEvent(currentReplyRef.current, event);
}
- setStreaming(false);
+ clearInterruptTimer();
+ setPhase('idle');
currentReplyRef.current = null;
} else if (currentReplyRef.current) {
appendEvent(currentReplyRef.current, event);
@@ -180,7 +231,7 @@ export function useMessages(
scheduleUpdate();
},
- [scheduleUpdate, audioManager],
+ [scheduleUpdate, audioManager, clearInterruptTimer],
);
// ── Lifecycle: fetch history + open SSE stream ──────────────────
@@ -189,7 +240,8 @@ export function useMessages(
currentReplyRef.current = null;
setMsgs([]);
setError(null);
- setStreaming(false);
+ clearInterruptTimer();
+ setPhase('idle');
setSubagentHitl([]);
audioManager?.disposeAll();
@@ -203,9 +255,26 @@ export function useMessages(
// 1. Fetch persisted history
setLoading(true);
try {
- const { messages } = await sessionApi.messages(sessionId, agentId);
+ const { messages, is_running } = await sessionApi.messages(sessionId, agentId);
if (cancelled) return;
msgsRef.current = messages;
+ // If a reply is in flight (running on a worker) OR the
+ // tail msg is parked on a pending tool_call (awaiting
+ // user confirmation / external execution), initialise the
+ // phase to ``streaming`` so the interrupt button is
+ // available immediately — otherwise a fresh page load
+ // while parked leaves the UI stuck on ``idle`` with no
+ // way to abort.
+ const tail = messages[messages.length - 1];
+ if (is_running || hasPendingToolCall(tail)) {
+ setPhase('streaming');
+ if (hasPendingToolCall(tail)) {
+ // Prime the ref so continuation events (which
+ // arrive without a fresh REPLY_START) apply to
+ // the right msg.
+ currentReplyRef.current = tail ?? null;
+ }
+ }
scheduleUpdate();
} catch (e) {
if (!cancelled) setError(e as Error);
@@ -235,8 +304,9 @@ export function useMessages(
cancelled = true;
controller.abort();
abortRef.current = null;
+ clearInterruptTimer();
};
- }, [agentId, sessionId, scheduleUpdate, processEvent, audioManager]);
+ }, [agentId, sessionId, scheduleUpdate, processEvent, audioManager, clearInterruptTimer]);
/**
* Send a user message. Appends the message to the local list
@@ -317,6 +387,42 @@ export function useMessages(
abortRef.current?.abort();
}, []);
+ /**
+ * Request interruption of the in-progress reply (running or parked
+ * on HITL). Optimistically moves ``phase`` to ``interrupting`` so
+ * the UI can disable the Stop button; the phase reverts to
+ * ``idle`` when the backend's terminating ``ReplyEndEvent``
+ * arrives via SSE (or after a 10s safety timeout, in case that
+ * event is lost).
+ *
+ * Backend contract:
+ * - 202: interrupt was accepted (cancel signal broadcast for a
+ * running reply, or wakeup enqueued for a parked one). The
+ * resulting ``ReplyEndEvent`` arrives through the SSE stream and
+ * drives the phase transition.
+ * - Idle sessions are a silent no-op at the agent layer, so
+ * spamming this callback is safe.
+ */
+ const interrupt = useCallback(async () => {
+ if (!agentId || !sessionId) return;
+ // Only escalate to ``interrupting`` if a reply is actually in
+ // flight; if we're already idle (SSE completed just before the
+ // click) leave the phase alone.
+ setPhase((prev) => (prev === 'streaming' ? 'interrupting' : prev));
+ clearInterruptTimer();
+ interruptTimerRef.current = setTimeout(() => {
+ interruptTimerRef.current = null;
+ setPhase((prev) => (prev === 'interrupting' ? 'idle' : prev));
+ }, INTERRUPT_TIMEOUT_MS);
+ try {
+ await sessionApi.interrupt(sessionId, agentId);
+ } catch (e) {
+ clearInterruptTimer();
+ setPhase((prev) => (prev === 'interrupting' ? 'idle' : prev));
+ setError(e as Error);
+ }
+ }, [agentId, sessionId, clearInterruptTimer]);
+
/**
* Confirm or deny a tool call that a *team member* is awaiting,
* from this leader view (design §3.6 — backend routing).
@@ -373,12 +479,13 @@ export function useMessages(
return {
msgs,
loading,
- streaming,
+ phase,
error,
send,
onUserConfirm,
onSubagentConfirm,
subagentHitl,
abort,
+ interrupt,
};
}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index f9fa2cf26..547fd7304 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -74,7 +74,9 @@
"newLine": "new line",
"attach": "Attach file",
"attachNotSupported": "This model does not support file attachments",
- "send": "Send"
+ "send": "Send",
+ "stop": "Stop generating",
+ "stopping": "Stopping ..."
},
"confirmCard": {
"toConfirm": "to confirm",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 8a77fe958..3b24d1518 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -74,7 +74,9 @@
"newLine": "换行",
"attach": "添加附件",
"attachNotSupported": "当前模型不支持文件附件",
- "send": "发送"
+ "send": "发送",
+ "stop": "停止生成",
+ "stopping": "停止中 ..."
},
"confirmCard": {
"toConfirm": "确认",
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 20b038288..56f776329 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -156,14 +156,11 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
}
}, []);
- const { msgs, streaming, send, onUserConfirm, onSubagentConfirm, subagentHitl } = useMessages(
- agentId,
- sessionId,
- {
+ const { msgs, phase, send, onUserConfirm, onSubagentConfirm, subagentHitl, interrupt } =
+ useMessages(agentId, sessionId, {
onTeamUpdated: handleTeamUpdated,
onStateUpdated: handleStateUpdated,
- },
- );
+ });
const {
mcps,
loading: mcpsLoading,
@@ -618,10 +615,11 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
<ChatContent
className={'max-w-[var(--chat-content-w)] w-full'}
msgs={msgs}
- sending={streaming}
+ phase={phase}
disabled={selectedModel === null}
onSend={send}
onUserConfirm={onUserConfirm}
+ onInterrupt={interrupt}
footerSlot={
subagentHitl.length > 0 ? (
<div className="space-y-2 pb-2">
diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yaml
index bd40abaaf..ceffa978e 100644
--- a/examples/web_ui/pnpm-lock.yaml
+++ b/examples/web_ui/pnpm-lock.yaml
@@ -58,8 +58,8 @@ importers:
frontend:
dependencies:
'@agentscope-ai/agentscope':
- specifier: ^0.0.12
- version: 0.0.12
+ specifier: ^0.0.13
+ version: 0.0.13
'@fontsource-variable/geist':
specifier: ^5.2.8
version: 5.2.8
@@ -208,8 +208,8 @@ importers:
packages:
- '@agentscope-ai/[email protected]':
- resolution: {integrity: sha512-yiCNx1sqtZ2X0YHY3X4+BavDxyQ2QutSlYlVLLJ9pVw3oZg1qEKcWA7HkXiNyXtEDDs/zTM4zco8hyeTCvjKWw==}
+ '@agentscope-ai/[email protected]':
+ resolution: {integrity: sha512-SUNKypyVR8ANu6mSiQ0cPaD2GuFzTJmTxj0FqFjjGR+gIy0J44L+46dOxbwfOoZS/2Cl60gMqV33A/K+XPcJVw==}
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
@@ -4644,7 +4644,7 @@ packages:
snapshots:
- '@agentscope-ai/[email protected]':
+ '@agentscope-ai/[email protected]':
dependencies:
'@cfworker/json-schema': 4.1.1
'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 2e701ea72..d9c982b0e 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -48,12 +48,15 @@ from ..event import (
DataBlockDeltaEvent,
DataBlockEndEvent,
ExceedMaxItersEvent,
+ ReplyEndReason,
+ UserInterruptEvent,
)
from ..exception import AgentOrientedException
from ..model import (
ChatResponse,
ChatUsage,
ChatModelBase,
+ FinishedReason,
)
from ..message import (
Msg,
@@ -193,31 +196,38 @@ class Agent:
inputs: Msg
| list[Msg]
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| None = None,
) -> AsyncGenerator[AgentEvent, None]:
"""Reply to the given inputs and stream agent events.
+ Args:
+ inputs (`Msg | list[Msg] | UserConfirmResultEvent | \
+ UserInterruptEvent | ExternalExecutionResultEvent | None`, \
+ optional):
+ The inputs that trigger this reply. See :meth:`reply` for
+ the full list of accepted variants.
- **NOTE**:
+ Yields:
+ `AgentEvent`:
+ Streamed events produced during the reply.
- - If requiring outside interaction for multiple tool calls and only
- receive partial confirmation or execution results, the agent won't
- re-send the requiring events for the unconfirmed or unexecuted tool
- calls.
+ .. note:: If requiring outside interaction for multiple tool calls
+ and only receive partial confirmation or execution results, the
+ agent won't re-send the requiring events for the unconfirmed
+ or unexecuted tool calls.
"""
- try:
- async for chunk in self._reply(inputs=inputs):
- if not isinstance(chunk, Msg):
- yield chunk
- finally:
- pass
+ async for chunk in self._reply(inputs=inputs):
+ if not isinstance(chunk, Msg):
+ yield chunk
async def reply(
self,
inputs: Msg
| list[Msg]
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| None = None,
) -> Msg:
@@ -225,7 +235,8 @@ class Agent:
Args:
inputs (`Msg | list[Msg] | UserConfirmResultEvent | \
- ExternalExecutionResultEvent | None`, optional):
+ UserInterruptEvent | ExternalExecutionResultEvent | None`, \
+ optional):
The inputs that trigger this reply. It can be:
- a single `Msg` or a list of `Msg` objects to start a new
@@ -233,6 +244,10 @@ class Agent:
- a `UserConfirmResultEvent` or
`ExternalExecutionResultEvent` to continue from the
outside interaction required by the previous reply,
+ - a `UserInterruptEvent` to abort a parked reply — the
+ agent closes all pending tool calls with an interrupted
+ tool result and ends the reply without entering the
+ reasoning-acting loop,
- `None` if there is nothing new to feed in (e.g. just
continue from the current state).
@@ -240,16 +255,13 @@ class Agent:
`Msg`:
A final reply message.
"""
- try:
- final_msg: Msg | None = None
- async for evt_or_msg in self._reply(inputs=inputs):
- if isinstance(evt_or_msg, Msg):
- final_msg = evt_or_msg
- if final_msg is None:
- raise RuntimeError("Agent did not produce a final message.")
- return final_msg
- finally:
- pass
+ final_msg: Msg | None = None
+ async for evt_or_msg in self._reply(inputs=inputs):
+ if isinstance(evt_or_msg, Msg):
+ final_msg = evt_or_msg
+ if final_msg is None:
+ raise RuntimeError("Agent did not produce a final message.")
+ return final_msg
async def observe(self, msgs: Msg | list[Msg] | None = None) -> None:
"""Receive external observation message(s) and save them into
@@ -496,29 +508,45 @@ class Agent:
else:
raise e from None
- # Update the summary
- self.state.summary = cfg.summary_template.format(**res.content)
-
- if self.offloader:
- path = await self.offloader.offload_context(
- self.state.session_id,
- msgs=msgs_to_compress,
+ if res.finished_reason == FinishedReason.INTERRUPTED:
+ logger.warning(
+ "The context compression was interrupted and skipped. ",
)
+ raise asyncio.CancelledError()
- self.state.summary += (
- f"\n<system-reminder>The compressed context is offloaded to "
- f"'{path}', you can refer to it when needed.</system-reminder>"
- )
+ # Update the summary
+ async def _apply_change() -> None:
+ """Apply the context change with interruption protection."""
+ new_summary = cfg.summary_template.format(**res.content)
+ if self.offloader:
+ path = await self.offloader.offload_context(
+ self.state.session_id,
+ msgs=msgs_to_compress,
+ )
+ new_summary += (
+ f"\n<system-reminder>The compressed context is offloaded "
+ f"to '{path}', you can refer to it when needed."
+ f"</system-reminder>"
+ )
- await self._clear_unreserved_read_cache(msgs_to_reserve)
+ # Protected from interruption
+ await self._clear_unreserved_read_cache(msgs_to_reserve)
- # Update the context
- self.state.context = msgs_to_reserve
+ # Update the context
+ self.state.summary = new_summary
+ self.state.context = msgs_to_reserve
- logger.info(
- "[AGENT %s]: The context compression finished.",
- self.name,
- )
+ logger.info(
+ "[AGENT %s]: The context compression finished.",
+ self.name,
+ )
+
+ apply_task = asyncio.create_task(_apply_change())
+ try:
+ await asyncio.shield(apply_task)
+ except asyncio.CancelledError:
+ await apply_task
+ raise
# ======================================================================
# Agent core methods, including _reply, _reasoning, _acting, etc.
@@ -529,6 +557,7 @@ class Agent:
inputs: Msg
| list[Msg]
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| None = None,
) -> AsyncGenerator[AgentEvent | Msg, None]:
@@ -543,6 +572,7 @@ class Agent:
inputs: Msg
| list[Msg]
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| None = inputs,
) -> AsyncGenerator[AgentEvent | Msg, None]:
@@ -572,164 +602,316 @@ class Agent:
async for item in execute_chain():
yield item
+ async def _close_unfinished_tool_calls(
+ self,
+ ) -> AsyncGenerator[
+ ToolResultStartEvent | ToolResultTextDeltaEvent | ToolResultEndEvent,
+ None,
+ ]:
+ """Close the unfinished tool calls on interruption, so the next
+ input will be handled normally."""
+ if not self.state.context:
+ return
+
+ last_msg = self.state.context[-1]
+ if last_msg.role != "assistant" or last_msg.name != self.name:
+ return
+
+ # Searching for tool calls that requires user confirmation or external
+ # execution without tool results
+ awaiting_tool_calls: dict = {}
+ for index, block in enumerate(last_msg.content):
+ if isinstance(block, ToolCallBlock):
+ awaiting_tool_calls[block.id] = index
+ elif isinstance(block, ToolResultBlock):
+ awaiting_tool_calls.pop(block.id, None)
+
+ interruption_message = (
+ "<system-reminder>The tool call has been interrupted by "
+ "the user.</system-reminder>"
+ )
+
+ for index in awaiting_tool_calls.values():
+ # First update the status
+ assert isinstance(last_msg.content[index], ToolCallBlock)
+ last_msg.content[index].state = ToolCallState.FINISHED
+
+ # Emit the full tool_result lifecycle (START → DELTA → END)
+ yield ToolResultStartEvent(
+ reply_id=self.state.reply_id,
+ tool_call_id=last_msg.content[index].id,
+ tool_call_name=last_msg.content[index].name,
+ )
+ yield ToolResultTextDeltaEvent(
+ reply_id=self.state.reply_id,
+ tool_call_id=last_msg.content[index].id,
+ delta=interruption_message,
+ )
+ yield ToolResultEndEvent(
+ reply_id=self.state.reply_id,
+ tool_call_id=last_msg.content[index].id,
+ state=ToolResultState.INTERRUPTED,
+ )
+ last_msg.content.append(
+ ToolResultBlock(
+ id=last_msg.content[index].id,
+ name=last_msg.content[index].name,
+ output=interruption_message,
+ state=ToolResultState.INTERRUPTED,
+ ),
+ )
+
async def _reply_impl(
self,
inputs: Msg
| list[Msg]
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| None = None,
) -> AsyncGenerator[AgentEvent | Msg, None]:
"""Core reply logic."""
- # Dispatch the unified inputs by type into the legacy local variables
- event: (UserConfirmResultEvent | ExternalExecutionResultEvent | None)
- msgs: Msg | list[Msg] | None
- if isinstance(
- inputs,
- (UserConfirmResultEvent, ExternalExecutionResultEvent),
- ):
- event = inputs
- msgs = None
- else:
- event = None
- msgs = inputs
- # ===================================================================
- # Step 1: Checking agent input:
- # - if incoming event and agent is waiting for an event
- # - if event is None and agent is not waiting for an event
- # ===================================================================
- is_awaiting = await self._check_incoming_event(event)
+ end_event: ReplyEndEvent | None = None
+ try:
+ # Dispatch the unified inputs by type into the legacy local
+ # variables
+ event: (
+ UserConfirmResultEvent
+ | UserInterruptEvent
+ | ExternalExecutionResultEvent
+ | None
+ )
+ msgs: Msg | list[Msg] | None
+ if isinstance(
+ inputs,
+ (
+ UserConfirmResultEvent,
+ UserInterruptEvent,
+ ExternalExecutionResultEvent,
+ ),
+ ):
+ event = inputs
+ msgs = None
+ else:
+ event = None
+ msgs = inputs
+
+ # Parked-interrupt short-circuit: only signal an INTERRUPTED
+ # end when there is actual HITL work to close; otherwise the
+ # session is effectively idle and the call is a silent no-op.
+ # ``finally`` reuses the CancelledError cleanup path when
+ # ``end_event`` is set — no reasoning-acting loop either way.
+ if isinstance(inputs, UserInterruptEvent):
+ if self.state.has_awaiting_tool_calls(self.name):
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.INTERRUPTED,
+ )
+ return
- # ===================================================================
- # Step 2: Handling agent event if applicable
- # - yield tool result events for the denied tool calls, or
- # - update the reply state as a new reply process
- # ===================================================================
- if is_awaiting:
- async for evt in self._handle_incoming_event(event):
- yield evt
- else:
- await self._handle_incoming_messages(msgs)
- # Update the context with the incoming message and state
- self.state.reply_id = _generate_id()
- self.state.cur_iter = 0
+ # ===================================================================
+ # Step 1: Checking agent input:
+ # - if incoming event and agent is waiting for an event
+ # - if event is None and agent is not waiting for an event
+ # ===================================================================
+ is_awaiting = await self._check_incoming_event(event)
+
+ # ===================================================================
+ # Step 2: Handling agent event if applicable
+ # - yield tool result events for the denied tool calls, or
+ # - update the reply state as a new reply process
+ # ===================================================================
+ if is_awaiting:
+ async for evt in self._handle_incoming_event(event):
+ yield evt
+ else:
+ await self._handle_incoming_messages(msgs)
+ # Update the context with the incoming message and state
+ self.state.reply_id = _generate_id()
+ self.state.cur_iter = 0
- yield ReplyStartEvent(
- session_id=self.state.session_id,
- reply_id=self.state.reply_id,
- name=self.name,
- )
+ yield ReplyStartEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ name=self.name,
+ )
- # ===================================================================
- # Step 3: Enter the reasoning-acting loop until reaching max_iters or
- # no more tool calls to execute
- # ===================================================================
- while self.state.cur_iter < self.react_config.max_iters:
- # ===============================================================
- # Step 3.1:
- # ===============================================================
- action, data = self._check_next_action()
- if action == "exit" and isinstance(data, Msg):
- yield data
- return
+ # =================================================================
+ # Step 3: Enter the reasoning-acting loop until reaching max_iters
+ # or no more tool calls to execute
+ # =================================================================
+ while self.state.cur_iter < self.react_config.max_iters:
+ # =============================================================
+ # Step 3.1:
+ # =============================================================
+ action, data = self._check_next_action()
+ if action == "exit" and isinstance(data, Msg):
+ yield data
+ return
+
+ # =============================================================
+ # Step 3.2: Execute reasoning if no more tools to be executed
+ # =============================================================
+ if action == "reasoning":
+ # Compressed the memory if needed before reasoning
+ await self.compress_context()
+
+ # Perform reasoning
+ interrupted = False
+ async for evt in self._reasoning():
+ # Exit the loop when no tool calls generated and the
+ # reply message is generated
+ if isinstance(evt, Msg):
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.COMPLETED,
+ )
+ yield evt
+ return
- # ===============================================================
- # Step 3.2: Execute reasoning if no more tools to be executed
- # ===============================================================
- if action == "reasoning":
- # Compressed the memory if needed before reasoning
- await self.compress_context()
- # Perform reasoning
- async for evt in self._reasoning():
- # Exit the loop when no tool calls generated and the reply
- # message is generated
- if isinstance(evt, Msg):
- yield ReplyEndEvent(
+ elif isinstance(evt, ModelCallEndEvent):
+ interrupted = (
+ evt.finished_reason
+ == FinishedReason.INTERRUPTED
+ )
+
+ yield evt
+
+ if interrupted:
+ end_event = ReplyEndEvent(
session_id=self.state.session_id,
reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.INTERRUPTED,
+ )
+ return
+
+ # =============================================================
+ # Step 3.3: Getting batches of tool calls to be executed
+ # - If not, finish loop by yielding RunFinishedEvent and exit
+ # - Otherwise, execute by batch and continue the loop
+ # =============================================================
+ for batch in await self._batch_tool_calls():
+ if batch.type == "sequential":
+ evt_generator = self._execute_sequential_tool_calls(
+ batch.tool_calls,
+ )
+
+ elif batch.type == "concurrent":
+ evt_generator = self._execute_concurrent_tool_calls(
+ batch.tool_calls,
+ )
+
+ else:
+ raise ValueError(
+ f"Invalid batch type: {batch.type}",
)
+
+ break_execution_for_hitl = False
+ break_execution_for_interruption = False
+ break_message = ""
+ async for evt in evt_generator:
yield evt
+ if isinstance(
+ evt,
+ (
+ RequireUserConfirmEvent,
+ RequireExternalExecutionEvent,
+ ),
+ ):
+ break_execution_for_hitl = True
+ break_message = (
+ "Waiting for tool calls to be confirmed or "
+ "executed from outside ..."
+ )
+
+ elif (
+ isinstance(evt, ToolResultEndEvent)
+ and evt.state == ToolResultState.INTERRUPTED
+ ):
+ # Handle the interruption event
+ break_execution_for_interruption = True
+
+ if break_execution_for_interruption:
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.INTERRUPTED,
+ )
return
- yield evt
- # ===============================================================
- # Step 3.3: Getting batches of tool calls to be executed
- # - If not, finish the loop by yielding RunFinishedEvent and exit
- # - Otherwise, execute by batch and continue the loop
- # ===============================================================
- for batch in await self._batch_tool_calls():
- if batch.type == "sequential":
- evt_generator = self._execute_sequential_tool_calls(
- batch.tool_calls,
- )
+ # If it requires outside interaction stop executing the
+ # next batch and wait for outside trigger events
+ if break_execution_for_hitl:
+ yield AssistantMsg(
+ id=self.state.reply_id,
+ name=self.name,
+ content=break_message,
+ )
+ return
- elif batch.type == "concurrent":
- evt_generator = self._execute_concurrent_tool_calls(
- batch.tool_calls,
- )
+ # Update iteration count after each round of reasoning-acting
+ self.state.cur_iter += 1
- else:
- raise ValueError(
- f"Invalid batch type: {batch.type}",
- )
+ # =================================================================
+ # Step 4: Handling the max iteration executed
+ # =================================================================
+ yield ExceedMaxItersEvent(
+ reply_id=self.state.reply_id,
+ name=self.name,
+ )
+ logger.warning(
+ "Agent %s exceeds the max iteration numbers %d. "
+ "Stop the react loop.",
+ self.name,
+ self.react_config.max_iters,
+ )
- break_execution = False
- async for evt in evt_generator:
- yield evt
- if isinstance(
- evt,
- (
- RequireUserConfirmEvent,
- RequireExternalExecutionEvent,
- ),
- ):
- break_execution = True
+ # Mirror the normal-exit path so subscribers (e.g. SSE clients
+ # waiting on a terminal event) don't hang when the loop bails
+ # out on max_iters.
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.EXCEED_MAX_ITERS,
+ )
- # If it requires outside interaction stop executing the next
- # batch and wait for outside trigger events
- if break_execution:
- # Yield a Msg object for outside handling
- yield AssistantMsg(
- id=self.state.reply_id,
- name=self.name,
- content="Waiting for tool calls to be confirmed or "
- "executed from outside ...",
- )
+ yield AssistantMsg(
+ id=self.state.reply_id,
+ name=self.name,
+ content="Executed maximum iterations of reasoning-acting loop "
+ "without finishing the task.",
+ )
- return
+ except asyncio.CancelledError:
+ # Handle the CancelledError within the _reply_impl for the
+ # agent middlewares
+ end_event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self.state.reply_id,
+ finished_reason=ReplyEndReason.INTERRUPTED,
+ )
- # Update the iteration count after each round of reasoning-acting
- self.state.cur_iter += 1
+ if self.react_config.interruption_raise_cancelled_error:
+ raise
- # ===================================================================
- # Step 4: Handling the max iteration executed
- # ===================================================================
- yield ExceedMaxItersEvent(
- reply_id=self.state.reply_id,
- name=self.name,
- )
- logger.warning(
- "Agent %s exceeds the max iteration numbers %d. "
- "Stop the react loop.",
- self.name,
- self.react_config.max_iters,
- )
+ finally:
+ if end_event is not None:
+ if end_event.finished_reason == ReplyEndReason.INTERRUPTED:
+ # Handle the context when interruption
+ async for _ in self._close_unfinished_tool_calls():
+ yield _
- # Mirror the normal-exit path so subscribers (e.g. SSE clients
- # waiting on a terminal event) don't hang when the loop bails
- # out on max_iters.
- yield ReplyEndEvent(
- session_id=self.state.session_id,
- reply_id=self.state.reply_id,
- )
+ # A fallback msg object
+ yield AssistantMsg(
+ id=self.state.reply_id,
+ name=self.name,
+ content=self.react_config.interruption_message,
+ )
- yield AssistantMsg(
- id=self.state.reply_id,
- name=self.name,
- content="Executed maximum iterations of reasoning-acting loop"
- "without finishing the task.",
- )
+ yield end_event
async def _reasoning(
self,
@@ -897,6 +1079,7 @@ class Agent:
output_tokens=completed_response.usage.output_tokens
if completed_response.usage
else 0,
+ finished_reason=completed_response.finished_reason,
)
self._save_to_context(
@@ -905,8 +1088,12 @@ class Agent:
)
# If no tool call is generated, return the final message directly
- if not any(
- isinstance(_, ToolCallBlock) for _ in completed_response.content
+ if (
+ completed_response.finished_reason != FinishedReason.INTERRUPTED
+ and not any(
+ isinstance(_, ToolCallBlock)
+ for _ in completed_response.content
+ )
):
last_ctx = self._get_last_msg()
final_usage = (
@@ -920,6 +1107,7 @@ class Agent:
yield AssistantMsg(
id=self.state.reply_id,
name=self.name,
+ # Text only response message
content=list(completed_response.content),
usage=final_usage,
)
@@ -1225,6 +1413,9 @@ class Agent:
RequireUserConfirmEvent,
RequireExternalExecutionEvent,
),
+ ) or (
+ isinstance(evt, ToolResultEndEvent)
+ and evt.state == ToolResultState.INTERRUPTED
):
break_execution = True
break
@@ -1256,6 +1447,16 @@ class Agent:
means every ``queue.put`` from every worker has already finished
before the generator returns.
+ If the caller task is cancelled from outside, the concurrent worker
+ tasks are cancelled explicitly (to avoid orphan tasks), any events
+ already queued by the workers (including interruption chunks emitted
+ by ``toolkit.call_tool`` when it catches ``CancelledError``) are
+ flushed to the caller, and the generator returns normally. The
+ caller is expected to detect the interruption via the flushed
+ ``ToolResultEndEvent(state=INTERRUPTED)`` events, mirroring the
+ event-based propagation used by
+ :meth:`_execute_sequential_tool_calls`.
+
Args:
tool_calls (`list[ToolCallBlock]`):
The tool calls to be executed concurrently.
@@ -1303,12 +1504,35 @@ class Agent:
gather_task = asyncio.create_task(_run_all())
- # Drain the queue until the sentinel is encountered.
- while True:
- event = await queue.get()
- if event is sentinel:
- break
- yield event
+ try:
+ # Drain the queue until the sentinel is encountered.
+ while True:
+ event = await queue.get()
+ if event is sentinel:
+ break
+ yield event
+ except asyncio.CancelledError:
+ # Cancel the gather tasks, which will be handled within the toolkit
+ gather_task.cancel()
+ try:
+ await gather_task
+ except asyncio.CancelledError:
+ pass
+ while True:
+ try:
+ event = queue.get_nowait()
+ except asyncio.QueueEmpty:
+ break
+ if event is sentinel:
+ continue
+ yield event
+ # Consume the cancel so this generator returns normally. The
+ # caller relies on the flushed ``ToolResultEndEvent(state=
+ # INTERRUPTED)`` events, not on the exception, to detect the
+ # interruption — mirroring the event-based propagation used by
+ # :meth:`_execute_sequential_tool_calls`.
+ asyncio.current_task().uncancel()
+ return
# All tasks are done at this point; collect and re-raise exceptions.
results = await gather_task
diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.py
index a530b02dc..ad9cf92ee 100644
--- a/src/agentscope/agent/_config.py
+++ b/src/agentscope/agent/_config.py
@@ -141,6 +141,25 @@ class ReActConfig(BaseModel):
won't continue reasoning and wait for outside interaction from the user.
"""
+ interruption_message: str = Field(
+ title="Interruption Message",
+ default="I notice the interruption. How can I help you?",
+ description="The quick reply message when interrupted.",
+ )
+ """The interruption message."""
+
+ interruption_raise_cancelled_error: bool = Field(
+ title="Raise CancelledError on Interruption",
+ default=False,
+ description="Whether to re-raise ``asyncio.CancelledError`` after "
+ "handling the interruption. When ``False``, the ``CancelledError`` "
+ "is swallowed once the interruption context has been produced.",
+ )
+ """Whether to re-raise the ``asyncio.CancelledError`` after the
+ interruption has been handled. When ``False``, the ``CancelledError``
+ is swallowed once the fallback interruption message and
+ ``ReplyEndEvent`` have been emitted."""
+
class ModelConfig(BaseModel):
"""The model related configuration."""
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.py
index 0128cbb33..b2ff904b8 100644
--- a/src/agentscope/app/_bus_ops.py
+++ b/src/agentscope/app/_bus_ops.py
@@ -29,6 +29,7 @@ if TYPE_CHECKING:
from agentscope.event import (
ExternalExecutionResultEvent,
UserConfirmResultEvent,
+ UserInterruptEvent,
)
@@ -76,6 +77,7 @@ async def enqueue_run_trigger(
kind: Literal["wake", "resume"] = MessageBusKeys.WAKEUP_KIND_WAKE,
inputs: UserConfirmResultEvent
| ExternalExecutionResultEvent
+ | UserInterruptEvent
| None = None,
) -> None:
"""Enqueue a typed run trigger and signal dispatchers.
@@ -85,10 +87,10 @@ async def enqueue_run_trigger(
- ``wake`` — idle-session wake-up. The dispatcher skips the entry
when the session is already running (the live run drains the inbox
itself). ``inputs`` must be ``None``.
- - ``resume`` — resume a HITL-parked session with a user confirmation
- or external execution result. The dispatcher waits (with backoff)
- until the parked run releases its lock, then spawns with
- ``input_msg`` set to the deserialised event.
+ - ``resume`` — resume a HITL-parked session with a user confirmation,
+ an external execution result, or a user interrupt. The dispatcher
+ waits (with backoff) until the parked run releases its lock, then
+ spawns with ``input_msg`` set to the deserialised event.
The payload is serialised to a plain dict before being pushed to the
wakeup queue; the ``MessageBus`` transport layer never sees event
diff --git a/src/agentscope/app/_manager/_background_task_manager.py b/src/agentscope/app/_manager/_background_task_manager.py
index 660770ce2..80cc25724 100644
--- a/src/agentscope/app/_manager/_background_task_manager.py
+++ b/src/agentscope/app/_manager/_background_task_manager.py
@@ -293,6 +293,7 @@ class BackgroundTaskManager:
"agent_id": agent_id,
"started_at": time.time(),
},
+ ensure_ascii=False,
)
await self._message_bus.registry_set(
MessageBusKeys.bg_tasks(session_id),
diff --git a/src/agentscope/app/_manager/_cancel_dispatcher.py b/src/agentscope/app/_manager/_cancel_dispatcher.py
index d5e9edf88..c5364f700 100644
--- a/src/agentscope/app/_manager/_cancel_dispatcher.py
+++ b/src/agentscope/app/_manager/_cancel_dispatcher.py
@@ -60,6 +60,7 @@ class CancelDispatcher:
self._bg_manager = bg_manager
self._session_task: asyncio.Task | None = None
self._task_cancel_task: asyncio.Task | None = None
+ self._interrupt_task: asyncio.Task | None = None
async def __aenter__(self) -> Self:
"""Start both dispatcher loops and wait until their bus
@@ -70,6 +71,7 @@ class CancelDispatcher:
"""
session_ready = asyncio.Event()
task_ready = asyncio.Event()
+ interrupt_ready = asyncio.Event()
self._session_task = asyncio.create_task(
self._session_cancel_loop(session_ready),
@@ -79,14 +81,23 @@ class CancelDispatcher:
self._task_cancel_loop(task_ready),
name="cancel-dispatcher:task",
)
+ self._interrupt_task = asyncio.create_task(
+ self._interrupt_loop(interrupt_ready),
+ name="cancel-dispatcher:interrupt",
+ )
await session_ready.wait()
await task_ready.wait()
+ await interrupt_ready.wait()
return self
async def __aexit__(self, *exc: object) -> None:
- """Cancel both dispatcher loops on context exit."""
- for task in (self._session_task, self._task_cancel_task):
+ """Cancel all dispatcher loops on context exit."""
+ for task in (
+ self._session_task,
+ self._task_cancel_task,
+ self._interrupt_task,
+ ):
if task is None:
continue
task.cancel()
@@ -96,6 +107,7 @@ class CancelDispatcher:
pass
self._session_task = None
self._task_cancel_task = None
+ self._interrupt_task = None
# ------------------------------------------------------------------
# Session-level cancel loop
@@ -116,7 +128,7 @@ class CancelDispatcher:
sid = payload.get("session_id")
if isinstance(sid, str):
self._cancel_session(sid)
- except Exception: # pylint: disable=broad-except
+ except Exception:
logger.exception(
"CancelDispatcher session-cancel loop crashed.",
)
@@ -184,3 +196,51 @@ class CancelDispatcher:
# Unblock ``__aenter__`` even if subscribe failed before
# ``on_ready`` ran, so startup cannot deadlock.
ready.set()
+
+ # ------------------------------------------------------------------
+ # Session-level interrupt loop
+ # ------------------------------------------------------------------
+
+ async def _interrupt_loop(self, ready: asyncio.Event) -> None:
+ """Subscribe to the session interrupt channel and cancel matching
+ local tasks.
+
+ Args:
+ ready (`asyncio.Event`):
+ Signalled after the underlying SUBSCRIBE completes.
+ """
+ try:
+ async for payload in self._bus.subscribe(
+ MessageBusKeys.session_interrupt_channel(),
+ on_ready=ready.set,
+ ):
+ sid = payload.get("session_id")
+ if isinstance(sid, str):
+ self._interrupt_session(sid)
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "CancelDispatcher interrupt loop crashed.",
+ )
+ finally:
+ ready.set()
+
+ def _interrupt_session(self, session_id: str) -> None:
+ """Cancel the local chat-run task for a session.
+
+ Unlike ``_cancel_session``, this method only cancels the
+ chat-run asyncio task—it does **not** cancel background tasks.
+ The agent handles ``CancelledError`` gracefully at each
+ breakpoint, preserving partial context.
+
+ Args:
+ session_id (`str`):
+ The session whose chat run should be interrupted.
+ """
+ task = self._registry.get(session_id)
+ if task is not None and not task.done():
+ logger.info(
+ "CancelDispatcher: interrupting local chat run for "
+ "session %s",
+ session_id,
+ )
+ task.cancel()
diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.py
index 6ffc5d3a4..593234052 100644
--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py
+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py
@@ -31,7 +31,11 @@ from typing import TYPE_CHECKING, Self
from pydantic import TypeAdapter
from ..._logging import logger
-from ...event import UserConfirmResultEvent, ExternalExecutionResultEvent
+from ...event import (
+ ExternalExecutionResultEvent,
+ UserConfirmResultEvent,
+ UserInterruptEvent,
+)
from ..message_bus import MessageBusKeys
from .._bus_ops import enqueue_run_trigger
@@ -42,9 +46,9 @@ if TYPE_CHECKING:
from ._chat_run_registry import ChatRunRegistry
# Parses a queued ``resume`` input dict back into its concrete event,
-# discriminated by the ``type`` field shared by both result events.
+# discriminated by the ``type`` field shared by these result events.
_RESUME_INPUT_ADAPTER: TypeAdapter = TypeAdapter(
- UserConfirmResultEvent | ExternalExecutionResultEvent,
+ UserConfirmResultEvent | ExternalExecutionResultEvent | UserInterruptEvent,
)
# Delay before re-queuing a ``resume`` trigger whose target session is
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 54ee04199..340e57ab8 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -46,6 +46,7 @@ from ._knowledge_base import (
from ._session import (
CreateSessionRequest,
CreateSessionResponse,
+ InterruptSessionResponse,
UpdateSessionRequest,
ListSessionsResponse,
ListMessagesResponse,
@@ -105,6 +106,7 @@ __all__ = [
# Session
"CreateSessionRequest",
"CreateSessionResponse",
+ "InterruptSessionResponse",
"UpdateSessionRequest",
"ListSessionsResponse",
"ListMessagesResponse",
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index 7eeba221f..e9832102d 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -208,3 +208,25 @@ class SessionStatusResponse(BaseModel):
"on external executor)."
),
)
+
+
+class InterruptSessionResponse(BaseModel):
+ """Response body for ``POST /sessions/{sid}/interrupt`` (HTTP 202).
+
+ The interrupt operation is idempotent and always succeeds for an
+ existing session (only ``404`` is raised when the session id does
+ not exist):
+
+ - If the session is **running**, an interrupt signal is published
+ so the local
+ :class:`~agentscope.app._manager.CancelDispatcher` cancels the
+ chat-run task; the agent then runs its ``CancelledError`` cleanup
+ path.
+ - If the session is **parked** on HITL / external execution, a
+ resume trigger carrying a
+ :class:`~agentscope.event.UserInterruptEvent` is enqueued so the
+ agent short-circuits into the same cleanup path.
+ - If the session is **idle**, the call is a no-op.
+ """
+
+ session_id: str = Field(description="Echo of the interrupted session id.")
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index 951d9e783..ef5e0dbdc 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -9,6 +9,7 @@ from fastapi.responses import StreamingResponse
from ..._utils._common import _generate_id
from ..deps import (
+ get_chat_service,
get_current_user_id,
get_message_bus,
get_session_service,
@@ -17,6 +18,7 @@ from ..deps import (
from ._schema import (
CreateSessionRequest,
CreateSessionResponse,
+ InterruptSessionResponse,
ListMessagesResponse,
ListSessionsResponse,
SessionStatusResponse,
@@ -26,7 +28,12 @@ from ._schema import (
UpdateSessionRequest,
)
from ..message_bus import MessageBus, MessageBusKeys
-from .._service import SessionService, SessionProjection, SubagentHitlProjector
+from .._service import (
+ ChatService,
+ SessionService,
+ SessionProjection,
+ SubagentHitlProjector,
+)
from ..storage import (
AgentRecord,
ChatModelConfig,
@@ -335,6 +342,49 @@ async def delete_session(
)
+@session_router.post(
+ "/{session_id}/interrupt",
+ status_code=status.HTTP_202_ACCEPTED,
+ summary="Interrupt a running or HITL-parked chat run for a session",
+ responses={
+ 404: {"description": "Session not found."},
+ },
+)
+async def interrupt_session(
+ session_id: str,
+ agent_id: str = Query(description="Agent the session belongs to."),
+ user_id: str = Depends(get_current_user_id),
+ chat_service: ChatService = Depends(get_chat_service),
+) -> InterruptSessionResponse:
+ """Request interruption of an in-progress reply for a session.
+
+ Thin HTTP wrapper around :meth:`ChatService.interrupt`; see that
+ method for the running vs not-running dispatch. Idempotent — an
+ idle target session is a silent no-op at the agent layer.
+
+ Args:
+ session_id: The session whose reply should be interrupted.
+ agent_id: The agent that owns the session.
+ user_id: Injected authenticated user id.
+ chat_service: Injected chat service.
+
+ Returns:
+ 202 with :class:`InterruptSessionResponse` echoing the
+ session id.
+
+ Raises:
+ HTTPException: 404 if the session does not exist.
+ """
+ try:
+ await chat_service.interrupt(user_id, session_id, agent_id)
+ except LookupError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=str(e),
+ ) from e
+ return InterruptSessionResponse(session_id=session_id)
+
+
@session_router.patch(
"/{session_id}",
response_model=SessionRecord,
@@ -646,7 +696,7 @@ async def stream_session_events(
MessageBusKeys.session_events(session_id),
max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,
):
- yield f"data: {json.dumps(event)}\n\n"
+ yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
# 1b. Inject pending subagent HITL cards projected onto this
# session as a team leader (design §3.5). These live in a
@@ -682,7 +732,12 @@ async def stream_session_events(
name=SubagentHitlProjector.EVT_REQUIRE,
value=payload,
)
- yield f"data: {json.dumps(custom.model_dump(mode='json'))}\n\n"
+ data = json.dumps(
+ custom.model_dump(mode="json"),
+ ensure_ascii=False,
+ )
+
+ yield f"data: {data}\n\n"
# 2. Live subscribe via a background feeder task that pushes
# events into a queue. The main loop reads from the queue
@@ -726,7 +781,7 @@ async def stream_session_events(
)
if item is None:
break
- yield f"data: {json.dumps(item)}\n\n"
+ yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"
except asyncio.TimeoutError:
yield ":\n\n"
finally:
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index a6e9b03c7..6ef52cefc 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -11,10 +11,12 @@ Events produced by the agent are not exposed back through this method
that wants them subscribes through the
``GET /sessions/{sid}/stream`` SSE endpoint.
"""
+import asyncio
+
from fastapi import HTTPException
+from .._bus_ops import enqueue_run_trigger, publish_session_event
from ..message_bus import MessageBus, MessageBusKeys
-from .._bus_ops import publish_session_event
from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
from ..storage import StorageBase, AgentRecord, SessionRecord
from .._manager import BackgroundTaskManager, SchedulerManager
@@ -45,6 +47,7 @@ from ...event import (
ReplyStartEvent,
UserConfirmResultEvent,
ExternalExecutionResultEvent,
+ UserInterruptEvent,
)
from ...message import AssistantMsg, Msg, ToolCallState
from ...permission import AdditionalWorkingDirectory
@@ -157,6 +160,7 @@ class ChatService:
| list[Msg]
| UserConfirmResultEvent
| ExternalExecutionResultEvent
+ | UserInterruptEvent
| None = None,
) -> None:
"""Drive a chat run to completion.
@@ -192,6 +196,9 @@ class ChatService:
- ``UserConfirmResultEvent`` /
``ExternalExecutionResultEvent``: resume an awaiting
tool call (Case B).
+ - ``UserInterruptEvent``: abort a parked reply — the
+ agent closes pending tool calls with interrupted
+ results and ends the reply (Case B, no reasoning).
"""
try:
await self._run_impl(user_id, session_id, agent_id, input_msg)
@@ -205,6 +212,65 @@ class ChatService:
str(e),
)
+ async def interrupt(
+ self,
+ user_id: str,
+ session_id: str,
+ agent_id: str,
+ ) -> None:
+ """Interrupt an in-progress reply for a session.
+
+ Two paths, chosen by session liveness:
+
+ - **Running** (lock held): publish on the interrupt channel so
+ the local :class:`~agentscope.app._manager.CancelDispatcher`
+ cancels its chat-run task; the agent's ``CancelledError``
+ cleanup runs (fake tool results for pending calls, fallback
+ message, ``ReplyEndEvent(INTERRUPTED)``).
+ - **Not running**: enqueue a ``resume`` trigger carrying a
+ :class:`UserInterruptEvent`. If the session is parked on
+ HITL, the agent short-circuits into the same cleanup path;
+ if it is idle, the agent silently no-ops. Callers do not
+ need to distinguish the two — the operation is idempotent.
+
+ Args:
+ user_id (`str`):
+ Authenticated caller's user id.
+ session_id (`str`):
+ Target session id.
+ agent_id (`str`):
+ Agent that owns the session.
+
+ Raises:
+ LookupError:
+ The session does not exist.
+ """
+ session = await self._storage.get_session(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ if session is None:
+ raise LookupError(f"Session '{session_id}' not found.")
+
+ if await self._message_bus.is_locked(
+ MessageBusKeys.session_lock(session_id),
+ ):
+ await self._message_bus.publish(
+ MessageBusKeys.session_interrupt_channel(),
+ {"session_id": session_id},
+ )
+ return
+
+ await enqueue_run_trigger(
+ self._message_bus,
+ user_id=user_id,
+ session_id=session_id,
+ agent_id=agent_id,
+ kind=MessageBusKeys.WAKEUP_KIND_RESUME,
+ inputs=UserInterruptEvent(reply_id=session.state.reply_id),
+ )
+
async def _run_impl(
self,
user_id: str,
@@ -214,6 +280,7 @@ class ChatService:
| list[Msg]
| UserConfirmResultEvent
| ExternalExecutionResultEvent
+ | UserInterruptEvent
| None,
) -> None:
"""The actual chat-run body; wrapped by :meth:`run` for error
@@ -445,9 +512,8 @@ class ChatService:
lock_key,
ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,
):
+ reply_msg: Msg | None = None
try:
- reply_msg: Msg | None = None
-
if input_msg is None or isinstance(input_msg, (Msg, list)):
# Case A: new reply (user message(s), or retrigger with
# empty input)
@@ -520,27 +586,36 @@ class ChatService:
if reply_msg is not None:
reply_msg.append_event(event)
- # Persist the reply Msg (upsert: overwrite if same id,
- # append if new).
- if reply_msg is not None:
- await self._storage.upsert_message(
- user_id,
- session_id,
- reply_msg,
+ finally:
+ # All persistence in a single coroutine, shielded from
+ # outer cancellation. Must complete BEFORE the session
+ # lock is released — otherwise another worker could
+ # acquire the lock and load a stale state from storage
+ # before this write lands.
+ async def _persist() -> None:
+ if reply_msg is not None:
+ await self._storage.upsert_message(
+ user_id,
+ session_id,
+ reply_msg,
+ )
+ await self._storage.update_session_state(
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ state=agent.state,
)
+ await self._message_bus.log_trim(events_key)
- # Persist the updated agent state. MUST happen inside
- # the session lock: if we released the lock first,
- # another process could acquire it and load a stale
- # state from storage before this write lands.
- await self._storage.update_session_state(
- user_id=user_id,
- agent_id=agent_id,
- session_id=session_id,
- state=agent.state,
- )
- finally:
- await self._message_bus.log_trim(events_key)
+ persist_task = asyncio.create_task(_persist())
+ try:
+ await asyncio.shield(persist_task)
+ except asyncio.CancelledError:
+ # Await the shielded task so the lock is only
+ # released after storage is consistent, then
+ # propagate to honour asyncio semantics.
+ await persist_task
+ raise
async def _project_event(
self,
diff --git a/src/agentscope/app/_service/_session_projection.py b/src/agentscope/app/_service/_session_projection.py
index eaa50b0ca..bf6f33d50 100644
--- a/src/agentscope/app/_service/_session_projection.py
+++ b/src/agentscope/app/_service/_session_projection.py
@@ -87,7 +87,7 @@ class SessionProjection:
await self._bus.registry_set(
MessageBusKeys.projection_namespace(target_sid),
MessageBusKeys.projection_field(kind, entry_id),
- json.dumps(payload),
+ json.dumps(payload, ensure_ascii=False),
)
async def delete(
diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.py
index 2d4e1773c..d1d336bb7 100644
--- a/src/agentscope/app/message_bus/_keys.py
+++ b/src/agentscope/app/message_bus/_keys.py
@@ -167,6 +167,7 @@ class MessageBusKeys:
_SESSION_CANCEL = "agentscope:session:cancel"
_TASK_CANCEL = "agentscope:task:cancel"
+ _SESSION_INTERRUPT = "agentscope:session:interrupt"
@classmethod
def session_cancel_channel(cls) -> str:
@@ -178,6 +179,17 @@ class MessageBusKeys:
"""Single-task cancel broadcast channel."""
return cls._TASK_CANCEL
+ @classmethod
+ def session_interrupt_channel(cls) -> str:
+ """Global session-interrupt broadcast channel.
+
+ Used by the interrupt API endpoint to request graceful
+ interruption of a running agent. Separate from
+ ``session_cancel_channel`` (which is used for hard-cancel on
+ session deletion).
+ """
+ return cls._SESSION_INTERRUPT
+
# ------------------------------------------------------------------
# Background task registry
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.py
index d6d6b8880..57341145f 100644
--- a/src/agentscope/app/message_bus/_redis_message_bus.py
+++ b/src/agentscope/app/message_bus/_redis_message_bus.py
@@ -219,7 +219,7 @@ class RedisMessageBus(MessageBus):
"""
entry_id = await self._client.xadd(
key,
- {"payload": json.dumps(payload)},
+ {"payload": json.dumps(payload, ensure_ascii=False)},
)
if ttl_secs is not None:
await self._client.expire(key, ttl_secs)
@@ -316,7 +316,7 @@ class RedisMessageBus(MessageBus):
kwargs["approximate"] = True
entry_id = await self._client.xadd(
key,
- {"payload": json.dumps(payload)},
+ {"payload": json.dumps(payload, ensure_ascii=False)},
**kwargs,
)
if ttl_secs is not None:
@@ -483,7 +483,10 @@ class RedisMessageBus(MessageBus):
JSON-serializable dict; encoded as the channel
message body.
"""
- await self._client.publish(key, json.dumps(payload))
+ await self._client.publish(
+ key,
+ json.dumps(payload, ensure_ascii=False),
+ )
async def subscribe(
self,
diff --git a/src/agentscope/event/__init__.py b/src/agentscope/event/__init__.py
index d03d7278a..a7b0b55ac 100644
--- a/src/agentscope/event/__init__.py
+++ b/src/agentscope/event/__init__.py
@@ -5,6 +5,7 @@ from ._event import (
EventType,
EventBase,
ReplyStartEvent,
+ ReplyEndReason,
ReplyEndEvent,
ModelCallStartEvent,
ModelCallEndEvent,
@@ -29,6 +30,7 @@ from ._event import (
RequireUserConfirmEvent,
RequireExternalExecutionEvent,
UserConfirmResultEvent,
+ UserInterruptEvent,
ExternalExecutionResultEvent,
CustomEvent,
AgentEvent,
@@ -40,6 +42,7 @@ __all__ = [
"EventType",
"EventBase",
"ReplyStartEvent",
+ "ReplyEndReason",
"ReplyEndEvent",
"ModelCallStartEvent",
"ModelCallEndEvent",
@@ -64,6 +67,7 @@ __all__ = [
"RequireUserConfirmEvent",
"RequireExternalExecutionEvent",
"UserConfirmResultEvent",
+ "UserInterruptEvent",
"ExternalExecutionResultEvent",
"CustomEvent",
"AgentEvent",
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index e1d71c75d..2104b69e3 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -14,6 +14,7 @@ from ..message import (
ToolResultBlock,
ToolResultState,
)
+from ..model import FinishedReason
from ..permission import PermissionRule
@@ -55,6 +56,7 @@ class EventType(StrEnum):
REQUIRE_EXTERNAL_EXECUTION = "REQUIRE_EXTERNAL_EXECUTION"
USER_CONFIRM_RESULT = "USER_CONFIRM_RESULT"
+ USER_INTERRUPT = "USER_INTERRUPT"
EXTERNAL_EXECUTION_RESULT = "EXTERNAL_EXECUTION_RESULT"
CUSTOM = "CUSTOM"
@@ -88,6 +90,14 @@ class ReplyStartEvent(EventBase):
"""Role of the agent."""
+class ReplyEndReason(StrEnum):
+ """The reason for reply ended."""
+
+ COMPLETED = "completed"
+ INTERRUPTED = "interrupted"
+ EXCEED_MAX_ITERS = "exceed_max_iters"
+
+
class ReplyEndEvent(EventBase):
"""Reply end event."""
@@ -97,6 +107,8 @@ class ReplyEndEvent(EventBase):
"""ID of the session this reply belongs to."""
reply_id: str
"""ID of the reply message produced by this reply."""
+ finished_reason: ReplyEndReason = ReplyEndReason.COMPLETED
+ """The finished reason of this reply."""
class ModelCallStartEvent(EventBase):
@@ -121,6 +133,10 @@ class ModelCallEndEvent(EventBase):
"""Number of input tokens consumed."""
output_tokens: int
"""Number of output tokens generated."""
+ finished_reason: FinishedReason = Field(
+ default=FinishedReason.COMPLETED,
+ )
+ """The finished reason of this model call."""
class TextBlockStartEvent(EventBase):
@@ -428,6 +444,31 @@ class UserConfirmResultEvent(EventBase):
"""Confirmation results for each pending tool call."""
+class UserInterruptEvent(EventBase):
+ """User-initiated interrupt targeting a parked reply.
+
+ Delivered to :meth:`Agent.reply_stream` (or :meth:`Agent.reply`) to
+ abort a reply that is currently waiting on external input — either
+ user confirmation (:class:`RequireUserConfirmEvent`) or external
+ execution (:class:`RequireExternalExecutionEvent`).
+
+ On receipt, the agent closes every pending tool call with an
+ interrupted tool result, emits a fallback assistant message, ends
+ the reply with :attr:`ReplyEndReason.INTERRUPTED`, and does **not**
+ enter the reasoning-acting loop.
+
+ .. note:: This event is only meaningful for parked replies. To
+ interrupt a running (actively-generating) reply, cancel the
+ underlying task instead — the agent handles that path via its
+ own ``CancelledError`` cleanup.
+ """
+
+ type: Literal[EventType.USER_INTERRUPT] = EventType.USER_INTERRUPT
+ """Event type."""
+ reply_id: str
+ """ID of the reply message this interrupt targets."""
+
+
class ExternalExecutionResultEvent(EventBase):
"""External execution result event."""
@@ -501,6 +542,7 @@ AgentEvent: TypeAlias = (
| ToolResultDataDeltaEvent
| ToolResultEndEvent
| UserConfirmResultEvent
+ | UserInterruptEvent
| ExternalExecutionResultEvent
| CustomEvent
)
diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.py
index 293af1879..241fb09cc 100644
--- a/src/agentscope/message/_base.py
+++ b/src/agentscope/message/_base.py
@@ -439,7 +439,10 @@ class Msg(BaseModel):
case EventType.USER_CONFIRM_RESULT:
for result in event.confirm_results:
b = self._find_block("tool_call", result.tool_call.id)
- if b is not None:
+ # Only ASKING calls can transition; skip stale results
+ # (e.g. arriving after an interrupt already resolved the
+ # tool call).
+ if b is not None and b.state == ToolCallState.ASKING:
assert isinstance(b, ToolCallBlock)
b.state = (
ToolCallState.ALLOWED
@@ -455,7 +458,16 @@ class Msg(BaseModel):
b.state = ToolCallState.SUBMITTED
case EventType.EXTERNAL_EXECUTION_RESULT:
+ # Skip results whose tool_call already has a tool_result
+ # (e.g. late arrival after an interrupt).
+ existing_ids = {
+ b.id
+ for b in self.content
+ if isinstance(b, ToolResultBlock)
+ }
for result in event.execution_results:
+ if result.id in existing_ids:
+ continue
self.content.append(result)
return self
diff --git a/src/agentscope/model/__init__.py b/src/agentscope/model/__init__.py
index 91386556d..e7bf1b83f 100644
--- a/src/agentscope/model/__init__.py
+++ b/src/agentscope/model/__init__.py
@@ -3,7 +3,7 @@
from ._base import ChatModelBase
from ._model_card import ModelCard
-from ._model_response import ChatResponse, StructuredResponse
+from ._model_response import ChatResponse, StructuredResponse, FinishedReason
from ._model_usage import ChatUsage
from ._anthropic import AnthropicChatModel
from ._dashscope import DashScopeChatModel
@@ -19,6 +19,7 @@ __all__ = [
"ChatUsage",
"ChatModelBase",
"ChatResponse",
+ "FinishedReason",
"ModelCard",
"StructuredResponse",
"AnthropicChatModel",
diff --git a/src/agentscope/model/_anthropic/_model.py b/src/agentscope/model/_anthropic/_model.py
index 426a85ac8..18cbb5835 100644
--- a/src/agentscope/model/_anthropic/_model.py
+++ b/src/agentscope/model/_anthropic/_model.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""The Anthropic chat model implementation."""
+import json
from collections import OrderedDict
from datetime import datetime
from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
@@ -9,6 +10,7 @@ from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
+from ..._utils._common import _generate_id
from ...credential import AnthropicCredential
from ...formatter import FormatterBase, AnthropicChatFormatter
from ...message import Msg, ThinkingBlock, ToolCallBlock, TextBlock
@@ -261,13 +263,14 @@ class AnthropicChatModel(ChatModelBase):
hasattr(content_block, "type")
and content_block.type == "tool_use"
):
- import json
-
content_blocks.append(
ToolCallBlock(
id=content_block.id,
name=content_block.name,
- input=json.dumps(content_block.input),
+ input=json.dumps(
+ content_block.input,
+ ensure_ascii=False,
+ ),
),
)
@@ -323,21 +326,22 @@ class AnthropicChatModel(ChatModelBase):
"""
usage = None
- response_id: str | None = None
- # All delta should have the same block identifier
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- thinking_signature = ""
- # index -> {id, name, input}
- acc_tool_calls: OrderedDict = OrderedDict()
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ # The mapping from index to tool call id
+ tool_call_mapping: dict = OrderedDict()
async for event in response:
- delta_content: list = []
+ delta_res = ChatResponse(content=[], is_last=False, id=response_id)
if event.type == "message_start":
message = event.message
- if response_id is None:
- response_id = getattr(message, "id", None)
+
+ # Update the response ID if exists
+ response_id = getattr(message, "id", None) or response_id
+ delta_res.id = response_id
+
if message.usage:
u = message.usage
usage = ChatUsage(
@@ -358,86 +362,61 @@ class AnthropicChatModel(ChatModelBase):
elif event.type == "content_block_start":
if event.content_block.type == "tool_use":
- block_index = event.index
tool_block = event.content_block
- acc_tool_calls[block_index] = {
- "id": tool_block.id,
- "name": tool_block.name,
- "input": "",
- }
+ # Record the id and name
+ tool_call_mapping[event.index] = (
+ tool_block.id,
+ tool_block.name,
+ )
+ # New tool call block with empty input
+ delta_res.append_tool_call(
+ block_id=tool_block.id,
+ name=tool_block.name,
+ input="",
+ )
elif event.type == "content_block_delta":
block_index = event.index
delta = event.delta
+
+ # Text block
if delta.type == "text_delta":
- acc_text.text += delta.text
- delta_content.append(
- TextBlock(id=acc_text.id, text=delta.text),
- )
+ delta_res.append_text(delta.text, block_id=text_id)
+
+ # Thinking block
elif delta.type == "thinking_delta":
- acc_thinking.thinking += delta.thinking
- delta_content.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta.thinking,
- ),
+ delta_res.append_thinking(
+ delta.thinking,
+ block_id=thinking_id,
)
+
+ # Special handling for Anthropic API that requires signature
elif delta.type == "signature_delta":
- thinking_signature = delta.signature
+ delta_res.append_thinking(
+ "",
+ block_id=thinking_id,
+ signature=delta.signature,
+ )
+
+ # Tool call block
elif (
delta.type == "input_json_delta"
- and block_index in acc_tool_calls
+ and block_index in tool_call_mapping
):
- fragment = delta.partial_json or ""
- acc_tool_calls[block_index]["input"] += fragment
- tc = acc_tool_calls[block_index]
- delta_content.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=fragment,
- ),
+ block_id, name = tool_call_mapping[block_index]
+ delta_res.append_tool_call(
+ block_id=block_id,
+ name=name,
+ input=delta.partial_json or "",
)
elif event.type == "message_delta":
if event.usage and usage:
usage.output_tokens = event.usage.output_tokens
- if delta_content:
- _kwargs: dict[str, Any] = {
- "content": delta_content,
- "is_last": False,
- "usage": usage,
- }
- if response_id:
- _kwargs["id"] = response_id
- yield ChatResponse(**_kwargs)
-
- # Build final accumulated content
- final_content: list = []
- if acc_thinking.thinking:
- acc_thinking.signature = thinking_signature
- final_content.append(acc_thinking)
- if acc_text.text:
- final_content.append(acc_text)
- for tc in acc_tool_calls.values():
- input_str = tc["input"]
- final_content.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=input_str,
- ),
- )
-
- _final_kwargs: dict[str, Any] = {
- "content": final_content,
- "is_last": True,
- "usage": usage,
- }
- if response_id:
- _final_kwargs["id"] = response_id
- yield ChatResponse(**_final_kwargs)
+ if delta_res.content:
+ delta_res.usage = usage
+ yield delta_res
def _format_tools(
self,
diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.py
index 2c35370c2..c6d9bc9fc 100644
--- a/src/agentscope/model/_base.py
+++ b/src/agentscope/model/_base.py
@@ -11,7 +11,7 @@ from typing import Type, Any, AsyncGenerator
import jsonschema
from pydantic import BaseModel
-from ._model_response import StructuredResponse, ChatResponse
+from ._model_response import StructuredResponse, ChatResponse, FinishedReason
from ._model_card import ModelCard
from .._logging import logger
from .._utils._common import _json_loads_with_repair
@@ -178,17 +178,26 @@ class ChatModelBase:
Additional keyword arguments passed to the underlying API.
"""
- retryable = tuple(self._get_retryable_exceptions())
+ retryable = self._get_retryable_exceptions()
last_error: Exception | None = None
for attempt in range(self.max_retries + 1):
+ # The accumulated chat response
try:
- return await self._call_api(
+ res = await self._call_api(
self.model,
messages=messages,
tools=tools,
tool_choice=tool_choice,
**kwargs,
)
+ break
+ except asyncio.CancelledError:
+ return ChatResponse(
+ content=[],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ )
+
except Exception as e:
if not isinstance(e, retryable):
raise
@@ -209,13 +218,58 @@ class ChatModelBase:
self.max_retries + 1,
self.model,
)
- if last_error is not None:
- raise last_error
- raise RuntimeError(
- f"Failed to call model {self.model} after "
- f"{self.max_retries + 1} retries.",
+ else:
+ if last_error is not None:
+ raise last_error
+ raise RuntimeError(
+ f"Failed to call model {self.model} after "
+ f"{self.max_retries + 1} retries.",
+ )
+
+ # =====================================================================
+ # Consume the model calling result
+ # =====================================================================
+ if isinstance(res, ChatResponse):
+ return res
+
+ # The accumulated chat response
+ acc_res = ChatResponse(
+ content=[],
+ is_last=True,
+ finished_reason=FinishedReason.COMPLETED,
)
+ async def _stream() -> AsyncGenerator[ChatResponse, None]:
+ """The wrapper around model calling."""
+ # For backward compatibility
+ yield_acc_res = True
+ try:
+ async for chunk in res:
+ if not chunk.is_last:
+ acc_res.append_chat_response(chunk)
+ acc_res.id = chunk.id
+ # Empty-content deltas are "carrier" chunks used
+ # by subclasses to propagate usage / id metadata
+ # (e.g. OpenAI-compatible APIs emit a trailing
+ # usage-only chunk with no choices). We absorb
+ # their metadata into ``acc_res`` above but do
+ # not surface them to the consumer, which keeps
+ # the visible stream free of spurious empty
+ # deltas.
+ if not chunk.content:
+ continue
+ else:
+ yield_acc_res = False
+ yield chunk
+ except asyncio.CancelledError:
+ acc_res.finished_reason = FinishedReason.INTERRUPTED
+ yield_acc_res = True
+
+ if yield_acc_res:
+ yield acc_res
+
+ return _stream()
+
@abstractmethod
async def _call_api(
self,
@@ -578,4 +632,5 @@ class ChatModelBase:
created_at=completed_response.created_at,
content=structured_output,
usage=completed_response.usage,
+ finished_reason=completed_response.finished_reason,
)
diff --git a/src/agentscope/model/_dashscope/_model.py b/src/agentscope/model/_dashscope/_model.py
index b502b2e9b..a7cf78486 100644
--- a/src/agentscope/model/_dashscope/_model.py
+++ b/src/agentscope/model/_dashscope/_model.py
@@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
"""The DashScope chat model class (OpenAI-compatible implementation)."""
import base64
-import io
import warnings
-import wave
from collections import OrderedDict
from datetime import datetime
from typing import Any, AsyncGenerator, List, Literal, Type, TYPE_CHECKING
@@ -22,8 +20,6 @@ from ...message import (
TextBlock,
ThinkingBlock,
ToolCallBlock,
- DataBlock,
- Base64Source,
)
from ...tool import ToolChoice
@@ -291,23 +287,30 @@ class DashScopeChatModel(ChatModelBase):
Incremental ``ChatResponse`` objects with ``is_last=False``
followed by a final one with ``is_last=True``.
"""
- usage = None
- response_id: str | None = None
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: OrderedDict = OrderedDict()
- # Raw PCM bytes accumulated across chunks. Storing the decoded form
- # (rather than concatenated base64 strings) avoids the risk of
- # corrupting the byte stream when an intermediate chunk happens to
- # carry base64 padding (``=``).
- acc_audio_data: bytearray = bytearray()
- audio_block_id: str | None = None
# ``True`` once the first audio chunk has been prefixed with a
# streaming WAV header and yielded.
audio_header_sent: bool = False
+ usage = None
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ audio_id = _generate_id()
+ # The mapping from index to tool call id
+ tool_call_mapping: dict = OrderedDict()
+
async with response as stream:
async for chunk in stream:
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
+
+ # Update the response ID if exists
+ response_id = getattr(chunk, "id", None) or response_id
+ delta_res.id = response_id
+
if chunk.usage:
u = chunk.usage
ptd = getattr(u, "prompt_tokens_details", None)
@@ -322,158 +325,81 @@ class DashScopeChatModel(ChatModelBase):
cache_input_tokens=cache_read,
)
- response_id = response_id or getattr(chunk, "id", None)
-
if not chunk.choices:
+ if usage is not None:
+ delta_res.usage = usage
+ yield delta_res
continue
choice = chunk.choices[0]
delta = choice.delta
- delta_thinking = (
- getattr(delta, "reasoning_content", None) or ""
- )
- delta_text = getattr(delta, "content", None) or ""
-
- # Collect audio output from Omni models (delta.audio.data).
- # Upstream sends raw PCM (24kHz, 16-bit mono); we prefix the
- # first chunk with a streaming WAV header so the frontend
- # can start playback immediately rather than waiting for
- # end-of-stream.
- delta_audio = getattr(delta, "audio", None)
- delta_audio_block: DataBlock | None = None
- if delta_audio is not None:
+ # Thinking
+ if getattr(delta, "reasoning_content", None):
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=delta.reasoning_content,
+ )
+
+ # Text
+ if getattr(delta, "content", None):
+ delta_res.append_text(
+ block_id=text_id,
+ text=delta.content,
+ )
+
+ # Tool call
+ for tool_call in getattr(delta, "tool_calls", None) or []:
+ index = tool_call.index
+ fn = getattr(tool_call, "function", None)
+ delta_name = getattr(fn, "name", None) if fn else None
+ delta_args = getattr(fn, "arguments", None) if fn else None
+
+ # Record the id and name in case following deltas
+ # don't provide them
+ if index not in tool_call_mapping:
+ tool_call_mapping[index] = (
+ tool_call.id,
+ delta_name or "unknown",
+ )
+
+ stored_id, stored_name = tool_call_mapping[index]
+
+ delta_res.append_tool_call(
+ block_id=tool_call.id or stored_id,
+ name=delta_name or stored_name,
+ input=delta_args or "",
+ )
+
+ # Data block
+ if getattr(delta, "audio", None):
+ delta_audio = getattr(delta, "audio", None)
if isinstance(delta_audio, dict):
audio_chunk = delta_audio.get("data", "")
else:
- audio_chunk = getattr(delta_audio, "data", "") or ""
+ audio_chunk = getattr(delta_audio, "data", "")
+
if audio_chunk:
- if audio_block_id is None:
- audio_block_id = _generate_id()
pcm_bytes = base64.b64decode(audio_chunk)
- acc_audio_data += pcm_bytes
if not audio_header_sent:
payload = _build_streaming_wav_header() + pcm_bytes
audio_header_sent = True
else:
payload = pcm_bytes
- delta_audio_block = DataBlock(
- id=audio_block_id,
- source=Base64Source(
- data=base64.b64encode(payload).decode(
- "ascii",
- ),
- media_type="audio/wav",
- ),
+ # ``append_data_block`` expects the raw incremental
+ # media bytes and handles base64 encoding internally
+ # (see ``ChatResponse.append_data_block``); passing an
+ # already base64-encoded string here would result in
+ # double-encoding.
+ delta_res.append_data_block(
+ block_id=audio_id,
+ data=payload,
+ media_type="audio/wav",
)
- acc_thinking.thinking += delta_thinking
- acc_text.text += delta_text
-
- delta_tool_call_blocks: List[ToolCallBlock] = []
- for tool_call in getattr(delta, "tool_calls", None) or []:
- idx = tool_call.index
- args = (
- tool_call.function.arguments
- if tool_call.function
- else ""
- ) or ""
- if idx in acc_tool_calls:
- acc_tool_calls[idx]["input"] += args
- else:
- acc_tool_calls[idx] = {
- "id": tool_call.id or "",
- "name": (
- tool_call.function.name
- if tool_call.function
- else ""
- ),
- "input": args,
- }
- tc = acc_tool_calls[idx]
- delta_tool_call_blocks.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=args,
- ),
- )
-
- delta_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock | DataBlock
- ] = []
- if delta_thinking:
- delta_contents.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta_thinking,
- ),
- )
- if delta_text:
- delta_contents.append(
- TextBlock(id=acc_text.id, text=delta_text),
- )
- delta_contents.extend(delta_tool_call_blocks)
- if delta_audio_block is not None:
- delta_contents.append(delta_audio_block)
-
- if delta_contents:
- _kwargs: dict[str, Any] = {
- "content": delta_contents,
- "usage": usage,
- "is_last": False,
- }
- if response_id:
- _kwargs["id"] = response_id
- yield ChatResponse(**_kwargs)
-
- final_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock | DataBlock
- ] = []
- if acc_thinking.thinking:
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
- for tc in acc_tool_calls.values():
- final_contents.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=tc["input"],
- ),
- )
- if acc_audio_data:
- # PCM bytes were already streamed incrementally above (first
- # chunk prefixed with a WAV header). Here we also assemble a
- # standalone fixed-size WAV and attach it to the ``is_last``
- # chunk so callers that consume the model directly (i.e.
- # without going through ``Agent``, which filters audio blocks
- # out of context) get a self-contained audio block for
- # downstream serialization / display.
- buf = io.BytesIO()
- with wave.open(buf, "wb") as wav:
- wav.setnchannels(1)
- wav.setsampwidth(2)
- wav.setframerate(24000)
- wav.writeframes(bytes(acc_audio_data))
- final_contents.append(
- DataBlock(
- id=audio_block_id,
- source=Base64Source(
- data=base64.b64encode(buf.getvalue()).decode("ascii"),
- media_type="audio/wav",
- ),
- ),
- )
-
- _final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "usage": usage,
- "is_last": True,
- }
- if response_id:
- _final_kwargs["id"] = response_id
- yield ChatResponse(**_final_kwargs)
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_deepseek/_model.py b/src/agentscope/model/_deepseek/_model.py
index 56d5fbb34..b04cd31e2 100644
--- a/src/agentscope/model/_deepseek/_model.py
+++ b/src/agentscope/model/_deepseek/_model.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
+from ..._utils._common import _generate_id
from ...credential import DeepSeekCredential
from ...formatter import FormatterBase, DeepSeekChatFormatter
from ...message import Msg, ThinkingBlock, ToolCallBlock, TextBlock
@@ -242,14 +243,24 @@ class DeepSeekChatModel(ChatModelBase):
followed by a final one with ``is_last=True``.
"""
usage = None
- response_id: str | None = None
- # All delta should have the same block identifier
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: OrderedDict = OrderedDict()
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ # The mapping from index to tool call id
+ tool_call_mapping: dict = OrderedDict()
async with response as stream:
async for chunk in stream:
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
+
+ # Update the response ID if exists
+ response_id = getattr(chunk, "id", None) or response_id
+ delta_res.id = response_id
+
if chunk.usage:
u = chunk.usage
usage = ChatUsage(
@@ -263,92 +274,60 @@ class DeepSeekChatModel(ChatModelBase):
),
)
- # Capture response_id from the first chunk that carries it
- response_id = response_id or getattr(chunk, "id", None)
-
if not chunk.choices:
+ # DeepSeek emits a trailing usage-only chunk with no
+ # choices; forward it as an empty-content delta so the
+ # base class ``__call__`` can absorb ``usage`` into
+ # ``acc_res``. The empty delta itself is filtered out
+ # of the surfaced stream by ``_stream``.
+ if usage is not None:
+ delta_res.usage = usage
+ yield delta_res
continue
choice = chunk.choices[0]
delta = choice.delta
- delta_thinking = (
- getattr(delta, "reasoning_content", None) or ""
- )
- delta_text = getattr(delta, "content", None) or ""
-
- acc_thinking.thinking += delta_thinking
- acc_text.text += delta_text
-
- delta_tool_call_blocks: List[ToolCallBlock] = []
- for tool_call in getattr(delta, "tool_calls", None) or []:
- idx = tool_call.index
- args = tool_call.function.arguments or ""
- if idx in acc_tool_calls:
- acc_tool_calls[idx]["input"] += args
- else:
- acc_tool_calls[idx] = {
- "id": tool_call.id,
- "name": tool_call.function.name,
- "input": args,
- }
- tc = acc_tool_calls[idx]
- delta_tool_call_blocks.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=args,
- ),
+ # Thinking block
+ if getattr(delta, "reasoning_content", None):
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=delta.reasoning_content,
)
- delta_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock
- ] = []
- if delta_thinking:
- delta_contents.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta_thinking,
- ),
+ # Text
+ if getattr(delta, "content", None):
+ delta_res.append_text(
+ block_id=text_id,
+ text=delta.content,
)
- if delta_text:
- delta_contents.append(
- TextBlock(id=acc_text.id, text=delta_text),
+
+ # Tool call
+ for tool_call in getattr(delta, "tool_calls", None) or []:
+ index = tool_call.index
+ fn = getattr(tool_call, "function", None)
+ delta_name = getattr(fn, "name", None) if fn else None
+ delta_args = getattr(fn, "arguments", None) if fn else None
+
+ # Record the id and name in case following deltas
+ # don't provide them
+ if index not in tool_call_mapping:
+ tool_call_mapping[index] = (
+ tool_call.id,
+ delta_name or "unknown",
+ )
+
+ stored_id, stored_name = tool_call_mapping[index]
+
+ delta_res.append_tool_call(
+ block_id=tool_call.id or stored_id,
+ name=delta_name or stored_name,
+ input=delta_args or "",
)
- delta_contents.extend(delta_tool_call_blocks)
-
- if delta_contents:
- _kwargs: dict[str, Any] = {
- "content": delta_contents,
- "usage": usage,
- "is_last": False,
- }
- if response_id:
- _kwargs["id"] = response_id
- yield ChatResponse(**_kwargs)
-
- final_contents: List[TextBlock | ToolCallBlock | ThinkingBlock] = []
- if acc_thinking.thinking:
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
- for tc in acc_tool_calls.values():
- final_contents.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=tc["input"],
- ),
- )
- _final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "usage": usage,
- "is_last": True,
- }
- if response_id:
- _final_kwargs["id"] = response_id
- yield ChatResponse(**_final_kwargs)
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_gemini/_model.py b/src/agentscope/model/_gemini/_model.py
index 3a50d7cef..3c7f1fc6f 100644
--- a/src/agentscope/model/_gemini/_model.py
+++ b/src/agentscope/model/_gemini/_model.py
@@ -318,24 +318,22 @@ class GeminiChatModel(ChatModelBase):
Incremental ``ChatResponse`` objects with ``is_last=False``
followed by a final one with ``is_last=True``.
"""
- # All delta should have the same block identifier
- # Use the API's response_id when available (it arrives at the first
- # chunk); otherwise generate a UUID to ensure all chunks share a
- # stable id.
- response_id: str | None = None
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: dict = {}
- usage = None
+
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
async for chunk in response:
# Capture response_id from the first chunk that carries it
- if response_id is None:
- response_id = (
- getattr(chunk, "response_id", None) or _generate_id()
- )
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
- delta_content: list = []
+ # Update the response ID if exists
+ response_id = getattr(chunk, "response_id", None) or response_id
+ delta_res.id = response_id
if (
chunk.candidates
@@ -344,70 +342,43 @@ class GeminiChatModel(ChatModelBase):
):
for part in chunk.candidates[0].content.parts:
if part.text:
+ # Thinking
if part.thought:
- acc_thinking.thinking += part.text
- delta_content.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=part.text,
- ),
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=part.text,
)
+
+ # Text
else:
- acc_text.text += part.text
- delta_content.append(
- TextBlock(id=acc_text.id, text=part.text),
+ delta_res.append_text(
+ block_id=text_id,
+ text=part.text,
)
+ # Tool call
if part.function_call:
- keyword_args = part.function_call.args or {}
if part.thought_signature:
call_id = base64.b64encode(
part.thought_signature,
).decode("utf-8")
else:
call_id = part.function_call.id or _generate_id()
- input_str = json.dumps(
- keyword_args,
- ensure_ascii=False,
- )
- acc_tool_calls[call_id] = {
- "name": part.function_call.name,
- "input": input_str,
- }
- delta_content.append(
- ToolCallBlock(
- id=call_id,
- name=part.function_call.name,
- input=input_str,
+
+ delta_res.append_tool_call(
+ block_id=call_id,
+ name=part.function_call.name,
+ input=json.dumps(
+ part.function_call.args or {},
+ ensure_ascii=False,
),
)
usage = self._extract_usage(chunk.usage_metadata, start_datetime)
- if delta_content:
- yield ChatResponse(
- id=response_id,
- content=delta_content,
- is_last=False,
- usage=usage,
- )
-
- final_content: list = []
- if acc_thinking.thinking:
- final_content.append(acc_thinking)
- if acc_text.text:
- final_content.append(acc_text)
- for call_id, tc in acc_tool_calls.items():
- final_content.append(
- ToolCallBlock(id=call_id, name=tc["name"], input=tc["input"]),
- )
-
- yield ChatResponse(
- id=response_id or _generate_id(),
- content=final_content,
- is_last=True,
- usage=usage,
- )
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_model_response.py b/src/agentscope/model/_model_response.py
index 0d42d55b3..aa29902ce 100644
--- a/src/agentscope/model/_model_response.py
+++ b/src/agentscope/model/_model_response.py
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
"""The model response module."""
+import base64
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Literal, Sequence
+from enum import StrEnum
+from typing import Any, Literal, Self, List
from ._model_usage import ChatUsage
from .._utils._common import _generate_id
@@ -12,15 +14,26 @@ from ..message import (
ToolCallBlock,
ThinkingBlock,
DataBlock,
+ Base64Source,
)
from ..types import JSONSerializableObject
+class FinishedReason(StrEnum):
+ """The finished reason of the model response."""
+
+ INTERRUPTED = "interrupted"
+ """The model response is interrupted by the asyncio.CancelledError."""
+
+ COMPLETED = "completed"
+ """The model response is completed."""
+
+
@dataclass
class ChatResponse(DictMixin):
"""The response of chat models."""
- content: Sequence[TextBlock | ToolCallBlock | ThinkingBlock | DataBlock]
+ content: List[TextBlock | ToolCallBlock | ThinkingBlock | DataBlock]
"""The content of the chat response, which can include text blocks,
tool use blocks, or thinking blocks."""
@@ -42,11 +55,268 @@ class ChatResponse(DictMixin):
usage: ChatUsage | None = field(default_factory=lambda: None)
"""The usage information of the chat response, if available."""
+ finished_reason: FinishedReason = field(
+ default=FinishedReason.COMPLETED,
+ )
+ """The finished reason of the chat response, available when `is_last`
+ is `True`."""
+
metadata: dict[str, JSONSerializableObject] = field(
default_factory=lambda: {},
)
"""The metadata of the chat response"""
+ def append_text(self, text: str, block_id: str | None = None) -> Self:
+ """Append text to the current response."""
+ for block in self.content:
+ if isinstance(block, TextBlock) and (
+ block_id is None or block_id == block.id
+ ):
+ block.text += text
+ return self
+
+ # Append a new block
+ assert isinstance(self.content, list)
+ self.content.append(
+ TextBlock(text=text, id=block_id or _generate_id()),
+ )
+ return self
+
+ def append_thinking(
+ self,
+ thinking: str,
+ block_id: str | None = None,
+ **extra_fields: Any,
+ ) -> Self:
+ """Append thinking to the current response.
+
+ Args:
+ thinking (`str`):
+ The thinking content to append.
+ block_id (`str | None`, defaults to `None`):
+ The id of the ``ThinkingBlock`` to accumulate into. If no
+ matching block exists in ``content``, a new one is
+ appended.
+ **extra_fields (`Any`):
+ Additional provider-specific fields to attach to the
+ ``ThinkingBlock`` (e.g. Anthropic's ``signature``, OpenAI
+ Responses API's ``reasoning_item_id``). Only non-``None``
+ values are applied.
+ """
+ for block in self.content:
+ if isinstance(block, ThinkingBlock) and (
+ block_id is None or block_id == block.id
+ ):
+ block.thinking += thinking
+ for key, value in extra_fields.items():
+ if value is not None:
+ setattr(block, key, value)
+ return self
+
+ assert isinstance(self.content, list)
+ block = ThinkingBlock(thinking=thinking, id=block_id or _generate_id())
+ for key, value in extra_fields.items():
+ if value is not None:
+ setattr(block, key, value)
+ self.content.append(block)
+ return self
+
+ def append_tool_call(
+ self,
+ block_id: str,
+ name: str,
+ input: str, # pylint: disable=redefined-builtin
+ **extra_fields: Any,
+ ) -> Self:
+ """Append tool call to the current response by tool call block ID.
+
+ Args:
+ block_id (`str`):
+ The id of the ``ToolCallBlock`` to accumulate into. If no
+ matching block exists in ``content``, a new one is
+ appended.
+ name (`str`):
+ The name of the tool being called.
+ input (`str`):
+ The incremental JSON string arguments to append.
+ **extra_fields (`Any`):
+ Additional provider-specific fields to attach to the
+ ``ToolCallBlock`` (e.g. OpenAI Responses API's
+ ``call_id``). Only non-``None`` values are applied.
+ """
+ for block in self.content:
+ if isinstance(block, ToolCallBlock) and block.id == block_id:
+ block.input += input
+ for key, value in extra_fields.items():
+ if value is not None:
+ setattr(block, key, value)
+ return self
+
+ block = ToolCallBlock(
+ id=block_id,
+ name=name,
+ input=input,
+ )
+ for key, value in extra_fields.items():
+ if value is not None:
+ setattr(block, key, value)
+ assert isinstance(self.content, list)
+ self.content.append(block)
+ return self
+
+ def append_data_block(
+ self,
+ block_id: str,
+ data: bytes,
+ media_type: str,
+ name: str | None = None,
+ ) -> Self:
+ """Append raw media bytes to the ``DataBlock`` with the given id.
+
+ The accumulated bytes are stored base64-encoded in
+ ``DataBlock.source.data`` (via a :class:`Base64Source`). Callers must
+ pass the *incremental* raw media bytes only — the method takes care
+ of base64 (de)coding internally, so consumers never have to worry
+ about base64 padding (``=``) corrupting concatenation.
+
+ .. note::
+
+ Byte-level delta accumulation only has a well-defined semantics
+ for streaming media where chunks can be safely concatenated
+ (currently ``audio/*``). For non-streamable media types
+ (e.g. ``image/*``, ``video/*``) each ``DataBlock`` should be
+ treated as a complete file and passed atomically rather than
+ accumulated through this method.
+
+ Args:
+ block_id (`str`):
+ The id of the ``DataBlock`` to accumulate into. If no
+ matching block exists in ``content``, a new one is
+ appended.
+ data (`bytes`):
+ The incremental raw media bytes to append.
+ media_type (`str`):
+ The IANA media type of the raw bytes (e.g. ``audio/pcm``,
+ ``audio/wav``). Used both to tag a newly-created block and
+ to guard against accidentally mixing bytes from different
+ media types under the same id.
+ name (`str | None`, defaults to `None`):
+ The optional ``name`` field used when a new ``DataBlock``
+ needs to be created. Ignored when an existing block with
+ ``block_id`` is found.
+
+ Returns:
+ `Self`:
+ The current ``ChatResponse`` instance for chaining.
+ """
+ for block in self.content:
+ if (
+ isinstance(block, DataBlock)
+ and block.id == block_id
+ and isinstance(block.source, Base64Source)
+ and block.source.media_type == media_type
+ ):
+ old_bytes = (
+ base64.b64decode(block.source.data)
+ if block.source.data
+ else b""
+ )
+ block.source.data = base64.b64encode(
+ old_bytes + data,
+ ).decode("ascii")
+ return self
+
+ self.content.append(
+ DataBlock(
+ id=block_id,
+ source=Base64Source(
+ data=base64.b64encode(data).decode("ascii"),
+ media_type=media_type,
+ ),
+ name=name,
+ ),
+ )
+ return self
+
+ def append_chat_response(self, chat_response: Self) -> Self:
+ """Append chat response to the current response."""
+ # Append content
+ new_block_dict = {_.id: _ for _ in chat_response.content}
+ for block in self.content:
+ if block.id in new_block_dict:
+ delta_block = new_block_dict.pop(block.id)
+ # Append data according to the block type
+ if isinstance(block, ThinkingBlock):
+ block.thinking += delta_block.thinking
+ # Provider-specific extra fields (e.g. Anthropic's
+ # ``signature``, OpenAI Responses API's
+ # ``reasoning_item_id``) are carried on the delta
+ # ``ThinkingBlock`` via pydantic's ``extra="allow"``.
+ # Copy any non-``None`` extras onto the accumulator.
+ for key, value in (delta_block.model_extra or {}).items():
+ if value is not None:
+ setattr(block, key, value)
+
+ elif isinstance(block, TextBlock):
+ block.text += delta_block.text
+
+ elif isinstance(block, ToolCallBlock):
+ block.input += delta_block.input
+ # Provider-specific extras (e.g. OpenAI Responses
+ # API's ``call_id``) may be attached on the delta
+ # block via pydantic's ``extra="allow"``.
+ for key, value in (delta_block.model_extra or {}).items():
+ if value is not None:
+ setattr(block, key, value)
+
+ elif isinstance(block, DataBlock):
+ # Only ``audio/*`` is treated as a streamable delta:
+ # callers accumulate raw media bytes across chunks and
+ # the concatenated result is a well-defined stream.
+ # For non-audio media types (``image/*``, ``video/*``,
+ # ...) each ``DataBlock`` is a complete standalone
+ # asset — byte concatenation is meaningless — so we
+ # overwrite in place with the latest delta instead.
+ if not (
+ isinstance(block.source, Base64Source)
+ and isinstance(delta_block.source, Base64Source)
+ and block.source.media_type
+ == delta_block.source.media_type
+ ):
+ # Source shape / media type mismatch: replace the
+ # whole block to avoid mixing incompatible data.
+ block.source = delta_block.source
+ elif block.source.media_type.startswith("audio/"):
+ old_bytes = (
+ base64.b64decode(block.source.data)
+ if block.source.data
+ else b""
+ )
+ delta_bytes = (
+ base64.b64decode(delta_block.source.data)
+ if delta_block.source.data
+ else b""
+ )
+ block.source.data = base64.b64encode(
+ old_bytes + delta_bytes,
+ ).decode("ascii")
+ else:
+ # Non-streamable media: latest delta wins.
+ block.source.data = delta_block.source.data
+
+ if new_block_dict:
+ # Attach new blocks to the content.
+ self.content.extend(
+ block.model_copy(deep=True)
+ for block in new_block_dict.values()
+ )
+
+ # Override the chat usage
+ if chat_response.usage:
+ self.usage = chat_response.usage
+
+ return self
+
@dataclass
class StructuredResponse:
@@ -73,3 +343,8 @@ class StructuredResponse:
default_factory=lambda: {},
)
"""The metadata of the chat response"""
+
+ finished_reason: FinishedReason = field(
+ default=FinishedReason.COMPLETED,
+ )
+ """The finished reason of the structured response."""
diff --git a/src/agentscope/model/_moonshot/_model.py b/src/agentscope/model/_moonshot/_model.py
index e4dc3d2c7..0ab3dca07 100644
--- a/src/agentscope/model/_moonshot/_model.py
+++ b/src/agentscope/model/_moonshot/_model.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
+from ..._utils._common import _generate_id
from ...credential import MoonshotCredential
from ...formatter import FormatterBase, MoonshotChatFormatter
from ...message import Msg, ThinkingBlock, ToolCallBlock, TextBlock
@@ -228,14 +229,24 @@ class MoonshotChatModel(ChatModelBase):
followed by a final one with ``is_last=True``.
"""
usage = None
- response_id: str | None = None
- # All delta should have the same block identifier
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: OrderedDict = OrderedDict()
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ # The mapping from index to tool call id
+ tool_call_mapping: dict = OrderedDict()
async with response as stream:
async for chunk in stream:
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
+
+ # Update the response ID if exists
+ response_id = getattr(chunk, "id", None) or response_id
+ delta_res.id = response_id
+
if chunk.usage:
u = chunk.usage
usage = ChatUsage(
@@ -249,96 +260,52 @@ class MoonshotChatModel(ChatModelBase):
),
)
- # Capture response_id from the first chunk that carries it
- response_id = response_id or getattr(chunk, "id", None)
-
if not chunk.choices:
continue
choice = chunk.choices[0]
delta = choice.delta
- # Thinking models (kimi-k2.6, kimi-k2-thinking) return
- # reasoning_content before content in the stream.
- delta_thinking = (
- getattr(delta, "reasoning_content", None) or ""
- )
- if delta_thinking:
- acc_thinking.thinking += delta_thinking
- _thinking_kwargs: dict[str, Any] = {
- "content": [
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta_thinking,
- ),
- ],
- "usage": usage,
- "is_last": False,
- }
- if response_id:
- _thinking_kwargs["id"] = response_id
- yield ChatResponse(**_thinking_kwargs)
- continue
-
- delta_text = getattr(delta, "content", None) or ""
- acc_text.text += delta_text
+ # Thinking
+ if getattr(delta, "reasoning_content", None):
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=delta.reasoning_content,
+ )
- delta_tool_call_blocks: List[ToolCallBlock] = []
- for tool_call in getattr(delta, "tool_calls", None) or []:
- idx = tool_call.index
- args = tool_call.function.arguments or ""
- if idx in acc_tool_calls:
- acc_tool_calls[idx]["input"] += args
- else:
- acc_tool_calls[idx] = {
- "id": tool_call.id,
- "name": tool_call.function.name,
- "input": args,
- }
- tc = acc_tool_calls[idx]
- delta_tool_call_blocks.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=args,
- ),
+ # Text
+ if getattr(delta, "content", None):
+ delta_res.append_text(
+ block_id=text_id,
+ text=delta.content,
)
- delta_contents: List[TextBlock | ToolCallBlock] = []
- if delta_text:
- delta_contents.append(
- TextBlock(id=acc_text.id, text=delta_text),
+ # Tool call
+ for tool_call in getattr(delta, "tool_calls", None) or []:
+ index = tool_call.index
+ fn = getattr(tool_call, "function", None)
+ delta_name = getattr(fn, "name", None) if fn else None
+ delta_args = getattr(fn, "arguments", None) if fn else None
+
+ # Record the id and name in case following deltas
+ # don't provide them
+ if index not in tool_call_mapping:
+ tool_call_mapping[index] = (
+ tool_call.id,
+ delta_name or "unknown",
+ )
+
+ stored_id, stored_name = tool_call_mapping[index]
+
+ delta_res.append_tool_call(
+ block_id=tool_call.id or stored_id,
+ name=delta_name or stored_name,
+ input=delta_args or "",
)
- delta_contents.extend(delta_tool_call_blocks)
-
- if delta_contents:
- _text_kwargs: dict[str, Any] = {
- "content": delta_contents,
- "usage": usage,
- "is_last": False,
- }
- if response_id:
- _text_kwargs["id"] = response_id
- yield ChatResponse(**_text_kwargs)
-
- final_contents: List[ThinkingBlock | TextBlock | ToolCallBlock] = []
- if acc_thinking.thinking:
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
- for tc in acc_tool_calls.values():
- final_contents.append(
- ToolCallBlock(id=tc["id"], name=tc["name"], input=tc["input"]),
- )
- _final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "usage": usage,
- "is_last": True,
- }
- if response_id:
- _final_kwargs["id"] = response_id
- yield ChatResponse(**_final_kwargs)
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_ollama/_model.py b/src/agentscope/model/_ollama/_model.py
index 72987072b..a85e0037f 100644
--- a/src/agentscope/model/_ollama/_model.py
+++ b/src/agentscope/model/_ollama/_model.py
@@ -247,79 +247,52 @@ class OllamaChatModel(ChatModelBase):
Incremental ``ChatResponse`` objects with ``is_last=False``
followed by a final one with ``is_last=True``.
"""
- # All delta should have the same block identifier.
- # Ollama does not return a request id, so we generate one upfront
- # to keep it stable.
- response_id = getattr(response, "id", None) or _generate_id()
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: dict = {}
- usage = None
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
async for chunk in response:
- delta_content: list = []
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
+
msg = chunk.message
- chunk_thinking = getattr(msg, "thinking", None)
- if chunk_thinking:
- acc_thinking.thinking += chunk_thinking
- delta_content.append(
- ThinkingBlock(id=acc_thinking.id, thinking=chunk_thinking),
+ # Thinking
+ if getattr(msg, "thinking", None):
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=msg.thinking,
)
+ # Text
if msg.content:
- acc_text.text += msg.content
- delta_content.append(
- TextBlock(id=acc_text.id, text=msg.content),
+ delta_res.append_text(
+ block_id=text_id,
+ text=msg.content,
)
+ # Tool call
for idx, tool_call in enumerate(msg.tool_calls or []):
- function = tool_call.function
- tool_id = f"{idx}_{function.name}"
- input_str = json.dumps(function.arguments)
- acc_tool_calls[tool_id] = {
- "name": function.name,
- "input": input_str,
- }
- delta_content.append(
- ToolCallBlock(
- id=tool_id,
- name=function.name,
- input=input_str,
+ delta_res.append_tool_call(
+ block_id=f"{idx}_{tool_call.function.name}",
+ name=tool_call.function.name,
+ input=json.dumps(
+ tool_call.function.arguments,
+ ensure_ascii=False,
),
)
current_time = (datetime.now() - start_datetime).total_seconds()
- usage = ChatUsage(
+ delta_res.usage = ChatUsage(
input_tokens=getattr(chunk, "prompt_eval_count", 0) or 0,
output_tokens=getattr(chunk, "eval_count", 0) or 0,
time=current_time,
)
- if delta_content:
- yield ChatResponse(
- id=response_id,
- content=delta_content,
- is_last=False,
- usage=usage,
- )
-
- final_content: list = []
- if acc_thinking.thinking:
- final_content.append(acc_thinking)
- if acc_text.text:
- final_content.append(acc_text)
- for tool_id, tc in acc_tool_calls.items():
- final_content.append(
- ToolCallBlock(id=tool_id, name=tc["name"], input=tc["input"]),
- )
-
- yield ChatResponse(
- id=response_id,
- content=final_content,
- is_last=True,
- usage=usage,
- )
+ yield delta_res
async def _parse_completion_response(
self,
@@ -352,7 +325,10 @@ class OllamaChatModel(ChatModelBase):
ToolCallBlock(
id=f"{idx}_{tool_call.function.name}",
name=tool_call.function.name,
- input=json.dumps(tool_call.function.arguments),
+ input=json.dumps(
+ tool_call.function.arguments,
+ ensure_ascii=False,
+ ),
),
)
diff --git a/src/agentscope/model/_openai_chat/_model.py b/src/agentscope/model/_openai_chat/_model.py
index f49aad9cb..76a1bdd37 100644
--- a/src/agentscope/model/_openai_chat/_model.py
+++ b/src/agentscope/model/_openai_chat/_model.py
@@ -2,8 +2,6 @@
"""The OpenAI Chat Completions model implementation."""
import warnings
import base64
-import io
-import wave
from collections import OrderedDict
from datetime import datetime
from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
@@ -304,8 +302,8 @@ class OpenAIChatModel(ChatModelBase):
Upstream sends raw PCM16 (24kHz, 16-bit mono — OpenAI's only
streaming-supported audio format). We prefix the first audio
chunk with a streaming WAV header so the frontend can start
- playback immediately, and assemble a fixed-size WAV on the
- final chunk for non-streaming consumers.
+ playback immediately; downstream accumulation is handled by
+ ``ChatResponse.append_data_block``.
Args:
start_datetime (`datetime`):
@@ -315,27 +313,34 @@ class OpenAIChatModel(ChatModelBase):
Yields:
`ChatResponse`:
- Incremental ``ChatResponse`` objects with ``is_last=False``
- followed by a final one with ``is_last=True``.
+ Incremental ``ChatResponse`` objects with ``is_last=False``.
+ The base class ``__call__`` accumulates them and emits the
+ final ``is_last=True`` chunk.
"""
- usage = None
- response_id: str | None = None
- # All delta should have the same block identifier
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- acc_tool_calls: OrderedDict = OrderedDict()
- # Raw audio bytes accumulated across chunks. Storing the decoded
- # form (rather than concatenated base64 strings) avoids corrupting
- # the byte stream when an intermediate chunk happens to carry
- # base64 padding (``=``).
- acc_audio_data: bytearray = bytearray()
- audio_block_id: str | None = None
# ``True`` once the first audio chunk has been prefixed with a
# streaming WAV header and yielded.
audio_header_sent: bool = False
+ usage = None
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ audio_id: str = _generate_id()
+ # The mapping from index to (tool call id, tool call name)
+ tool_call_mapping: dict = OrderedDict()
+
async with response as stream:
async for chunk in stream:
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
+
+ # Update the response ID if exists
+ response_id = getattr(chunk, "id", None) or response_id
+ delta_res.id = response_id
+
if chunk.usage:
u = chunk.usage
details = getattr(u, "prompt_tokens_details", None)
@@ -352,158 +357,97 @@ class OpenAIChatModel(ChatModelBase):
else 0,
)
- # Capture response_id from the first chunk that carries it
- response_id = response_id or getattr(chunk, "id", None)
-
if not chunk.choices:
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
continue
choice = chunk.choices[0]
delta = choice.delta
+ # Thinking
delta_thinking = getattr(delta, "reasoning_content", None)
if not isinstance(delta_thinking, str):
delta_thinking = getattr(delta, "reasoning", None)
- if not isinstance(delta_thinking, str):
- delta_thinking = ""
+ if isinstance(delta_thinking, str) and delta_thinking:
+ delta_res.append_thinking(
+ block_id=thinking_id,
+ thinking=delta_thinking,
+ )
+ # Text
delta_text = getattr(delta, "content", None) or ""
- # Collect audio output (delta.audio.data /
- # delta.audio.transcript)
- delta_audio_block: DataBlock | None = None
- transcript_chunk: str = ""
+ # Audio (delta.audio.data / delta.audio.transcript). Omni
+ # models deliver text via ``delta.audio.transcript`` rather
+ # than ``delta.content``; fold it into ``delta_text`` so the
+ # agent's streaming pipeline emits ``TextBlockDelta`` events
+ # alongside the audio chunks.
delta_audio = getattr(delta, "audio", None)
if delta_audio is not None:
if isinstance(delta_audio, dict):
- audio_chunk = delta_audio.get("data", "")
- transcript_chunk = delta_audio.get("transcript", "")
+ audio_chunk = delta_audio.get("data", "") or ""
+ transcript_chunk = (
+ delta_audio.get("transcript", "") or ""
+ )
else:
audio_chunk = getattr(delta_audio, "data", "") or ""
transcript_chunk = (
getattr(delta_audio, "transcript", "") or ""
)
+ if transcript_chunk:
+ delta_text += transcript_chunk
if audio_chunk:
- if audio_block_id is None:
- audio_block_id = _generate_id()
pcm_bytes = base64.b64decode(audio_chunk)
- acc_audio_data += pcm_bytes
if not audio_header_sent:
payload = _build_streaming_wav_header() + pcm_bytes
audio_header_sent = True
else:
payload = pcm_bytes
- delta_audio_block = DataBlock(
- id=audio_block_id,
- source=Base64Source(
- data=base64.b64encode(payload).decode(
- "ascii",
- ),
- media_type="audio/wav",
- ),
+ # ``append_data_block`` expects the raw incremental
+ # media bytes and handles base64 encoding internally
+ # (see ``ChatResponse.append_data_block``); passing an
+ # already base64-encoded string here would result in
+ # double-encoding.
+ delta_res.append_data_block(
+ block_id=audio_id,
+ data=payload,
+ media_type="audio/wav",
)
- # Omni models deliver text via ``delta.audio.transcript``
- # (not ``delta.content``); fold it into ``delta_text`` so
- # the agent's streaming pipeline emits ``TextBlockDelta``
- # events alongside the audio chunks.
- if transcript_chunk:
- delta_text += transcript_chunk
- acc_thinking.thinking += delta_thinking
- acc_text.text += delta_text
+ if delta_text:
+ delta_res.append_text(
+ block_id=text_id,
+ text=delta_text,
+ )
- delta_tool_call_blocks: List[ToolCallBlock] = []
+ # Tool call
for tool_call in getattr(delta, "tool_calls", None) or []:
- idx = tool_call.index
- args = tool_call.function.arguments or ""
- if idx in acc_tool_calls:
- acc_tool_calls[idx]["input"] += args
- else:
- acc_tool_calls[idx] = {
- "id": tool_call.id,
- "name": tool_call.function.name,
- "input": args,
- }
- tc = acc_tool_calls[idx]
- delta_tool_call_blocks.append(
- ToolCallBlock(
- id=tc["id"],
- name=tc["name"],
- input=args,
- ),
- )
+ index = tool_call.index
+ fn = getattr(tool_call, "function", None)
+ delta_name = getattr(fn, "name", None) if fn else None
+ delta_args = getattr(fn, "arguments", None) if fn else None
+
+ # Record the id and name in case following deltas
+ # don't provide them
+ if index not in tool_call_mapping:
+ tool_call_mapping[index] = (
+ tool_call.id,
+ delta_name or "unknown",
+ )
- delta_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock | DataBlock
- ] = []
- if delta_thinking:
- delta_contents.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta_thinking,
- ),
- )
- if delta_text:
- delta_contents.append(
- TextBlock(id=acc_text.id, text=delta_text),
+ stored_id, stored_name = tool_call_mapping[index]
+
+ delta_res.append_tool_call(
+ block_id=tool_call.id or stored_id,
+ name=delta_name or stored_name,
+ input=delta_args or "",
)
- delta_contents.extend(delta_tool_call_blocks)
- if delta_audio_block is not None:
- delta_contents.append(delta_audio_block)
-
- if delta_contents:
- _kwargs: dict[str, Any] = {
- "content": delta_contents,
- "usage": usage,
- "is_last": False,
- }
- if response_id:
- _kwargs["id"] = response_id
- yield ChatResponse(**_kwargs)
-
- final_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock | DataBlock
- ] = []
- if acc_thinking.thinking:
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
- for tc in acc_tool_calls.values():
- final_contents.append(
- ToolCallBlock(id=tc["id"], name=tc["name"], input=tc["input"]),
- )
- if acc_audio_data:
- # PCM bytes were already streamed incrementally above (first
- # chunk prefixed with a WAV header). Here we also assemble a
- # standalone fixed-size WAV and attach it to the ``is_last``
- # chunk so callers that consume the model directly (i.e.
- # without going through ``Agent``, which filters audio blocks
- # out of context) get a self-contained audio block for
- # downstream serialization / display.
- buf = io.BytesIO()
- with wave.open(buf, "wb") as wav:
- wav.setnchannels(1)
- wav.setsampwidth(2)
- wav.setframerate(24000)
- wav.writeframes(bytes(acc_audio_data))
- final_contents.append(
- DataBlock(
- id=audio_block_id,
- source=Base64Source(
- data=base64.b64encode(buf.getvalue()).decode("ascii"),
- media_type="audio/wav",
- ),
- ),
- )
- _final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "usage": usage,
- "is_last": True,
- }
- if response_id:
- _final_kwargs["id"] = response_id
- yield ChatResponse(**_final_kwargs)
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_openai_response/_model.py b/src/agentscope/model/_openai_response/_model.py
index 5b6a78efc..8c1ac4522 100644
--- a/src/agentscope/model/_openai_response/_model.py
+++ b/src/agentscope/model/_openai_response/_model.py
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
"""The OpenAI Responses API chat model implementation."""
+from collections import OrderedDict
from datetime import datetime
from typing import Literal, Any, AsyncGenerator, List, TYPE_CHECKING, Type
from pydantic import BaseModel, Field
+from ..._utils._common import _generate_id
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse
from .._model_usage import ChatUsage
@@ -236,10 +238,12 @@ class OpenAIResponseModel(ChatModelBase):
) -> AsyncGenerator[ChatResponse, None]:
"""Parse the OpenAI Responses API streaming response.
- Each event yields only the delta content produced by that event so
- that callers see a true incremental stream, consistent with other
- model implementations. The final ``response.completed`` event emits
- an ``is_last=True`` response with the full accumulated state.
+ Each event yields only the *delta* content produced by that event so
+ that the base ``ChatModelBase.__call__`` can accumulate the full
+ response. Because the Responses API only returns the upstream
+ response id on the final ``response.completed`` event, we assign a
+ locally-generated ``response_id`` up-front so every delta chunk
+ carries a stable id.
Args:
start_datetime (`datetime`):
@@ -249,76 +253,70 @@ class OpenAIResponseModel(ChatModelBase):
Yields:
`ChatResponse`:
- Incremental ``ChatResponse`` objects with ``is_last=False``
- followed by a final one with ``is_last=True``.
+ Incremental ``ChatResponse`` objects with ``is_last=False``.
+ The base class ``__call__`` accumulates them and emits the
+ final ``is_last=True`` chunk.
"""
usage: ChatUsage | None = None
- response_id: str | None = None
- # All delta should have the same block identifier
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
- tool_calls: dict[str, dict[str, Any]] = {}
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
+ # Mapping from Responses API item id (fc_xxx) to (call_id, name)
+ # so subsequent argument deltas can be routed to the right tool
+ # call block.
+ tool_call_mapping: dict = OrderedDict()
async for event in response:
event_type = event.type
-
- if response_id is None:
- resp_obj = getattr(event, "response", None)
- if resp_obj is not None:
- response_id = getattr(resp_obj, "id", None)
-
- delta_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock
- ] = []
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
if event_type == "response.reasoning_summary_text.delta":
# Reasoning summary text is NOT emitted by all models.
# As of 2026-05, o1 and o4-mini do not stream reasoning
- # summary deltas. This handler exists for forward
+ # summary deltas. This handler exists for forward
# compatibility with models that do expose it.
- delta = event.delta
- acc_thinking.thinking += delta
- delta_contents.append(
- ThinkingBlock(id=acc_thinking.id, thinking=delta),
+ delta_res.append_thinking(
+ event.delta,
+ block_id=thinking_id,
)
elif event_type == "response.output_text.delta":
- delta = event.delta
- acc_text.text += delta
- delta_contents.append(TextBlock(id=acc_text.id, text=delta))
+ delta_res.append_text(event.delta, block_id=text_id)
elif event_type == "response.output_item.added":
item = event.item
if getattr(item, "type", None) == "function_call":
- # item.id → fc_xxx (item identifier, needed for
- # function_call.id in multi-turn history)
- # item.call_id → call_xxx (needed for
- # function_call_output.call_id)
- tool_calls[item.id] = {
- "id": item.id,
- "call_id": getattr(item, "call_id", None),
- "name": getattr(item, "name", ""),
- "input": "",
- }
+ # item.id -> fc_xxx (used as ToolCallBlock.id
+ # and echoed back as function_call.id
+ # in multi-turn history)
+ # item.call_id -> call_xxx (used as
+ # function_call_output.call_id)
+ # Only record the id/name/call_id here — do NOT emit
+ # an empty-input delta so downstream consumers don't
+ # see a leading no-op chunk. The block is created on
+ # the first argument delta below.
+ tool_call_mapping[item.id] = (
+ getattr(item, "call_id", None),
+ getattr(item, "name", "") or "unknown",
+ )
elif event_type == "response.function_call_arguments.delta":
item_id = event.item_id
- if item_id in tool_calls:
- tool_calls[item_id]["input"] += event.delta
- tc = tool_calls[item_id]
- delta_contents.append(
- ToolCallBlock(
- id=tc["id"],
- call_id=tc.get("call_id"),
- name=tc["name"],
- input=event.delta,
- ),
+ if item_id in tool_call_mapping:
+ call_id, name = tool_call_mapping[item_id]
+ delta_res.append_tool_call(
+ block_id=item_id,
+ name=name,
+ input=event.delta or "",
+ call_id=call_id,
)
elif event_type == "response.completed":
resp = event.response
- if response_id is None:
- response_id = getattr(resp, "id", None)
if resp.usage:
u = resp.usage
details = getattr(u, "input_tokens_details", None)
@@ -334,63 +332,26 @@ class OpenAIResponseModel(ChatModelBase):
if details
else 0,
)
- # Attach reasoning item IDs from the completed response so the
- # formatter can echo them back in multi-turn history.
- # The Responses API requires every function_call item to be
- # accompanied by its preceding reasoning item (see the
- # function-calling guide). The reasoning item may have an
- # empty summary when the model does not expose it (e.g.
- # o1/o4-mini as of 2026-05).
+ # Attach reasoning item id metadata from the completed
+ # response so the formatter can echo it back in
+ # multi-turn history. The Responses API requires every
+ # function_call item to be accompanied by its preceding
+ # reasoning item (see the function-calling guide); the
+ # reasoning item may have an empty summary when the model
+ # does not expose it (e.g. o1/o4-mini as of 2026-05).
for output_item in getattr(resp, "output", []):
if getattr(output_item, "type", None) == "reasoning":
reasoning_item_id = getattr(output_item, "id", None)
if reasoning_item_id:
- acc_thinking = ThinkingBlock(
- id=acc_thinking.id,
- thinking=acc_thinking.thinking,
+ delta_res.append_thinking(
+ thinking="",
+ block_id=thinking_id,
reasoning_item_id=reasoning_item_id,
)
- # Emit the full accumulated state as the final response
- final_contents: List[
- TextBlock | ToolCallBlock | ThinkingBlock
- ] = []
- if acc_thinking.thinking or getattr(
- acc_thinking,
- "reasoning_item_id",
- None,
- ):
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
- for tc in tool_calls.values():
- final_contents.append(
- ToolCallBlock(
- id=tc["id"],
- call_id=tc.get("call_id"),
- name=tc["name"],
- input=tc["input"] or "{}",
- ),
- )
- final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "is_last": True,
- "usage": usage,
- }
- if response_id:
- final_kwargs["id"] = response_id
- yield ChatResponse(**final_kwargs)
- return
-
- # Yield incremental delta for non-terminal events
- if delta_contents:
- chat_resp_kwargs: dict[str, Any] = {
- "content": delta_contents,
- "is_last": False,
- "usage": usage,
- }
- if response_id:
- chat_resp_kwargs["id"] = response_id
- yield ChatResponse(**chat_resp_kwargs)
+
+ if delta_res.content or usage:
+ delta_res.usage = usage
+ yield delta_res
def _parse_completion_response(
self,
diff --git a/src/agentscope/model/_xai/_model.py b/src/agentscope/model/_xai/_model.py
index 2e59c9be7..d6f14df65 100644
--- a/src/agentscope/model/_xai/_model.py
+++ b/src/agentscope/model/_xai/_model.py
@@ -5,6 +5,7 @@ from typing import Any, AsyncGenerator, List, Literal, TYPE_CHECKING, Type
from pydantic import BaseModel, Field
+from ..._utils._common import _generate_id
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse
from .._model_usage import ChatUsage
@@ -298,83 +299,87 @@ class XAIChatModel(ChatModelBase):
) -> AsyncGenerator[ChatResponse, None]:
"""Parse the xAI streaming response from ``xai_sdk``.
+ Each iteration yields only the incremental *delta* content; the
+ base ``ChatModelBase.__call__`` accumulates them and emits the
+ final ``is_last=True`` chunk. ``xai_sdk`` does not stream tool
+ calls or usage — both are only available on the final response
+ object — so after the delta loop exits we emit one last carrier
+ delta containing the full ``ToolCallBlock`` list and ``usage``
+ for the accumulator to merge.
+
Args:
start_datetime (`datetime`):
The start datetime of the response generation.
chat (`Any`):
The ``xai_sdk`` chat session object.
- client (`Any`):
+ client (`AsyncClient`):
The ``xai_sdk.AsyncClient`` instance; closed when the
generator is exhausted or abandoned.
Yields:
`ChatResponse`:
- Incremental ``ChatResponse`` objects with ``is_last=False``
- followed by a final one with ``is_last=True``.
+ Incremental ``ChatResponse`` objects with ``is_last=False``.
"""
- acc_text = TextBlock(text="")
- acc_thinking = ThinkingBlock(thinking="")
+ # xAI exposes the upstream response id from the very first
+ # streamed ``response`` object; fall back to a locally-generated
+ # id so every delta carries a stable identifier before then.
+ response_id: str = _generate_id()
+ text_id: str = _generate_id()
+ thinking_id: str = _generate_id()
last_response = None
- response_id: str | None = None
try:
async for response, chunk in chat.stream():
- if response_id is None:
- response_id = getattr(response, "id", None) or None
+ upstream_id = getattr(response, "id", None)
+ if upstream_id:
+ response_id = upstream_id
+
+ delta_res = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
- delta_text: str = chunk.content or ""
delta_thinking: str = chunk.reasoning_content or ""
-
- delta_contents: List[TextBlock | ThinkingBlock] = []
-
if delta_thinking:
- acc_thinking.thinking += delta_thinking
- delta_contents.append(
- ThinkingBlock(
- id=acc_thinking.id,
- thinking=delta_thinking,
- ),
+ delta_res.append_thinking(
+ delta_thinking,
+ block_id=thinking_id,
)
+
+ delta_text: str = chunk.content or ""
if delta_text:
- acc_text.text += delta_text
- delta_contents.append(
- TextBlock(id=acc_text.id, text=delta_text),
- )
+ delta_res.append_text(delta_text, block_id=text_id)
- if delta_contents:
- _kwargs: dict[str, Any] = {
- "content": delta_contents,
- "is_last": False,
- }
- if response_id:
- _kwargs["id"] = response_id
- yield ChatResponse(**_kwargs)
+ if delta_res.content:
+ yield delta_res
last_response = response
finally:
await client.close()
- final_contents: List[TextBlock | ToolCallBlock | ThinkingBlock] = []
- if acc_thinking.thinking:
- final_contents.append(acc_thinking)
- if acc_text.text:
- final_contents.append(acc_text)
+ # ``xai_sdk`` does not stream tool calls or usage — both are only
+ # populated on the final accumulated ``response`` object. Emit a
+ # single trailing carrier delta so the base accumulator picks up
+ # the ``ToolCallBlock``s and ``ChatUsage``.
+ trailing = ChatResponse(
+ content=[],
+ is_last=False,
+ id=response_id,
+ )
if last_response is not None:
for tc in last_response.tool_calls or []:
- final_contents.append(
- ToolCallBlock(
- id=tc.id,
- name=tc.function.name,
- input=tc.function.arguments,
- ),
+ trailing.append_tool_call(
+ block_id=tc.id,
+ name=tc.function.name,
+ input=tc.function.arguments,
)
- usage = None
if last_response is not None and last_response.usage is not None:
u = last_response.usage
- usage = ChatUsage(
+ trailing.usage = ChatUsage(
input_tokens=u.prompt_tokens,
output_tokens=u.completion_tokens,
time=(datetime.now() - start_datetime).total_seconds(),
@@ -385,14 +390,8 @@ class XAIChatModel(ChatModelBase):
),
)
- final_kwargs: dict[str, Any] = {
- "content": final_contents,
- "usage": usage,
- "is_last": True,
- }
- if response_id:
- final_kwargs["id"] = response_id
- yield ChatResponse(**final_kwargs)
+ if trailing.content or trailing.usage:
+ yield trailing
def _parse_completion_response(
self,
diff --git a/src/agentscope/rag/_vdb/_milvus_lite.py b/src/agentscope/rag/_vdb/_milvus_lite.py
index 4126d2117..de94c9ef3 100644
--- a/src/agentscope/rag/_vdb/_milvus_lite.py
+++ b/src/agentscope/rag/_vdb/_milvus_lite.py
@@ -406,7 +406,7 @@ class MilvusLiteStore(VectorStoreBase):
@staticmethod
def _build_document_filter(document_id: str) -> str:
"""Build a Milvus scalar filter for a document id."""
- return f"document_id == {json.dumps(document_id)}"
+ return f"document_id == {json.dumps(document_id, ensure_ascii=False)}"
@staticmethod
def _build_metadata_filter(
@@ -417,7 +417,8 @@ class MilvusLiteStore(VectorStoreBase):
return ""
return " and ".join(
- f"metadata[{json.dumps(key)}] == {json.dumps(value)}"
+ f"metadata[{json.dumps(key, ensure_ascii=False)}] == "
+ f"{json.dumps(value, ensure_ascii=False)}"
for key, value in metadata_filter.items()
)
diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.py
index 2bda779ae..3f3b6765d 100644
--- a/src/agentscope/state/_state.py
+++ b/src/agentscope/state/_state.py
@@ -13,6 +13,7 @@ from ..message import (
DataBlock,
Msg,
ToolCallBlock,
+ ToolCallState,
ToolResultBlock,
HintBlock,
)
@@ -219,3 +220,32 @@ class AgentState(BaseModel):
content=blocks,
),
)
+
+ def has_awaiting_tool_calls(self, name: str) -> bool:
+ """Whether the tail assistant message written by ``name`` has
+ any tool call still awaiting an outside response — an
+ ``ASKING`` user confirmation or a ``SUBMITTED`` external
+ execution with no matching tool result yet.
+
+ Args:
+ name (`str`):
+ Only messages authored by this agent name are inspected;
+ observed messages from other agents are ignored.
+
+ Returns:
+ `bool`:
+ ``True`` when at least one such tool call is pending.
+ """
+ if not self.context:
+ return False
+ last_msg = self.context[-1]
+ if last_msg.role != "assistant" or last_msg.name != name:
+ return False
+ result_ids = {b.id for b in last_msg.get_content_blocks("tool_result")}
+ return any(
+ tc.state == ToolCallState.ASKING
+ or (
+ tc.state == ToolCallState.SUBMITTED and tc.id not in result_ids
+ )
+ for tc in last_msg.get_content_blocks("tool_call")
+ )
diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.py
index 759323da3..14b322442 100644
--- a/tests/agent_basic_test.py
+++ b/tests/agent_basic_test.py
@@ -240,10 +240,12 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REPLY_END",
"session_id": session_id,
+ "finished_reason": "completed",
},
]
@@ -422,10 +424,12 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REPLY_END",
"session_id": session_id,
+ "finished_reason": "completed",
},
]
@@ -692,6 +696,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "TOOL_RESULT_START",
@@ -735,8 +740,13 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
+ },
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
},
- {"type": "REPLY_END", "session_id": session_id},
]
basic_dict = self._get_event_base(reply_id)
@@ -909,6 +919,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
]
@@ -960,8 +971,13 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
+ },
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
},
- {"type": "REPLY_END", "session_id": session_id},
]
# Assert prefix events (fixed order)
@@ -1155,6 +1171,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
]
@@ -1227,8 +1244,13 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
+ },
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
},
- {"type": "REPLY_END", "session_id": session_id},
]
# Assert prefix events (fixed order)
diff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.py
new file mode 100644
index 000000000..359110ba1
--- /dev/null
+++ b/tests/agent_interrupt_test.py
@@ -0,0 +1,949 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=redefined-builtin
+"""Tests for agent interruption:
+
+- :class:`AgentInterruptCancelTest`: ``task.cancel()`` lands during tool
+ execution and the agent must close every pending tool call with an
+ ``INTERRUPTED`` result and end the reply with
+ ``ReplyEndReason.INTERRUPTED``.
+- :class:`AgentInterruptEventTest`: a :class:`UserInterruptEvent` is
+ delivered to a parked reply and the agent must close every pending
+ HITL tool call the same way, without entering the reasoning-acting
+ loop.
+"""
+import asyncio
+from typing import Any, AsyncGenerator
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString, MockModel
+
+from agentscope.agent import Agent
+from agentscope.event import (
+ ReplyEndEvent,
+ UserInterruptEvent,
+)
+from agentscope.message import (
+ TextBlock,
+ ToolCallBlock,
+ UserMsg,
+)
+from agentscope.model import ChatResponse
+from agentscope.permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from agentscope.tool import (
+ ToolBase,
+ ToolChunk,
+ Toolkit,
+)
+
+# Sleep the too long enough that a ``task.cancel()`` scheduled a few
+# milliseconds later is guaranteed to land while the tool is still inside
+# its ``asyncio.sleep``.
+_SLOW = 5.0
+
+_INTERRUPT_MSG = (
+ "<system-reminder>The tool call has been interrupted by "
+ "the user.</system-reminder>"
+)
+
+_CONFIRM_SUGGESTED_RULES = [
+ {
+ "tool_name": "user_confirm_concurrent",
+ "rule_content": None,
+ "behavior": "allow",
+ "source": "suggested",
+ },
+]
+
+
+def _tool_input_schema() -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "input": {"type": "string"},
+ "timeout": {"type": "number"},
+ },
+ "required": [],
+ }
+
+
+class _TimeoutConcurrentTool(ToolBase):
+ """Concurrent tool that sleeps ``timeout`` seconds before finishing."""
+
+ name: str = "timeout_concurrent"
+ description: str = "Sleeps and returns."
+ input_schema: dict[str, Any] = _tool_input_schema()
+ is_concurrency_safe: bool = True
+ is_read_only: bool = True
+ is_external_tool: bool = False
+ is_mcp: bool = False
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ decision_reason="ok",
+ message="ok",
+ )
+
+ async def __call__(
+ self,
+ timeout: float = _SLOW,
+ input: str = "",
+ **kwargs: Any,
+ ) -> AsyncGenerator[ToolChunk, None]:
+ await asyncio.sleep(timeout)
+ yield ToolChunk(
+ content=[TextBlock(text=f"done:{input}")],
+ is_last=True,
+ )
+
+
+class _TimeoutSequentialTool(_TimeoutConcurrentTool):
+ """Sequential (not concurrency-safe) variant."""
+
+ name: str = "timeout_sequential"
+ is_concurrency_safe: bool = False
+
+
+class _UserConfirmConcurrentTool(_TimeoutConcurrentTool):
+ """Concurrent tool that always asks for user confirmation."""
+
+ name: str = "user_confirm_concurrent"
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ return PermissionDecision(
+ behavior=PermissionBehavior.ASK,
+ decision_reason="needs confirm",
+ message="needs confirm",
+ )
+
+
+class _ExternalConcurrentTool(_TimeoutConcurrentTool):
+ """Concurrent tool that requires external execution."""
+
+ name: str = "external_concurrent"
+ is_external_tool: bool = True
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
+
+
+def _msg_base(name: str = "Friday") -> dict[str, Any]:
+ """Assistant message dict skeleton — ``finished_at`` stays ``None``
+ on assistant replies (only user inputs get a finish timestamp)."""
+ return {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ "metadata": {},
+ "name": name,
+ "role": "assistant",
+ "usage": None,
+ }
+
+
+def _user_msg_dict(content: str) -> dict[str, Any]:
+ return {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": AnyString(),
+ "metadata": {},
+ "name": "user",
+ "role": "user",
+ "content": [
+ {"type": "text", "id": AnyString(), "text": content},
+ ],
+ "usage": None,
+ }
+
+
+def _tool_call_dict(
+ tc_id: str,
+ name: str,
+ input: str,
+ suggested_rules: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ return {
+ "type": "tool_call",
+ "id": tc_id,
+ "name": name,
+ "input": input,
+ "state": "finished",
+ "suggested_rules": suggested_rules or [],
+ }
+
+
+def _interrupted_tool_result_dict(
+ tc_id: str,
+ name: str,
+ output_is_blocks: bool,
+) -> dict[str, Any]:
+ """Interrupted tool_result dict.
+
+ ``output_is_blocks`` toggles between the two output shapes actually
+ produced by the framework:
+
+ - ``True`` — ``list[TextBlock]``, emitted by the toolkit's
+ ``CancelledError`` path (in-flight tool cancelled mid-run).
+ - ``False`` — raw ``str``, emitted by
+ :meth:`Agent._close_unfinished_tool_calls` for HITL tool calls
+ that never actually started (ASKING / SUBMITTED).
+ """
+ output: Any
+ if output_is_blocks:
+ output = [
+ {"type": "text", "id": AnyString(), "text": _INTERRUPT_MSG},
+ ]
+ else:
+ output = _INTERRUPT_MSG
+ return {
+ "type": "tool_result",
+ "id": tc_id,
+ "name": name,
+ "output": output,
+ "state": "interrupted",
+ "metadata": {},
+ }
+
+
+async def _run_and_cancel(
+ agent: Agent,
+ inputs: Any,
+ cancel_after: float = 0.05,
+) -> list[Any]:
+ """Drive ``agent.reply_stream(inputs)`` in a background task, cancel
+ after ``cancel_after`` seconds, and return the collected events."""
+ events: list[Any] = []
+
+ async def _drive() -> None:
+ async for evt in agent.reply_stream(inputs):
+ events.append(evt)
+
+ task = asyncio.create_task(_drive())
+ await asyncio.sleep(cancel_after)
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ return events
+
+
+def _assert_interrupted_end(
+ testcase: IsolatedAsyncioTestCase,
+ events: list[Any],
+ reply_id: str,
+ session_id: str,
+) -> None:
+ """The final event must be a ``ReplyEndEvent`` with
+ ``finished_reason='interrupted'`` for the given reply/session."""
+ testcase.assertIsInstance(events[-1], ReplyEndEvent)
+ testcase.assertDictEqual(
+ events[-1].model_dump(mode="json"),
+ {
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "reply_id": reply_id,
+ "finished_reason": "interrupted",
+ },
+ )
+
+
+class AgentInterruptCancelTest(IsolatedAsyncioTestCase):
+ """``task.cancel()`` lands during tool execution."""
+
+ def _make_agent(self, tools: list[ToolBase]) -> tuple[Agent, MockModel]:
+ model = MockModel(model="mock-model", stream=True)
+ agent = Agent(
+ name="Friday",
+ system_prompt="You are a test agent.",
+ model=model,
+ toolkit=Toolkit(tools=tools),
+ )
+ return agent, model
+
+ async def test_sequential_tool_cancelled_mid_execution(self) -> None:
+ """Sequential batch: model emits one slow sequential tool call,
+ ``task.cancel()`` fires while it sleeps, the tool call is patched
+ to FINISHED with an INTERRUPTED result (produced via the toolkit
+ cancel path, so ``output`` is a ``list[TextBlock]``) and the
+ reply ends with INTERRUPTED."""
+ agent, model = self._make_agent([_TimeoutSequentialTool()])
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Calling."),
+ ToolCallBlock(
+ id="tc-seq",
+ name="timeout_sequential",
+ input="{}",
+ ),
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+
+ events = await _run_and_cancel(
+ agent,
+ UserMsg(name="user", content="Hi"),
+ )
+
+ _assert_interrupted_end(
+ self,
+ events,
+ reply_id=agent.state.reply_id,
+ session_id=agent.state.session_id,
+ )
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Calling.",
+ },
+ _tool_call_dict(
+ "tc-seq",
+ "timeout_sequential",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-seq",
+ "timeout_sequential",
+ output_is_blocks=True,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_concurrent_tool_cancelled_mid_execution(self) -> None:
+ """Concurrent batch: two slow concurrent tool calls running in
+ parallel, cancel patches both to INTERRUPTED via the toolkit
+ cancel path."""
+ agent, model = self._make_agent([_TimeoutConcurrentTool()])
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Calling both."),
+ ToolCallBlock(
+ id="tc-a",
+ name="timeout_concurrent",
+ input='{"input": "a"}',
+ ),
+ ToolCallBlock(
+ id="tc-b",
+ name="timeout_concurrent",
+ input='{"input": "b"}',
+ ),
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+
+ events = await _run_and_cancel(
+ agent,
+ UserMsg(name="user", content="Hi"),
+ )
+
+ _assert_interrupted_end(
+ self,
+ events,
+ reply_id=agent.state.reply_id,
+ session_id=agent.state.session_id,
+ )
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Calling both.",
+ },
+ _tool_call_dict(
+ "tc-a",
+ "timeout_concurrent",
+ '{"input": "a"}',
+ ),
+ _tool_call_dict(
+ "tc-b",
+ "timeout_concurrent",
+ '{"input": "b"}',
+ ),
+ _interrupted_tool_result_dict(
+ "tc-a",
+ "timeout_concurrent",
+ output_is_blocks=True,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-b",
+ "timeout_concurrent",
+ output_is_blocks=True,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_cancel_during_user_confirm_and_running_tool(
+ self,
+ ) -> None:
+ """Concurrent batch mixes a user-confirmation tool (parks in
+ ASKING state without ever running, so its result comes from the
+ agent ``_close_unfinished_tool_calls`` path with a ``str``
+ output) and a slow running tool (whose result comes from the
+ toolkit cancel path with a ``list[TextBlock]`` output).
+
+ The running tool's result is appended first (flushed from the
+ concurrent queue), the ASKING tool's result is appended last
+ by the agent cleanup."""
+ agent, model = self._make_agent(
+ [_UserConfirmConcurrentTool(), _TimeoutConcurrentTool()],
+ )
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Mixed batch."),
+ ToolCallBlock(
+ id="tc-confirm",
+ name="user_confirm_concurrent",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="tc-run",
+ name="timeout_concurrent",
+ input="{}",
+ ),
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+
+ events = await _run_and_cancel(
+ agent,
+ UserMsg(name="user", content="Hi"),
+ )
+
+ _assert_interrupted_end(
+ self,
+ events,
+ reply_id=agent.state.reply_id,
+ session_id=agent.state.session_id,
+ )
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Mixed batch.",
+ },
+ _tool_call_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ "{}",
+ suggested_rules=_CONFIRM_SUGGESTED_RULES,
+ ),
+ _tool_call_dict(
+ "tc-run",
+ "timeout_concurrent",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-run",
+ "timeout_concurrent",
+ output_is_blocks=True,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_cancel_during_external_and_running_tool(self) -> None:
+ """Concurrent batch mixes an external-execution tool (parks in
+ SUBMITTED without running → ``str`` output on cleanup) and a
+ slow running tool (toolkit cancel → ``list[TextBlock]``)."""
+ agent, model = self._make_agent(
+ [_ExternalConcurrentTool(), _TimeoutConcurrentTool()],
+ )
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Mixed batch."),
+ ToolCallBlock(
+ id="tc-ext",
+ name="external_concurrent",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="tc-run",
+ name="timeout_concurrent",
+ input="{}",
+ ),
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+
+ events = await _run_and_cancel(
+ agent,
+ UserMsg(name="user", content="Hi"),
+ )
+
+ _assert_interrupted_end(
+ self,
+ events,
+ reply_id=agent.state.reply_id,
+ session_id=agent.state.session_id,
+ )
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Mixed batch.",
+ },
+ _tool_call_dict(
+ "tc-ext",
+ "external_concurrent",
+ "{}",
+ ),
+ _tool_call_dict(
+ "tc-run",
+ "timeout_concurrent",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-run",
+ "timeout_concurrent",
+ output_is_blocks=True,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-ext",
+ "external_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_cancel_with_confirm_external_and_running_tool(
+ self,
+ ) -> None:
+ """Confirm + external + slow running, all three cancelled."""
+ agent, model = self._make_agent(
+ [
+ _UserConfirmConcurrentTool(),
+ _ExternalConcurrentTool(),
+ _TimeoutConcurrentTool(),
+ ],
+ )
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Mixed batch."),
+ ToolCallBlock(
+ id="tc-confirm",
+ name="user_confirm_concurrent",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="tc-ext",
+ name="external_concurrent",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="tc-run",
+ name="timeout_concurrent",
+ input="{}",
+ ),
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+
+ events = await _run_and_cancel(
+ agent,
+ UserMsg(name="user", content="Hi"),
+ )
+
+ _assert_interrupted_end(
+ self,
+ events,
+ reply_id=agent.state.reply_id,
+ session_id=agent.state.session_id,
+ )
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Mixed batch.",
+ },
+ _tool_call_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ "{}",
+ suggested_rules=_CONFIRM_SUGGESTED_RULES,
+ ),
+ _tool_call_dict(
+ "tc-ext",
+ "external_concurrent",
+ "{}",
+ ),
+ _tool_call_dict(
+ "tc-run",
+ "timeout_concurrent",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-run",
+ "timeout_concurrent",
+ output_is_blocks=True,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ output_is_blocks=False,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-ext",
+ "external_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
+
+
+class AgentInterruptEventTest(IsolatedAsyncioTestCase):
+ """A :class:`UserInterruptEvent` is delivered to a parked reply.
+
+ HITL tool calls that never actually ran are patched by
+ :meth:`Agent._close_unfinished_tool_calls`, whose ``tool_result``
+ output is always the raw interrupt ``str`` (never ``list[TextBlock]``)."""
+
+ def _make_agent(self, tools: list[ToolBase]) -> tuple[Agent, MockModel]:
+ model = MockModel(model="mock-model", stream=True)
+ agent = Agent(
+ name="Friday",
+ system_prompt="You are a test agent.",
+ model=model,
+ toolkit=Toolkit(tools=tools),
+ )
+ return agent, model
+
+ async def _park_with(
+ self,
+ agent: Agent,
+ model: MockModel,
+ pending_tool_calls: list[ToolCallBlock],
+ ) -> None:
+ """Drive one reply that yields the given tool calls so the reply
+ parks in either ASKING or SUBMITTED state."""
+ model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ TextBlock(text="Need HITL."),
+ *pending_tool_calls,
+ ],
+ is_last=True,
+ ),
+ ],
+ ],
+ )
+ async for _ in agent.reply_stream(
+ UserMsg(name="user", content="Hi"),
+ ):
+ pass
+
+ async def test_interrupt_event_on_idle_agent_is_noop(self) -> None:
+ """No parked HITL → ``UserInterruptEvent`` yields nothing and
+ leaves state untouched."""
+ agent, _ = self._make_agent([])
+
+ events = []
+ async for evt in agent.reply_stream(
+ UserInterruptEvent(reply_id="noop"),
+ ):
+ events.append(evt)
+
+ self.assertListEqual(events, [])
+ self.assertListEqual(agent.state.context, [])
+
+ async def test_interrupt_event_after_user_confirm(self) -> None:
+ """Parked in ASKING state: ``UserInterruptEvent`` patches the
+ tool call to FINISHED and appends an INTERRUPTED result (``str``
+ output) and ends the reply with INTERRUPTED."""
+ agent, model = self._make_agent([_UserConfirmConcurrentTool()])
+ await self._park_with(
+ agent,
+ model,
+ [
+ ToolCallBlock(
+ id="tc-confirm",
+ name="user_confirm_concurrent",
+ input="{}",
+ ),
+ ],
+ )
+ reply_id = agent.state.reply_id
+ session_id = agent.state.session_id
+
+ events = []
+ async for evt in agent.reply_stream(
+ UserInterruptEvent(reply_id=reply_id),
+ ):
+ events.append(evt)
+
+ _assert_interrupted_end(self, events, reply_id, session_id)
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Need HITL.",
+ },
+ _tool_call_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ "{}",
+ suggested_rules=_CONFIRM_SUGGESTED_RULES,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_interrupt_event_after_external_execution(self) -> None:
+ """Parked in SUBMITTED: ``UserInterruptEvent`` patches the same
+ way (``str`` output)."""
+ agent, model = self._make_agent([_ExternalConcurrentTool()])
+ await self._park_with(
+ agent,
+ model,
+ [
+ ToolCallBlock(
+ id="tc-ext",
+ name="external_concurrent",
+ input="{}",
+ ),
+ ],
+ )
+ reply_id = agent.state.reply_id
+ session_id = agent.state.session_id
+
+ events = []
+ async for evt in agent.reply_stream(
+ UserInterruptEvent(reply_id=reply_id),
+ ):
+ events.append(evt)
+
+ _assert_interrupted_end(self, events, reply_id, session_id)
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Need HITL.",
+ },
+ _tool_call_dict(
+ "tc-ext",
+ "external_concurrent",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-ext",
+ "external_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
+
+ async def test_interrupt_event_after_both_confirm_and_external(
+ self,
+ ) -> None:
+ """Parked with both ASKING and SUBMITTED tool calls: a single
+ ``UserInterruptEvent`` closes both."""
+ agent, model = self._make_agent(
+ [_UserConfirmConcurrentTool(), _ExternalConcurrentTool()],
+ )
+ await self._park_with(
+ agent,
+ model,
+ [
+ ToolCallBlock(
+ id="tc-confirm",
+ name="user_confirm_concurrent",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="tc-ext",
+ name="external_concurrent",
+ input="{}",
+ ),
+ ],
+ )
+ reply_id = agent.state.reply_id
+ session_id = agent.state.session_id
+
+ events = []
+ async for evt in agent.reply_stream(
+ UserInterruptEvent(reply_id=reply_id),
+ ):
+ events.append(evt)
+
+ _assert_interrupted_end(self, events, reply_id, session_id)
+
+ context_dicts = [
+ msg.model_dump(mode="json") for msg in agent.state.context
+ ]
+ self.assertListEqual(
+ context_dicts,
+ [
+ _user_msg_dict("Hi"),
+ {
+ **_msg_base(),
+ "content": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "text": "Need HITL.",
+ },
+ _tool_call_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ "{}",
+ suggested_rules=_CONFIRM_SUGGESTED_RULES,
+ ),
+ _tool_call_dict(
+ "tc-ext",
+ "external_concurrent",
+ "{}",
+ ),
+ _interrupted_tool_result_dict(
+ "tc-confirm",
+ "user_confirm_concurrent",
+ output_is_blocks=False,
+ ),
+ _interrupted_tool_result_dict(
+ "tc-ext",
+ "external_concurrent",
+ output_is_blocks=False,
+ ),
+ ],
+ },
+ ],
+ )
diff --git a/tests/agui_protocol_test.py b/tests/agui_protocol_test.py
index fa6b36ca3..d07fb6cb8 100644
--- a/tests/agui_protocol_test.py
+++ b/tests/agui_protocol_test.py
@@ -40,8 +40,10 @@ from agentscope.event import (
ToolResultStartEvent,
ToolResultTextDeltaEvent,
UserConfirmResultEvent,
+ ReplyEndReason,
)
from agentscope.message import ToolCallBlock, ToolResultBlock, ToolResultState
+from agentscope.model import FinishedReason
async def _collect_stream(
@@ -212,6 +214,7 @@ class AGUIProtocolLifecycleTest(IsolatedAsyncioTestCase):
event = ReplyEndEvent(
session_id="sess_1",
reply_id="reply_1",
+ finished_reason=ReplyEndReason.COMPLETED,
)
result = self.mw._convert_to_protocol(event)
@@ -265,6 +268,7 @@ class AGUIProtocolStepTest(IsolatedAsyncioTestCase):
reply_id="reply_1",
input_tokens=100,
output_tokens=50,
+ finished_reason=FinishedReason.COMPLETED,
)
result = self.mw._convert_to_protocol(end_event)
@@ -669,12 +673,17 @@ class AGUIProtocolCamelCaseTest(IsolatedAsyncioTestCase):
reply_id="r",
name="a",
),
- ReplyEndEvent(session_id="s", reply_id="r"),
+ ReplyEndEvent(
+ session_id="s",
+ reply_id="r",
+ finished_reason=ReplyEndReason.COMPLETED,
+ ),
ModelCallStartEvent(reply_id="r", model_name="m"),
ModelCallEndEvent(
reply_id="r",
input_tokens=1,
output_tokens=1,
+ finished_reason=FinishedReason.COMPLETED,
),
TextBlockStartEvent(reply_id="r", block_id="b"),
TextBlockDeltaEvent(reply_id="r", block_id="b", delta="x"),
diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.py
index 72752fdd5..08c06f60d 100644
--- a/tests/event_to_message_test.py
+++ b/tests/event_to_message_test.py
@@ -35,6 +35,7 @@ from agentscope.event import (
ExternalExecutionResultEvent,
ModelCallEndEvent,
ReplyEndEvent,
+ ReplyEndReason,
RequireExternalExecutionEvent,
RequireUserConfirmEvent,
TextBlockDeltaEvent,
@@ -58,6 +59,7 @@ from agentscope.message import (
ToolResultBlock,
ToolResultState,
)
+from agentscope.model import FinishedReason
# ---------------------------------------------------------------------------
# Fixed IDs used throughout – hard-coded so ground-truth dicts are readable.
@@ -693,6 +695,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):
reply_id=_REPLY_ID,
input_tokens=10,
output_tokens=20,
+ finished_reason=FinishedReason.COMPLETED,
)
gt_model_call_end_1 = _base(
_final_content,
@@ -703,6 +706,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):
reply_id=_REPLY_ID,
input_tokens=5,
output_tokens=8,
+ finished_reason=FinishedReason.COMPLETED,
)
gt_model_call_end_2 = _base(
_final_content,
@@ -716,6 +720,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):
reply_id=_REPLY_ID,
session_id=_SESSION_ID,
created_at=_FIXED_END_TS,
+ finished_reason=ReplyEndReason.COMPLETED,
)
gt_reply_end = _base(
_final_content,
diff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.py
index 498553794..f59454efd 100644
--- a/tests/hitl_external_execution_test.py
+++ b/tests/hitl_external_execution_test.py
@@ -146,6 +146,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
]
self.final_mock_responses = [
@@ -334,6 +335,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
*self._get_require_external_execution_events(
reply_id,
@@ -410,7 +412,11 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
self.sequential_result_1,
),
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
events,
@@ -563,6 +569,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
*self._get_require_external_execution_events(
reply_id,
@@ -687,7 +694,11 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
state="error",
),
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
@@ -863,6 +874,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
*self._get_require_external_execution_events(
reply_id,
@@ -988,6 +1000,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
{
"type": "REPLY_END",
"session_id": session_id,
+ "finished_reason": "completed",
},
]
@@ -1162,6 +1175,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
*self._get_require_external_execution_events(
reply_id,
@@ -1260,6 +1274,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
{
"type": "REPLY_END",
"session_id": session_id,
+ "finished_reason": "completed",
},
]
self.assertListEqual(
diff --git a/tests/hitl_mixed_interrupt.py b/tests/hitl_mixed_interrupt.py
index 07ce2a171..bee97b16c 100644
--- a/tests/hitl_mixed_interrupt.py
+++ b/tests/hitl_mixed_interrupt.py
@@ -12,7 +12,6 @@ from agentscope.tool import (
ToolBase,
Toolkit,
ToolChunk,
- RegisteredTool,
)
from agentscope.permission import (
PermissionDecision,
@@ -354,10 +353,7 @@ class AgentMixTest(IsolatedAsyncioTestCase):
"""Test one tool call that needs confirmation and external
execution."""
mixed_tool = MockMixedSequentialTool()
- self.agent.toolkit.tools[mixed_tool.name] = RegisteredTool(
- tool=mixed_tool,
- group="basic",
- )
+ self.agent.toolkit = Toolkit(tools=[mixed_tool])
self._set_model_tool_call_responses(
[
@@ -558,10 +554,7 @@ class AgentMixTest(IsolatedAsyncioTestCase):
"""Test sequential tool calls that need confirmation and external
execution."""
mixed_tool = MockMixedSequentialTool()
- self.agent.toolkit.tools[mixed_tool.name] = RegisteredTool(
- tool=mixed_tool,
- group="basic",
- )
+ self.agent.toolkit = Toolkit(tools=[mixed_tool])
self._set_model_tool_call_responses(
[
@@ -917,10 +910,7 @@ class AgentMixTest(IsolatedAsyncioTestCase):
"""Test concurrent tool calls that need confirmation and external
execution."""
mixed_tool = MockMixedConcurrentTool()
- self.agent.toolkit.tools[mixed_tool.name] = RegisteredTool(
- tool=mixed_tool,
- group="basic",
- )
+ self.agent.toolkit = Toolkit(tools=[mixed_tool])
self._set_model_tool_call_responses(
[
diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.py
index 2e6e2d5ce..7e27cf92e 100644
--- a/tests/hitl_user_confirmation_test.py
+++ b/tests/hitl_user_confirmation_test.py
@@ -196,6 +196,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
]
@@ -307,6 +308,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REQUIRE_USER_CONFIRM",
@@ -404,7 +406,11 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
self.sequential_result_1,
),
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
@@ -566,6 +572,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REQUIRE_USER_CONFIRM",
@@ -724,7 +731,11 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
self.sequential_result_2,
),
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
events,
@@ -912,6 +923,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REQUIRE_USER_CONFIRM",
@@ -1076,7 +1088,11 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
self.concurrent_result_2,
),
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
events,
@@ -1262,6 +1278,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"type": "MODEL_CALL_END",
"input_tokens": 0,
"output_tokens": 0,
+ "finished_reason": "completed",
},
{
"type": "REQUIRE_USER_CONFIRM",
@@ -1423,7 +1440,11 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
expected_final_events = [
*self.final_text_events,
- {"type": "REPLY_END", "session_id": session_id},
+ {
+ "type": "REPLY_END",
+ "session_id": session_id,
+ "finished_reason": "completed",
+ },
]
self.assertListEqual(
final_events,
diff --git a/tests/middleware_test.py b/tests/middleware_test.py
index 0d08c5dba..381061263 100644
--- a/tests/middleware_test.py
+++ b/tests/middleware_test.py
@@ -106,10 +106,10 @@ class TestMiddleware(IsolatedAsyncioTestCase):
"mw1_TEXT_BLOCK_END",
"mw2_MODEL_CALL_END",
"mw1_MODEL_CALL_END",
- "mw2_REPLY_END",
- "mw1_REPLY_END",
"mw2_msg",
"mw1_msg",
+ "mw2_REPLY_END",
+ "mw1_REPLY_END",
"mw2_post",
"mw1_post",
]
diff --git a/tests/model_anthropic_test.py b/tests/model_anthropic_test.py
index 6c6dcefb3..0ebde9a5b 100644
--- a/tests/model_anthropic_test.py
+++ b/tests/model_anthropic_test.py
@@ -312,6 +312,18 @@ class TestAnthropicStream(IsolatedAsyncioTestCase):
),
],
),
+ # ``signature_delta`` is emitted as its own delta chunk
+ # carrying the signature but no additional thinking text.
+ (
+ False,
+ [
+ ThinkingBlock.model_construct(
+ id=A,
+ thinking="",
+ signature="sig_abc",
+ ),
+ ],
+ ),
(False, [TextBlock.model_construct(id=A, text="Result")]),
(
True,
@@ -378,6 +390,19 @@ class TestAnthropicStream(IsolatedAsyncioTestCase):
self.assertListEqual(
[(r.is_last, r.content) for r in responses],
[
+ # Anthropic emits a ``content_block_start`` event before the
+ # first delta, which surfaces as an initial empty-input
+ # ``ToolCallBlock`` delta.
+ (
+ False,
+ [
+ ToolCallBlock(
+ id="toolu_1",
+ name="get_weather",
+ input="",
+ ),
+ ],
+ ),
(
False,
[
diff --git a/tests/model_base_test.py b/tests/model_base_test.py
new file mode 100644
index 000000000..db93734b1
--- /dev/null
+++ b/tests/model_base_test.py
@@ -0,0 +1,469 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for :class:`agentscope.model.ChatModelBase.__call__` — the
+retry / accumulation / interrupt wrapper around ``_call_api``."""
+import asyncio
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString, MockModel
+
+from agentscope.message import TextBlock, ThinkingBlock, ToolCallBlock, UserMsg
+from agentscope.model import ChatResponse, FinishedReason
+
+
+def _dump(chat_response: ChatResponse) -> dict:
+ """Normalize a ``ChatResponse`` (a ``dict``-subclass with pydantic
+ blocks inside) into a plain dict suitable for
+ ``assertDictEqual`` / ``assertListEqual`` comparison."""
+ d = dict(chat_response)
+ d["content"] = [b.model_dump(mode="json") for b in d["content"]]
+ if d["usage"] is not None:
+ d["usage"] = dict(d["usage"])
+ return d
+
+
+def _expected(
+ content: list,
+ is_last: bool,
+ finished_reason: FinishedReason = FinishedReason.COMPLETED,
+ usage: dict | None = None,
+) -> dict:
+ """Build the expected serialized ``ChatResponse`` dict, with
+ ``AnyString`` placeholders for auto-generated fields (id,
+ created_at)."""
+ return {
+ "content": content,
+ "is_last": is_last,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "type": "chat_response",
+ "usage": usage,
+ "finished_reason": finished_reason,
+ "metadata": {},
+ }
+
+
+class ChatModelBaseCallTest(IsolatedAsyncioTestCase):
+ """Test ``ChatModelBase.__call__`` end-to-end with a ``MockModel``.
+
+ Covers the four scenarios that ``__call__`` must handle:
+
+ 1. Non-stream success — the underlying ``ChatResponse`` is returned
+ verbatim.
+ 2. Non-stream ``CancelledError`` raised from inside ``_call_api`` —
+ converted to a ``ChatResponse`` with
+ ``finished_reason=INTERRUPTED``.
+ 3. Stream success — every delta is forwarded, followed by an
+ accumulated final ``ChatResponse`` with ``is_last=True`` and
+ ``finished_reason=COMPLETED``.
+ 4. Stream ``CancelledError`` raised while consuming the underlying
+ async generator — deltas produced so far are forwarded, followed
+ by an accumulated final ``ChatResponse`` with
+ ``finished_reason=INTERRUPTED``.
+ """
+
+ async def asyncSetUp(self) -> None:
+ """The async setup method."""
+ self.model = MockModel(model="mock-model")
+ self.messages = [UserMsg(name="user", content="hi")]
+
+ # ------------------------------------------------------------------
+ # 1) non-stream success
+ # ------------------------------------------------------------------
+ async def test_non_stream_success(self) -> None:
+ """Non-stream ``_call_api`` returns a ``ChatResponse``; the base
+ class must return it unchanged."""
+ response = ChatResponse(
+ content=[TextBlock(text="hello", id="t1")],
+ is_last=True,
+ )
+ self.model.set_responses([response])
+
+ result = await self.model(messages=self.messages)
+
+ self.assertIsInstance(result, ChatResponse)
+ self.assertDictEqual(
+ _dump(result),
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "t1"},
+ ],
+ is_last=True,
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # 2) non-stream CancelledError raised from inside _call_api
+ # ------------------------------------------------------------------
+ async def test_non_stream_cancelled_error(self) -> None:
+ """``CancelledError`` raised from inside a non-stream
+ ``_call_api`` is translated into an empty ``ChatResponse`` with
+ ``finished_reason=INTERRUPTED``."""
+ self.model.set_responses([asyncio.CancelledError()])
+
+ result = await self.model(messages=self.messages)
+
+ self.assertIsInstance(result, ChatResponse)
+ self.assertDictEqual(
+ _dump(result),
+ _expected(
+ content=[],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # 3) stream success
+ # ------------------------------------------------------------------
+ async def test_stream_success_with_final_accumulation(self) -> None:
+ """A well-behaved stream of deltas is forwarded chunk-by-chunk;
+ the base class appends a final accumulated ``ChatResponse``
+ with ``is_last=True``."""
+ deltas = [
+ ChatResponse(
+ content=[TextBlock(text="hello", id="t1")],
+ is_last=False,
+ id="chunk-1",
+ ),
+ ChatResponse(
+ content=[TextBlock(text=" world", id="t1")],
+ is_last=False,
+ id="chunk-2",
+ ),
+ ]
+ self.model.set_responses([deltas])
+
+ gen = await self.model(messages=self.messages)
+ collected = [_dump(c) async for c in gen]
+
+ self.assertListEqual(
+ collected,
+ [
+ # delta 1 — passed through verbatim
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "t1"},
+ ],
+ is_last=False,
+ ),
+ # delta 2 — passed through verbatim
+ _expected(
+ content=[
+ {"type": "text", "text": " world", "id": "t1"},
+ ],
+ is_last=False,
+ ),
+ # accumulated final — synthesised by ChatModelBase
+ _expected(
+ content=[
+ {
+ "type": "text",
+ "text": "hello world",
+ "id": "t1",
+ },
+ ],
+ is_last=True,
+ finished_reason=FinishedReason.COMPLETED,
+ ),
+ ],
+ )
+
+ # ------------------------------------------------------------------
+ # 4) stream CancelledError raised while consuming the generator
+ # ------------------------------------------------------------------
+ async def test_stream_cancelled_error_mid_consumption(self) -> None:
+ """``CancelledError`` raised mid-stream is caught inside the
+ base class's ``_stream`` wrapper. Deltas produced before the
+ cancellation are still forwarded, and a final accumulated
+ ``ChatResponse`` with ``finished_reason=INTERRUPTED`` is
+ appended."""
+ deltas = [
+ ChatResponse(
+ content=[TextBlock(text="hello", id="t1")],
+ is_last=False,
+ id="chunk-1",
+ ),
+ asyncio.CancelledError(),
+ # anything after the exception must not be reached
+ ChatResponse(
+ content=[TextBlock(text=" world", id="t1")],
+ is_last=False,
+ id="chunk-2",
+ ),
+ ]
+ self.model.set_responses([deltas])
+
+ gen = await self.model(messages=self.messages)
+ collected = [_dump(c) async for c in gen]
+
+ self.assertListEqual(
+ collected,
+ [
+ # the one delta yielded before the cancellation
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "t1"},
+ ],
+ is_last=False,
+ ),
+ # accumulated final with INTERRUPTED — content reflects
+ # only the deltas received before the cancellation
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "t1"},
+ ],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ ),
+ ],
+ )
+
+ # ------------------------------------------------------------------
+ # 5) stream CancelledError — thinking + text content interrupted
+ # ------------------------------------------------------------------
+ async def test_stream_cancelled_error_with_thinking_and_text(
+ self,
+ ) -> None:
+ """Same as (4) but the underlying stream produces multiple
+ ``ThinkingBlock`` and ``TextBlock`` deltas (across the same
+ block ids) before the cancellation. The accumulated final
+ response must merge the deltas by block id in their original
+ order."""
+ deltas = [
+ # thinking (part 1)
+ ChatResponse(
+ content=[
+ ThinkingBlock(thinking="let me ", id="think-1"),
+ ],
+ is_last=False,
+ id="chunk-1",
+ ),
+ # thinking (part 2, same block-id, plus signature)
+ ChatResponse(
+ content=[
+ ThinkingBlock(thinking="think...", id="think-1"),
+ ],
+ is_last=False,
+ id="chunk-2",
+ ),
+ # text (part 1, new block-id)
+ ChatResponse(
+ content=[TextBlock(text="hello", id="text-1")],
+ is_last=False,
+ id="chunk-3",
+ ),
+ asyncio.CancelledError(),
+ # unreachable
+ ChatResponse(
+ content=[TextBlock(text=" world", id="text-1")],
+ is_last=False,
+ id="chunk-4",
+ ),
+ ]
+ self.model.set_responses([deltas])
+
+ gen = await self.model(messages=self.messages)
+ collected = [_dump(c) async for c in gen]
+
+ self.assertListEqual(
+ collected,
+ [
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "let me ",
+ "id": "think-1",
+ },
+ ],
+ is_last=False,
+ ),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "think...",
+ "id": "think-1",
+ },
+ ],
+ is_last=False,
+ ),
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "text-1"},
+ ],
+ is_last=False,
+ ),
+ # accumulated final — thinking merged, text merged, no
+ # trailing " world" (it came after the cancellation)
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "let me think...",
+ "id": "think-1",
+ },
+ {
+ "type": "text",
+ "text": "hello",
+ "id": "text-1",
+ },
+ ],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ ),
+ ],
+ )
+
+ # ------------------------------------------------------------------
+ # 6) stream CancelledError — thinking + text + tool_call interrupted
+ # ------------------------------------------------------------------
+ async def test_stream_cancelled_error_with_thinking_text_tool_call(
+ self,
+ ) -> None:
+ """Same as (5) but the stream also produces a
+ ``ToolCallBlock`` whose ``input`` string is streamed across
+ multiple deltas. The cancellation happens after the partial
+ tool_call input; the accumulated final response must contain
+ the tool_call with the concatenated ``input`` received so far."""
+ deltas = [
+ # thinking
+ ChatResponse(
+ content=[
+ ThinkingBlock(thinking="planning...", id="think-1"),
+ ],
+ is_last=False,
+ id="chunk-1",
+ ),
+ # text
+ ChatResponse(
+ content=[
+ TextBlock(text="calling tool", id="text-1"),
+ ],
+ is_last=False,
+ id="chunk-2",
+ ),
+ # tool_call (part 1: name + partial input)
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="tool-1",
+ name="get_weather",
+ input='{"city":"',
+ ),
+ ],
+ is_last=False,
+ id="chunk-3",
+ ),
+ # tool_call (part 2: input continuation, same block-id)
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="tool-1",
+ name="get_weather",
+ input='Beijing"',
+ ),
+ ],
+ is_last=False,
+ id="chunk-4",
+ ),
+ asyncio.CancelledError(),
+ # unreachable — the closing "}" never arrives
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="tool-1",
+ name="get_weather",
+ input="}",
+ ),
+ ],
+ is_last=False,
+ id="chunk-5",
+ ),
+ ]
+ self.model.set_responses([deltas])
+
+ gen = await self.model(messages=self.messages)
+ collected = [_dump(c) async for c in gen]
+
+ self.assertListEqual(
+ collected,
+ [
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "planning...",
+ "id": "think-1",
+ },
+ ],
+ is_last=False,
+ ),
+ _expected(
+ content=[
+ {
+ "type": "text",
+ "text": "calling tool",
+ "id": "text-1",
+ },
+ ],
+ is_last=False,
+ ),
+ _expected(
+ content=[
+ {
+ "type": "tool_call",
+ "id": "tool-1",
+ "name": "get_weather",
+ "input": '{"city":"',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ is_last=False,
+ ),
+ _expected(
+ content=[
+ {
+ "type": "tool_call",
+ "id": "tool-1",
+ "name": "get_weather",
+ "input": 'Beijing"',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ is_last=False,
+ ),
+ # accumulated final — thinking / text preserved,
+ # tool_call.input concatenated to the partial JSON
+ # received before the cancellation (no closing "}")
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "planning...",
+ "id": "think-1",
+ },
+ {
+ "type": "text",
+ "text": "calling tool",
+ "id": "text-1",
+ },
+ {
+ "type": "tool_call",
+ "id": "tool-1",
+ "name": "get_weather",
+ "input": '{"city":"Beijing"',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ ),
+ ],
+ )
+
+ async def asyncTearDown(self) -> None:
+ """The async teardown method."""
diff --git a/tests/model_openai_response_test.py b/tests/model_openai_response_test.py
index 5d7c86708..14291a028 100644
--- a/tests/model_openai_response_test.py
+++ b/tests/model_openai_response_test.py
@@ -288,7 +288,6 @@ class TestOpenAIResponseStream(IsolatedAsyncioTestCase):
(True, [TextBlock.model_construct(id=A, text="Hello world")]),
],
)
- self.assertEqual(responses[-1].id, "resp-1")
@patch("openai.AsyncClient")
async def test_stream_reasoning_and_text(
@@ -337,6 +336,20 @@ class TestOpenAIResponseStream(IsolatedAsyncioTestCase):
[ThinkingBlock.model_construct(id=A, thinking="Thinking")],
),
(False, [TextBlock.model_construct(id=A, text="Answer")]),
+ # ``reasoning_item_id`` is only known at
+ # ``response.completed``; it is emitted as a dedicated
+ # carrier delta chunk (empty thinking text) that the base
+ # accumulator merges onto the existing ``ThinkingBlock``.
+ (
+ False,
+ [
+ ThinkingBlock.model_construct(
+ id=A,
+ thinking="",
+ reasoning_item_id="rs_123",
+ ),
+ ],
+ ),
(
True,
[
diff --git a/tests/model_response_test.py b/tests/model_response_test.py
new file mode 100644
index 000000000..9e8ab334b
--- /dev/null
+++ b/tests/model_response_test.py
@@ -0,0 +1,456 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for :class:`agentscope.model.ChatResponse` and its
+``append_*`` helpers."""
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.message import TextBlock
+from agentscope.model import ChatResponse, FinishedReason, ChatUsage
+
+
+def _dump(chat_response: ChatResponse) -> dict:
+ """Convert a ``ChatResponse`` into a plain-dict form suitable for
+ ``assertDictEqual`` / ``assertListEqual`` comparison.
+
+ ``ChatResponse`` inherits from ``DictMixin`` (a ``dict`` subclass) but
+ keeps its content blocks as pydantic models, so we normalize them via
+ ``model_dump(mode="json")`` here.
+ """
+ d = dict(chat_response)
+ d["content"] = [b.model_dump(mode="json") for b in d["content"]]
+ if d["usage"] is not None:
+ d["usage"] = dict(d["usage"])
+ return d
+
+
+def _expected(
+ content: list,
+ usage: dict | None = None,
+ finished_reason: FinishedReason = FinishedReason.COMPLETED,
+ is_last: bool = True,
+) -> dict:
+ """Build the expected serialized-``ChatResponse`` dict, with
+ ``AnyString`` placeholders for auto-generated fields."""
+ return {
+ "content": content,
+ "is_last": is_last,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "type": "chat_response",
+ "usage": usage,
+ "finished_reason": finished_reason,
+ "metadata": {},
+ }
+
+
+class ChatResponseAppendTest(IsolatedAsyncioTestCase):
+ """Test the ``append_*`` methods of ``ChatResponse``."""
+
+ async def asyncSetUp(self) -> None:
+ """The async setup method."""
+
+ # ------------------------------------------------------------------
+ # append_text
+ # ------------------------------------------------------------------
+ async def test_append_text_new_block(self) -> None:
+ """A new text block is created when the list is empty."""
+ r = ChatResponse(content=[TextBlock(text="exists")], is_last=True)
+ r.append_text("hello", block_id="t1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {"type": "text", "text": "exists", "id": AnyString()},
+ {"type": "text", "text": "hello", "id": "t1"},
+ ],
+ ),
+ )
+
+ async def test_append_text_merge_same_id(self) -> None:
+ """Two ``append_text`` calls with the same ``block_id`` merge
+ into a single text block."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_text("hello", block_id="t1")
+ r.append_text(" world", block_id="t1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {"type": "text", "text": "hello world", "id": "t1"},
+ ],
+ ),
+ )
+
+ async def test_append_text_different_ids_are_separate_blocks(
+ self,
+ ) -> None:
+ """``append_text`` with different ``block_id`` values creates
+ separate text blocks in order."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_text("first", block_id="t1")
+ r.append_text("second", block_id="t2")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {"type": "text", "text": "first", "id": "t1"},
+ {"type": "text", "text": "second", "id": "t2"},
+ ],
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # append_thinking
+ # ------------------------------------------------------------------
+ async def test_append_thinking_no_signature(self) -> None:
+ """A thinking block is created without ``signature`` field when
+ the caller does not provide one."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_thinking("why", block_id="th1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {"type": "thinking", "thinking": "why", "id": "th1"},
+ ],
+ ),
+ )
+
+ async def test_append_thinking_with_signature_on_create(self) -> None:
+ """Signature can be supplied at block-creation time."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_thinking("why", block_id="th1", signature="sig-1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "why",
+ "id": "th1",
+ "signature": "sig-1",
+ },
+ ],
+ ),
+ )
+
+ async def test_append_thinking_merge_multiple_deltas_no_signature(
+ self,
+ ) -> None:
+ """Multiple consecutive thinking deltas without signature merge
+ into one block. Regression test: the previous implementation
+ raised ``AttributeError`` on the second delta because
+ ``signature`` was accessed unconditionally."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_thinking("hello", block_id="th1")
+ r.append_thinking(" world", block_id="th1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "hello world",
+ "id": "th1",
+ },
+ ],
+ ),
+ )
+
+ async def test_append_thinking_signature_after_thinking(self) -> None:
+ """The Anthropic pattern: several thinking deltas followed by a
+ signature-only delta, all sharing the same ``block_id``."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_thinking("hello", block_id="th1")
+ r.append_thinking(" world", block_id="th1")
+ r.append_thinking("", block_id="th1", signature="sig-1")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "hello world",
+ "id": "th1",
+ "signature": "sig-1",
+ },
+ ],
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # append_tool_call
+ # ------------------------------------------------------------------
+ async def test_append_tool_call_new_block(self) -> None:
+ """A new tool call block is created on first append."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_tool_call(block_id="tc1", name="fn", input='{"x":1}')
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "tool_call",
+ "id": "tc1",
+ "name": "fn",
+ "input": '{"x":1}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ ),
+ )
+
+ async def test_append_tool_call_merge_input_by_id(self) -> None:
+ """Multiple ``append_tool_call`` calls sharing the same
+ ``block_id`` concatenate their ``input`` payload."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_tool_call(block_id="tc1", name="fn", input='{"x"')
+ r.append_tool_call(block_id="tc1", name="fn", input=":1}")
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "tool_call",
+ "id": "tc1",
+ "name": "fn",
+ "input": '{"x":1}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ ),
+ )
+
+ async def test_append_tool_call_multiple_calls(self) -> None:
+ """Different ``block_id`` values produce separate tool-call
+ blocks in the order they were appended."""
+ r = ChatResponse(content=[], is_last=True)
+ r.append_tool_call(block_id="tc1", name="fn_a", input='{"x":1}')
+ r.append_tool_call(block_id="tc2", name="fn_b", input='{"y":2}')
+
+ self.assertDictEqual(
+ _dump(r),
+ _expected(
+ content=[
+ {
+ "type": "tool_call",
+ "id": "tc1",
+ "name": "fn_a",
+ "input": '{"x":1}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ {
+ "type": "tool_call",
+ "id": "tc2",
+ "name": "fn_b",
+ "input": '{"y":2}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # append_chat_response
+ # ------------------------------------------------------------------
+ async def test_append_chat_response_merges_matching_ids(self) -> None:
+ """Blocks with matching ids across mixed types are merged, not
+ duplicated. Verifies text / thinking / tool_call all merge in
+ one call."""
+ acc = ChatResponse(content=[], is_last=True)
+
+ # First delta contains one of each block type.
+ d1 = ChatResponse(content=[], is_last=False)
+ d1.append_text("hello", block_id="txt")
+ d1.append_thinking("why", block_id="th")
+ d1.append_tool_call(block_id="tc", name="fn", input='{"a"')
+ acc.append_chat_response(d1)
+
+ # Second delta extends each block by matching ids.
+ d2 = ChatResponse(content=[], is_last=False)
+ d2.append_text(" world", block_id="txt")
+ d2.append_thinking(" not", block_id="th")
+ d2.append_tool_call(block_id="tc", name="fn", input=":1}")
+ acc.append_chat_response(d2)
+
+ self.assertDictEqual(
+ _dump(acc),
+ _expected(
+ content=[
+ {
+ "type": "text",
+ "text": "hello world",
+ "id": "txt",
+ },
+ {
+ "type": "thinking",
+ "thinking": "why not",
+ "id": "th",
+ },
+ {
+ "type": "tool_call",
+ "id": "tc",
+ "name": "fn",
+ "input": '{"a":1}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ ),
+ )
+
+ async def test_append_chat_response_extends_new_ids(self) -> None:
+ """Delta blocks whose ids are not present in the accumulator
+ are appended as new blocks."""
+ acc = ChatResponse(content=[], is_last=True)
+ d1 = ChatResponse(content=[], is_last=False)
+ d1.append_text("hello", block_id="t1")
+ acc.append_chat_response(d1)
+
+ d2 = ChatResponse(content=[], is_last=False)
+ d2.append_text("second", block_id="t2")
+ d2.append_tool_call(block_id="tc1", name="fn", input="{}")
+ acc.append_chat_response(d2)
+
+ self.assertDictEqual(
+ _dump(acc),
+ _expected(
+ content=[
+ {"type": "text", "text": "hello", "id": "t1"},
+ {"type": "text", "text": "second", "id": "t2"},
+ {
+ "type": "tool_call",
+ "id": "tc1",
+ "name": "fn",
+ "input": "{}",
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ ),
+ )
+
+ async def test_append_chat_response_thinking_then_signature(
+ self,
+ ) -> None:
+ """A signature-only delta arriving after several thinking-only
+ deltas via ``append_chat_response`` correctly attaches the
+ signature to the accumulated thinking block."""
+ acc = ChatResponse(content=[], is_last=True)
+
+ d1 = ChatResponse(content=[], is_last=False)
+ d1.append_thinking("hello", block_id="th1")
+ acc.append_chat_response(d1)
+
+ d2 = ChatResponse(content=[], is_last=False)
+ d2.append_thinking(" world", block_id="th1")
+ acc.append_chat_response(d2)
+
+ d3 = ChatResponse(content=[], is_last=False)
+ d3.append_thinking("", block_id="th1", signature="sig-1")
+ acc.append_chat_response(d3)
+
+ self.assertDictEqual(
+ _dump(acc),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "hello world",
+ "id": "th1",
+ "signature": "sig-1",
+ },
+ ],
+ ),
+ )
+
+ async def test_append_chat_response_multiple_thinking_deltas_no_signature(
+ self,
+ ) -> None:
+ """Regression test for the ``AttributeError`` that used to be
+ raised when merging two consecutive thinking deltas that never
+ carried a ``signature``."""
+ acc = ChatResponse(content=[], is_last=True)
+
+ d1 = ChatResponse(content=[], is_last=False)
+ d1.append_thinking("foo", block_id="th1")
+ acc.append_chat_response(d1)
+
+ d2 = ChatResponse(content=[], is_last=False)
+ d2.append_thinking("bar", block_id="th1")
+ acc.append_chat_response(d2)
+
+ self.assertDictEqual(
+ _dump(acc),
+ _expected(
+ content=[
+ {
+ "type": "thinking",
+ "thinking": "foobar",
+ "id": "th1",
+ },
+ ],
+ ),
+ )
+
+ async def test_append_chat_response_usage_override(self) -> None:
+ """``usage`` from the delta overrides ``self.usage`` when
+ non-``None``; a delta with no usage leaves it untouched."""
+ acc = ChatResponse(content=[], is_last=True)
+
+ # First delta carries an early usage snapshot.
+ d1 = ChatResponse(
+ content=[],
+ is_last=False,
+ usage=ChatUsage(input_tokens=1, output_tokens=1, time=0.1),
+ )
+ d1.append_text("hi", block_id="t1")
+ acc.append_chat_response(d1)
+
+ # Second delta has no usage → previous should be preserved.
+ d2 = ChatResponse(content=[], is_last=False)
+ d2.append_text(" there", block_id="t1")
+ acc.append_chat_response(d2)
+
+ # Third delta carries the final usage → it wins.
+ d3 = ChatResponse(
+ content=[],
+ is_last=False,
+ usage=ChatUsage(input_tokens=5, output_tokens=10, time=0.5),
+ )
+ acc.append_chat_response(d3)
+
+ self.assertDictEqual(
+ _dump(acc),
+ _expected(
+ content=[
+ {"type": "text", "text": "hi there", "id": "t1"},
+ ],
+ usage={
+ "input_tokens": 5,
+ "output_tokens": 10,
+ "time": 0.5,
+ "cache_creation_input_tokens": 0,
+ "cache_input_tokens": 0,
+ "type": "chat",
+ "metadata": None,
+ },
+ ),
+ )
+
+ async def asyncTearDown(self) -> None:
+ """The async teardown method."""
diff --git a/tests/model_xai_test.py b/tests/model_xai_test.py
index 4e6de9c59..254f8155c 100644
--- a/tests/model_xai_test.py
+++ b/tests/model_xai_test.py
@@ -417,6 +417,20 @@ class TestXAIStream(IsolatedAsyncioTestCase):
[(r.is_last, r.content) for r in responses],
[
(False, [TextBlock.model_construct(id=A, text="I'll search")]),
+ # ``xai_sdk`` does not stream tool calls — they only
+ # appear on the final accumulated response object, so
+ # the parser emits them as a dedicated trailing carrier
+ # delta that the base accumulator merges.
+ (
+ False,
+ [
+ ToolCallBlock(
+ id="call-1",
+ name="search",
+ input='{"q":"test"}',
+ ),
+ ],
+ ),
(
True,
[
diff --git a/tests/service_agent_interrupt_test.py b/tests/service_agent_interrupt_test.py
new file mode 100644
index 000000000..6d1ba41f2
--- /dev/null
+++ b/tests/service_agent_interrupt_test.py
@@ -0,0 +1,171 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=missing-class-docstring,missing-function-docstring
+"""Service-layer integration tests for the agent interruption pipeline.
+
+Covers the plumbing that translates an external interrupt signal into a
+local ``task.cancel()``:
+
+ message bus publish
+ → ``CancelDispatcher`` (background subscriber)
+ → ``ChatRunRegistry`` lookup
+ → ``task.cancel()``
+ → agent exits with ``finished_reason='interrupted'``
+ → the next reply on the same session works normally.
+
+FastAPI is intentionally not started — the HTTP layer is a thin wrapper
+around :meth:`ChatService.interrupt`. This suite validates the
+service-level wiring using :class:`InMemoryMessageBus` so no Redis is
+required.
+"""
+import asyncio
+from typing import Any
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from agentscope.agent import Agent
+from agentscope.app._manager import (
+ CancelDispatcher,
+ ChatRunRegistry,
+ BackgroundTaskManager,
+)
+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys
+from agentscope.event import ReplyEndEvent
+from agentscope.message import (
+ TextBlock,
+ UserMsg,
+)
+from agentscope.model import ChatResponse
+from agentscope.tool import Toolkit
+
+
+class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):
+ """Service-layer interrupt plumbing tests."""
+
+ async def test_full_interrupt_flow(self) -> None:
+ """Complete flow: user message → agent runs → interrupt published
+ → CancelDispatcher cancels task → agent exits with interrupted
+ → next message works.
+ """
+ bus = InMemoryMessageBus()
+ registry = ChatRunRegistry()
+ bg_manager = BackgroundTaskManager(message_bus=bus)
+
+ session_id = "full-e2e-session"
+
+ # ---- Build a model that streams slowly ----
+ class SlowModel:
+ """Streaming model with await points for testing."""
+
+ def __init__(self) -> None:
+ self.model = "slow-e2e"
+ self.stream = True
+ self.max_retries = 0
+ self.context_size = 1000
+
+ async def __call__(
+ self,
+ *_args: Any,
+ **_kwargs: Any,
+ ) -> Any:
+ async def _stream() -> Any:
+ await asyncio.sleep(0.03)
+ yield ChatResponse(
+ content=[TextBlock(text="part1 ")],
+ is_last=False,
+ )
+ await asyncio.sleep(0.03)
+ yield ChatResponse(
+ content=[TextBlock(text="part2")],
+ is_last=False,
+ )
+ await asyncio.sleep(0.03)
+ yield ChatResponse(
+ content=[TextBlock(text="part1 part2 full")],
+ is_last=True,
+ )
+
+ return _stream()
+
+ async def count_tokens(
+ self,
+ *_args: Any,
+ **_kwargs: Any,
+ ) -> int:
+ return 100
+
+ # ---- Agent ----
+ agent = Agent(
+ name="FullE2EAgent",
+ system_prompt="You are a test agent.",
+ model=SlowModel(),
+ toolkit=Toolkit(),
+ )
+
+ # ---- Start agent in background, register in ChatRunRegistry ----
+ finished_reason_1 = None
+
+ async def _chat_run() -> None:
+ nonlocal finished_reason_1
+ async for evt in agent.reply_stream(
+ UserMsg(name="user", content="Hello"),
+ ):
+ if isinstance(evt, ReplyEndEvent):
+ finished_reason_1 = evt.finished_reason
+
+ registry.spawn(_chat_run(), session_id=session_id)
+
+ # ---- Start CancelDispatcher ----
+ async with bus:
+ async with CancelDispatcher(
+ message_bus=bus,
+ registry=registry,
+ bg_manager=bg_manager,
+ ):
+ # Wait for agent to start streaming
+ await asyncio.sleep(0.04)
+
+ # Step 1: Publish interrupt (simulating API endpoint)
+ await bus.publish(
+ MessageBusKeys.session_interrupt_channel(),
+ {"session_id": session_id},
+ )
+
+ # Wait for cancellation to propagate and agent to finish
+ await asyncio.sleep(0.3)
+
+ # Step 2: Verify agent was interrupted
+ self.assertEqual(
+ finished_reason_1,
+ "interrupted",
+ "Full flow: agent should exit with interrupted",
+ )
+
+ # Step 3: Verify chat-run task is done
+ task = registry.get(session_id)
+ self.assertTrue(
+ task is None or task.done(),
+ "Chat-run task should be cleaned up after interrupt",
+ )
+
+ # ---- Step 4: Next conversation round should work ----
+ model2 = SlowModel()
+ agent2 = Agent(
+ name="FullE2EAgent-Round2",
+ system_prompt="You are a test agent.",
+ model=model2,
+ toolkit=Toolkit(),
+ )
+ # Copy the interrupted context
+ agent2.state = agent.state
+
+ finished_reason_2 = None
+ async for evt in agent2.reply_stream(
+ UserMsg(name="user", content="Continue please"),
+ ):
+ if isinstance(evt, ReplyEndEvent):
+ finished_reason_2 = evt.finished_reason
+
+ self.assertEqual(
+ finished_reason_2,
+ "completed",
+ "Next round after full-flow interruption should complete normally",
+ )
diff --git a/tests/utils.py b/tests/utils.py
index 1a2835767..ac9cdf110 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -73,11 +73,28 @@ class MockModel(ChatModelBase):
def set_responses(
self,
- mock_responses: list[ChatResponse | list[ChatResponse]],
+ mock_responses: list[
+ ChatResponse | BaseException | list[ChatResponse | BaseException]
+ ],
) -> None:
- """Set the mock responses."""
+ """Set the mock responses.
+
+ Each item in ``mock_responses`` may be:
+
+ - ``ChatResponse`` — returned directly by the next non-stream call.
+ - ``BaseException`` — raised from inside the next non-stream call
+ (use e.g. ``asyncio.CancelledError()`` to simulate an
+ interrupted API call).
+ - ``list[ChatResponse | BaseException]`` — returned as an async
+ generator by the next stream call, where each element is
+ either yielded (``ChatResponse``) or raised (``BaseException``)
+ at that position in the stream.
+ """
self.mock_chat_responses = mock_responses
- if all(isinstance(_, ChatResponse) for _ in mock_responses):
+ if all(
+ isinstance(_, (ChatResponse, BaseException))
+ for _ in mock_responses
+ ):
self.stream = False
else:
self.stream = True
@@ -91,10 +108,16 @@ class MockModel(ChatModelBase):
"""Mock the API call."""
mock_responses = self.mock_chat_responses[self.cnt]
self.cnt += 1
+
+ if isinstance(mock_responses, BaseException):
+ raise mock_responses
+
if isinstance(mock_responses, list):
async def _stream() -> AsyncGenerator[ChatResponse, None]:
for response in mock_responses:
+ if isinstance(response, BaseException):
+ raise response
yield response
return _stream()