# 下一步决策

```
from openprogram import Agent, decision

class ExampleAgent(Agent):
    method_options = {'route_message': {'tool': True}}

    def route_message(self, msg: str) -> str:
        return decision.make("Pick one way to handle this message.", {
            "analyze":  analyze_sentiment,        # a function
            "fallback": fallback_reply,           # a function
            "done":     "CONVERSATION_OVER",      # a value
        })
```

模型选了函数：带解析和注入的参数运行，返回其返回值。选了值：直接返回该值。决策本身就是分支，不用写 `if`。

## 先干活，最后决策

```
from openprogram import Agent, agent

class ExampleAgent(Agent):
    method_options = {'handle_ticket': {'tool': True}}

    def handle_ticket(self, ticket: str) -> dict:
        """Read the ticket, look things up, then decide which flow to route to."""
        return agent(
            f"Handle this ticket: {ticket}",
            toolset="default",          # before: research with tools, run commands
            choices={                   # closing: the return must be one of these
                "refund":    issue_refund,
                "escalate":  escalate_to_human,
                "close":     {"status": "closed"},
            },
        )
```

|  | `decision.make(prompt, options)` | `agent(prompt, choices=options)` |
| --- | --- | --- |
| 模型做什么 | 只做选择 | 完整一轮：推理并使用 `tools` 或 `toolset` 的工具；最终回复必须是一个 `{"call": ...}` JSON |
| 提示词 | 你的提示词加菜单；提示词本身要要求模型选择 | 自动拼入菜单和 `DECISION_FINISH_INSTRUCTION` |
| 重试 | `max_retries`，默认 1，0 表示关闭 | 固定一次 |

不带 `choices` 时 `agent` 返回回复文本。在 `Agent` 方法内两者都用外层调用的 Runtime。在任何 Agent 调用之外要传 `runtime=`，否则 `decision.make` 抛 `RuntimeError`。代码：`openprogram/runtime/agent/decision.py`。

## 与原生工具调用对比

|  | [原生工具调用](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/tool-calling.zh.html) | 下一步决策 |
| --- | --- | --- |
| 选项如何到达模型 | 协议的 `tools` 字段 | 提示词里的文本菜单 |
| 选择的表达 | 结构化 `ToolCall` | 回复正文里的 JSON |
| 谁解析 | Provider 和 agent loop | `decision.py` |
| 选项可以是值 | 不可以 | 可以，通常是 `done`、`escalate` |
| 依赖 | Provider 工具调用 | 纯文本 |

同一个 `Agent` 方法既可作原生工具，也可作选项。另外要考虑每次决策和重试是否应成为可追踪的 DAG 节点。

## 选项

| 类型 | 被选中时 | Schema 来源 |
| --- | --- | --- |
| 函数 | 运行并返回其返回值 | 函数签名 |
| 值 | 返回固定值 | 无 |
| Schema | 模型按 schema 填写，返回 `{"decision": name, **字段}` | 你声明的 schema |

```
decision.make("...", {
    "retry":     retry_fn,                            # function option
    "skip":      "SKIPPED",                           # value option
    "abort":     (AbortSignal(), "pick when stuck"),  # value option + description
    "emit_plan": ("Produce a plan.", {                # schema option: ("description", schema)
        "steps": [{"action": str, "target": str}],
        "rationale": str,
    }),
})
```

字典形式：`{name: handler}`。列表形式：可调用对象、`(callable, "description")`、`"name"`、`("name", "description")` 或 `("name", "description", schema)`；函数选项的名称是其 `__name__`。

### Schema 写法

| 写法 | 含义 |
| --- | --- |
| `field: str`（任意 Python 类型） | 该类型的标量 |
| `field: "description"` | 带描述的 `str` 标量 |
| `field: [subschema]` | 列表，模板必须恰好一个；`[str, int]` 抛 `TypeError` |
| `field: {subfield: ...}` | 嵌套对象，至少要有一个键不属于元描述集合 |
| `field: {"type": T, "description": ..., "options": [...]}` | 元描述。键全部落在 `{type, description, options, fields, items}` 内的字典都按此解析。 |

元组在 handler 位置是保留语法：字面量二元组值会被误读为 `(value, "description")`。若总要返回同一结构，用单选项的 `decision.make` 或 `exec(response_format=...)`。

**内部步骤**

1. **`render_options`** 为每个选项输出签名 `name(param: type, ...)`、描述、带 `options` 的参数详情，以及一行 `Call:` JSON 示例，占位符是原生字面量（`0`、`false`、`[]`、`{}`、`"<str>"`）并带嵌套形状。只显示 `source="llm"` 的参数。
2. **调用模型。**`decision.make` 发送 `runtime.exec(prompt + menu)`；`exec(choices=)` 把菜单拼进本轮。
3. **`parse_args`** 按下表检查回复，返回 `(chosen, kwargs)`：函数或名称字符串。
4. **重试**（遇 `_ParseError`）：上次回复、错误原因和重新渲染的菜单通过 `runtime.exec` 发回，和普通模型调用一样进入 DAG。用尽后抛 `DecisionError`，带最后的错误类型、信息和回复开头。它继承 `ValueError`；框架没有内置兜底。
5. **`resolve_decision`** 运行 `chosen(**kwargs)` 或查值；带 schema 的值选项返回 `{"decision": name, **kwargs}`。

| parse_args 步骤 | 行为 |
| --- | --- |
| `extract_action` | 从 JSON 代码块或纯文本里找带 `call` 键（别名 `action`、`function`、`tool`）的 JSON |
| 名称不存在 | `_ParseError("unknown_call")` |
| `_validate_field` | 校验类型（`str/int/float/bool/list/dict`；`bool` 不算 `int`，`float` 接受 `int`）、枚举和嵌套 |
| 函数选项 | `source="context"` 参数取自 `context` 字典，注入 `runtime` 类参数，丢弃多余字段，检查必填 |
| 值和 schema 选项 | 声明的字段都必填，其余丢弃 |
