# Next-step decisions

Code lists a fixed menu. The model answers with JSON naming one option. Only a validated answer runs; code stays in control. Source: `openprogram/runtime/agent/decision.py`.

| Entry | Model does | Runtime |
| --- | --- | --- |
| `decision.make(prompt, options)` | Picks, nothing else | The enclosing `Agent` method's (`_current_runtime`), or `runtime=` outside any Agent call |
| `agent(prompt, choices=options)` | Runs a full turn with tools, then picks as its wrap-up | Same |

## Compared with a native tool call

|  | Native tool call | Next-step decision |
| --- | --- | --- |
| Options reach the model | Provider `tools` field | Text menu in the prompt |
| Choice arrives as | Protocol-level `ToolCall` | JSON in the reply body |
| Parsed by | Provider and `runtime/agent/loop` | `decision.py` |
| Non-function option | No | Yes |
| Needs provider tool use | Yes | No, plain text is enough |
| Each decision and retry | Part of the tool loop | Its own traceable DAG call |

An `Agent` method can be both a native tool for `exec(tools=[...])` and a decision option. See [tool calling](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/tool-calling.html).

## Pure decision: 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("Pick a way to handle this message.", {
            "analyze":  analyze_sentiment,    # function: run, return its result
            "fallback": fallback_reply,
            "done":     "CONVERSATION_OVER",  # value: returned as-is
        })
```

The decision is the branch: the caller writes no `if`.

## Work, then decide: 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"Handle this ticket: {ticket}",
            toolset="default",        # the work: tools and reasoning
            choices={                 # the wrap-up: must pick one
                "refund":   issue_refund,
                "escalate": escalate_to_human,
                "close":    {"status": "closed"},
            },
        )
```

`choices` goes to `Runtime.exec`, which adds the menu and `DECISION_FINISH_INSTRUCTION` to the prompt and runs a normal turn. The last reply must be a `{"call": ...}` JSON, resolved by `resolve_decision`. `decision.make` is the same with no work before it.

## Options

| Kind | When picked | Schema from |
| --- | --- | --- |
| Function | Runs it, returns its return value | Function signature |
| Value | Returns the fixed value | None |
| Schema | Model fills the schema; returns `{"decision": name, **fields}` | Declared by you |

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

A list works too. Each item: a callable, `(callable, "description")`, `"name"`, `("name", "description")` or `("name", "description", schema)`. A function's name comes from `__name__`.

| Schema field | Meaning |
| --- | --- |
| `field: str` (any Python type) | Scalar of that type |
| `field: "description"` | `str` scalar with a description |
| `field: [sub-schema]` | List of matching elements |
| `field: {sub-field: ...}` | Nested object |
| `field: {"type": T, "description": ..., "options": [...]}` | Type, description and enum |

Always the same structure, no branching: a single-option `decision.make`, or `exec(response_format=...)`.

## From reply to result

1. `render_options` writes the menu: signature, description, arguments, one-line `Call:` JSON example. Only `source="llm"` arguments show.
2. The model is called: `runtime.exec(prompt + menu)`, or the turn `agent` was already sending.
3. `parse_args` extracts and validates the JSON.
4. On failure, one more pick (`max_retries=1`, 0 disables): `runtime.exec` sends the last reply, the error and the menu again. It lands in the DAG. Still invalid: `DecisionError`.
5. `resolve_decision` runs the function or looks up the value.

**Validation rules**

| Check | Rule |
| --- | --- |
| JSON | From a `json` code block or raw text, with a key `call`, `action`, `function` or `tool` |
| Unknown option | `_ParseError("unknown_call")`; no JSON is `no_action`; non-object args is `bad_args` |
| Field type | `str int float bool list dict`, nested recursively. `bool` is not `int`; `float` accepts `int`. Enum through `options`. |
| Function option | Fills `source="context"` from `context`, injects runtime arguments, drops extras, requires arguments with no default |
| Value or schema option | All schema fields required, extras dropped |
| Returns | `(chosen, kwargs)`: the function, or the option name |
| Menu placeholders | JSON literals: `0 false [] {} "<str>"`; enum values listed |

**DecisionError**

Subclass of `ValueError`, carrying the last error type, message and reply head. `except DecisionError` catches only "the model never picked a valid option". The framework has no fallback; the caller decides.

## Implementation status

All of this is implemented.
