SQLiteSessionExtension#
Restore model context and preserve immutable original messages. See the guide.
- class zett_agent.extensions.sqlite.SQLiteSessionExtension(path=None)[source]#
Restore and save agent sessions in an owned SQLite database.
- Parameters:
path (str | Path | None) – Database file or None for the storage default under the user data directory. Use an explicit temporary path in tests.
Examples
Persist and query a conversation:
persistence = SQLiteSessionExtension("sessions.sqlite") try: client = await create_agent( model, config=AgentRunConfig(session_id="demo"), extensions=[persistence, ToolGuidelinesExtension()], ) await client.run("Remember the project requirements.") messages = await persistence.list_raw_messages("demo", limit=20) finally: await persistence.close()
Note
Explicit extensions replace Agent defaults. Storage restores context; do not add a second history restorer to the same request unnecessarily.
- async list_raw_messages(session_id, *, after_sequence=0, through_sequence=None, limit=10000, offset=0)[source]#
Forward a paginated Raw Log query to the owned session storage.
- Parameters:
session_id (str) – Conversation whose immutable messages are requested.
after_sequence (int) – Exclusive lower sequence bound; zero starts at the beginning.
through_sequence (int | None) – Inclusive upper bound; None leaves it unbounded.
limit (int) – Maximum number of records returned.
offset (int) – Records to skip after applying sequence filters.
- Returns:
Original messages in ascending sequence order, with timing and usage.
- Return type:
list[RawMessageRecord]
- async create_session(*, session_id=None, parent_session_id=None, title=None, agent_name=None, session_type=0)[source]#
Create an empty session in the owned storage.
- Parameters:
session_id (str | None)
parent_session_id (str | None)
title (str | None)
agent_name (str | None)
session_type (int)
- Return type:
- async list_sessions(*, session_types=None, limit=100, offset=0)[source]#
Forward a paginated session-summary query to owned storage.
- Parameters:
session_types (Sequence[int] | None)
limit (int)
offset (int)
- Return type:
list[SessionSummary]
- async get_session(session_id)[source]#
Forward a typed session metadata lookup to the owned storage.
- Parameters:
session_id (str)
- Return type:
SessionSummary | None
- async update_session(session_id, *, title=None, agent_name=None)[source]#
Forward a typed session update to the owned storage.
- Parameters:
session_id (str)
title (str | None)
agent_name (str | None)
- Return type:
SessionSummary | None
- async delete_session(session_id)[source]#
Delete one session and its Raw Log and snapshot records explicitly.
- Parameters:
session_id (str)
- Return type:
bool
- async close()[source]#
Release the SQLite connection pool without deleting history.
- Return type:
None
- accept(config, event)#
Handle one external event and report whether it was accepted.
The Agent broadcasts each event to every registered extension. Override this synchronous hook when an extension waits for input from another thread, HTTP request, TUI, or Web UI. The default ignores the event. Config is passed separately and can be None before initialization. Each extension decides whether the supplied identity and payload match its protocol. Return True to include this extension’s name in the broadcast result; returning False does not stop later receivers.
- Parameters:
config (AgentRunConfig | None)
event (ExternalEvent)
- Return type:
bool
- async after_model(context, response)#
Run after the complete assistant message is appended.
- Parameters:
context (AgentRunContext)
response (ModelResponse)
- Return type:
None
- async after_run(context, result)#
Run after a successful final answer is appended.
- Parameters:
context (AgentRunContext)
result (AssistantMessage)
- Return type:
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.- Parameters:
context (AgentRunContext)
call (ToolCall)
result (ToolMessage)
error (Exception | None)
- Return type:
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.
- Parameters:
context (AgentRunContext)
result (AssistantMessage)
- Return type:
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.Examples
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."), )
- Parameters:
context (AgentRunContext)
request (ModelRequest)
- Return type:
None
- async before_run(context)#
Run after the transformed user input is appended and published.
- Parameters:
context (AgentRunContext)
- Return type:
None
- async before_tool(context, call)#
Run before one requested tool is invoked.
- Parameters:
context (AgentRunContext)
call (ToolCall)
- Return type:
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.
- Parameters:
context (AgentRunContext)
- Return type:
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.Examples
Usage:
async def on_compact(self, context): await self.compact(context)
- Parameters:
context (AgentRunContext)
- Return type:
None
- async on_error(context, error)#
Release bookkeeping; append-only Raw Log history remains available.
- Parameters:
context (AgentRunContext)
error (Exception)
- Return type:
None
- async on_event(context, event)#
Process a published notification; inspect its concrete type with match.
- Parameters:
context (AgentRunContext)
event (ExtensionEvent)
- Return type:
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.- Parameters:
context (AgentRunContext)
- Return type:
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.- Parameters:
context (AgentRunContext)
request (ModelRequest)
call_next (ModelRequestNext)
- Return type:
AsyncIterator[ModelEvent]
- async on_state(context)#
Restore context and map every dialogue position to its Raw Log boundary.
- Parameters:
context (AgentRunContext)
- Return type:
None
- async on_success(context, result)#
Release bookkeeping; original messages were appended as they arrived.
- Parameters:
context (AgentRunContext)
result (AssistantMessage)
- Return type:
None
- async on_tool(context)#
Register local or provider-hosted tools before context restoration.
All extensions finish this hook before the first on_state() call, so prompt extensions can reliably inspect
context.toolsandcontext.server_toolsas complete request-scoped registries.Examples
Usage:
async def on_tool(self, context): context.register_tool(read_file) context.register_server_tool(ServerToolDefinition(type="web_search"))
- Parameters:
context (AgentRunContext)
- Return type:
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.- Parameters:
context (AgentRunContext)
call (ToolCall)
call_next (ToolCallNext)
- Return type:
- 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.