0Pricing
Claude Architect · บทเรียน

tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ

ให้โมเดลเลือก บังคับใช้เครื่องมือ หรือระบุเครื่องมือหนึ่งรายการตามชื่อ

tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ เป็นบทเรียน Claude Architect ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Claude Architect และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Claude Architect มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Who Decides: Model or You?

When you give Claude tools, one question shapes the whole interaction: who decides whether a tool runs?

The tool_choice field on your API request answers it. You can let the model decide, force it to call some tool, or pin one specific tool by name.

Getting this right is core to Tool Allocation: the wrong setting produces chatty text when you needed structured data, or a forced tool call when the model should have just answered.

The Three Modes

There are three values for tool_choice:

  • auto — the model freely picks: emit text, or call a tool.
  • any — the model must call some tool (its choice which), so the turn returns a tool call, never free text.
  • {"type":"tool","name":"X"} — force one specific named tool.

Each maps to a different intent: flexible reasoning, guaranteed structured output, or a hard-pinned action.

request = {
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": tools,
    "tool_choice": {"type": "auto"},  # or "any", or a named tool
    "messages": messages,
}

auto: Let the Model Choose

auto is the default mindset for agentic loops. The model inspects the conversation and decides on its own whether a tool is needed or a plain text reply suffices.

Use it when the path is open-ended: a support agent that might answer a question directly, or might need to look up an order first.

With auto, the stop reason tells you what happened: tool_use means run the tool and continue the loop; end_turn means the model answered in text and is done.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "auto"},
    messages=messages,
)

if resp.stop_reason == "tool_use":
    # run the requested tool(s), append results, loop again
    ...
elif resp.stop_reason == "end_turn":
    # model replied with text; turn complete
    ...

any: Guarantee a Tool Call

any forces the model to call some tool every turn — it cannot reply with free-form prose. It still chooses which tool, but a tool call is guaranteed.

This is the classic lever for guaranteed structured output: if your only tool is a schema-shaped record_result, then any means every response comes back as validated JSON arguments, never an unparseable paragraph.

classify_tool = {
    "name": "record_sentiment",
    "description": "Record the sentiment of a customer message.",
    "input_schema": {
        "type": "object",
        "properties": {
            "sentiment": {"type": "string",
                          "enum": ["positive", "neutral", "negative"]}
        },
        "required": ["sentiment"],
    },
}

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=512,
    tools=[classify_tool],
    tool_choice={"type": "any"},  # must call a tool -> structured output
    messages=messages,
)

Forced: Pin One Tool by Name

The most specific mode forces exactly one tool: {"type":"tool","name":"X"}. The model has no choice about which tool — only how to fill its arguments.

Use it when the action is already decided and you just need the model to extract the parameters. Example: you know this turn must produce an extraction record, so you pin extract_invoice and let Claude fill the fields.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[extract_invoice_tool],
    tool_choice={"type": "tool", "name": "extract_invoice"},
    messages=[{"role": "user", "content": invoice_text}],
)

# resp.content[0] is a tool_use block with the extracted fields
fields = resp.content[0].input

any vs forced: The Subtle Line

Both any and forced guarantee a tool call. The difference is choice:

  • any — model still selects which tool from the set. Good when several tools are valid and you want structured output but flexible routing.
  • forced {"type":"tool","name":"X"} — no routing decision at all; tool X runs.

Rule of thumb: if you've already made the decision in code, force the tool. If the model should still decide which structured action fits, use any.

Structured Output Is the Big Win

Pairing a JSON-Schema tool with any or a forced tool is how architects get reliable structured output. The schema eliminates syntax errors and enforces required fields — no fragile regex on prose.

One schema rule matters here: mark a field required only if it is always present. Never require a field that may be absent — the model will fabricate a value to satisfy the schema.

extract_invoice_tool = {
    "name": "extract_invoice",
    "description": "Extract structured fields from an invoice document.",
    "input_schema": {
        "type": "object",
        "properties": {
            "invoice_number": {"type": "string"},
            "total": {"type": "number"},
            "due_date": {"type": "string"},  # may be absent -> NOT required
        },
        # only fields that are ALWAYS present belong here
        "required": ["invoice_number", "total"],
    },
}

auto Keeps the Agentic Loop Alive

In a multi-step agent, auto is usually right because the loop is model-driven. You send the full history each turn, read stop_reason, run any requested tools, append results, and repeat — until the model emits end_turn.

If you forced a tool on every turn, the model could never signal completion with text, and your loop would have no natural stop. Reserve forcing for single, decided actions.

while True:
    resp = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        tools=tools,
        tool_choice={"type": "auto"},
        messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason == "tool_use":
        results = run_tools(resp.content)
        messages.append({"role": "user", "content": results})
        continue
    break  # end_turn -> terminate on stop_reason, never on text

Don't Confuse Choice with Enforcement

tool_choice controls whether a tool is called — it does not enforce business rules. Forcing process_refund does not guarantee the refund is allowed.

Critical guarantees (identity verified, refund under the policy cap) belong in deterministic preconditions and hooks, which are 100% reliable, not in tool_choice or prompt text (~90% probabilistic).

Think of tool_choice as routing, and hooks/preconditions as guardrails.

Description Still Drives Selection

Even with auto or any, the model's tool pick depends on tool descriptions, not names. A good description states purpose, return values, input formats with examples, edge cases, and applicability boundaries.

Overlapping or vague descriptions cause misrouting that no tool_choice value can fix. Keep about 4-5 well-scoped tools per agent; 18+ degrades selection reliability.

tool_choice sets the policy; descriptions make the routing accurate.

A Practical Decision Guide

Pick by intent:

  • auto — open-ended agent turns; the model may answer in text or act. Default for the agentic loop.
  • any — you need structured output but several tools could apply; model routes among them.
  • forced (name) — the action is already decided; you only need argument extraction (classification, single-shot extraction).

If you've made the decision in code, force it. If the model should reason about whether and which, use auto or any.

# Single-shot classification: decision already made -> force it
resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=256,
    tools=[record_sentiment_tool],
    tool_choice={"type": "tool", "name": "record_sentiment"},
    messages=[{"role": "user", "content": review_text}],
)
sentiment = resp.content[0].input["sentiment"]

Quick Check

Choose the best tool_choice for the scenario below.

Recap: Choose, Guarantee, or Pin

Key takeaways:

  • auto — model picks text or a tool; the default for model-driven agentic loops that must be able to signal end_turn.
  • any — must call some tool; the lever for guaranteed structured output with flexible routing.
  • {"type":"tool","name":"X"} — pins one tool; use when the action is decided and you only need argument extraction.
  • tool_choice is routing, not enforcement — put critical guarantees in hooks/preconditions.
  • Accurate selection still depends on strong tool descriptions and 4-5 scoped tools per agent.

คำถามที่พบบ่อย

บทเรียน “tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Claude Architect ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Claude Architect มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ”

ให้โมเดลเลือก บังคับใช้เครื่องมือ หรือระบุเครื่องมือหนึ่งรายการตามชื่อ คุณปฏิบัติ Claude Architect ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Claude Architect หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Claude Architect บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Claude Architect นี้ได้ไหม

ได้ บทเรียน Claude Architect ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ควรมีเครื่องมือกี่รายการต่อเอเจนต์
  2. tool_choice: อัตโนมัติ / ใดก็ได้ / บังคับ
  3. เครื่องมือในตัวของ Claude Code
  4. รูปแบบการสืบค้นแบบเพิ่มทีละขั้น
← กลับไปที่ Claude Architect