LIVE · Thursday 3 December

How to Choose an Agent's Next Step: Rules, Routers, ReAct, Tree Search, Contextual Bandits or POMDPs

Most agent workflows need code that limits the legal actions and a model that picks among them. Search, bandits and POMDP policies earn their cost only when their assumptions hold.

By Thomas13 min read

For most agent workflows, the best model for choosing the next step is a constrained loop in which code determines which actions are legal and a model scores only those actions. Rules handle known processes, and a router or option scorer handles ambiguous inputs. ReAct handles tasks where each tool result changes the plan. Tree search such as Language Agent Tree Search (LATS), contextual bandits and MDP or POMDP policies are worth their extra cost only when you can evaluate branches, measure rewards or model hidden state.

The six methods differ in what uncertainty they handle and what feedback they need

The choice depends on three questions. The first is how much the system is unsure about. The second is how far an action's consequences reach. The third is what feedback you can collect. The table puts the main methods side by side, with the primary reference for each.

Method and reference Uncertainty it handles Feedback and reward horizon Compute per decision
Rules or state machine (Anthropic) None beyond what the rules anticipate No learning; the next step is fixed by conditions Negligible
Classifier, LLM router or option scorer (Anthropic) Which known branch fits the current input Labelled examples; one step at a time One model call
ReAct (Yao et al.) Facts that appear only during execution Tool observations after each step One generation per step
Tree search, including LATS (Zhou et al.) Which sequence of actions works best An evaluator that can score branches Many calls per decision
Contextual bandit (Vowpal Wabbit) Which action pays off in a given context A measurable reward for the chosen action only Small, after logging
MDP or POMDP policy (Kaelbling et al.) Hidden state and delayed consequences A model of transitions, observations and rewards Heavy to solve exactly

Anthropic's guide "Building effective agents," published December 19, 2024, is the source for the first distinction in this table. It defines workflows as systems "orchestrated through predefined code paths." In agents, by contrast, the model directs its own process and tool use. The guide recommends "finding the simplest solution possible, and only increasing complexity when needed."

Rules and routers work when the branches are known in advance

A state machine is the right tool when the process is stable and its prerequisites are clear. If validation fails, the system revises. If it passes, the system submits. Anthropic's guide says that workflows "offer predictability and consistency for well-defined tasks." Rules are also easy to test, because every transition is written down. Their weakness is that every situation that nobody anticipated needs a new rule.

A router keeps the fixed branches but lets a model decide which branch fits. Anthropic describes routing as a pattern that "classifies an input and directs it to a specialized followup task." The guide says that it works well "where there are distinct categories that are better handled separately." It also says that the classifier can be an LLM or a traditional model. An option scorer is a router whose candidate list changes at each step. It receives the current state and the legal actions, and it returns a score for each action. Correct classification of the current step, however, does not prove that the whole plan is good.

ReAct helps when each observation changes the plan, but it can repeat itself

ReAct, from Yao and colleagues at ICLR 2023, interleaves reasoning traces with actions. The model writes a reasoning step, calls a tool, receives the result and chooses again. On the ALFWorld and WebShop benchmarks, the paper reports that ReAct beat imitation and reinforcement learning methods by 34 and 10 points of absolute success rate.

The paper's own error analysis shows where the method breaks. On HotpotQA, reasoning errors made up 47% of ReAct's failures. The authors describe a frequent pattern in which the model "repetitively generates the previous thoughts and actions" and cannot leave the loop. Searches that returned nothing useful caused another 23% of error cases. Both failures are reasons to put code around the model: a step budget, a check for repeated actions and a retrieval step that can be retried.

Tree search pays off only when branches can be scored reliably

LATS, presented at ICML 2024, combines Monte Carlo tree search with a language model that acts, evaluates states and writes self-reflections on failed attempts. It also uses feedback from the environment. The paper reports 92.7% pass@1 on the HumanEval coding benchmark with GPT-4 and an average score of 75.9 on WebShop with GPT-3.5.

The cost is many model calls per decision. The official LATS repository exposes the number of samples per expansion, the number of evaluations per state and the number of iterations as settings. Each setting multiplies the calls. A 2024 ACL paper by Chen and colleagues found that advanced planning methods need a discriminator with at least 90% accuracy to beat simple re-ranking. With LLM discriminators, tree search was at least 10 to 20 times slower for negligible gains on text-to-SQL and math tasks. Search is therefore worth trying when early choices decide later success and a test, a grader or the environment can score each branch.

