Skip to main content
Agent is the stateful orchestration class in ai-query. Use it when you need model configuration, tools, persistent state, message history, events, or transport/RPC behavior attached to a stable agent ID.

Import

Constructor

Parameters

str
required
Stable agent identifier. Used for storage keys, routing, and RPC.
LanguageModel | None
Default model for chat(), stream(), run(), and turn().
str
Default system prompt.
ToolSet | None
Default tools available to model calls.
Storage | None
Storage backend. Defaults to MemoryStorage().
StateT | None
State used when storage has no saved state for this agent.
StopCondition | list[StopCondition] | None
Default stop condition for tool loops.
ProviderOptions | None
Default provider-specific options.
ReasoningConfig | None
Default reasoning controls.
RetryPolicy | None
Default provider-call retry policy for chat(), stream(), run(), and turn().
OnReasoningEvent | None
Callback for provider reasoning events. Agent also emits these as reasoning events.
AgentHooks | None
Default runtime hooks for step control, tool policy, tool result overrides, and reasoning observation.
AgentTransport | None
Transport used for remote agent calls.
EventBus | None
Optional event bus used by server/transport layers.

Class Attributes

bool
When True, emitted events are persisted for replay.
dict | BaseModel
Optional subclass blueprint for initial or typed state.

Properties

str
Agent ID.
Storage
Storage backend.
StateT
Current loaded state. Raises RuntimeError before start().
list[Message]
Current message history.

start

Loads state, messages, event log, action registry, and starts the mailbox processor. Idempotent and concurrency-safe.

stop

Stops the mailbox processor and calls on_stop().

Context Manager

Equivalent to await agent.start() followed by await agent.stop().

chat

Appends a user message, runs the model/tool loop, persists messages, and returns final text. Raises:
Exception
Raised if self.model is not configured.
Exception
Raised if signal aborts.

stream

Streams text chunks while persisting final message history. Raises the same errors as chat().

run

Runs an AgentTurn and returns its structured result. Use this when you need steps, usage, finish_reason, or output_message.

turn

Creates a live turn. The turn starts lazily when events(), text_stream(), or result() is consumed. Raises:
Exception
Raised if self.model is not configured.

set_state

Replaces current state, persists it, and emits a state event.

update_state

Merges keyword updates into state, persists the state, and emits a state event. For Pydantic state, uses model_copy(update=kwargs) when available.

clear

Clears message history and persists an empty message list.

emit

Emits an agent event. Parameters:
str
required
Event type to deliver to connected clients.
dict[str, Any]
required
Event payload.
bool
When True, the event is stored in the replay log and may be returned by replay_events(). When False, the event is delivered live to connected clients but omitted from replay persistence.
Returns:
int
Monotonic event ID for this agent instance.
If enable_event_log = True, events are persisted to storage. Notes:
  • Event IDs remain monotonic even for replay=False events.
  • Replay streams may therefore contain gaps in event IDs.
  • Use replay=False for ephemeral UI commands such as open_document that should not re-run on reconnect.

replay_events

Yields events with id > after_id from the in-memory/persisted event log.

clear_event_log

Clears event log and resets event counter.

handle_request

Serverless request dispatcher. Supported actions:
  • chat
  • action
  • invoke
  • state

handle_request_stream

Serverless streaming request handler. Yields SSE-formatted strings for chat requests.

call

Returns a proxy for calling another agent through the configured transport.

handle_invoke

Handles inbound calls from other agents or transports. Resolution order:
  1. registered @action method
  2. legacy on_call_{method} handler
  3. error response

serve

Starts an AgentServer for this agent class.

Lifecycle Hooks

Override in subclasses:

@action

Marks an agent method as externally callable via action/RPC routes.

Examples

Basic agent

Persistent agent

Live turn

See Also