qitos and accessible as:
AgentModule
AgentModule
AgentModule is the strategy layer of QitOS. You subclass it to define your agent’s state shape, system prompt, decision logic, and reduction rules. The Engine drives the execution loop and calls each hook in order.| Parameter | Type | Description |
|---|---|---|
tool_registry | ToolRegistry | None | Registry of tools the agent can call |
llm | Any | LLM callable used for model decisions |
model_parser | Any | Parser that converts raw model output to a Decision |
memory | Memory | None | Optional memory adapter |
history | History | None | Optional history adapter |
**config | Any | Extra keyword args stored as self.config |
init_state and reduce are required.init_state (required)
init_state (required)
Engine.run() before the step loop begins. Use **kwargs to accept extra parameters forwarded from AgentModule.run().reduce (required)
reduce (required)
build_system_prompt
build_system_prompt
None to use no system prompt. Called at the start of each step’s decide phase. Default returns None.prepare
prepare
str(state).decide
decide
Decision to bypass the Engine’s model call, or None to let the Engine call the LLM and parse the output. Default returns None.should_stop
should_stop
True to terminate the run with StopReason.AGENT_CONDITION. Default returns False..run() methodConvenience method that builds an Engine, runs it, and returns the final result.| Parameter | Type | Default | Description |
|---|---|---|---|
task | str | Task | required | Task objective or structured Task object |
return_state | bool | False | When True, returns the full EngineResult; otherwise returns state.final_result |
hooks | List[Any] | None | None | Additional EngineHook instances to register |
render_hooks | List[Any] | None | None | Additional render hook instances |
engine_kwargs | Dict[str, Any] | None | None | Extra keyword arguments forwarded to the Engine constructor |
workspace | str | None | None | Path to workspace root; auto-constructs a HostEnv when set |
max_steps | int | None | None | Override the maximum number of steps |
env | Any | None | Explicit Env instance; takes precedence over workspace |
parser | Any | None | Parser to pass to the Engine |
search | Any | None | Search strategy instance |
critics | List[Any] | None | None | List of Critic instances |
stop_criteria | List[Any] | None | None | Custom stop criteria list |
history_policy | Any | None | HistoryPolicy instance |
trace | Any | None | True to enable default tracing, or a TraceWriter instance |
render | Any | None | True to enable default render hook |
trace_logdir | str | "./runs" | Directory where trace files are written |
trace_prefix | str | None | None | Prefix for the auto-generated run ID |
theme | str | "research" | Render theme name |
**state_kwargs | Any | Extra kwargs forwarded to init_state() |
state.final_result by default, or an EngineResult when return_state=True.Engine
Engine
Engine is the execution kernel. It owns the phase loop, tool execution, recovery, tracing, and stop-criteria evaluation. You normally obtain an Engine through AgentModule.build_engine() or AgentModule.run(), but you can also construct one directly.| Parameter | Type | Default | Description |
|---|---|---|---|
agent | AgentModule | required | Agent whose hooks the Engine will call |
budget | RuntimeBudget | None | RuntimeBudget(max_steps=10) | Step, time, and token budgets |
validation_gate | StateValidationGate | None | default gate | Pre/post phase state validation |
recovery_handler | RecoveryHandler | None | None | Callable invoked on recoverable errors |
recovery_policy | RecoveryPolicy | None | default policy | Controls retry behaviour on failures |
trace_writer | TraceWriter | None | None | Writes structured trace artifacts to disk |
parser | Parser[ActionT] | None | None | Parser for raw model output |
stop_criteria | List[StopCriteria] | None | [FinalResultCriteria()] | Ordered list of stop criteria |
branch_selector | BranchSelector | None | FirstCandidateSelector() | Strategy for picking among branch candidates |
search | Search | None | None | Search strategy for branch decisions |
critics | List[Critic] | None | [] | Critics evaluated after each step |
env | Env | None | None | Environment for observe/step lifecycle |
history_policy | HistoryPolicy | None | HistoryPolicy() | Controls message history assembly |
hooks | List[EngineHook] | None | [] | Engine lifecycle hooks |
render_hooks | List[Any] | None | None | Render hooks merged into hooks |
task. Resets run state, initialises the env, calls agent.init_state(), then iterates the decide→act→reduce→check_stop cycle until a stop condition triggers. Returns an EngineResult.EngineResult
EngineResult
EngineResult is the dataclass returned by Engine.run().| Field | Type | Description |
|---|---|---|
state | StateT | Final typed state after the run |
records | List[StepRecord] | Per-step records including decision, actions, and observations |
events | List[RuntimeEvent] | Ordered list of all runtime events emitted during the run |
step_count | int | Number of steps executed |
task_result | TaskResult | None | Structured task outcome, populated when a Task object was passed |
Decision
Decision
Decision is the canonical output of the decide phase. Use the factory class methods rather than constructing directly.| Mode | Meaning |
|---|---|
"act" | Execute one or more actions |
"final" | Produce a final answer and stop |
"wait" | Skip action execution this step |
"branch" | Propose multiple candidate decisions for the branch selector |
.validate() — Raises ValueError if the decision is structurally invalid (e.g. act with no actions).Action
Action
Action is the normalized action contract emitted by the policy and consumed by the executor.| Field | Type | Description |
|---|---|---|
name | str | Tool name to call |
args | Dict[str, Any] | Keyword arguments forwarded to the tool |
kind | ActionKind | Currently only ActionKind.TOOL ("tool") |
action_id | str | None | Optional unique identifier for the action |
timeout_s | float | None | Per-action timeout override in seconds |
max_retries | int | Number of retries on failure |
idempotent | bool | Whether the action is safe to retry |
classification | str | User-defined label for grouping/filtering |
metadata | Dict[str, Any] | Arbitrary extra metadata |
Action.from_dict(payload) — Construct from a plain dict.StateSchema
StateSchema
StateSchema is the canonical typed state base class. Subclass it to define your agent’s state fields.| Field | Description |
|---|---|
task | The task objective string |
current_step | Step counter incremented by advance_step() |
max_steps | Hard cap on steps; validated on every advance_step() call |
final_result | The agent’s final answer string |
stop_reason | A StopReason value string set when the run ends |
metadata | Free-form dict for agent-specific data |
metrics | Free-form dict for numeric metrics |
Task, TaskBudget, TaskResource, TaskResult
Task, TaskBudget, TaskResource, TaskResult
Use
Task when you need to pass structured metadata, resources, and budget constraints alongside the objective string.Task helper methodsEnv, EnvSpec
Env, EnvSpec
Env is the abstract environment interface. Implement it to provide a custom observe/step lifecycle for your agent.EnvSpec is a dataclass used inside Task to declare the environment type and configuration:tool decorator
tool decorator
The
Example
tool decorator marks a callable as a QitOS tool and attaches metadata to it without changing its call semantics.| Parameter | Type | Description |
|---|---|---|
name | str | None | Override the tool name (defaults to the function’s __name__) |
description | str | None | Override the tool description (defaults to the docstring) |
timeout_s | float | None | Per-call timeout in seconds |
max_retries | int | Number of retries on failure |
permissions | ToolPermission | None | Permission flags for the tool |
required_ops | List[str] | None | Runtime ops required from the environment |
ToolRegistry
ToolRegistry
ToolRegistry stores tools and toolsets and is passed to AgentModule and Engine at construction time.ToolRegistry() (no parameters)MethodsBaseTool. Returns self for chaining.namespace (defaults to toolset.name).@tool and register them all.Memory
Memory
Memory is the abstract interface for long-term memory adapters.MemoryRecord is the unit of storage:History, HistoryPolicy
History, HistoryPolicy
History is the abstract interface for model message history adapters.HistoryPolicy controls how the Engine assembles history for model calls:| Field | Description |
|---|---|
roles | Message roles to include |
max_messages | Maximum number of messages to include |
step_window | If set, only include messages from the last N steps |
max_tokens | If set, trim messages to fit within this token budget |
HistoryMessage is the unit of storage:StopReason
StopReason
StopReason is a string enum. Its value is written to state.stop_reason when a run ends.| Value | When set |
|---|---|
success | Agent completed successfully |
final | Decision.final() was accepted |
max_steps | StateSchema.max_steps reached |
budget_steps | RuntimeBudget.max_steps reached |
budget_time | RuntimeBudget.max_runtime_seconds elapsed |
budget_tokens | RuntimeBudget.max_tokens consumed |
agent_condition | AgentModule.should_stop() returned True |
critic_stop | A Critic returned action="stop" |
stagnation | No state change detected for N steps |
env_terminal | Env.is_terminal() returned True |
task_validation_failed | Task.validate_structured() produced issues |
env_capability_mismatch | Environment missing required ops |
unrecoverable_error | Fatal error with no recovery path |
QitosRuntimeError
QitosRuntimeError
QitosRuntimeError is the base class for all structured runtime errors in QitOS.RuntimeErrorInfo carries structured context:ModelExecutionError, ParseExecutionError, ToolExecutionError, StateExecutionError, SystemExecutionError.