AskUserExtension#
Build extensions, choose hooks, and manage request-scoped state. See the guide.
- class zett_agent.extensions.ask_user.AskUserExtension[源代码]#
Register ask_user and suspend its execution until accept() receives a reply.
The normal tool lifecycle remains intact; waiting happens before TOOL_STARTED.
sequenceDiagram participant Model participant Agent participant Extension participant UI Model->>Agent: ask_user ToolCall Agent->>Extension: before_tool() + context.emit() Extension-->>UI: AskUserEvent Note over Agent,Extension: waiting before TOOL_STARTED UI->>Extension: ExternalEvent via accept() Extension-->>Agent: resume Agent->>Extension: TOOL_STARTED and ask_user() Extension-->>Model: ToolMessageAsk-user pause and resume protocol#
While waiting, RunCancelledEvent cancels the Future and on_error() completes it with that error. Both paths wake the suspended coroutine.
Closing or cancelling the stream removes the pending route, so a late UI response cannot resume an abandoned request.
示例
Register the extension and forward its custom event to a UI:
ask_user = AskUserExtension() client = await create_agent(model, extensions=[ask_user]) async for event in client.stream("Help me choose a format"): if event.name == "ask_user": show_question(event.payload)
Outbound protocol:
AgentEvent( type=CUSTOM, name="ask_user", session_id="session-42", payload={ "session_id": "session-42", "tool_call_id": "call-7", "question": "Which format?", "options": ["Markdown", "Plain text"], "allow_multiple": False, "response_event": "ask_user_response", }, )
Inbound protocol:
agent.emit_external_event( ExternalEvent( name="ask_user_response", payload={"tool_call_id": "call-7", "answer": "Markdown"}, ), config=AgentRunConfig(session_id="session-42"), )
ExternalEventExtension owns routing, synchronization, wake-up, and cleanup. The response payload is application-defined and returned unchanged to the model. Agent.emit_external_event() returns an empty list when no extension accepts an unrelated, malformed, duplicate, stale, or cancelled event.
警告
A UI must route the response with the matching session and tool-call ID. Displaying a question is not equivalent to authorizing an action.
参见
ExternalEventExtensionowns waiting and wake-up; 发出事件并接收用户输入 contains a complete approval example.- async on_tool(context)[源代码]#
Register a request-scoped ask_user tool bound to this context.
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async before_tool(context, call)[源代码]#
Emit AskUserEvent, then wait for the matching external response.
- 参数:
context (AgentRunContext)
call (ToolCall)
- 返回类型:
None
- accept(config, event)#
Claim a matching response and wake its waiter on the Future's loop.
Usually called by Agent.emit_external_event, not directly by the UI. True means this extension accepted delivery; False leaves other extensions free to recognize the event. Neither argument is modified.
- 参数:
config (AgentRunConfig | None)
event (ExternalEvent)
- 返回类型:
bool
- async after_model(context, response)#
Run after the complete assistant message is appended.
- 参数:
context (AgentRunContext)
response (ModelResponse)
- 返回类型:
None
- async after_run(context, result)#
Run after a successful final answer is appended.
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
None
- async after_tool(context, call, result, error)#
Inspect or modify a tool result before it is appended.
erroris the original execution exception for a failed result and None after successful execution. Changes made toresultare included in context, persistence, and the next model request. Raising prevents the result from being appended.- 参数:
context (AgentRunContext)
call (ToolCall)
result (ToolMessage)
error (Exception | None)
- 返回类型:
None
- async after_turn(context, result)#
Run once the turn's assistant message and tool results are settled.
resultis the assistant message that opened the turn: either the final answer, or the tool-calling message whose ToolMessages were appended. Every requested call is settled first, including calls that failed, and calls that steering skipped, which arrive as unsuccessful or skipped ToolMessages.Steering that interrupts a turn is accepted while the runtime settles that batch, so its UserMessage is already appended when this hook runs and the steering turn follows as the next turn.
A turn that never completed, because the request failed or was cancelled, has no after_turn call; use on_error and RunCancelledEvent for those paths.
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
None
- async before_model(context, request)#
Inspect the current request before preprocessing a primary model call.
Request fields are frozen. Change messages through
AgentRunContext.add_message()orAgentRunContext.replace_messages(), local tools through context.tools, and provider tools through context.server_tools; the runtime rebuilds these fields before the next hook and before calling the provider. This is a shallow request view, not an immutable copy of each message or tool definition.示例
Inspect the tools offered in this iteration:
async def before_model(self, context, request): offered = {definition.name for definition in request.tools} if "write_file" in offered: context.add_message( SystemMessage(content="Read existing files before editing."), )
- 参数:
context (AgentRunContext)
request (ModelRequest)
- 返回类型:
None
- async before_run(context)#
Run after the transformed user input is appended and published.
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async before_turn(context)#
Run before this turn's model call.
Runs after before_run() on the first turn and after the previous turn's after_turn() on later ones. Model request assembly, compaction, and before_model() follow this hook, so context edited here reaches the provider.
- 参数:
context (AgentRunContext)
- 返回类型:
None
- property name: str#
Unique registration identity, defaulting to the concrete class name.
Override with a class attribute or assign an instance name to register independently configured instances of the same extension type.
- async on_compact(context)#
Summarize restored context when a caller asks for compaction.
Agent.compactrestores the session throughon_toolandon_stateexactly as a request does, appends no input message, and makes no primary model call: the only work a compaction pass does is what this hook performs. The default does nothing, so an extension with nothing to compact pays nothing.示例
Usage:
async def on_compact(self, context): await self.compact(context)
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async on_error(context, error)#
Complete active waits with the request's original error.
- 参数:
context (AgentRunContext)
error (Exception)
- 返回类型:
None
- async on_event(context, event)#
Cancel active waits when their request enters CANCELLED.
- 参数:
context (AgentRunContext)
event (ExtensionEvent)
- 返回类型:
None
- async on_message(context)#
Transform context.input_message after state restoration, before append.
Replace the pending UserMessage to implement externally selected modes. Do not append or persist it here: the runtime appends the final message exactly once after all input hooks finish. before_run sees that message through
AgentRunContext.add_message()orAgentRunContext.replace_messages(), and persistence subscribers have already received it.- 参数:
context (AgentRunContext)
- 返回类型:
None
- async on_model_request(context, request, call_next)#
Wrap one provider request and its complete streamed response.
Pass
request(or a dataclass replacement) tocall_next. The default closes the inner stream so cancellation reaches the provider.- 参数:
context (AgentRunContext)
request (ModelRequest)
call_next (ModelRequestNext)
- 返回类型:
AsyncIterator[ModelEvent]
- async on_state(context)#
Restore history and initialize state before any input conversion.
示例
Usage:
async def on_state(self, context): context.add_message(SystemMessage(content="Use concise answers."), index=0)
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async on_success(context, result)#
Run once after all after_run hooks succeed, before RUN_COMPLETED.
This callback observes a completed request, not an intermediate model step. Failed or cancelled requests do not trigger it. Callback errors propagate through on_error and prevent RUN_COMPLETED from being emitted.
示例
Usage:
async def on_success(self, context, result): await save_answer(context.session_id, result.content)
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
None
- async on_tool_call(context, call, call_next)#
Wrap one registered local tool handler and return its
ToolResult.An extension may adjust
call.arguments, return without calling the next layer, transform its result, or raise into normal tool-failure handling.- 参数:
context (AgentRunContext)
call (ToolCall)
call_next (ToolCallNext)
- 返回类型:
- property pending: bool#
Return whether this extension is participating in an active request.
The Agent updates this state for every registered extension, including extensions whose hooks are currently idle. One extension instance may be shared by multiple Agents and sessions;
pendingremains true until all requests using that instance have finished, failed, or been cancelled. Persistent data retained between requests does not count.