OpenProgram Docs

Runtime

Wraps an LLM provider, computes context from the session DAG, calls the model and writes the reply back. Source.

from openprogram import Agent, Runtime

def my_llm(content, model="host-model", response_format=None):
    texts = [block["text"] for block in content if block["type"] == "text"]
    return call_my_api("\n".join(texts), model=model)

runtime = Runtime(call=my_llm, model="host-model")

class Observer(Agent):
    tools = []

    def observe(self, task: str):
        """Identify the requested screen element."""
        return self([
            {"type": "text", "text": f"Find: {task}"},
            {"type": "image", "path": "screenshot.png"},
        ])

observer = Observer(runtime=runtime)
try:
    answer = observer.observe("login button")
finally:
    runtime.close()

Ordinary methods inherit the Runtime; no decorator or manual Context. See Agent and Context.

Constructor

Runtime(call=None, model="default", max_retries=None, api_key=None, skills=None)
ParameterMeaning
callfn(content: list[dict], model: str, response_format: dict) -> str, wrapped into the standard provider path via CallableModel, so DAG recording and history rendering are the same. With neither call nor a provider:model_id model, subclass and override _call().
modelDefault "default". "provider:model_id" resolves through openprogram.models.providers; unknown values raise ValueError. Any other string only works with call= or a subclass.
max_retriesAttempts including the first, at least 1. None reads OPENPROGRAM_MAX_RETRIES, default 6.
api_keyNone resolves from the credential store
skillsNone/False off; True probes default user and repo directories; list[str] is explicit. Appends <available_skills> to the system prompt on every exec().
AttributeMeaning
modelDefault model name
max_retriesResolved retry budget
systemAssignable system prompt; method_options[...]["system"] sets it for one call
thinking_level"off" (default), "low", "medium", "high", "xhigh"; passed to the provider
session_idThis Runtime's own "op-<hex>". Not sent as the prompt-cache key: calls with the same model, system prompt and tools share an id derived from them, across Runtimes. Assign it to name the key yourself
on_streamfn(event_dict) for text, thinking, tool_use, tool_result events
last_usage{input_tokens, output_tokens, total_tokens, cache_read, cache_create, ...} of the last call

exec()

Runtime.exec(content, context=None, response_format=None, model=None,
             tools=None, toolset=None, tools_source=None, tools_allow=None,
             tools_deny=None, tool_choice=None, parallel_tool_calls=None,
             max_iterations=None, stop_after_tool_round=False, choices=None,
             timeout_s=None, on_retry=None, web_search=None, stream_fn=None,
             effort=None, execution_kind="agent") -> Any
CalledBehaviour
In an Agent method or managed functionrender_context uses expose and render_range to choose history nodes, render_dag_messages renders them, _call() sends, and the reply goes into the llm node opened at the start. Each exec() is a new llm node.
No DAG store installedcontent becomes one user message in a single-turn call; nothing recorded
ParameterMeaning
contentlist[dict] or a string (one text block)
contextLegacy, ignored
response_formatBare JSON Schema or JsonSchemaOutput. See structured output.
modelOverrides the default model
toolsRegistered Agent methods, {"spec":..., "execute":...} dicts, or objects with .spec/.execute; the loop runs until plain text. None is not "no tools": it gets the full registered toolset. Use toolset="none" or tools=[].
toolsetPreset; "full" is the implicit default, "none" opts out
tools_sourceFilter per channel source
tools_allow, tools_denyName allow and deny lists
tool_choiceUnset means "auto". "required", "none", or {"type":"function","name":"X"}; mapped per provider.
parallel_tool_callsUnset leaves the provider default; True/False allows or forbids several calls in one turn
max_iterationsUnset means 20. One iteration is a model call plus its tools. Effective value max(1, n). Chat turns pass no cap.
stop_after_tool_roundStops after one tool round, for caller-owned workflows that consume receipts first. Cannot be combined with response_format.
choicesConstrains the end of the turn; see next-step decision
timeout_sWall-clock budget for the whole call including retry sleeps; raises LLMError (reason=TIMEOUT, retryable=False). None falls back to OPENPROGRAM_EXEC_TIMEOUT_S (unset or 0: unbounded).
on_retryGets a RetryInfo before each backoff sleep; not fired for the terminal failure; its exceptions are swallowed
web_searchProvider's native web search, where supported
stream_fnPer-call stream override, for the dispatcher and tests
effortReasoning effort for this call only; thinking_level is unchanged
execution_kindDAG label; llm for the one-request primitive, otherwise agent

Content blocks

