Skip to main content

enterprise_ai.loop

Source: sdks/python/src/enterprise_ai/loop/__init__.py. Back to the Python SDK reference index.

note

This page is generated by tools/docs/gen_sdk_reference.py from the SDK sources and the OpenAPI text folders. Do not edit it by hand: change the source and regenerate.

Model LoopBudget​

Local budgets; None means unlimited.

Fields:

NameTypeRequiredDescription
max_stepsintnoMaximum number of model calls (plan steps). Default 20.
max_tool_callsint | NonenoMaximum number of tool calls over the run; None is unlimited.
max_output_tokensint | NonenoMaximum number of output tokens over the run; None is unlimited.
max_costDecimal | NonenoMaximum measured cost of the run, as a Decimal; None is unlimited.
max_recoveriesintnoMaximum number of recoveries after a failed tool call or a rejected answer before the run fails. Default 3.
max_durationfloat | NonenoMaximum duration of the run, in seconds; None is unlimited.
max_secondsfloat | NonenoAlias of max_duration, kept for compatibility.

LoopBudget.from_manifest​

from_manifest(manifest: dict[str, Any]) -> LoopBudget

Budgets from spec.autonomy, spec.budgets and spec.runtime.limits.

NameTypeDefaultRequiredDescription
manifestdict[str, Any]yesAgent manifest as a dict, read under its spec key.

Returns: LoopBudget. A LoopBudget: Local budgets; None means unlimited.

Model LoopState​

Serializable state of a run (stored in checkpoints).

Fields:

NameTypeRequiredDescription
messageslist[dict[str, Any]]noChat messages of the run, tool results included.
stepintnoCurrent step, free text (up to 500 characters).
tool_callsintnoNumber of tool calls executed so far.
input_tokensintnoInput tokens counted over the run.
output_tokensintnoOutput tokens counted over the run.
coststrnoMeasured cost so far, as a decimal string. Default "0".
pendinglist[dict[str, Any]]noTool calls asked by the model and not executed yet.
finalAnynoTrue when this is the last step of the run. Default false.
statusstrnoStatus of the run: running (default), completed, failed, budget_exhausted or stopped.
recoveriesintnoNumber of recoveries so far (failed tool calls or rejected answers).
last_errorstr | NonenoLast failure or the name of the spent budget, or None.
phasestrnoNext phase to run: plan (default), act, verify or done.
started_atfloatnoMonotonic clock value at the start, used for max_duration; not saved in checkpoints.

LoopState.from_dict​

from_dict(data: dict[str, Any]) -> LoopState

Rebuild a state from a checkpoint dict; unknown keys and started_at are ignored.

NameTypeDefaultRequiredDescription
datadict[str, Any]yesDict produced by to_dict, for example the state of a checkpoint.

Returns: LoopState. A LoopState: Serializable state of a run (stored in checkpoints).

LoopState.to_dict​

to_dict() -> dict[str, Any]

Serializable form of the state for a checkpoint, without started_at.

This element takes no parameter.

Returns: dict[str, Any]. Dict of every field except started_at.

Model LoopResult​

Outcome of :meth:AgentLoop.run.

Fields:

NameTypeRequiredDescription
statusstryesFinal status of the run: completed, failed, budget_exhausted or stopped.
outputAnyyesOutput of the operation (transcript, image references...).
stateLoopStateyesSerializable state of a run (stored in checkpoints).
reasonstr | NonenoWhy the action is taken. Written to the audit trail with the actor and the time.

Attributes:

NameTypeRequiredDescription
okboolyesTrue when status is completed.

Class AgentLoop​

Run an agent with budgets and governance hooks.

Attributes:

NameTypeRequiredDescription
agent_idyesIdentifier of the agent watched by the kill switch, or None.
approval_foryesGlob patterns of tools that need a human approval.
approval_timeoutyesMaximum wait for an approval decision, in seconds.
budgetyesLocal budgets (LoopBudget) applied by route.
busyesMessage bus read by serve, or None.
checkpoint_everyyesNumber of steps between two checkpoints; 0 saves only the final one.
clientyesEnterprise AI client used for checkpoints, approvals, kill switch, sessions and usage, or None to run offline.
context_budgetyesContextBudget used by prepare_context, or None.
final_verifieryesFunction checking the final answer, or None to accept every answer.
history_limityesNumber of last session messages loaded as history; 0 loads every one.
kill_poll_everyyesNumber of steps between two polls of the agent status; 0 disables the poll.
last_runnerAnyyesLast AgentRunner built by runner, or None.
modelyesModel identifier, or None.
model_callyesFunction (messages, tools) -> completion called in the plan phase.
on_eventyesCallback (kind, data) called on each loop event, or None.
poll_intervalyesPause between two intake cycles of serve, in seconds.
processed_runsset[str]yesIdentifiers of the pending runs already taken by serve, so none is run twice.
record_stepsyesWhen True, each phase is recorded as a run step on the server.
remote_toolyesFunction (name, arguments) running the tools that are not local, or None.
remote_tool_specsyesOpenAI tools entries of the remote tools.
run_idyesIdentifier of the server run, or None.
runner_optionsyesExtra keyword arguments passed to every AgentRunner.
session_cursorsdict[str, str | None]yesWatched sessions with the identifier of the last message processed (None before the first).
session_idyesDefault session of the loop, or None.
stop_eventyesEvent that stops the loop when set (heartbeat or killed agent).
toolsdict[str, LocalTool]yesLocal tools by name (a dict of LocalTool).
verifieryesFunction checking each tool result, or None to accept every result.