Contextual bandits learn from rewards, and POMDPs model what the agent cannot see

A contextual bandit fits a decision that repeats many times with a reward that can be measured. The Vowpal Wabbit documentation defines it as a learner that "repeatedly observes a context, chooses an action, and observes a loss/cost/reward for the chosen action only." Each logged example records the action, its cost and the probability with which it was chosen. That probability lets Vowpal Wabbit's offline evaluation estimate how a new policy would have done, using unbiased estimators such as IPS or doubly robust. A bandit suits a choice such as which retrieval strategy to use for a query type. A standard bandit optimizes one decision at a time, so it does not account for what an action does to later steps.

An MDP or POMDP policy addresses exactly that gap. Kaelbling, Littman and Cassandra's 1998 paper describes an agent that keeps a belief state, a summary of its past observations, and maps that belief to an action. It treats actions that gather information and actions that change the world in the same framework. The price is a complete model of dynamics and rewards. The paper also cites experiments suggesting that even the witness algorithm becomes impractical for problems with more than 15 states and 15 observations. POMDPs are therefore a way to state a problem precisely more often than a solver that you can run on a live agent.

A constrained loop separates filtering, selection and execution

The practical design combines the cheap parts of these methods. Code observes the state and filters the allowed actions. A scorer selects among those actions. Code then resolves arguments, checks permissions, executes the tool, verifies the result and updates the state. Anthropic's guide supports each control in this loop. It recommends stopping conditions "such as a maximum number of iterations," ground truth from the environment at each step, and "extensive testing in sandboxed environments."

The loop below runs as written with the built-in rules scorer and a toy order-status task. It exercises retrieval, retry after a failed call, asking the user and finishing. The scorer receives an explicit state, question and option list, and it never builds tool arguments or grants permissions.

import json
from dataclasses import dataclass, field

ACTIONS = {
    "retrieve": "search the knowledge base for evidence the answer still needs",
    "retry": "repeat the last tool call, which failed",
    "ask_user": "ask the user for information that is missing",
    "finish": "return the answer, which is supported by the evidence",
}

@dataclass
class State:
    goal: str
    evidence: list = field(default_factory=list)
    missing: list = field(default_factory=list)
    last_error: str = ""
    history: list = field(default_factory=list)
    retries: int = 0

def looping(s, window=3):
    tail = s.history[-window:]
    return len(tail) == window and len(set(tail)) == 1

def allowed(s, budget):
    # Code, not the model, decides which actions are legal right now.
    if len(s.history) >= budget["max_steps"] or looping(s):
        return []                       # budget spent or stuck: stop and hand off
    acts = []
    if s.missing:
        acts.append("ask_user")
    if s.last_error and s.retries < budget["max_retries"]:
        acts.append("retry")
    if not s.missing:
        acts.append("retrieve")
    if s.evidence and not s.last_error and not s.missing:
        acts.append("finish")
    return acts

def select(scorer, s, options, threshold):
    state = json.dumps({"goal": s.goal, "evidence": s.evidence, "missing": s.missing,
                        "last_error": s.last_error, "history": s.history})
    probs = scorer(state, {a: ACTIONS[a] for a in options},
                   "Which action should the agent take next?")
    i = max(range(len(options)), key=probs.__getitem__)
    return (options[i] if probs[i] >= threshold else None), probs[i]

def resolve_args(action, s):
    # Arguments are built by code from state, never by the scorer.
    return {"retrieve": {"query": s.goal}, "ask_user": {"fields": s.missing}}.get(action, {})

def authorized(action, args, user):
    return action in user["permitted_actions"]

def verified(s):
    # Completion needs evidence, not the model's claim that it is done.
    return bool(s.evidence) and not s.missing and not s.last_error

