# Runtime

封装 LLM provider，从会话 DAG 计算上下文，调用模型并写回回复。[源码](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()
```

普通方法继承 Runtime，无需装饰器或手动 Context。见 [Agent 与 Context](https://fzkuji.github.io/OpenProgram/docs/reference/api/agent.zh.html)。

## 构造函数

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

| 参数 | 含义 |
| --- | --- |
| `call` | `fn(content: list[dict], model: str, response_format: dict) -> str`，经 `CallableModel` 包入标准 provider 路径，DAG 记录和历史渲染相同。既无 `call` 也无 `provider:model_id` 模型时，子类化并覆盖 `_call()`。 |
| `model` | 默认 `"default"`。`"provider:model_id"` 经 `openprogram.models.providers` 解析，未知值抛 `ValueError`。其他字符串只在有 `call=` 或子类时有效。 |
| `max_retries` | 尝试次数，含第一次，至少 1。`None` 读 `OPENPROGRAM_MAX_RETRIES`，默认 6。 |
| `api_key` | `None` 从凭据库解析 |
| `skills` | `None`/`False` 关闭；`True` 探测默认用户和仓库目录；`list[str]` 显式指定。每次 `exec()` 向系统提示追加 `<available_skills>`。 |

| 属性 | 含义 |
| --- | --- |
| `model` | 默认模型名 |
| `max_retries` | 解析后的重试额度 |
| `system` | 可赋值的系统提示；`method_options[...]["system"]` 在单次调用中设置 |
| `thinking_level` | `"off"`（默认）、`"low"`、`"medium"`、`"high"`、`"xhigh"`；传给 provider |
| `session_id` | 这个 Runtime 自己的 `"op-<hex>"`。不作提示缓存 key 发出：模型、系统提示和工具都相同的调用共用一个由它们算出的 id，跨 Runtime 也一样。给它赋值即自己指定 key |
| `on_stream` | `fn(event_dict)`，接收 text、thinking、tool_use、tool_result 事件 |
| `last_usage` | 上次调用的 `{input_tokens, output_tokens, total_tokens, cache_read, cache_create, ...}` |

## 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
```

| 调用场景 | 行为 |
| --- | --- |
| 在 Agent 方法或受管函数内 | `render_context` 按 `expose` 和 `render_range` 选历史节点，`render_dag_messages` 渲染，`_call()` 发送，回复写入开始时打开的 `llm` 节点。每次 `exec()` 都是新 `llm` 节点。 |
| 未安装 DAG 存储 | `content` 作为一条用户消息单轮调用，不记录 |

| 参数 | 含义 |
| --- | --- |
| `content` | `list[dict]` 或字符串（一个文本块） |
| `context` | 遗留参数，被忽略 |
| `response_format` | JSON Schema 或 `JsonSchemaOutput`，见[结构化输出](#structured-output) |
| `model` | 覆盖默认模型 |
| `tools` | 已注册的 Agent 方法、`{"spec":..., "execute":...}` 字典或带 `.spec`/`.execute` 的对象；循环直到返回纯文本。**`None` 不是“无工具”**：它拿到全部已注册工具。要无工具用 `toolset="none"` 或 `tools=[]`。 |
| `toolset` | 预设；`"full"` 是隐式默认，`"none"` 不用工具 |
| `tools_source` | 按渠道来源过滤 |
| `tools_allow`, `tools_deny` | 名称允许和拒绝列表 |
| `tool_choice` | 未设即 `"auto"`。`"required"`、`"none"` 或 `{"type":"function","name":"X"}`；按 provider 映射。 |
| `parallel_tool_calls` | 未设时用 provider 默认；`True`/`False` 允许或禁止一轮多个调用 |
| `max_iterations` | 未设即 20。一次迭代是一次模型调用加其工具。实际值 `max(1, n)`。聊天回合不设上限。 |
| `stop_after_tool_round` | 一轮工具后停止，供先消费回执的调用方工作流使用。不能与 `response_format` 同用。 |
| `choices` | 约束回合**结束**方式，见[下一步决策](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/next-step-decision.zh.html) |
| `timeout_s` | 整个调用的墙钟预算，含重试等待；抛 `LLMError`（`reason=TIMEOUT`，`retryable=False`）。`None` 回退到 `OPENPROGRAM_EXEC_TIMEOUT_S`（未设或 `0`：不限）。 |
| `on_retry` | 每次退避等待前收到 `RetryInfo`；最终失败不触发；回调异常被吞掉 |
| `web_search` | provider 原生网络搜索（如支持） |
| `stream_fn` | 单次流函数覆盖，供分发器和测试使用 |
| `effort` | 仅本次调用的推理强度，不改 `thinking_level` |
| `execution_kind` | DAG 标签；单请求原语为 `llm`，否则 `agent` |

### 内容块

```
{"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"}
```

媒体接受 `path`（自动读取编码，按扩展名猜类型）或 `data` + `mime_type`。文本块可带 `"role": "system"`。文本和图片块接受 `cache_control`。未知类型被跳过。

### 返回值

| 调用 | 返回 |
| --- | --- |
| `response_format=None` | 回复 `str` |
| 结构化 `response_format` | 本地校验后的 Python JSON 值 |
| `choices` | 所选函数的返回值，或所选的值 |

### 异常

| 异常 | 时机 |
| --- | --- |
| `RuntimeError` | runtime 已关闭 |
| `TypeError`, `NotImplementedError` | 编程错误，从不重试 |
| `LLMError` | 重试耗尽或不可重试。字段包括 `reason`、`retryable`、`http_status`、`retry_after_s`、`attempts`、`elapsed_s`、`provider`、`model`。 |
| `StructuredOutputSchemaError` | `invalid_schema` |
| `StructuredOutputUnsupportedError` | `unsupported`：没有经过验证的无损 provider 或回退 |
| `StructuredOutputValidationError` | `invalid_json`, `validation_failed`, `missing_submission`, `mixed_submission` |
| `StructuredOutputGenerationError` | `refusal`, `incomplete` |

结构化输出错误提供 `.code` 和有界的 `.issues`。provider 候选文本不属于诊断内容。

**结构化输出**

- 已验证的 provider 和模型组合使用原生映射。否则 `fallback="auto"` 可走已验证的隐藏严格工具路径；提示回退需要显式 `fallback="prompt"`。不支持或有损的组合直接失败。
- 最终值在本地按原 schema 解析和校验。
- `max_validation_retries` 为 `0`、`1` 或 `2`（默认 `2`），校验修复和截断生成共用。同时转给 `_call()`。

## 其他方法

| 方法 | 效果 |
| --- | --- |
| `await async_exec(content, ...)` | 参数相同（无 `choices`），返回和错误契约相同。调用 `_async_call()`；`call=` 函数可同步或异步；重试用 `asyncio.sleep`，可取消。 |
| `_call(content, model="default", response_format=None)` | 一次调用，无重试。配置了 provider 模型或 `call=` 时经 `AgentSession`，否则 `NotImplementedError`。**子类化时覆盖它。** 历史由 provider 路径从 DAG 渲染。返回原始文本或校验后的 JSON 值。 |
| `await _async_call(...)` | 异步 `_call()`；异步 provider 覆盖它 |
| `close()` | 结束会话；之后 `exec()` 抛 `RuntimeError`。`with Runtime(...) as rt:` 退出时关闭。子类在此清理。 |

### 询问用户

| 方法 | 询问 |
| --- | --- |
| `ask(prompt, options=, multi=, allow_custom=, questions=[...], timeout=300.0, default=None)` | 一个问题或一张卡片多个问题 |
| `confirm(prompt, detail=, timeout=300.0, default=False)` | 是或否 |
| `form(prompt, fields, detail=, timeout=300.0, default=None)` | 多字段表单 |
| `can_ask()` | 是否有人应答；无头运行时为 False |

需要已连接的前端会话。拒绝回答抛 `UserDeclined`。超时时有 `default` 则返回，否则抛 `AskTimeout`。

## 重试

| 情况 | 处理 |
| --- | --- |
| 瞬态异常 | 记录尝试，退避 1.5 秒 × 2^attempt ±25% 抖动，重试至 `max_retries`。`Retry-After` 作为下限。基数：`OPENPROGRAM_RETRY_BACKOFF_BASE`。 |
| 永久错误：图片数据错误、认证过期、key 无效或 `retryable=False` | 立即 `LLMError`，`retryable=False` |
| provider 已耗尽传输重试（`transport_exhausted`） | `LLMError`，不再重试 |
| `TypeError`, `NotImplementedError` | 立即抛出 |
| 全部失败 | 带尝试报告的结构化 `LLMError` |

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

**重试的边界**

| 额度 | 规则 |
| --- | --- |
| 失败恢复 | 结构化输出修复和重复的工具响应共用。重复响应被丢弃，在同一 Agent 上下文中重新生成，保留已完成的工具结果和回执。没有总 token 或时长上限。 |
| 传输 | `OPENPROGRAM_PROVIDER_STREAM_RETRIES` 减一，独立计算，断连不消耗修复额度。恢复的请求归还额度：按请求限制，而不是按 Agent 循环。 |
| 等待网络 | 端点不可达、重试用尽且没有已提交输出：最多等待 `OPENPROGRAM_NETWORK_WAIT_MAX_S`（默认 30 分钟），每 5 至 30 秒检查，然后继续。恢复上限为 0、单次尝试请求、取消或截止时间会结束等待。 |

- 调用方的显式限制、取消、权限失败和恢复耗尽仍是最终结果。
- 重复响应不等于允许重复外部写入；结果不确定的写入须先检查。
- 函数逻辑错误仍需修改代码。

[Providers](https://fzkuji.github.io/OpenProgram/docs/reference/api/providers.zh.html)