Constructor AgentLoop​

AgentLoop(model_call: ModelCall | None = None, model: str | None = None, session_id: str | None = None, bus: Any = None, context_budget: Any = None, history_limit: int = 50, poll_interval: float = 2.0, watch_sessions: list[str] | None = None, runner_options: dict[str, Any] | None = None, tools: dict[str, LocalTool] | list[LocalTool] | None = None, remote_tool: Callable[[str, dict[str, Any]], Any] | None = None, remote_tool_specs: list[dict[str, Any]] | None = None, budget: LoopBudget | None = None, verifier: Verifier | None = None, final_verifier: Callable[[Any], bool | str] | None = None, approval_for: list[str] | None = None, client: Any = None, agent_id: str | None = None, run_id: str | None = None, checkpoint_every: int = 1, kill_poll_every: int = 1, record_steps: bool = True, stop_event: threading.Event | None = None, on_event: Callable[[str, dict[str, Any]], None] | None = None, approval_timeout: float = 3600.0) -> None

Configure the loop: model, local and remote tools, budgets, verifiers, approvals and the client used for checkpoints, kill switch and run steps.

NameTypeDefaultRequiredDescription
model_callModelCall | NoneNonenoFunction (messages, tools) -> completion returning an OpenAI style completion; an optional eai_cost key is added to the cost.
modelstr | NoneNonenoModel identifier used by the runner and the context builder.
session_idstr | NoneNonenoDefault session whose history is loaded and to which answers are posted.
busAnyNonenoMessage bus read by serve: inbound messages are answered and the answer is published outbound; None disables it.
context_budgetAnyNonenoContextBudget used to fit the system prompt, history and input in prepare_context; None keeps every message.
history_limitint50noNumber of last session messages loaded as history; 0 loads every one. Default 50.
poll_intervalfloat2.0noPause between two intake cycles of serve, in seconds. Default 2.0.
watch_sessionslist[str] | NoneNonenoSessions whose new messages are processed by serve, from the start.
runner_optionsdict[str, Any] | NoneNonenoExtra keyword arguments passed to every AgentRunner built by runner.
toolsdict[str, LocalTool] | list[LocalTool] | NoneNonenoLocal tools, as a list of LocalTool or a dict by name.
remote_toolCallable[[str, dict[str, Any]], Any] | NoneNonenoFunction (name, arguments) that runs a tool which is not local, for example through the Tool Gateway.
remote_tool_specslist[dict[str, Any]] | NoneNonenoOpenAI tools entries of the remote tools, offered to the model next to the local ones.
budgetLoopBudget | NoneNonenoLocal budgets (LoopBudget); by default 20 steps and 3 recoveries, nothing else limited.
verifierVerifier | NoneNonenoFunction (name, result) checking each tool result: True accepts it, any other value is a failure reason and triggers a recovery.
final_verifierCallable[[Any], bool | str] | NoneNonenoFunction checking the final answer: True accepts it, any other value is the rejection reason sent back to the model.
approval_forlist[str] | NoneNonenoGlob patterns of tools that need a human approval, matched against name and tool:<name>; empty by default.
clientAnyNonenoParent client.
agent_idstr | NoneNonenoIdentifier of the agent whose status is polled by the kill switch and reported in usage events.
run_idstr | NoneNonenoIdentifier of the server run used for checkpoints, run steps and usage events.
checkpoint_everyint1noSave a checkpoint after the act phase every N steps; 0 saves only the final one. Default 1.
kill_poll_everyint1noPoll the agent status for the kill switch every N steps; 0 disables the poll. Default 1.
record_stepsboolTruenoWhen True (default) and a run id is set, each phase is recorded as a run step on the server.
stop_eventthreading.Event | NoneNonenoEvent that stops the loop when set (heartbeat); a new threading.Event by default.
on_eventCallable[[str, dict[str, Any]], None] | NoneNonenoCallback (kind, data) called on each loop event (plan, tool, approval_requested, done).
approval_timeoutfloat3600.0noMaximum wait for an approval decision, in seconds. Default 3600.0.

