GyaanStack. Blog

Articles / agentsllmpython

How AI agents make decisions: tool choice, confidence and when to use code

How an LLM agent picks its next action, what steers the pick, and a local Qwen3 experiment measuring tool-choice accuracy as descriptions and tool count change.

By Raghunath · · 14 min read

An agent's "decision" is a few generated tokens. At each step the model reads the conversation plus a menu of tools and writes either plain text or a tool call. The tool call is text in a fixed format that your runtime parses. Nothing in the model weighs options the way a planner does. The only way to steer it is to change what pushes probability toward the right tool name at the moment the model writes it.

This post is about that moment. The loop around it is covered in the agent engineering cheat sheet, the control-flow patterns (ReAct, plan-and-execute, routers) in AI agent architectures explained, and the request and response shapes in the function calling tutorial. Here the questions are narrower. What makes a model pick tool A over tool B? How much do descriptions and menu size matter, measured? Can you tell when the model is unsure? And which decisions should never reach the model at all?

A decision is a sampled token sequence#

When you send tools to a chat API, the server does not hand the model a data structure. It renders the tools into the prompt with the model's chat template. For Qwen3 in Ollama you can read the template with ollama show qwen3:4b-instruct --template. It puts the JSON schemas inside <tools></tools> tags in the system turn and tells the model to answer with:

<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call>

