OpenProgram Docs

Agent and Context

EntryDoes
agent() / agent_async()Runs a model tool loop
AgentStores reusable configuration, scopes ordinary subclass methods
ContextSupplies named content and history selection
from openprogram import Agent, agent, agent_async

answer = agent("Summarize this text", tools=[])

class Researcher(Agent):
    instructions = "Return a short, factual answer."
    tools = []

    def prepare(self, question):
        """Remove surrounding whitespace."""
        return question.strip()

    def research(self, question):
        """Answer the prepared question."""
        return self(self.prepare(question))

researcher = Researcher(model="configured-model")
answer = researcher.research("A question")
# In async code: answer = await researcher.arun("A question")
# Or: answer = await agent_async("A question", tools=[])

All entries use the existing Runtime and Session DAG. Ordinary calls need no manual Context.

Direct calls and Agent classes

OptionEffect
promptA string or content blocks
model, effort, runtimeCommon options. Tool execution options: Runtime
toolsNone resolves available tools. [] requests none.
choicesThe closing reply becomes a next-step decision; returns the resolved pick
RuleBehaviour
Agent(model=, instructions=, context=, tools=, runtime=, effort=, **options)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
ConstructionNo model request, no execution session
InvocationInherits an active execution, otherwise owns a separate one and releases its resources. Reusing an instance does not continue an earlier independent conversation.
MethodsInstance, 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.

Context

from openprogram import Agent, Context

context = Context(
    {"notes": "Use the project terminology."},
    providers={"current_topic": lambda current: "Agent context"},
)
researcher = Agent(context=context, tools=[])

The framework derives and binds Context automatically; this is optional. Content is separate from system instructions and tool authority.

NameEffect
Context(blocks=None, *, parent=None, providers=None, history=, call_id=, store=None, head_id=None)Mutable mapping of named content
derive()Child with independent content
Context.current()The task binding, or None
merge(other)Overlays named content and explicit selection; keeps the scope call identity
bind()For host integrations that need an explicit binding
providersSynchronous callables taking the current Context, run for each model request. A failure aborts that request. Expression strings are never executed.
historyThe request sees
NoneNothing
"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 callNo 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

ParameterTypeDefaultMeaning
capture_ioboolmethod False, tool TrueRecord arguments and return values. Structural call identity stays available without them.
resumableboolFalseOpt in to durable steps
exposestrmethod "full", tool "io"What others see of this function in the DAG (table below). Any other value raises ValueError.
render_rangedictNoneHow many history nodes this function's llm() reads: {"callers": N, "subcalls": M}, sliced by seq
inputdictNonePer-parameter UI metadata for the WebUI form: description, placeholder, multiline, options (dropdown and JSON-schema enum), hidden (out of the form and tool schema)
systemstrNoneSystem prompt for this function's LLM calls; restored afterwards
exposeName and return valueLLM exchangesNested code calls
"io"visiblehiddenhidden
"llm"hiddenvisiblehidden
"full"visible, with docstring and parametersvisiblevisible
"hidden"no DAG nodes writtenno DAG nodes writtenno DAG nodes written
render_range keyCounts nodesDefaultValues
callerswritten before this frame started; newest NNone, unlimited0 is a full wall
subcallswritten after this frame started; newest N-1, unlimited, so the frame sees its own progressN>=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.

ParameterTypeDefaultMeaning
tool / as_toolboolFalseRegister as a tool. False: Python-direct only
namestrNoneOverride; default __name__
descriptionstrNoneOverride; default docstring
parametersdictNoneJSON-schema override; default from type hints and input, excluding runtime-injected and hidden parameters
labelstrNoneLabel in tool UIs
toolsettuple()Toolset names, used by exec(toolset=...)
unsafe_intuple()Channel sources where the tool is filtered out
check_fnCallableNonePer-call gate before dispatch; falsy blocks
requires_envtuple()Env variables that must be set for it to be offered
can_useCallableNoneAvailability predicate at tool resolution
max_result_weightintNoneA 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—NoneForwarded to the tool registry, same shape as @function
cacheboolFalseMemoize tool-dispatched calls on (name, args)
cache_ttlfloat300.0Seconds, with cache=True
timeoutfloatNoneHard wall-clock kill in seconds; the model receives an error result
available_ifCallableNoneFalsy or raising skips registration; method scopes stay active
deferboolFalseDeferred tool: schema loaded on demand
register_globallyboolTrueFalse 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.

Introspection and safety
  • fn.spec: generated tool spec {"name", "description", "parameters"}. fn.execute(**kwargs) invokes with LLM-provided kwargs.
  • 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
MomentWrite
Enter the functioncode node (output=None, status="running"); docstring in metadata.doc, prepended to function_name(args) when rendering
Each llm() in the bodyOne llm node
ExitBackfill 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.

ConstructRule
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_policyAfter a restart
keep_original (default)Retained source runs. After adopting B, a later restart keeps B even if the installed code is C.
use_latestCompleted results stay; the current function runs the remaining compatible steps

The task's Continue control can override the policy.

OutcomeCases
PausesDeleted or reordered recorded steps, changed completed inputs, an unavailable or changed pinned dependency
Keeps the active versionA candidate that fails compatibility before adopting any remaining step
Still checkedPermission and tool parameter contract changes
Rejected before steps runImports inside retained helpers, dynamic import APIs, generated code, third-party and user package objects as opaque dependencies (only the pinned standard library is supported)
UnsupportedCalls and external mutations outside steps, asynchronous orchestration, generators, live handles, non-JSON results
Needs reconciliationThe process died after an external action started but before its result was committed; recovery cannot assume it failed
Never an automatic retryExplicit pauses, cancellation, unanswered approvals, uncertain external results
Authoring notes
  • Pass persistent state through JSON step inputs and results. Do not share mutable globals, closures or defaults between steps.
  • Import step dependencies at module scope. Source-defined Python helpers are retained recursively.
  • If B needs a different local state shape, write the conversion as pure orchestration over saved JSON before its remaining steps.
  • Manual calls resume the same execution and function record. Chat calls return their eventual result to the original pending tool call.
  • Restart-owned interruptions follow execution.auto_resume_window_seconds (default -1, no limit; 0 disables automatic restart).
  • The function run dialog distinguishes functions that declare this contract from ordinary ones, which need a new run after interruption.

Managed Program sources

CapturedNot captured
Source-defined functions, submodules and nested definitions inside authorized package roots: selected first-party sources, installed and catalogued Program packages, owner-recorded external harnesses, published Programs, retained source snapshotsArbitrary host files, unrelated dependencies, lambdas, generated code, unavailable source

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.

Session turns and continuation

NameEffect
Agent.run_turn(request, *, context=None, on_event=None, cancel_event=None, execution_context=None)Returns TurnResult. Instance configuration applies before a fresh turn. Import TurnRequest and TurnResult from openprogram.
arun_turn(request, **options)Same, asynchronous, with cooperative cancellation
resume_turn(continuation, **options), aresume_turn(...)Reuse the checkpoint's request without repeating admission
Context.for_session(store, session_id, head_id=, blocks=, providers=)Binds a persistent store and branch. A request for another session is rejected. Context.session_id exposes the graph identity.
ChatAgentProduction 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.

Runtime

Last updated · 2026-11-25