AgentLoop.act​

act(state: LoopState) -> LoopState

Execute pending tool calls; failures and rejections become tool messages.

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState, whose pending tool calls are executed; it is updated in place.

Returns: LoopState. A LoopState: Serializable state of a run (stored in checkpoints).

AgentLoop.check_budget​

check_budget(state: LoopState) -> str | None

Name of the exhausted budget, or None.

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState, compared with the limits of budget.

Returns: str \| None. max_steps, max_tool_calls, max_output_tokens, max_cost or max_duration, or None when no budget is spent.

AgentLoop.check_kill_switch​

check_kill_switch(state: LoopState) -> None

Raise :class:AgentStopped when the heartbeat or the agent status asks to stop.

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState; its step number decides whether the agent status is polled this time.

Returns: None.

Raises: AgentStopped.

AgentLoop.checkpoint​

checkpoint(state: LoopState) -> Any

POST the state to the server checkpoints API (when a run id is known).

NameTypeDefaultRequiredDescription
stateLoopStateyesState to save, sent with the label step-<n>.

Returns: Any. Answer of the checkpoints API, or None without a client or a run id.

AgentLoop.history​

history(session_id: str) -> list[dict[str, Any]]

List the messages of a session. Messages in order, paginated with cursor. after (message id or timestamp) lets a runtime poll the new messages only; an unknown message id or a malformed timestamp answers 400 invalid_request.

Route: /v1/sessions/{session_id}/messages (GET).

NameTypeDefaultRequiredDescription
session_idstryesIdentifier (UUID) of the session.

Returns: list[dict[str, Any]]. Decoded JSON answer of the operation "List the messages of a session".

Raises: the typed errors of the transport (Errors).

AgentLoop.needs_approval​

needs_approval(name: str) -> bool

Tell whether a tool call needs a human approval: the local tool requires one or its name matches approval_for.

NameTypeDefaultRequiredDescription
namestryesName of the tool, matched as name and tool:<name>.

Returns: bool. True when the call must be approved first.

AgentLoop.plan​

plan(state: LoopState) -> LoopState

Call the model; store tool calls in pending or the answer in final.

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState; its messages are sent to the model and it is updated in place.

Returns: LoopState. A LoopState: Serializable state of a run (stored in checkpoints).

AgentLoop.poll_once​

poll_once() -> list[TurnResult]

List the runs. Runs of the tenant, newest first, paginated with cursor. Filters: agent_id (id or name; agent is an alias), state, session_id, parent_run_id. An unknown state or a malformed UUID answers 400 invalid_request.

Route: /v1/runs (GET).

This element takes no parameter.

Returns: list[TurnResult]. A TurnResult: Outcome of :meth:AgentRunner.run_turn.

Raises: the typed errors of the transport (Errors).

AgentLoop.prepare_context​

prepare_context(input: Any, session_id: str | None = None, system: str | None = None) -> list[dict[str, Any]]

System prompt + session history + the new input, fitted in context_budget when set.

NameTypeDefaultRequiredDescription
inputAnyyesNew user input; a non text value is serialized as JSON, None adds no user message.
session_idstr | NoneNonenoSession whose history is loaded; None uses no history.
systemstr | NoneNonenoSystem prompt placed first, or None.

Returns: list[dict[str, Any]]. List of chat messages (role, content) ready for the model.

AgentLoop.request_approval​

request_approval(name: str, arguments: dict[str, Any]) -> bool

Create an approval and wait for the decision. True when approved.

NameTypeDefaultRequiredDescription
namestryesName of the tool, sent as the resource of the approval (tools:invoke action).
argumentsdict[str, Any]yesArguments of the tool call, sent as the reason of the approval (JSON, at most 500 characters).

Returns: bool. True when the decision is approved; raises ApprovalRequired without a client.

Raises: ApprovalRequired.

AgentLoop.resume​

resume(run_id: str) -> TurnResult

List the checkpoints of a run. Checkpoints of the run in sequence order. One page only. 404 run_not_found.

Route: /v1/runs/{run_id}/checkpoints (GET).

NameTypeDefaultRequiredDescription
run_idstryesIdentifier (UUID) of the run.

Returns: TurnResult. A TurnResult: Outcome of :meth:AgentRunner.run_turn.

