Instance settings override class defaults; per-call options override instance settings. **options accepts the keyword options of agent().
Agent.from_spec(spec, **overrides)
Uses an AgentSpec configuration without creating a saved Agent entry
Construction
No model request, no execution session
Invocation
Inherits an active execution, otherwise owns a separate one and releases its resources. Reusing an instance does not continue an earlier independent conversation.
Methods
Instance, static and class methods get automatic call scopes, including single-underscore helpers. Dunder methods and generators are excluded. Recording registers no model tool.
The class-and-method interface takes inspiration from NVIDIA-labs OO Agents. OpenProgram does not claim NOOA API compatibility.
Overlays named content and explicit selection; keeps the scope call identity
bind()
For host integrations that need an explicit binding
providers
Synchronous callables taking the current Context, run for each model request. A failure aborts that request. Expression strings are never executed.
history
The request sees
None
Nothing
"thread"
Only earlier requests made with this same Context object
"chat"
The visible conversation (Context default)
callable
(node, context) filters conversation nodes after the visibility checks
unset in a Workflow role call
No history
These settings cannot expand tool permissions. Model interactions stay in the execution session.
Explicit session lifetime
To make several independent calls continue one session, pass an existing SessionNodeWriter.
from openprogram import Agent, Context
from openprogram.state.store import SessionStore, SessionNodeWriter
store = SessionStore(root_path="/var/lib/myapp/sessions")
store.create_session("research", agent_id="main")
writer = SessionNodeWriter(store, "research")
researcher = Agent(context=Context(store=writer), tools=[])
try:
first = researcher("List the project requirements.")
second = researcher("Review the requirements from the previous call.")
finally:
store.close()
head_id selects an existing branch tip; None continues the current head.
The caller owns and closes the store. Execution scopes do not.
This supplies the event lifetime for NOOA-style repeated instance calls. The Agent still stores configuration; its default calls stay independent.
Method options
from openprogram import Agent
from openprogram.runtime.agent import llm
class ExampleAgent(Agent):
method_options = {
'f': {'tool': True},
}
def f(self, x: str) -> str:
"""One-line summary of what f does."""
return llm([{"type": "text", "text": f"...{x}..."}])
_example_agent = ExampleAgent()
f = _example_agent.f
Signature and docstring supply names, types, defaults and summaries; method_options supplies the rest, with no decorator. Agent owns method execution and registration. Context resolves request content and visible history.
Execution and Context
Parameter
Type
Default
Meaning
capture_io
bool
method False, tool True
Record arguments and return values. Structural call identity stays available without them.
What others see of this function in the DAG (table below). Any other value raises ValueError.
render_range
dict
None
How many history nodes this function's llm() reads: {"callers": N, "subcalls": M}, sliced by seq
input
dict
None
Per-parameter UI metadata for the WebUI form: description, placeholder, multiline, options (dropdown and JSON-schema enum), hidden (out of the form and tool schema)
system
str
None
System prompt for this function's LLM calls; restored afterwards
expose
Name and return value
LLM exchanges
Nested code calls
"io"
visible
hidden
hidden
"llm"
hidden
visible
hidden
"full"
visible, with docstring and parameters
visible
visible
"hidden"
no DAG nodes written
no DAG nodes written
no DAG nodes written
render_range key
Counts nodes
Default
Values
callers
written before this frame started; newest N
None, unlimited
0 is a full wall
subcalls
written after this frame started; newest N
-1, unlimited, so the frame sees its own progress
N>=0 truncates; 0 walls off the frame
Tool registration parameters
With tool=True the method registers as an LLM-callable tool in openprogram.programs, beside @function tools. Names and semantics match @function.
Parameter
Type
Default
Meaning
tool / as_tool
bool
False
Register as a tool. False: Python-direct only
name
str
None
Override; default __name__
description
str
None
Override; default docstring
parameters
dict
None
JSON-schema override; default from type hints and input, excluding runtime-injected and hidden parameters
label
str
None
Label in tool UIs
toolset
tuple
()
Toolset names, used by exec(toolset=...)
unsafe_in
tuple
()
Channel sources where the tool is filtered out
check_fn
Callable
None
Per-call gate before dispatch; falsy blocks
requires_env
tuple
()
Env variables that must be set for it to be offered
can_use
Callable
None
Availability predicate at tool resolution
max_result_weight
int
None
A smaller bound for this tool's result than the model's, in weight (a CJK character 1, anything else 0.25). The tool never cuts its text: the agent loop bounds it once and keeps the whole text in the conversation's tool_results/
requires_approval
—
None
Forwarded to the tool registry, same shape as @function
cache
bool
False
Memoize tool-dispatched calls on (name, args)
cache_ttl
float
300.0
Seconds, with cache=True
timeout
float
None
Hard wall-clock kill in seconds; the model receives an error result
available_if
Callable
None
Falsy or raising skips registration; method scopes stay active
defer
bool
False
Deferred tool: schema loaded on demand
register_globally
bool
True
False keeps it out of the global registry
Runtime for a method
A method runs on its Agent's Runtime, or the caller's when the Agent has none: ExampleAgent(runtime=rt).f("x") runs f, its model requests and the Agent methods it calls on rt. Configure Runtimes where the program starts, not through method arguments. For two models in one workflow, give the second role its own Agent instance.
Older functions: runtime injection
Parameters named runtime, exec_runtime or review_runtime are filled when the caller passes none: from the current call chain, or for an entry-point call from create_runtime(), closed when the function returns. Several such parameters get the same runtime. They never appear in the tool schema or WebUI form. New methods do not declare them.
Re-entering itself more than 5 levels deep raises RecursionError; an injected situational prompt also steers the model away.
add_pre_invocation_hook / remove_pre_invocation_hook: hooks run at the top of every call and may raise CancelledError to abort it, as the WebUI stop button does.
Recording to the DAG
Moment
Write
Enter the function
code node (output=None, status="running"); docstring in metadata.doc, prepended to function_name(args) when rendering
Each llm() in the body
One llm node
Exit
Backfill the same code node's output and status
expose="hidden" writes nothing. With no DAG store installed, recording is a no-op.
Durable steps and code selection
from openprogram import Agent
from openprogram.runtime.agent.durable_steps import step
class ExampleAgent(Agent):
method_options = {
'report': {'tool': True, 'resumable': True},
}
def report(self, topic: str):
research = step("research", collect_research, topic)
return step("write", write_report, research)
_example_agent = ExampleAgent()
report = _example_agent.report
Execution is restored at explicit steps, not arbitrary Python stack frames. collect_research and write_report are ordinary source-defined functions.
Construct
Rule
step(name, fn, *args, **kwargs)
JSON-compatible inputs and results. A completed step returns its saved result without calling the action again. Repeated names are distinguished by occurrence; keep order and completed inputs stable.
workflow(name, fn, *args, **kwargs)
Nested orchestration
parallel({"branch": (fn, args, kwargs)})
Named workflows run concurrently, each with independent durable progress; waits for every branch before releasing ownership
execution.code_change_policy
After a restart
keep_original (default)
Retained source runs. After adopting B, a later restart keeps B even if the installed code is C.
use_latest
Completed results stay; the current function runs the remaining compatible steps
The task's Continue control can override the policy.
Outcome
Cases
Pauses
Deleted or reordered recorded steps, changed completed inputs, an unavailable or changed pinned dependency
Keeps the active version
A candidate that fails compatibility before adopting any remaining step
Still checked
Permission and tool parameter contract changes
Rejected before steps run
Imports inside retained helpers, dynamic import APIs, generated code, third-party and user package objects as opaque dependencies (only the pinned standard library is supported)
Unsupported
Calls and external mutations outside steps, asynchronous orchestration, generators, live handles, non-JSON results
Needs reconciliation
The process died after an external action started but before its result was committed; recovery cannot assume it failed
A package lists public entries in PROGRAM_ENTRIES; a plain entry can carry an __agent_options__ mapping. Captured helpers do not become tools. Explicit method metadata is preserved; generators are excluded.
Binds a persistent store and branch. A request for another session is rejected. Context.session_id exposes the graph identity.
ChatAgent
Production conversation type; inherits this contract. Overriding turn entry methods does not wrap them as helper calls.
Event callbacks receive the runtime event dictionaries and run on the execution thread. Durable pause and steering keep the existing execution-control owner and safe-point protocol.