{"type": "text",  "text": "Find the login button."}
{"type": "image", "path": "screenshot.png"}
{"type": "image", "data": "<base64>", "mime_type": "image/png"}
{"type": "video", "path": "clip.mp4"}
{"type": "audio", "path": "recording.wav"}

Media takes path (read and encoded, type guessed from the extension) or data + mime_type. A text block may carry "role": "system". Text and image blocks accept cache_control. Unknown block types are skipped.

Return value

CallReturns
response_format=NoneReply str
structured response_formatLocally validated Python JSON value
choicesReturn value of the selected function, or the selected value

Errors

ExceptionWhen
RuntimeErrorThe runtime is closed
TypeError, NotImplementedErrorProgramming errors, never retried
LLMErrorRetries exhausted or non-retryable. Fields include reason, retryable, http_status, retry_after_s, attempts, elapsed_s, provider, model.
StructuredOutputSchemaErrorinvalid_schema
StructuredOutputUnsupportedErrorunsupported: no verified lossless provider or fallback
StructuredOutputValidationErrorinvalid_json, validation_failed, missing_submission, mixed_submission
StructuredOutputGenerationErrorrefusal, incomplete

Structured-output errors expose .code and bounded .issues. Provider candidate text is not part of the diagnostics.

Structured output
  • Verified provider and model combinations use their native mapping. Otherwise fallback="auto" may use the verified hidden strict-tool path; prompt fallback needs explicit fallback="prompt". Unsupported or lossy combinations fail closed.
  • The final value is parsed and validated locally against the original schema.
  • max_validation_retries is 0, 1 or 2 (default 2); validation repair and truncated generation share it. Also forwarded to _call().

Other methods

MethodEffect
await async_exec(content, ...)Same parameters except choices; same return and error contract. Calls _async_call(); a call= function may be sync or async; retries use asyncio.sleep, so cancellation works.
_call(content, model="default", response_format=None)One call, no retry. Routes through AgentSession when a provider model or call= is configured, else NotImplementedError. Override when subclassing. History is rendered from the DAG by the provider path. Returns raw text, or the validated JSON value.
await _async_call(...)Async _call(); override for an async provider
close()Ends the session; later exec() raises RuntimeError. with Runtime(...) as rt: closes on exit. Subclasses clean up here.

Asking the user

MethodAsks
ask(prompt, options=, multi=, allow_custom=, questions=[...], timeout=300.0, default=None)One question or several in one card
confirm(prompt, detail=, timeout=300.0, default=False)Yes or no
form(prompt, fields, detail=, timeout=300.0, default=None)Multi-field form
can_ask()Is anyone there? False on headless runs

Needs a connected front-end session. A declined question raises UserDeclined. A timeout returns default when given, else raises AskTimeout.

Retries

SituationHandling
Transient exceptionRecords the attempt, backs off 1.5 s × 2^attempt ±25% jitter, retries up to max_retries. Retry-After is a lower bound. Base: OPENPROGRAM_RETRY_BACKOFF_BASE.
Permanent error: bad image data, expired auth, invalid key, or retryable=FalseLLMError at once, retryable=False
Provider already spent its transport retries (transport_exhausted)LLMError, not retried again
TypeError, NotImplementedErrorRaised at once
All retries failStructured LLMError with an attempt report
LLMError: exec() failed after 3 attempt(s):
Attempt 1: ConnectionError: timeout
Attempt 2: RateLimitError: 429 Too Many Requests
Attempt 3: ConnectionError: timeout
rt = Runtime(call=my_llm)                # OPENPROGRAM_MAX_RETRIES, else 6
rt = Runtime(call=my_llm, max_retries=1) # raise on the first failure
The boundaries of retrying
AllowanceRule
Failure recoveryShared by structured-output repairs and repetitive tool-enabled responses. A repetitive response is discarded and regenerated in the same Agent context, keeping completed tool results and receipts. No aggregate token or duration limit.
TransportOPENPROGRAM_PROVIDER_STREAM_RETRIES minus one, separate, so a dropped connection spends no repair. A request that recovers returns them: bounded per request, not per Agent loop.
Network waitEndpoint unreachable, retries spent, no output committed: waits up to OPENPROGRAM_NETWORK_WAIT_MAX_S (default 30 minutes), checking every 5 to 30 s, then continues. A recovery limit of 0, a single-attempt request, cancellation or the deadline ends it.
  • Explicit caller limits, cancellation, permission failures and exhausted recovery remain authoritative.
  • Repeating a response is not permission to repeat an external write; an uncertain write needs inspection first.
  • Function logic errors still need a code fix.

Providers

Last updated · 2026-11-25