def run(task, tools, scorer, user, fallback=None, threshold=0.6,
        budget={"max_steps": 8, "max_retries": 2}):
    s, log = State(goal=task["goal"], missing=list(task.get("missing", []))), []
    while True:
        options = allowed(s, budget)                                  # filter
        if not options:
            log.append(("handoff", "budget or loop")); return False, log
        action, p = select(scorer, s, options, threshold)             # select
        if action is None:                                            # defer
            if fallback is None:
                log.append(("handoff", "low confidence")); return False, log
            action, _ = select(fallback, s, options, 0.0); p = None   # parent model decides
        if action not in options:
            log.append(("invalid", action)); return False, log
        args = resolve_args(action, s)
        if not authorized(action, args, user):
            log.append(("blocked", action)); return False, log
        s.history.append(action); log.append((action, p))
        if action == "finish":
            return verified(s), log                                   # verify
        result = tools[action](s, args)                               # execute
        s.last_error = result.get("error", "")                        # update
        s.retries = s.retries + 1 if action == "retry" else 0
        s.evidence += result.get("evidence", [])
        s.missing = [m for m in s.missing if m not in result.get("answered", [])]

def rules_scorer(state, options, question):
    # Fixed priority order, as a baseline: one-hot "probabilities".
    order = ["ask_user", "retry", "finish", "retrieve"]
    pick = min(options, key=order.index)
    return [1.0 if o == pick else 0.0 for o in options]

def tod_scorer(path="picker"):
    from tod.release.load import load_picker
    picker = load_picker(path)          # bf16 and chunked_eager attention from picker.json
    return lambda state, options, question: picker.predict(
        state=state, options=options, question=question)

def prompted_scorer(model="claude-haiku-5-5"):
    import anthropic
    client = anthropic.Anthropic()
    def score(state, options, question):
        prompt = (f"{question}\nState: {state}\nOptions:\n"
                  + "\n".join(f"- {k}: {v}" for k, v in options.items())
                  + "\nReply with the option name only.")
        msg = client.messages.create(model=model, max_tokens=1024,
                                     messages=[{"role": "user", "content": prompt}])
        text = "".join(b.text for b in msg.content if b.type == "text").strip()
        return [1.0 if k == text else 0.0 for k in options]
    return score

if __name__ == "__main__":
    calls = {"n": 0}
    def retrieve(s, args):
        calls["n"] += 1
        return {"error": "timeout"} if calls["n"] == 1 else {"evidence": ["order 1182 shipped"]}
    tools = {"retrieve": retrieve,
             "retry": lambda s, args: {"evidence": ["order 1182 shipped"]},
             "ask_user": lambda s, args: {"answered": args.get("fields", [])}}
    user = {"permitted_actions": set(ACTIONS)}
    print(run({"goal": "Where is my order?", "missing": ["order_number"]},
              tools, rules_scorer, user))

Run as a script, it prints a successful run in which the agent asks for the order number, retrieves, retries after a timeout and finishes. Deferral is a design choice in this loop, not a property of any model. When the scorer's top probability falls below the threshold, the turn goes to the fallback scorer, such as prompted_scorer(). With no fallback, the loop stops and hands the task to a person. A prompted router returns one label without a probability, so it cannot supply its own deferral signal.

Parsec, a small language model lab, publishes an option scorer of this kind called TOD, and tod_scorer() loads it. Parsec's TOD page says that the model ranks the next action from a supplied list, generates no free text and cannot invent actions. A confidence gate passes uncertain turns unchanged to the parent model. According to the page, the price is $0.30 per 1,000 decisions, flat regardless of context length, and it is charged on top of the parent model's costs. The release consists of LoRA adapters on Google's gemma-4-12B-it plus a ModernBERT-base retriever that handles long option lists. The model card lists the adapters as Apache-2.0, while the base model stays under Gemma 4 terms that each user must accept. The GitHub code repository has no licence file of its own. Parsec's repository reports a median latency of 542 ms for up to 16 options on one A100-40G GPU in bf16 at batch size 1, which is Parsec's own measurement. On the public JevBench decision set, the release scores below its own untrained base model, and Parsec's page says that it plans to recover the lost decisions in the next release. Parsec's decision-models page also offers tuning on a customer's own decisions, at no published price.

To reproduce a run, pin the exact release rather than a moving branch. The commands below fetch the Hugging Face commit dated October 1, 2026 and the matching code commit, and they check the bundle's hashes.

hf auth login   # after accepting the Gemma 4 licence on Hugging Face
hf download parsecai/tod --revision 07d34d592ffce0f0517e3f26dcd4288218958005 --local-dir picker
(cd picker && sha256sum -c sha256sums.txt)
pip install "git+https://github.com/daseinlabs/tod@642834e248edb57d4c30aacd3fb06b81fc8ad771"

