Howwise RSS
AI & Automation7 min read

LLM Not Calling the Right Tool: Diagnose and Fix It

Short answer

When an LLM is not calling the right tool, first classify the failure as no call, wrong tool, bad arguments or looping. Then fix descriptions, tighten schemas, cut tool count, validate in code and return errors the model can act on.

Key takeaways
  • Classify every failure as no call, wrong tool, bad arguments or looping before changing anything, using logged raw tool-call payloads and the exact tool list sent.
  • Most wrong-tool errors come from vague or overlapping descriptions; state when to use a tool and when not to, and merge near-duplicates.
  • Strict mode guarantees valid shape, not correct values, so validate arguments and semantics in your own code before executing.
  • Keep roughly 5 to 20 tools per agent and use routers, sub-agents or tool search beyond that.
  • Return tool errors as results with a fixable message, cap retries at 2 to 3, and enforce a hard iteration limit.

How do I diagnose why my LLM is not calling the right tool?

Do not edit prompts until you know which failure you have. The four failure modes have different fixes, and changing descriptions will not cure a loop or a schema problem.

Log three things for every failing run: the exact tool list and schemas sent in the request (after any framework filtering), the raw tool-call payload the model returned (name and arguments as a string), and the tool result you sent back. Frameworks such as LangChain and n8n often rewrite descriptions or drop tools, so what the model saw may differ from what you wrote.

SymptomLikely causeFirst fix
Model answers in text, no tool callDescription does not match the request; prompt never says tools are required; tool missing from requestAdd 'use when' lines, say in the system prompt when a lookup is mandatory, confirm the tool was actually sent
Calls a similar but wrong toolOverlapping tools, vague names such as search or get_dataRename verb-first, add 'use X instead for Y', merge duplicates
Right tool, wrong or invented argumentsFree-string params, missing enums, no examples, required info absent from the conversationEnums, formats, per-parameter examples, an ask_clarifying_question path
Malformed JSON or missing required fieldsNon-strict mode, weak or small model, huge schemaEnable strict mode, flatten schema, validate and retry
Same call repeated, or endless retriesError text unhelpful, result too large or ambiguous, no stop ruleActionable errors, trimmed results, max iterations, repeat-call detection
import json, logging
log = logging.getLogger("agent")

def log_turn(request_tools, response):
    log.info("tools_sent=%s", [t["name"] for t in request_tools])
    for block in response.content:           # Anthropic shape
        if block.type == "tool_use":
            log.info("tool_call name=%s input=%s", block.name, json.dumps(block.input))
    # OpenAI: response.choices[0].message.tool_calls[i].function.arguments (a JSON string)

How do I write tool descriptions the model picks correctly?

The model chooses tools almost entirely from the name, description and parameter descriptions. Treat them as a prompt, not a code comment.

A good description covers what the tool does, when to use it, when not to, input formats and units, and what it returns. Use distinct verb-first names: search_orders and get_order_by_id beat orders and order_lookup.

If two tools overlap, either merge them (one get_order with an optional filter) or add a contrast line in each: 'For a known order ID use get_order_by_id instead.' Contrast lines are the cheapest fix for wrong-tool picks.

