# Agent 与 Context

| 入口 | 作用 |
| --- | --- |
| `agent()` / `agent_async()` | 执行模型工具循环 |
| `Agent` | 保存可复用配置，为普通子类方法建立作用域 |
| `Context` | 提供命名内容和历史选择 |

```
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=[])
```

所有入口复用现有 Runtime 和 Session DAG。普通调用不用手动构造 Context。

## 直接调用与 Agent 类

| 选项 | 效果 |
| --- | --- |
| `prompt` | 字符串或内容块 |
| `model`, `effort`, `runtime` | 常用选项。工具执行选项见 [Runtime](https://fzkuji.github.io/OpenProgram/docs/reference/api/runtime.zh.html) |
| `tools` | `None` 解析可用工具，`[]` 表示不要工具 |
| `choices` | 结束回复变成[下一步决策](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/next-step-decision.zh.html)，返回解析后的选择 |

| 规则 | 行为 |
| --- | --- |
| `Agent(model=, instructions=, context=, tools=, runtime=, effort=, **options)` | 实例设置覆盖类默认值，单次调用选项覆盖实例设置。`**options` 接受 `agent()` 的关键字选项。 |
| `Agent.from_spec(spec, **overrides)` | 使用 AgentSpec 配置，不创建已保存的 Agent 条目 |
| 构造 | 不发模型请求，不建执行会话 |
| 调用 | 继承活动中的执行，否则自有一个独立执行并释放其资源。重用实例不会接续之前的独立对话。 |
| 方法 | 实例、静态和类方法自动获得调用作用域，包括单下划线辅助方法。排除双下划线方法和生成器。记录不会注册模型工具。 |

类与方法接口受 [NVIDIA-labs OO Agents](https://github.com/NVIDIA-NeMo/labs-OO-Agents) 启发。OpenProgram 不声明与 NOOA API 兼容。

## 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=[])
```

框架自动派生并绑定 Context，上面的配置是可选的。内容与系统指令、工具权限相互独立。

| 名称 | 效果 |
| --- | --- |
| `Context(blocks=None, *, parent=None, providers=None, history=, call_id=, store=None, head_id=None)` | 可变的命名内容映射 |
| `derive()` | 派生内容独立的子 Context |
| `Context.current()` | 当前任务绑定，或 `None` |
| `merge(other)` | 叠加命名内容和显式选择，保留作用域调用身份 |
| `bind()` | 供需要显式绑定的宿主集成使用 |
| `providers` | 接收当前 Context 的同步可调用对象，每次模型请求都运行。失败则中止该请求。绝不执行表达式字符串。 |

| `history` | 请求看到 |
| --- | --- |
| `None` | 无历史 |
| `"thread"` | 仅同一个 Context 对象之前的请求 |
| `"chat"` | 可见对话（Context 默认） |
| 可调用对象 | `(node, context)`，在可见性检查之后过滤对话节点 |
| Workflow 角色调用未设置 | 无历史 |

这些设置不能扩大工具权限。模型交互保留在执行会话中。

## 显式会话生命周期

要让多次独立调用接续同一会话，传入现有的 `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` 选择现有分支末端；`None` 接续当前 head。
- store 由调用方持有并关闭，执行作用域不会关闭它。
- 这提供了 NOOA 风格重复实例调用所需的事件生命周期。Agent 仍只保存配置，默认调用仍相互独立。

## 方法配置

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

签名和 docstring 提供名称、类型、默认值和摘要，其余由 `method_options` 提供，无需装饰器。Agent 负责方法执行和注册，Context 解析请求内容和可见历史。

### 执行与 Context

| 参数 | 类型 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `capture_io` | `bool` | 方法 `False`，工具 `True` | 记录参数和返回值。不记录时结构性调用身份仍可用。 |
| `resumable` | `bool` | `False` | 启用[持久步骤](#durable-steps-and-code-selection) |
| `expose` | `str` | 方法 `"full"`，工具 `"io"` | 别的函数在 DAG 中能看到它的什么（见下表）。其他值抛出 `ValueError`。 |
| `render_range` | `dict` | `None` | 此函数内 `llm()` 读多少历史节点：`{"callers": N, "subcalls": M}`，按 `seq` 切片 |
| `input` | `dict` | `None` | WebUI 表单的逐参数元数据：`description`、`placeholder`、`multiline`、`options`（下拉框和 JSON-schema `enum`）、`hidden`（不进表单和工具 schema） |
| `system` | `str` | `None` | 此函数 LLM 调用的系统提示，调用后恢复 |

| `expose` | 名称和返回值 | LLM 交互 | 嵌套代码调用 |
| --- | --- | --- | --- |
| `"io"` | 可见 | 隐藏 | 隐藏 |
| `"llm"` | 隐藏 | 可见 | 隐藏 |
| `"full"` | 可见，含 docstring 和参数 | 可见 | 可见 |
| `"hidden"` | 不写 DAG 节点 | 不写 DAG 节点 | 不写 DAG 节点 |

| `render_range` 键 | 统计的节点 | 默认 | 取值 |
| --- | --- | --- | --- |
| `callers` | 此帧开始前写入的，取最新 N 个 | `None`，不限 | `0` 完全隔断 |
| `subcalls` | 此帧开始后写入的，取最新 N 个 | `-1`，不限，帧能看到自身进展 | `N>=0` 截断；`0` 隔断本帧 |

**工具注册参数**

`tool=True` 时，方法注册为 `openprogram.programs` 中可由 LLM 调用的工具，与 `@function` 工具并列，名称和语义与 `@function` 相同。

| 参数 | 类型 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `tool` / `as_tool` | `bool` | `False` | 注册为工具。`False`：只能 Python 直接调用 |
| `name` | `str` | `None` | 覆盖，默认 `__name__` |
| `description` | `str` | `None` | 覆盖，默认 docstring |
| `parameters` | `dict` | `None` | JSON-schema 覆盖；默认由类型注解和 `input` 生成，排除运行时注入和 `hidden` 参数 |
| `label` | `str` | `None` | 工具界面中的标签 |
| `toolset` | `tuple` | `()` | 所属工具集，供 `exec(toolset=...)` 使用 |
| `unsafe_in` | `tuple` | `()` | 过滤此工具的渠道来源 |
| `check_fn` | `Callable` | `None` | 分发前的单次门禁；假值阻止调用 |
| `requires_env` | `tuple` | `()` | 必须设置才提供此工具的环境变量 |
| `can_use` | `Callable` | `None` | 解析工具时的可用性判断 |
| `max_result_weight` | `int` | `None` | 这个工具结果比模型上限更小的上限，按权重计（中日韩字符算 1，其余算 0.25）。工具从不自己截断：由 agent 循环截一次，完整文字存在对话的 `tool_results/` |
| `requires_approval` | — | `None` | 转给工具注册表，形式同 `@function` |
| `cache` | `bool` | `False` | 按 `(name, args)` 缓存工具分发调用 |
| `cache_ttl` | `float` | `300.0` | `cache=True` 时的秒数 |
| `timeout` | `float` | `None` | 硬性墙钟超时（秒）；模型收到错误结果 |
| `available_if` | `Callable` | `None` | 假值或抛异常时跳过注册，方法作用域仍有效 |
| `defer` | `bool` | `False` | 延迟工具：按需加载 schema |
| `register_globally` | `bool` | `True` | `False` 时不进全局注册表 |

### 方法使用的 Runtime

方法运行在其 Agent 的 Runtime 上，Agent 没有时用调用方的：`ExampleAgent(runtime=rt).f("x")` 让 `f`、其中的模型请求和它调用的 Agent 方法都用 `rt`。在程序入口配置 Runtime，不要通过方法参数传递。一个工作流用两个模型时，给第二个角色单独的 Agent 实例。

**旧函数：Runtime 注入**

名为 `runtime`、`exec_runtime` 或 `review_runtime` 的参数在调用方未传时自动填充：取自当前调用链；入口调用则用 `create_runtime()` 创建，函数返回时关闭。多个这样的参数得到同一个 runtime。它们不出现在工具 schema 和 WebUI 表单里。新方法不声明它们。

**内省与安全**

- `fn.spec`：生成的工具 spec `{"name", "description", "parameters"}`。`fn.execute(**kwargs)` 以 LLM 提供的参数调用。
- 自身重入超过 5 层抛出 `RecursionError`；注入的情境提示也会引导模型避免自调用。
- `add_pre_invocation_hook` / `remove_pre_invocation_hook`：钩子在每次调用开始时运行，可抛 `CancelledError` 中止，WebUI 停止按钮即如此。

**写入 DAG**

| 时机 | 写入 |
| --- | --- |
| 进入函数 | `code` 节点（`output=None`，`status="running"`）；docstring 存入 `metadata.doc`，渲染时放在 `function_name(args)` 之前 |
| 函数体内每次 `llm()` | 一个 `llm` 节点 |
| 退出 | 回填同一 `code` 节点的 `output` 和 `status` |

`expose="hidden"` 不写任何节点。没有安装 DAG 存储时，记录为空操作。

## 持久步骤与代码选择

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

执行在显式步骤处恢复，而不是任意 Python 栈帧。`collect_research` 和 `write_report` 是普通的源码定义函数。

| 构造 | 规则 |
| --- | --- |
| `step(name, fn, *args, **kwargs)` | 输入和结果须兼容 JSON。已完成的步骤返回保存的结果，不再调用动作。重复名称按出现次序区分；保持顺序和已完成输入稳定。 |
| `workflow(name, fn, *args, **kwargs)` | 嵌套编排 |
| `parallel({"branch": (fn, args, kwargs)})` | 具名工作流并发运行，各有独立的持久进度；所有分支结束才释放所有权 |

| `execution.code_change_policy` | 重启后 |
| --- | --- |
| `keep_original`（默认） | 运行保留的源码。采用 B 后，之后重启仍保留 B，即使已安装的是 C。 |
| `use_latest` | 已完成结果保留，当前函数运行其余兼容步骤 |

任务的“继续”控件可以覆盖此策略。

| 结果 | 情形 |
| --- | --- |
| 暂停 | 已记录步骤被删除或重排、已完成输入改变、固定依赖不可用或已改变 |
| 保留当前版本 | 在采用任何剩余步骤之前未通过兼容性检查的候选 |
| 仍要检查 | 权限和工具参数契约的变化 |
| 步骤运行前拒绝 | 保留的辅助函数内的 import、动态 import API、生成代码、作为不透明依赖的第三方和用户包对象（仅支持固定的标准库） |
| 不支持 | 步骤外的调用和外部修改、异步编排、生成器、活动句柄、非 JSON 结果 |
| 需要对账 | 外部动作开始后、结果提交前进程崩溃；恢复时不能假定动作失败 |
| 绝不自动重试 | 显式暂停、取消、未答复的审批、不确定的外部结果 |

**编写要点**

- 持久状态经 JSON 步骤输入和结果传递。步骤之间不要共享可变全局变量、闭包或默认值。
- 在模块作用域导入步骤依赖。源码定义的 Python 辅助函数会被递归保留。
- 如果 B 需要不同的本地状态形状，在其剩余步骤之前用对已保存 JSON 的纯编排完成转换。
- 手动调用恢复同一执行和函数记录。聊天调用把最终结果返回给原来待处理的工具调用。
- 重启导致的中断遵循 `execution.auto_resume_window_seconds`（默认 `-1` 不限；`0` 关闭自动重启）。
- 函数运行对话框会区分声明此契约的函数和中断后需要重新运行的普通函数。

## 受管 Program 源码

| 捕获 | 不捕获 |
| --- | --- |
| 授权包根内源码定义的函数、子模块和嵌套定义：选定的第一方源码、已安装和已编目的 Program 包、所有者记录的外部 harness、已发布的 Program、保留的源码快照 | 任意宿主文件、无关依赖、lambda、生成代码、不可用的源码 |

包在 `PROGRAM_ENTRIES` 中列出公开入口，普通入口可带 `__agent_options__` 映射。被捕获的辅助函数不会变成工具。显式方法元数据保留，生成器排除。

## 会话回合与继续

| 名称 | 效果 |
| --- | --- |
| `Agent.run_turn(request, *, context=None, on_event=None, cancel_event=None, execution_context=None)` | 返回 `TurnResult`。全新回合之前应用实例配置。`TurnRequest` 和 `TurnResult` 从 `openprogram` 导入。 |
| `arun_turn(request, **options)` | 同上，异步，支持协作式取消 |
| `resume_turn(continuation, **options)`, `aresume_turn(...)` | 复用检查点的请求，不重复准入 |
| `Context.for_session(store, session_id, head_id=, blocks=, providers=)` | 绑定持久 store 和分支。针对其他会话的请求被拒绝。`Context.session_id` 暴露图身份。 |
| `ChatAgent` | 生产对话类型，继承此契约。覆盖回合入口方法不会把它们包装成辅助调用。 |

事件回调接收 runtime 事件字典，在执行线程上运行。持久暂停和转向沿用现有执行控制所有者和安全点协议。

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