Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Why Your LLM Orders Fried Chicken When You're Dieting: The 'Should-Call' Problem in Function Calling

This article analyzes a real incident where an LLM incorrectly placed a food order despite user refusal, revealing that Function Calling's core challenge is deciding when not to call tools, and demonstrates how proper tool descriptions, intent classification, parameter validation, and safety layers prevent such failures.

The Incident: When "No" Becomes "Yes"

A side project "life assistant" integrated a food-delivery API with an LLM. During testing, a colleague typed: "I'm a bit hungry... but I'm dieting, forget it, let's not eat." The model immediately emitted tool_call: place_order with fried chicken and cola. The rider accepted the order. The team was stunned.

The author traced the execution and realized the fundamental issue: Function Calling's real difficulty isn't whether it can call , but whether it should call . The previous article built the bridge; this one installs the traffic light at the bridgehead.

Split the Decision into Two Distinct Tasks

The author initially thought "the model's judgment is weak" — too vague. Breaking down the faulty call revealed two completely different jobs:

Intent recognition (intent) : Does the user's utterance belong to the "order food" category? "A bit hungry" suggests yes; "dieting", "forget it", "don't eat" close the door. The model must first decide: take the tool path or reply naturally. This is a binary/multi-class classification — deciding which route .

Parameter extraction (slot filling) : Once intent says "call place_order ", all required slots must be filled: what, which shop, address, notes. Missing a required slot means asking the user, not inventing a value.

These two have different failure modes: intent error = "shouldn't call but did" (fried chicken ordered); parameter error = "should call but filled wrong" (wrong address). Mitigations differ, so they must be treated separately.

Three Decision Paths for Every User Turn

After this insight, the decision map became clear. Every user utterance faces three roads:

① Call (tool_call) : Intent clear, parameters complete → emit structured call.

② Clarify (clarify) : Want to call but missing required slots, or utterance self-contradictory → ask first, don't force.

③ Reply (reply) : No tool needed → natural-language response.

The accident forced a ③ utterance into ①. The traffic light was wired backwards.

Root Cause: The Description Was Two Characters

The place_order tool's description was simply "下单" ("place order"). That's all the model had to judge by. It saw "hungry", recalled a tool named "place order", and connected them. Negative signals — "dieting", "forget it", "don't eat" — were absent from the description, so the model had no reason to treat them as "don't call" signals.

The author rewrote the description as a proper prompt for the model, covering three points:

When to use (positive triggers)

When NOT to use (negative boundaries, negation signals, confusable scenarios) — most critical, most often omitted