So when a request arrives, the model generates token by token. The first fork is whether it starts with <tool_call> or with ordinary words. If it opens the tag, the next fork is the tool name, and after that come the arguments. Ollama's parser turns the tagged text back into a tool_calls field.

 system: rules + <tools> [16 JSON schemas] </tools>
 user:   "Order 7007 was delivered but the box was empty."
                           |
                           v
          next token?  "<tool_call>"  vs  "I'm sorry..."      fork 1: act or answer
                           |
                           v
          {"name": "  refund_order  vs  get_return_policy     fork 2: which tool
                        vs  create_support_ticket ...
                           |
                           v
          "arguments": {"order_id": "7007", ...}             fork 3: arguments
                           |
                           v
          runtime parses JSON -> your code runs the function

Three consequences follow. First, everything in the prompt competes at those forks: the system prompt, the conversation so far, every tool name and every description. Second, the name is itself several tokens, so tools that share a prefix (get_order_status, get_invoice) stay in competition until the tokens diverge. Third, sampling settings matter. At temperature 0 you get the single most likely path; at higher temperatures the same request can take a different branch on a different run.

What steers the pick#

The description. Anthropic's tool-definition guide is blunt: detailed descriptions are "by far the most important factor in tool performance," and it asks for at least three to four sentences per tool. A good description says what the tool returns, when to use it, and, most usefully, when to use a neighbouring tool instead.

The menu size. Each extra tool is another candidate at fork 2. OpenAI's function-calling guide suggests aiming for fewer than 20 functions available at the start of a turn, and calls this a soft suggestion. Anthropic's guide recommends consolidating related operations into fewer tools to reduce selection ambiguity.

The name. Names are the part the model writes, so they carry weight even when descriptions are empty. track_shipment already says a lot.

The tool-choice setting. auto, any/required, a named tool, or none change which fork 1 outcomes are allowed. The table of settings per provider, and the forcing restrictions on recent Claude models, are in the function calling tutorial. The setting can force a call but it cannot make the model pick the right one.

The next section measures the first two on a laptop.

The experiment: 20 labelled requests, one small model#

The setup is a customer-support agent for an Indian online store. Five tools do the real work, and they come in two confusable pairs on purpose:

  • get_order_status (state and delivery date) versus track_shipment (courier scans and live location)
  • cancel_order (not yet shipped) versus refund_order (already delivered)
  • update_shipping_address

Eleven distractors sit alongside them in the larger menu. Some are harmless (apply_coupon, reset_password); some are close neighbours (get_return_policy, create_support_ticket, get_invoice).

Every tool has two descriptions. The "good" one follows the advice above, including the "use the other tool for X" line. The "terse" one is a word or two ("Refund."). Names and parameter schemas stay identical. That gives four menus: 5 or 16 tools, good or terse descriptions.

The 20 requests have a labelled correct answer each: 17 that need a specific tool and 3 ("Thanks, that's all I needed.", "What is a tracking number?", "Hello!") where the right move is to call nothing. A request counts as correct only if the first tool call matches the label, or if there is no call when none was wanted.

The model is qwen3:4b-instruct (Q4_K_M, 4.0B parameters) on Ollama 0.40.16, temperature 0, fixed seed, run on a MacBook. The core of the script:

def chat(model, messages, tools=None, temperature=0.0, think=False, **extra):
    body = {"model": model, "messages": messages, "stream": False, "think": think,
            "options": {"temperature": temperature, "seed": extra.pop("seed", 0), **extra}}
    if tools:
        body["tools"] = tools
    req = urllib.request.Request(OLLAMA, json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        return json.load(r)

def pick(model, text, tools, **kw):
    """Return the first tool name the model called, or None for a plain-text reply."""
    msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": text}]
    out = chat(model, msgs, tools, **kw)
    calls = out["message"].get("tool_calls") or []
    return (calls[0]["function"]["name"] if calls else None), out

chat is the only function that touches a model. To run the same eval against a hosted API, replace its body with your provider's client call and map the reply's tool call back to a name. The full script, with all tool definitions and the 20 cases, uses only the Python standard library.

Results: descriptions beat menu size#

qwen3:4b-instruct  think=False tools= 5 desc=good  acc=20/20 (100%)
qwen3:4b-instruct  think=False tools= 5 desc=terse acc=17/20 (85%)
      miss x2: get_order_status -> track_shipment
      miss x1: get_order_status -> None
qwen3:4b-instruct  think=False tools=16 desc=good  acc=20/20 (100%)
qwen3:4b-instruct  think=False tools=16 desc=terse acc=16/20 (80%)
      miss x2: get_order_status -> track_shipment
      miss x1: get_order_status -> None
      miss x1: refund_order -> get_order_status
Menu Good descriptions Terse descriptions
5 tools 20/20 17/20
16 tools 20/20 16/20

The script also printed seconds per request; that column is cut from the output above because other jobs were sharing the same Ollama server during the run, so the timings measure queueing more than the model. Output length was about 30 tokens per request in every condition.

What the table says:

  • Descriptions moved accuracy by 15 to 20 points. Every miss came from a terse menu. With good descriptions, both menus scored 20 of 20.
  • Tripling the menu cost one request, and only when the descriptions were terse. At 16 tools, menu length was not this model's main problem. Do not read that as "tool count never matters"; it means descriptions matter first, at this size.
  • The misses sit on the confusable pair. In both terse menus, three misses were status requests that went to track_shipment or got a plain-text reply. With only "Order status." and "Shipment tool." to go on, a question about delivery dates reads like a shipping question. The good description's last sentence ("Not for the parcel's live location: use track_shipment") is the part that separates them. The one extra miss at 16 tools was a refund request sent to get_order_status.
  • None of the three no-tool requests triggered a call. Fork 1 errors were rare (one status request per terse menu got a text reply instead of a call); most mistakes happened at fork 2.

Twenty requests is a small set. One request is five points, so treat the gap between 80% and 85% as noise. The gap between 80% and 100% held across both menu sizes, which makes it far more likely to be real. To compare two close configurations, you need a few hundred labelled requests.

Thinking before acting#

Reasoning models write a chain of thought before the tool call, so fork 2 happens after a few hundred tokens of self-talk about the request. Ollama exposes this with the think parameter, and the reasoning comes back in message.thinking, separate from message.content.

The comparison here is the hardest menu (16 tools, terse descriptions) on qwen3:4b, the reasoning build of the same 4B model family:

qwen3:4b           think=True  tools=16 desc=terse acc=17/20 (85%)    473 out-tok/req
      miss x2: get_order_status -> track_shipment
      miss x1: refund_order -> get_order_status
qwen3:4b           think=False tools=16 desc=terse acc=17/20 (85%)    432 out-tok/req
      miss x2: get_order_status -> track_shipment
      miss x1: refund_order -> get_order_status

The think=False row is not the clean control it looks like. Ollama's docs say models that cannot turn thinking off fall back to their lowest level. This build kept reasoning anyway, and the reasoning moved into message.content as plain text ("Okay, the user said...") instead of disappearing, which is why it still produced 432 tokens per request. Check the output before you trust a thinking switch.

The cleaner comparison is against qwen3:4b-instruct from the main grid, a non-reasoning model of the same size: 16 of 20 at about 31 output tokens per request. Reasoning bought one more correct request, which is inside the noise for 20 cases, for roughly 15 times the output tokens. Two status requests still went to track_shipment with reasoning on. Reasoning cannot recover information that is not in the prompt. If "Shipment tool." is all the model knows, thinking harder about it does not tell it where status ends and tracking begins. Fixing the description did.

Reasoning earns its cost on multi-step decisions: which of several tools to call first, whether a result answers the question, what to do after an error. For a single routing pick, spend the effort on descriptions first.

Confidence: what logprobs can and cannot tell you#

A natural idea is to read the probability the model gave its chosen tool name and ask a human, or a bigger model, when it is low. Two practical problems show up fast.

The first is access. OpenAI's Chat Completions API has logprobs and top_logprobs (up to 20 alternatives per position). Ollama 0.40.16 returns logprobs for plain chat, but a request that combines logprobs with tools fails with {"error":"logprobs is not supported with tools + stream"}, even with "stream": false. Many agent stacks never see token probabilities at all.

The workaround is to turn the tool choice into a one-token answer. List the 16 tools plus a NONE option as lettered choices, ask for the letter only, set num_predict to 1, and read the first token's distribution:

out = _chat_lp(model, [{"role": "system", "content": prompt},
                       {"role": "user", "content": text}])
first = out["logprobs"][0]
tok, p = first["token"].strip(), math.exp(first["logprob"])

The second problem is calibration, and it is the bigger one. On the hardest menu (16 tools, terse descriptions) the letter router got 18 of 20 right. Every one of the 20 answers came back with probability at or above 0.9, including both wrong ones:

    wrong at p=1.000: When will order 8820 be delivered?               -> track_shipment (wanted get_order_status)
    wrong at p=1.000: Order 7007 was delivered but the box was empty.  -> get_return_policy (wanted refund_order)
qwen3:4b-instruct letter-router tools=16 desc=terse: p>=0.9: 18/20 right, p<0.9: 0/0 right

A threshold at 0.9 would have flagged nothing. The model's token probability measures how sure it is about the next token given its reading of the prompt. It says nothing about whether that reading matches your business rules. If you want a confidence gate, calibrate it on labelled data first: plot accuracy against probability on a few hundred real requests and pick the threshold from that plot. For a small instruction-tuned model, expect it to be overconfident.

Self-consistency: sample several times and vote#

Self-consistency (Wang et al., 2022) samples several reasoning paths at non-zero temperature and takes the majority answer. The paper applied it to chain-of-thought math; the same trick applies to a tool pick. Agreement between samples also gives you a confidence signal that does not need logprobs.

Here it is on the weakest setup, qwen3:1.7b with 16 terse tools, three samples at temperature 0.8 per request against one greedy (temperature 0) pick:

qwen3:1.7b tools=16 desc=terse: greedy 15/20, majority of 3 @T=0.8: 14/20
    unanimous votes: 15 requests, 12/15 right
    split     votes:  5 requests, 2/5 right

The vote did not beat greedy decoding (14 against 15). Three samples at 0.8 add noise faster than they add signal on a one-step classification, and voting tends to help more on long reasoning chains, where many paths can reach the same answer. Agreement was still useful as a flag. When all three samples agreed, the answer was right 80% of the time; when they split, 40%. Routing the five split requests to a bigger model or a clarifying question would have caught three of the six errors, at the cost of three times the calls. Whether that trade is worth it depends on what a wrong tool call costs you.

Put the decision in code when code knows the answer#

Look at which mistakes the model made across the runs. The cancel versus refund split and the status versus tracking split both depend on one fact: has the order shipped? The model cannot know that from the user's sentence. The user often does not say, and when they do ("it left the warehouse yesterday") they might be wrong. Your database knows.

So split the decision. Let the model classify what the customer wants, at a coarser grain where the classes are easy to tell apart, and let code choose the concrete action from state:

def resolve(intent: str, order_id: str) -> str:
    state = ORDERS.get(order_id)
    if state is None:
        return "ask_user: I can't find that order number. Can you check it?"
    if intent == "undo_order":
        if state in ("placed", "packed"):
            return f"cancel_order({order_id})"
        if state == "delivered":
            return f"refund_order({order_id})"
        return f"ask_user: order {order_id} is in transit; refuse delivery or wait to return it"
    if intent == "where_is_it":
        return f"track_shipment({order_id})" if state == "shipped" else f"get_order_status({order_id})"
    raise ValueError(f"unknown intent {intent}")
undo_order   4040 -> cancel_order(4040)
undo_order   7007 -> refund_order(7007)
undo_order   6650 -> ask_user: order 6650 is in transit; refuse delivery or wait to return it
where_is_it  6650 -> track_shipment(6650)
where_is_it  2288 -> get_order_status(2288)
undo_order   9999 -> ask_user: I can't find that order number. Can you check it?

The model now picks from two intents instead of four tools, and the hard part is a lookup that is right every time. It also handled a case the four-tool menu had no answer for: an order that is in transit can be neither cancelled nor refunded yet.

A rule of thumb for where the line goes:

The decision depends on Who should make it
Free-form meaning of the user's words The model
A fact in your database (order state, account tier, balance) Code, after a lookup
A policy written down somewhere (refund window, approval limits) Code, with the rule in one place
Whether an irreversible action may run (payment, delete, email to a customer) Code or a human, never the model alone
Which of two tools whose descriptions differ only by a precondition Merge them into one tool and branch in code

The last row is the one teams miss most often. If two tools only differ by a condition the model has to guess, merge them and let the function branch. Anthropic's advice to consolidate related operations points the same way.

Turn the 20 cases into a test#

The labelled set is cheap to keep. Run it in CI whenever someone edits a tool description, adds a tool, or changes the model, and fail the build if accuracy drops below the number you accept. Three practical notes from running it:

  • Keep the confusable pairs in the set. Easy cases pass on every configuration and tell you nothing.
  • Include "no tool" cases. A model that calls a tool for "Hello!" will run up cost and latency in production.
  • Record the full miss list, not only the score. A drop from 19 to 18 matters less than which request broke and what it went to.

The agent evaluation tutorial covers scoring whole trajectories once single-step choice is stable.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.