# 下一步决策

代码列出固定菜单，模型回一段 JSON 选一项，通过校验才执行，控制权留在代码。源码：`openprogram/runtime/agent/decision.py`。

| 入口 | 模型做什么 | Runtime |
| --- | --- | --- |
| `decision.make(prompt, options)` | 只选择 | 外层 `Agent` 方法的（`_current_runtime`）；不在 Agent 调用内时传 `runtime=` |
| `agent(prompt, choices=options)` | 先用工具跑完整一轮，收尾时选择 | 同上 |

## 和原生工具调用的区别

|  | 原生工具调用 | 下一步决策 |
| --- | --- | --- |
| 选项如何给模型 | provider 的 `tools` 字段 | prompt 里的文本菜单 |
| 选择的形式 | 协议层 `ToolCall` | 回复正文里的 JSON |
| 解析者 | provider 和 `runtime/agent/loop` | `decision.py` |
| 选项可以不是函数 | 不可以 | 可以 |
| 依赖 provider 的 tool use | 依赖 | 不依赖，纯文本即可 |
| 每次决策和重试 | 属于工具循环 | 单独的可追踪 DAG 调用 |

同一个 `Agent` 方法既可作 `exec(tools=[...])` 的原生工具，也可作决策选项。见[工具调用](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/tool-calling.zh.html)。

## 纯决策：decision.make

```
from openprogram import Agent, decision

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

    def route_message(self, msg: str) -> str:
        return decision.make("选一种方式处理这条消息。", {
            "analyze":  analyze_sentiment,    # 函数：执行并返回结果
            "fallback": fallback_reply,
            "done":     "CONVERSATION_OVER",  # 值：原样返回
        })
```

决策本身就是分支，调用方不写 `if`。

## 先做事，再决策：agent(choices=)

```
from openprogram import Agent, agent

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

    def handle_ticket(self, ticket: str) -> dict:
        return agent(
            f"处理这个工单： {ticket}",
            toolset="default",        # 做事：工具和推理
            choices={                 # 收尾：必须选一项
                "refund":   issue_refund,
                "escalate": escalate_to_human,
                "close":    {"status": "closed"},
            },
        )
```

`choices` 交给 `Runtime.exec`，它把菜单和 `DECISION_FINISH_INSTRUCTION` 加进 prompt，跑一轮普通对话。最后一条回复必须是 `{"call": ...}` JSON，由 `resolve_decision` 解析。`decision.make` 相当于前面没有做事的这一过程。

## 选项

| 类型 | 选中后 | schema 来源 |
| --- | --- | --- |
| 函数 | 执行，返回其返回值 | 函数签名 |
| 值 | 返回固定值 | 无 |
| schema | 模型按 schema 填写，返回 `{"decision": name, **fields}` | 自己声明 |

```
decision.make("...", {
    "retry":     retry_fn,                         # 函数
    "skip":      "SKIPPED",                        # 值
    "abort":     (AbortSignal(), "pick when it can't continue"),  # 值 + 说明
    "emit_plan": ("Produce a plan.", {             # schema： ("description", schema)
        "steps": [{"action": str, "target": str}],
        "rationale": str,
    }),
})
```

也可用列表。每项是可调用对象、`(callable, "说明")`、`"name"`、`("name", "说明")` 或 `("name", "说明", schema)`。函数选项的名字取 `__name__`。

| schema 字段 | 含义 |
| --- | --- |
| `field: str`（任意 Python 类型） | 该类型的标量 |
| `field: "说明"` | 带说明的 `str` 标量 |
| `field: [子 schema]` | 列表，元素符合子 schema |
| `field: {子字段: ...}` | 嵌套对象 |
| `field: {"type": T, "description": ..., "options": [...]}` | 类型、说明和枚举 |

不需要分支、总是同一结构：用单选项的 `decision.make`，或 `exec(response_format=...)`。

## 从回复到结果

1. `render_options` 生成菜单：签名、说明、参数、一行 `Call:` JSON 示例。只显示 `source="llm"` 的参数。
2. 调用模型：`runtime.exec(prompt + menu)`，或 `agent` 本来要发的那一轮。
3. `parse_args` 提取并校验 JSON。
4. 失败时再选一次（`max_retries=1`，设 0 关闭）：`runtime.exec` 发送上次回复、错误原因和菜单，同样进 DAG。仍无效则抛 `DecisionError`。
5. `resolve_decision` 执行函数或查出值。

**校验规则**

| 检查 | 规则 |
| --- | --- |
| JSON | 来自 `json` 代码块或原文，键为 `call`、`action`、`function` 或 `tool` |
| 未知选项 | `_ParseError("unknown_call")`；没有 JSON 是 `no_action`；args 不是对象是 `bad_args` |
| 字段类型 | `str int float bool list dict`，递归校验嵌套。`bool` 不算 `int`，`float` 接受 `int`。枚举用 `options`。 |
| 函数选项 | 从 `context` 填 `source="context"` 参数，注入 runtime 参数，丢弃多余字段，要求无默认值的参数都在 |
| 值或 schema 选项 | schema 字段全部必填，多余字段丢弃 |
| 返回 | `(chosen, kwargs)`：函数，或选项名 |
| 菜单占位 | JSON 字面量：`0 false [] {} "<str>"`；枚举列出可选值 |

**DecisionError**

继承 `ValueError`，带最后的错误类型、消息和回复开头。`except DecisionError` 只捕获“模型始终没选出有效项”。框架不做兜底，由调用方决定。

## 实现状态

以上全部已实现。
