Field Notes

Adding a decision step to anthropic4s

Adding a decision step to anthropic4s

Earlier this month I wrote about decision models in llama.cpp: Kev-4B served at /v1/systemone, picking an answer in one forward pass and returning a probability for every option, with zero output tokens. anthropic4s is my pure-Scala SDK for the Claude API. This post is about putting the two together. anthropic4s 1.1.0 ships an optional module, anthropic4s-decide, and the part I found more interesting than the client itself is where a decision step belongs in an agent.

Why a second model next to Claude

The Claude API has no decision endpoint. The closest thing is structured output on a small model such as Haiku: you get an answer, but no probabilities and no logprobs. For routing a ticket, or for checking “did the user really ask for this?”, I want a number I can put a threshold on, and I want it fast. In my earlier measurements, Kev-4B on the Radeon 8060S answered a single choice question in about 65 ms once warm.

So the split is simple. The small model makes the quick calls. Claude does the thinking.

The API: questions are typed values

A System One request carries a state (text, JSON or a conversation) and a set of questions of three kinds: choice, score and noul (a yes/no answered with a probability). In Scala I wanted each question to know its own answer type, so a batch comes back typed instead of as a bag of JSON.

sealed trait Team
object Team {
  case object Billing   extends Team
  case object Shipping  extends Team
  case object Technical extends Team
}
val team = Question.choice[Team]("Which team should handle this?")(
  Criterion(Team.Billing, "billing", "payments, charges, refunds, invoices"),
  Criterion(Team.Shipping, "shipping", "delivery, tracking, lost or late parcels"),
  Criterion(Team.Technical, "technical", "bugs, errors, login problems")
)
val angry   = Question.noul("Is the customer angry?")
val urgency = Question.score("How urgent is this?")("can wait", "this week", "today", "right now")
Decide.ember[IO](DecideConfig.local()).use { decide =>
  // One request, typed per question: IO[(ChoiceAnswer[Team], Double, ScoreAnswer)]
  decide.run(ticket, (team.as("team"), angry.as("angry"), urgency.as("urgency")).tupled)
}
  • Question.choice[A] gives a ChoiceAnswer[A]: the chosen Team, not a string label, plus every option's probability and a confidence.
  • Question.score takes 2 to 10 ordered levels and gives a weighted score with nearest and mostLikely, which can differ. Question.noul gives a Double.
  • Duplicate labels, duplicate ids or a score outside 2–10 levels fail with DecideError.InvalidQuestion before anything is sent.
  • The module depends on http4s and circe, not on anthropic4s core. If all you need is classification, you can use it alone.

The probe that saved the release

I wrote the decoder from the protocol description, and the fake server in the tests from the same reading. Eleven tests were green. Then I pointed the client at the real llama-server. Choice probabilities were an object keyed by label, as expected. Score probabilities were not the array I had assumed: they were an object keyed by level index.

Two code panels comparing the assumed score probabilities, a JSON array, with the real llama-server response, an object keyed by level index with a legend.
The tests and the decoder shared one wrong assumption, so they agreed with each other and both were wrong.

Without that probe, every score answer would have failed with DecideError.Decode while CI stayed green. The fix was small: decode a Map[Int, Double] and put the values back in level order. The lasting change was the fixture. The fake server now replays a response captured from the real one, so the tests record how the server actually behaves.

Two places in an agent

Diagram of two flows. Left, a router: user request, decide.ask with a confidence, then a cheap model when confidence is at least 0.8, or Opus with every tool when it is lower. Right, a guard: Claude calls book_table, withBeforeTool asks the decision model, and the call is allowed at 0.5 or above, otherwise denied with a reason.
A router in front picks the cheapest setup; a guard beside the tool runner checks side effects before they run.

A router in front

The router asks one choice question and only trusts the answer when it is confident:

decide.ask(text, intent).flatMap { route =>
  if (route.confidence < 0.8) agent(claude, decide, Model.ClaudeOpus5_5, allTools, text)
  else route.choice match {
    case Intent.Chat    => chat(claude, text)                                              // Haiku, no tools
    case Intent.Weather => agent(claude, decide, Model.ClaudeHaiku5_5, List(Tools.weather), text)
    case Intent.Booking => agent(claude, decide, Model.ClaudeSonnet5_5, allTools, text)
  }
}

