# Runtime

Wraps an LLM provider, computes context from the session DAG, calls the model and writes the reply back. [Source](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/agent/runtime/runtime.py).

```
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](https://fzkuji.github.io/OpenProgram/docs/reference/api/agent.html).

## Constructor

```
Runtime(call=None, model="default", max_retries=None, api_key=None, skills=None)
```

| Parameter | Meaning |
| --- | --- |
| `call` | `fn(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()`. |
| `model` | Default `"default"`. `"provider:model_id"` resolves through `openprogram.models.providers`; unknown values raise `ValueError`. Any other string only works with `call=` or a subclass. |
| `max_retries` | Attempts including the first, at least 1. `None` reads `OPENPROGRAM_MAX_RETRIES`, default 6. |
| `api_key` | `None` resolves from the credential store |
| `skills` | `None`/`False` off; `True` probes default user and repo directories; `list[str]` is explicit. Appends `<available_skills>` to the system prompt on every `exec()`. |

| Attribute | Meaning |
| --- | --- |
| `model` | Default model name |
| `max_retries` | Resolved retry budget |
| `system` | Assignable system prompt; `method_options[...]["system"]` sets it for one call |
| `thinking_level` | `"off"` (default), `"low"`, `"medium"`, `"high"`, `"xhigh"`; passed to the provider |
| `session_id` | This 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_stream` | `fn(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
```

| Called | Behaviour |
| --- | --- |
| In an Agent method or managed function | `render_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 installed | `content` becomes one user message in a single-turn call; nothing recorded |

| Parameter | Meaning |
| --- | --- |
| `content` | `list[dict]` or a string (one text block) |
| `context` | Legacy, ignored |
| `response_format` | Bare JSON Schema or `JsonSchemaOutput`. See [structured output](#structured-output). |
| `model` | Overrides the default model |
| `tools` | Registered 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=[]`. |
| `toolset` | Preset; `"full"` is the implicit default, `"none"` opts out |
| `tools_source` | Filter per channel source |
| `tools_allow`, `tools_deny` | Name allow and deny lists |
| `tool_choice` | Unset means `"auto"`. `"required"`, `"none"`, or `{"type":"function","name":"X"}`; mapped per provider. |
| `parallel_tool_calls` | Unset leaves the provider default; `True`/`False` allows or forbids several calls in one turn |
| `max_iterations` | Unset means 20. One iteration is a model call plus its tools. Effective value `max(1, n)`. Chat turns pass no cap. |
| `stop_after_tool_round` | Stops after one tool round, for caller-owned workflows that consume receipts first. Cannot be combined with `response_format`. |
| `choices` | Constrains the **end** of the turn; see [next-step decision](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/next-step-decision.html) |
| `timeout_s` | Wall-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_retry` | Gets a `RetryInfo` before each backoff sleep; not fired for the terminal failure; its exceptions are swallowed |
| `web_search` | Provider's native web search, where supported |
| `stream_fn` | Per-call stream override, for the dispatcher and tests |
| `effort` | Reasoning effort for this call only; `thinking_level` is unchanged |
| `execution_kind` | DAG 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

| Call | Returns |
| --- | --- |
| `response_format=None` | Reply `str` |
| structured `response_format` | Locally validated Python JSON value |
| `choices` | Return value of the selected function, or the selected value |

### Errors

| Exception | When |
| --- | --- |
| `RuntimeError` | The runtime is closed |
| `TypeError`, `NotImplementedError` | Programming errors, never retried |
| `LLMError` | Retries exhausted or non-retryable. Fields include `reason`, `retryable`, `http_status`, `retry_after_s`, `attempts`, `elapsed_s`, `provider`, `model`. |
| `StructuredOutputSchemaError` | `invalid_schema` |
| `StructuredOutputUnsupportedError` | `unsupported`: no verified lossless provider or fallback |
| `StructuredOutputValidationError` | `invalid_json`, `validation_failed`, `missing_submission`, `mixed_submission` |
| `StructuredOutputGenerationError` | `refusal`, `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

| Method | Effect |
| --- | --- |
| `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

| Method | Asks |
| --- | --- |
| `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

| Situation | Handling |
| --- | --- |
| Transient exception | Records 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=False` | `LLMError` at once, `retryable=False` |
| Provider already spent its transport retries (`transport_exhausted`) | `LLMError`, not retried again |
| `TypeError`, `NotImplementedError` | Raised at once |
| All retries fail | Structured `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**

| Allowance | Rule |
| --- | --- |
| Failure recovery | Shared 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. |
| Transport | `OPENPROGRAM_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 wait | Endpoint 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](https://fzkuji.github.io/OpenProgram/docs/reference/api/providers.html)