What to do when uncertain (ask, don't assume)

A before/after comparison shows the difference:

Function-level description : Before: 下单; After:

Call ONLY when user explicitly says "order/help me order/get one". Do NOT call for idle chat, complaints about hunger, or negation/hesitation like "dieting/forget it/don't eat/reconsider/too expensive"; reply naturally instead.

Negative signals : Before: None; After: Listed explicitly: dieting / forget it / don't eat / reconsider / too expensive…

When uncertain : Before: Not specified; After:

If unsure or user contradicts self, ask for confirmation first; do not order directly.

Field-level description (item) : Before: item (empty); After: Dish name; if user hasn't specified, DO NOT invent — ask. High-risk warning : Before: None; After:

This action charges real money and is irreversible; requires user re-confirmation before trigger.

After rewriting, the same "hungry but dieting" utterance cleanly took path ③: "Let's hold off, tell me when you really want it" — zero tool calls.

Tool description isn't "what this tool does"; it's "when this tool should wake up and when it should stay asleep." Write the boundaries clearly and intent recognition is half solved. Write only an action name and you hand the judgment entirely to the model's free association.

Caution: overly long descriptions hurt when many tools compete for tokens. Rule: write boundaries, not fluff, not adjectives.

Parameter Extraction: Ask When It Should, Don't Invent

Intent correct, next gate is slot filling. The author cataloged common failure patterns:

Missing required parameter → model invents one. User: "Order my usual place." address required; model didn't ask, pulled last address from context — which was the office, but user is now home. Worse: item unspecified, model filled "random", API rejected.

Correct behavior: missing required or ambiguous → path ② clarify, ask user, fill missing slots then call.

A slot-governance table was built from production fixes:

Required present, types match → Model action: Direct tool_call; Guardrail layer: —

Missing required → Model action: Clarify, list missing; Guardrail layer: Pre-dispatch validation

Value not in enum → Model action: Return error, let model correct; Guardrail layer: Parameter validation

Self-contradiction in utterance → Model action: Ask for confirmation, don't guess; Guardrail layer: Intent layer

Has default (e.g., unit=c ) → Model action: Omittable, fill locally; Guardrail layer: Schema default User explicitly says "no/forget it" → Model action: Direct reply, skip parameter phase; Guardrail layer: Intent-layer negative signal

Parameter validation cannot rely on model self-discipline. Even with "don't invent" in description, models occasionally hallucinate. Dispatch must hard-validate: required complete? enum match? type correct? string length sane? This code layer is the final gate.

Compound Intent: Why Models Drop the Second Half

The offending sentence: "A bit hungry... but dieting, forget it, let's not eat." Front half "hungry" = positive trigger; back half "but/forget it/don't eat" = three reversal signals. Final intent clearly lands on "don't order." Yet the model latched onto the first "hungry" and fired place_order.

This isn't illiteracy; intent recognition inherently trips on compound sentences with negation, self-reversal, or contrast. Humans hear "what does the whole sentence ultimately want?"; models often "scan for trigger-like token → act."

Collected failure patterns:

"Hungry... but forget it"              Focus on second half: don't call
"Not that I don't want to eat, just too expensive"  Double negation + reason: don't call
"Let's order then... just kidding"     End reversal: don't call
"Show me options, don't order yet"     Explicit retrieval only: don't call place_order

Listing a few negative keywords in description blocks the first pattern but not the later twisted ones. Don't treat intent recognition as keyword matching; treat it as "judge final intent." Uncertain or self-contradictory → downgrade to clarify or reply (paths ②/③). Better to skip one action than to gamble.

The tool_choice Switch: Don't Force Every Turn

A hidden mindset trap: post-mortem revealed the team assumed "model didn't call tool = this turn did nothing = failure." Prompts were stuffed with "use tools whenever possible", "be proactive" — effectively jamming the traffic light to permanent green. A well-behaved assistant that says "let's hold off" was judged "not smart enough."

The API provides tool_choice to control this:

{"tool_choice": "auto"}
{"tool_choice": "none"}
{"tool_choice": "required"}
{"tool_choice":{"type": "function", "function": {"name": "place_order"}}}
auto

is default, model decides whether to call; none forces no call, pure text generation, suitable for "this turn is just chat or summary"; required forces a call (model still picks which); the last form locks to a specific function. required is generally avoided on high-risk tools because it shuts off the "should I?" judgment entirely.

For true stability, a two-step approach works: first round lets model emit only an intent label (no tools attached), after "call / don't call" is clear, decide whether to send a second request with tools. Extra round-trip and token cost (calculated in the next article), but "judge" and "act" are fully separated — worth it for high-risk scenarios.

Allowing the model "no tool this turn" is a capability, not a defect. An Agent that dares not skip a tool is about as broken as one that calls tools at random.

Where Slots Come From: Explicit, Memory, Defaults

Intent judged, slot filling still has a fuzzy layer: where do parameters actually come from? The author identifies three sources:

User explicit — "Order a salad, deliver home", item, address directly present.

Context or memory backfill — User says "order from my usual place", shop not in this utterance, must retrieve from conversation history or long-term memory.

Defaults — unit defaults to c, limit defaults to 20 locally, schema default handles it, don't make the model generate every time.

Most accidents happen when source 2 and 3 get mixed. Models love to treat "user didn't say" as "use default". address not given → silently fill last office address — but user is now home. Rule established: Required slots must come from "explicit" or "trusted memory"; if unavailable, ask, don't guess, and never substitute a default. Defaults only serve truly optional parameters.

Clarification etiquette: ask only the missing ones ("Which address?"), don't re-read the whole form; and clarification itself counts as a step , must be included in step budget, otherwise ambiguous users can loop "please clarify" until dawn.

Complete Run: fake_llm + Dispatch Multi-Turn Loop

Theory done, here's a runnable skeleton wiring all pieces: three decision branches, proper descriptions, dispatch with registry and validation, result backfill, error feedback, high-risk re-confirmation. fake_llm stubs the model (local Python, direct output); swap in real API tools= request for a working backbone.

import json
# ---------- ① Tool implementations ----------
def search_food(keyword: str) -> str:
    return f"[{keyword}] nearby 3 shops: A(salad) / B(fried chicken) / C(porridge)"
def place_order(item: str, address: str, shop: str = "default") -> str:
    return f"Ordered: {item} @ {shop} → {address} (real charge)"
REGISTRY = {"search_food": search_food, "place_order": place_order}
# ---------- ② Schema: description covers when to use / when not / what if unsure ----------
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "search_food",
            "description": "Call when user wants to find food or see shops; do NOT call for pure chat or when already decided to order.",
            "parameters": {
                "type": "object",
                "properties": {
                    "keyword": {"type": "string", "description": "Desired category or shop name"}
                },
                "required": ["keyword"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "place_order",
            "description": "Call ONLY when user explicitly says 'order/help me order/get one'. "
                "When 'dieting/forget it/don't eat/reconsider/too expensive' or other negation/hesitation appears, 【DO NOT CALL】, reply naturally. "
                "If item or address missing, ask first, don't guess. This action charges real money and is irreversible.",
            "parameters": {
                "type": "object",
                "properties": {
                    "item": {"type": "string", "description": "Dish name, must ask if not specified"},
                    "address": {"type": "string", "description": "Delivery address, must ask if not specified"},
                    "shop": {"type": "string", "enum": ["A", "B", "C"]}
                },
                "required": ["item", "address"]
            }
        }
    }
]
SCHEMA = {t["function"]["name"]: t["function"]["parameters"] for t in TOOLS}
# ---------- ③ Hard validation: code catches what model misses ----------
def validate(name: str, args: dict):
    if name not in REGISTRY:
        return False, f"Tool {name} not in registry, don't call randomly"
    spec = SCHEMA[name]
    for key in spec.get("required", []):
        if key not in args:
            return False, f"Missing required param {key}, please ask user"
    for key, rule in spec.get("properties", {}).items():
        if "enum" in rule and args.get(key) not in rule["enum"]:
            return False, f"{key} can only be {rule['enum']}"
    return True, ""