confidence is not the top probability. It is (p − 1/n) / (1 − 1/n), so a 0.53 favourite among three options is only 0.29 confident. That rescaling is what makes one threshold readable across questions with different numbers of options, though I would still tune it per question.

The criteria matter more than I expected. The rule I ended up with is: describe what an option needs, not what it is about. “Should I eat outside tonight?” never says “weather”, but it needs today's weather to answer.

Table of one live run. Capital of Belgium routed to chat at 0.99 confidence, ran on Haiku. Eating outside routed to weather at 0.29, fell back to Opus. The booking request routed to booking at 0.23, fell back to Opus, and the guard saw 0.70 and allowed the booking.
One live run: the top choice was right every time, but only the chat question cleared the 0.8 threshold.

This is one run of three requests, not a benchmark. What it shows is the failure mode I want: when the small model is unsure, the request goes to the expensive path and is still answered correctly. Unsure costs money, not correctness.

A guard beside the tool runner

anthropic4s's tool runner already has a hook that runs before each tool call. The guard asks the decision model whether the user actually asked for a booking:

def bookingGuard(decide: Decide[IO], userText: String): ContentBlock.ToolUse => IO[ToolDecision] = call =>
  if (call.name != "book_table") IO.pure(ToolDecision.Allow)
  else
    decide
      .ask(conversation(userText), bookingAsked)
      .map { p =>
        if (p >= 0.5) ToolDecision.Allow
        else ToolDecision.Deny("The user did not ask for a booking. Do not book anything.")
      }
      .handleError(_ => ToolDecision.Deny("Bookings cannot be checked right now."))
val config = RunnerConfig.default[IO].withMaxIterations(10).withBeforeTool(bookingGuard(decide, text))

Deny does not run the tool and sends the reason back to Claude as an error tool result, so the agent changes course instead of crashing. Abort would stop the whole run. The handleError makes it fail closed: if the decision model cannot answer, nothing is booked.

Describing what true and false mean helped here. Without .describe(...), a real booking request scored 0.57, too close to a coin flip. With it, the booking went to 0.69, while a weather-only question only moved from 0.08 to 0.11. The gap between yes and no grew, so a 0.5 threshold has room on both sides. In the live run the guard saw 0.70 on the real booking and let it through. The deny and fail-closed paths are covered by tests with the testkit's ScriptedModel: the booking tool counts how often it really ran, and a decision model that is down must leave that count at zero.

Down is the normal failure

To check that configuration from the environment worked, I pointed DECIDE_BASE_URL at port 9, where nothing listens. The program crashed with a raw java.net.ConnectException, which went straight past the recover { case e: DecideError => ... } in my own example. The most common way of being down escaped the error type I documented. Transport failures now become DecideError.Unavailable(endpoint, cause).

DecideConfig.fromEnv reads the optional DECIDE_BASE_URL, DECIDE_API_KEY and DECIDE_TIMEOUT. With none set, it is llama-server on localhost:8081. For Play controllers there is FutureDecide, the same idea as FutureAnthropic.

Shipping it

The build uses sbt-typelevel, where tlBaseVersion is build-wide, so all eight artifacts went to Maven Central as 1.1.0 together. The core did not change and MiMa checks that 1.1.0 stays binary compatible with 1.0.0. The new module declares tlVersionIntroduced so MiMa does not look for a 1.0.0 that never existed. One CI catch: the generated workflow has to list decide/target, or the module is built but never published, and githubWorkflowCheck failed until I regenerated it.

I also updated the anthropic4s Claude Code plugin. It has a new decision-models reference, and every Scala snippet in it is a region of a file that compiles and runs its tests against the published 1.1.0.

What I would watch

  • Thresholds are per question. Three requests tell you the shape, not the number. Tune on real traffic.
  • Batching is not always faster. In my earlier measurement, three questions in one request took about 412 ms, against about 244 ms for three separate calls. Measure both; with Cats Effect, parTupled is one word away.
  • Score was the weakest question type in my earlier tests. I would trust a choice before a score.
  • Cold start was about 2.5 s, which is why the default timeout is 10 s.

The code is on GitHub, with the router and the guard in the AgentDecisions example.

Keep reading