Raises: ValueError, the typed errors of the transport (Errors).

AgentLoop.route​

route(state: LoopState) -> str

Next phase: plan, act, verify or done (applies budgets and recovery limits).

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState; its status and last_error are set when the loop ends.

Returns: str. Name of the next phase: plan, act, verify or done.

AgentLoop.run_legacy​

run_legacy(task: Any = None, system: str | None = None, messages: list[dict[str, Any]] | None = None, state: LoopState | None = None, raise_on_budget: bool = False) -> LoopResult

Drive the loop to completion. Resumes from state when given (checkpoint restore).

NameTypeDefaultRequiredDescription
taskAnyNonenoTask given to the agent as a user message; a non text value is serialized as JSON.
systemstr | NoneNonenoSystem prompt, added first when the messages hold none.
messageslist[dict[str, Any]] | NoneNonenoPrevious chat messages to start from.
stateLoopState | NoneNonenoState restored from a checkpoint; when given, task, system and messages are ignored.
raise_on_budgetboolFalsenoWhen True, a spent budget raises BudgetExhausted instead of returning a result. Default False.

Returns: LoopResult. A LoopResult: Outcome of :meth:AgentLoop.run.

Raises: BudgetExhausted.

AgentLoop.run_once​

run_once(input: Any = None, session_id: str | None = None, run_id: str | None = None, system: str | None = None, state: dict[str, Any] | None = None) -> TurnResult

Run one Navin turn (:class:AgentRunner) and post the answer to the session.

NameTypeDefaultRequiredDescription
inputAnyNonenoNew user input of the turn; ignored when state is given.
session_idstr | NoneNonenoSession of the turn, used for history and to post the answer; defaults to the session_id of the loop.
run_idstr | NoneNonenoServer run of the turn; defaults to the run_id of the loop.
systemstr | NoneNonenoSystem prompt of the turn, or None.
statedict[str, Any] | NoneNonenoRunner state restored from a checkpoint to resume the turn.

Returns: TurnResult. A TurnResult: Outcome of :meth:AgentRunner.run_turn.

AgentLoop.runner​

runner(run_id: str | None = None, session_id: str | None = None) -> AgentRunner

An :class:AgentRunner sharing this loop's model, tools, budget and stop event.

NameTypeDefaultRequiredDescription
run_idstr | NoneNonenoServer run of the runner; defaults to the run_id of the loop.
session_idstr | NoneNonenoSession of the runner; defaults to the session_id of the loop.

Returns: AgentRunner. A AgentRunner: Run agent turns against the platform gateway with tools, rules and governance.

AgentLoop.serve​

async serve(max_cycles: int | None = None) -> None

Serve until :meth:shutdown: bus inbound messages, pending runs and new session messages.

NameTypeDefaultRequiredDescription
max_cyclesint | NoneNonenoStop after this number of intake cycles; None serves until shutdown.

Returns: None.

AgentLoop.shutdown​

shutdown() -> None

Ask :meth:serve to exit after the current turn.

This element takes no parameter.

Returns: None.

AgentLoop.start_state​

start_state(task: Any, system: str | None = None, messages: list[dict[str, Any]] | None = None) -> LoopState

Build the initial LoopState: previous messages, the system prompt when none is present, then the task as a user message.

NameTypeDefaultRequiredDescription
taskAnyyesTask appended as a user message; a non text value is serialized as JSON, None adds nothing.
systemstr | NoneNonenoSystem prompt, inserted first when the messages hold none.
messageslist[dict[str, Any]] | NoneNonenoPrevious chat messages, copied.

Returns: LoopState. A LoopState: Serializable state of a run (stored in checkpoints).

AgentLoop.tool_specs​

tool_specs() -> list[dict[str, Any]]

OpenAI tools list: local tools plus remote Tool Gateway tools.

This element takes no parameter.

Returns: list[dict[str, Any]]. List of OpenAI tools entries, local tools first.

AgentLoop.verify​

verify(state: LoopState) -> LoopState

Check the final answer; a rejected answer is sent back to the model (recover).

NameTypeDefaultRequiredDescription
stateLoopStateyesCurrent LoopState, whose final answer is checked; it is updated in place.

Returns: LoopState. A LoopState: Serializable state of a run (stored in checkpoints).

AgentLoop.watch​

watch(session_id: str, after: str | None = None) -> None

Process new messages of session_id in :meth:serve.

NameTypeDefaultRequiredDescription
session_idstryesSession to watch.
afterstr | NoneNonenoIdentifier of the last message already seen; None processes the session from the start.

Returns: None.