# ---------- ④ Stub brain: simulates three decisions by keywords ----------
def fake_llm(messages, tools, user_confirmed=False) -> dict:
    last = messages[-1]["content"]
    # If history has error feedback — admit mistake and fix params
    if any(m["role"] == "tool" and "[ERR]" in m["content"] for m in messages):
        return {"role": "assistant", "content": "Sorry, params wrong. Please tell me delivery address?", "tool_calls": None}
    # Negation/hesitation signals → direct reply, never call place_order
    if any(w in last for w in ["减肥", "算了", "别吃", "再想想", "太贵"]):
        return {"role": "assistant", "content": "Let's hold off, ping me when you really want it~", "tool_calls": None}
    # Search intent
    if "有啥" in last or "找" in last or "看看" in last:
        return {
            "role": "assistant",
            "content": None,
            "tool_calls": [{
                "id": "c1",
                "type": "function",
                "function": {
                    "name": "search_food",
                    "arguments": json.dumps({"keyword": "轻食"})
                }
            }]
        }
    # Explicit order intent, but check required first
    if "下单" in last or "帮我点" in last:
        if "地址" not in last and not user_confirmed:
            return {"role": "assistant", "content": "OK, which address?", "tool_calls": None}
        return {
            "role": "assistant",
            "content": None,
            "tool_calls": [{
                "id": "c2",
                "type": "function",
                "function": {
                    "name": "place_order",
                    "arguments": json.dumps({"item": "salad", "shop": "A"})
                }
            }]
        }
    return {"role": "assistant", "content": "I'm here, what can I do?", "tool_calls": None}