The repository warns against sdpa attention on this base model and against bitsandbytes int8, which it says changes some picks. Keep the defaults from picker.json, which load bf16 weights with chunked_eager attention on a CUDA GPU.

Measure whole tasks before trusting any router

A comparison of rules, a prompted router and an unmodified option scorer on the same agent workflows has not been published. The harness below makes that comparison possible once the loop is saved as loop.py. It runs each router on identical workflows and reports end-to-end task success, invalid actions, recovery after a failed call, time per task and cost per successful task. A second function scores decisions separately against labelled next actions. It reports accuracy, coverage at the deferral threshold and calibration error.

import time
from loop import run

def evaluate(name, scorer, workflows, cost_per_decision, threshold=0.6):
    wins = invalid = recovered = failures_seen = decisions = deferred = 0
    seconds = 0.0
    for wf in workflows:
        t0 = time.perf_counter()
        ok, log = run(wf["task"], wf["make_tools"](), scorer, wf["user"], threshold=threshold)
        seconds += time.perf_counter() - t0
        wins += ok
        invalid += sum(1 for e in log if e[0] == "invalid")
        decisions += len(log)
        deferred += sum(1 for e in log if e[1] is None or e[0] == "handoff")
        if "retry" in [e[0] for e in log]:
            failures_seen += 1
            recovered += ok
    spend = decisions * cost_per_decision
    return {"router": name, "task_success": wins / len(workflows),
            "invalid_actions": invalid,
            "recovery_rate": recovered / failures_seen if failures_seen else None,
            "seconds_per_task": seconds / len(workflows),
            "cost_per_success": spend / wins if wins else None,
            "deferral_share": deferred / decisions if decisions else 0}

def decision_metrics(scorer, records, threshold=0.6, bins=10):
    # Scored apart from task success: labelled (state, options, correct label) records.
    rows = []
    for r in records:
        probs = scorer(r["state"], r["options"], r["question"])
        i = max(range(len(probs)), key=probs.__getitem__)
        rows.append((probs[i], list(r["options"])[i] == r["label"]))
    kept = [hit for p, hit in rows if p >= threshold]
    ece = 0.0
    for b in range(bins):
        cell = [(p, hit) for p, hit in rows if b / bins < p <= (b + 1) / bins]
        if cell:
            conf = sum(p for p, _ in cell) / len(cell)
            acc = sum(hit for _, hit in cell) / len(cell)
            ece += len(cell) / len(rows) * abs(conf - acc)
    return {"accuracy": sum(hit for _, hit in rows) / len(rows),
            "coverage": len(kept) / len(rows),
            "accuracy_when_served": sum(kept) / len(kept) if kept else None,
            "calibration_error": ece}

The cost_per_decision input for a prompted router can be worked out from list prices. Assume 3,000 input tokens and 20 output tokens per decision. Anthropic's pricing page lists Claude Haiku 5.5 at $0.10 per million input tokens and $0.50 per million output tokens for prompts up to 100,000 tokens, which gives about $0.00031 per decision. Sonnet 5.5, at $2 and $10, gives about $0.0062 per decision. Haiku 5.5 uses adaptive thinking at a default effort of medium, according to Anthropic's models page, so the real output per decision should be measured rather than assumed.

The two sets of numbers answer different questions. A router can pick the labelled action more often and still finish fewer tasks, because one wrong step early can end a run. Any latency figure from the harness should be reported with the release, the hardware, the number of options and the inference settings. Custom tuning belongs after this step, and only if held-out workflows show the unmodified scorer losing to the alternatives.

A next-step scorer does not make an agent a planner

Picking a plausible next action is a local decision. It does not show that the sequence of actions is optimal over a long horizon. A scorer also cannot supply state that the loop never gave it, because it receives only the state string and the options. It does not learn from rewards online, which is the job of a bandit. It cannot discover a valid action that is missing from the list, because the filter determines what exists.

Those limits point to the simpler options as often as to the complex ones. Rules alone are enough when every branch can be written down and tested. A prompted model is enough when the options are few, the volume is low and you have no labelled decisions. Search is preferable when early choices decide the outcome and a grader can score branches. A bandit is preferable when the same choice recurs at high volume with a reward that you can log, together with the probability of each chosen action.

Sources

More in Research

All Research →