// BEFORE
{"name": "orders", "description": "Order tool",
 "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}}

// AFTER
{"name": "search_orders",
 "description": "Find orders by customer email and optional status. Use when the user has no order ID. If you have an order ID, use get_order_by_id instead. Returns up to 10 orders as {id, status, total_usd, created_at}, newest first. Does not return line items.",
 "parameters": {"type": "object",
  "properties": {
   "customer_email": {"type": "string", "format": "email", "description": "Customer email, e.g. ana@example.com"},
   "status": {"type": "string", "enum": ["pending", "shipped", "delivered", "refunded"], "description": "Omit to include all statuses"}
  },
  "required": ["customer_email"],
  "additionalProperties": false}}

What makes a JSON schema produce valid arguments?

Every free string is a place for the model to improvise. Replace them with constraints wherever you can: enums for closed sets, format and pattern for IDs and dates, minimum and maximum for numbers, required for everything essential, and additionalProperties set to false.

Keep schemas flat. Deeply nested objects and optional-heavy schemas raise error rates, because the model must decide which of many fields to fill. Prefer two simple tools over one with ten optional parameters.

Put the unit and an example in each short parameter description, for example 'amount_cents: integer, 1999 means $19.99'. Ambiguity about units is a top source of silently wrong values.

Strict mode helps with shape. In OpenAI, set strict: true on the function (it requires additionalProperties false and all properties listed as required; model optional fields as a type that includes null). Anthropic offers strict tool use with a similar schema-conformance guarantee. Both use constrained decoding, so output is guaranteed to parse and match the schema. Neither guarantees the values are right: a perfectly shaped order_id can still be invented.

tool = {
  "type": "function",
  "function": {
    "name": "get_order_by_id",
    "strict": True,
    "description": "Fetch one order by ID. Use only when the user supplied an ID like ORD-12345.",
    "parameters": {
      "type": "object",
      "properties": {"order_id": {"type": "string", "description": "Format ORD-12345"}},
      "required": ["order_id"],
      "additionalProperties": False
    }
  }
}
Tip: Some constraints (pattern, min/max) may be unsupported or ignored in strict mode depending on provider and version, so enforce them again in your own validation.

How many tools can an LLM agent handle?

Selection accuracy falls as the tool list grows, because descriptions compete and consume context. A practical rule: aim for roughly 5 to 20 tools per agent, and treat 20 as the point to start restructuring. Weaker models degrade sooner.

Beyond that, choose one of three patterns. A router step picks a domain first (billing, orders, support) and passes only that domain's tools to the next call. Sub-agents each own a small toolset and the parent delegates. Dynamic retrieval embeds tool descriptions and loads only the top 5 to 10 matching tools per turn; Anthropic's tool search feature and LangGraph's tool-selection patterns follow this idea.

Whatever you pick, remove tools nobody uses and merge near-duplicates first. That is often enough.

When should I force tool choice with tool_choice?

Forcing removes the option of skipping a tool, which suits extraction, classification and a routing first step. Leave it on auto for open-ended conversation, where answering directly is sometimes correct.

GoalOpenAIAnthropicLangChain
Model decidestool_choice: "auto"tool_choice: {"type": "auto"}default
Must call some tooltool_choice: "required"{"type": "any"}bind_tools(tools, tool_choice="any")
Must call this tool{"type": "function", "function": {"name": "x"}}{"type": "tool", "name": "x"}bind_tools(tools, tool_choice="x")
No tools"none"{"type": "none"}omit tools
Warning: Forcing has costs. If no tool fits, the model will invent arguments to satisfy the call. With Anthropic, forced choice (any or a named tool) is not compatible with extended thinking and the response skips any natural-language preamble. Always include an escape tool such as ask_clarifying_question or none_of_these with a reason field.

How do I validate arguments and return errors the model can recover from?

Never execute raw model output. Parse it, validate the shape with Pydantic or Zod, then run semantic checks: the ID exists, the user has permission, the amount is within range. Return failures as tool results, not exceptions, so the model can correct itself.

Make the message say what was wrong and how to fix it. 'order_id must match ORD-12345; got 12345' works; a stack trace does not. On Anthropic set is_error: true on the tool_result block; on OpenAI send a normal tool message with the error text.

Allow 2 to 3 retries per tool call, then escalate to a human or a fallback. Enforce a hard cap of about 8 to 15 loop iterations per request, and stop when the same tool and arguments repeat twice.

For destructive actions (refunds, deletes, sends), require a confirmation gate in code, such as a pending-action token the user must approve. The model should propose, your code should authorize.

import json, hashlib
from pydantic import BaseModel, Field, ValidationError

class GetOrder(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d{5}$")

MAX_STEPS, MAX_RETRIES = 10, 3

def run_tool(name, raw_args, user, seen, fails):
    sig = hashlib.md5((name + raw_args).encode()).hexdigest()
    if sig in seen:
        return {"is_error": True, "content": "Duplicate call. Use the earlier result or ask the user."}
    seen.add(sig)
    try:
        args = GetOrder.model_validate_json(raw_args)
    except ValidationError as e:
        fails[name] = fails.get(name, 0) + 1
        if fails[name] > MAX_RETRIES:
            return {"is_error": True, "content": "Too many invalid calls. Stop and ask the user for the order ID."}
        msg = "; ".join(f"{'.'.join(map(str, x['loc']))}: {x['msg']}" for x in e.errors())
        return {"is_error": True, "content": f"Invalid arguments: {msg}. Example: ORD-12345"}
    order = db_get(args.order_id)
    if order is None:
        return {"is_error": True, "content": f"No order {args.order_id}. Ask the user to confirm the ID."}
    if order["owner"] != user.id:
        return {"is_error": True, "content": "Not permitted for this user."}
    # Trim output: return only needed fields
    return {"content": json.dumps({k: order[k] for k in ("id", "status", "total_usd")})}

What system prompt and test setup keep tool use dependable?

State plainly when tools are mandatory: 'For any question about order status, call a tool; never answer from memory.' Remove contradictions such as 'be brief' alongside 'always explain your tool choice', and avoid listing tool details in the prompt that differ from the schema.

Add one to three few-shot examples of correct calls, especially for the confusing pair of tools. Use low temperature (0 to 0.3) for tool-calling steps. Smaller models need more explicit descriptions and fewer tools than frontier ones, so retest when you switch models.

Keep tool outputs short and structured: return only fields the model needs, cap lists (for example 10 rows), and truncate long text with a note such as 'truncated, 240 more rows; refine the query'. Huge payloads push earlier instructions out of attention and get ignored.

Build an eval set of 30 to 50 prompts, each with the expected tool and key arguments, including negative cases where no tool should be called. Rerun it after every description, schema or model change, and track tool-selection accuracy and argument-validity rate. Without this, edits are guesses.

Common questions

Why does my agent skip tools and answer from its own knowledge?

Usually nothing tells it that the tool is required, or the description does not match how users phrase the request. Add a system prompt rule for those question types and a 'use when' line to the description. If it still skips, force tool_choice on that first step.

Does strict mode stop the model from inventing argument values?

No. Strict mode constrains the output to valid JSON matching your schema, but a value like an order ID can be well formed and still made up. Use enums where possible and check values against your database before acting.

How many retries should an agent get after a tool error?

Two to three per tool call is a sound default, since most self-corrections happen on the first retry. After that, escalate to a human or fall back to a simpler path, and keep a global iteration cap as a backstop.

Why does the agent call the same tool repeatedly?

Typically the result was an unclear error, an empty result with no guidance, or an output so large the model missed the answer. Return explicit next steps, trim results, and block identical repeat calls in code.

Do tool names really matter, or only descriptions?

Both matter because the name is the strongest single signal the model sees. Verb-first, specific names such as search_orders and get_order_by_id reduce confusion between similar tools.

Related topics:function callingllm agentstool useopenaianthropic