# ---------- ⑤ Dispatch + main loop (error feedback, re-confirm, max_steps) ----------
def run(user_text: str, max_steps: int = 6) -> str:
    messages = [{"role": "user", "content": user_text}]
    for step in range(1, max_steps + 1):
        reply = fake_llm(messages, TOOLS)
        messages.append(reply)
        if not reply.get("tool_calls"):  # ③ reply / ② clarify
            return reply["content"]
        for call in reply["tool_calls"]:
            name = call["function"]["name"]
            args = json.loads(call["function"]["arguments"])
            ok, err = validate(name, args)
            if not ok:  # validation failed → error feedback, let model self-correct
                messages.append({
                    "role": "tool",
                    "tool_call_id": call["id"],
                    "content": "[ERR] " + err
                })
                continue
            if name == "place_order":  # high-risk: re-confirm (HITL placeholder)
                print("  [Confirm] Real charge pending, human nodded")
            result = REGISTRY[name](**args)
            messages.append({
                "role": "tool",
                "tool_call_id": call["id"],
                "content": str(result)
            })
    return "Hit step limit, no convergence"
if __name__ == "__main__":
    for q in [
        "有点饿,但我在减肥,算了还是别吃了吧",
        "附近中午有啥轻食?",
        "帮我点一份"
    ]:
        print("User:", q)
        print("Assistant:", run(q), "
")

Output roughly:

User: 有点饿,但我在减肥,算了还是别吃了吧
Assistant: 那咱先忍忍,真馋了跟我说~
User: 附近中午有啥轻食?
Assistant: [轻食] 附近 3 家店:A(轻食) / B(炸鸡) / C(粥) ... (model closes after seeing result)
User: 帮我点一份
Assistant: 好,送到哪个地址?

Note the third turn: model deliberately omitted address (planted in stub), validate blocked it, fed [ERR] Missing required param address back as role=tool, model next turn corrected and asked for address — error not thrown to user, but fed back to model for self-correction .

Three Safety Nets, Consolidated

Compress the lessons from this incident into a checklist for any tool-enabled Agent:

Refusal / Should-not-call — Typical: chat, negation, pure knowledge. Mitigation: description writes clear "when not to use", model takes reply path. Layer: Intent + schema.

Wild call — Typical: tool not in registry, params missing/out-of-range, model hard-codes. Mitigation: dispatch hard validation → error feedback → model self-corrects. Layer: Code + feedback.

Irreversible chaos — Typical: order, delete data, transfer, send message. Mitigation: re-confirmation / Human-in-the-loop, or read-only accounts. Layer: Permission.

Infinite loop — Typical: endless clarify, endless retry, repeated param edits. Mitigation: max_steps cap + duplicate action detection. Layer: Loop.

Final heart-to-heart: Don't treat "model will judge" as excuse to skip validation. Model provides "intent", not "guarantee". Description is soft constraint, dispatch validation is hard constraint, both must exist. If we had added re-confirmation before place_order earlier, even a wrong intent judgment wouldn't have let that fried chicken reach the rider. High-risk actions, never let the model decide alone.

Closing

Back to that fried chicken order. Later we didn't delete the tool or swap the model. Just changed description from two characters "下单" to a full paragraph with negative signals, clarification rules, and risk warnings, and added a validation layer before dispatch. Same sentence "hungry but dieting, forget it" — model politely replied in natural language, never touched the API.

This shifted my understanding of Function Calling another notch. First article treated it as a bridge , thought "callable" meant victory; this time realized the bridge is only step one, the traffic light at the bridgehead — "should I cross?" — is what truly makes it an Agent . Tool description, intent discrimination, parameter validation, error feedback — together they turn a model from "given hands it waves wildly" into "knows when to keep hands in pockets".

Next article flips the camera underneath the bridge: you send one request, model emits tool_calls, local execution, backfill, second request… how messages silently grow, why a simple Q&A costs two inference rounds, and how parallel tool_calls work. That token bill stared me down for half a day before it made sense.

See you in the next one.

Previous in this stage: L3-2 Part 1 "From 0 to 1 Writing an Agent: Function Calling Is the Fulcrum" | Next: L3-2 Part 3 "Function Calling Under the Hood"
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion