Claude Architect · บทเรียน

รูปแบบต่อต้าน: จำกัดจำนวนรอบโดยพลการ

ขีดจำกัดเป็นตาข่ายนิรภัย ไม่ใช่กลไกหยุดการทำงาน

บทเรียน 4 จาก 413 ขั้นตอน

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

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

The Tempting Shortcut

You build an agentic loop. To feel safe, you write for i in range(5) and call it done. The agent stops after 5 turns.

This feels responsible. It is actually an anti-pattern. An arbitrary iteration cap as your primary stop mechanism cuts the model off mid-thought and produces incomplete work.

This lesson shows you the right mental model: a cap is a safety net, never the thing that decides when the task is finished.

How the Loop Actually Ends

The agentic loop is simple: send a request, inspect stop_reason, and react.

  • tool_use → run the tools, append results to history, loop again
  • end_turn → the model is finished; you stop

The model signals completion via stop_reason. Your job is to listen for that signal, not to guess a turn count in advance.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=messages,
    tools=tools,
)

if resp.stop_reason == "tool_use":
    # run tools, append results, loop again
    pass
elif resp.stop_reason == "end_turn":
    # task complete -- this is the real stop
    pass

Why a Cap Is the Wrong Primary Stop

A multi-step task does not have a fixed length. A code refactor might need 3 turns; a research task might legitimately need 14.

If your loop stops at i == 5:

  • The model may be mid tool-call, returning truncated or useless output.
  • You ship incomplete work and call it 'done'.
  • You are guessing the future instead of reacting to the model's actual stop_reason.

Decisions about when work is complete are model-driven. The cap knows nothing about the task.

The Even Worse Cousin

There is a related anti-pattern that often hides next to iteration caps: parsing the model's text for completion words like 'done', 'finished', or 'complete'.

This is fragile. The model might write 'I'm not done yet' and your if 'done' in text check would fire incorrectly. Worse, it might genuinely finish without ever saying the magic word.

Terminate on stop_reason, never by scanning prose. The protocol gives you a reliable signal; text does not.

# ANTI-PATTERN -- do NOT do this
if "done" in resp.content[0].text.lower():
    break  # fragile: text is not a control signal

# CORRECT -- react to the protocol
if resp.stop_reason == "end_turn":
    break

So What Is a Cap For?

Caps are not useless. They are a safety net for the case where the loop misbehaves — a tool that keeps failing, or a model that gets stuck cycling.

Think of it like a circuit breaker: it should almost never trip. If your cap is firing on normal, healthy tasks, it is set too low and it is doing the wrong job.

The primary stop is end_turn. The cap only catches runaway loops that would otherwise burn tokens forever.

The Correct Loop Shape

Here is the pattern that gets it right. The while True reacts to stop_reason; the cap sits outside as a guardrail with a generous limit.

Notice: a healthy task exits via end_turn. The cap only ever matters when something has gone wrong.

MAX_TURNS = 25  # generous safety net, not the plan

for turn in range(MAX_TURNS):
    resp = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        messages=messages,
        tools=tools,
    )
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "end_turn":
        break  # PRIMARY stop -- model says it's finished

    if resp.stop_reason == "tool_use":
        results = run_tools(resp.content)
        messages.append({"role": "user", "content": results})
else:
    # reached only if the net trips -- log and escalate
    log.warning("Hit MAX_TURNS -- investigate stuck loop")

When the Net Trips, Don't Pretend Success

The difference between a safety net and a stop mechanism shows up in what you do when the limit is hit.

A correct safety net treats hitting the cap as an error condition: log it, surface partial results, and escalate. It is a signal that something is stuck.

An anti-pattern cap silently returns whatever it has as if the task succeeded. That is silent error suppression — you hide a failure and ship broken output downstream.

Hard Code for Guarantees, Not for Decisions

A useful rule for architects: reserve hard code for guarantees; leave decisions to the model.

  • 'Is this task complete?' is a decision → the model answers it via end_turn.
  • 'Never exceed N turns under any circumstances' is a guarantee → deterministic code enforces it.

An iteration cap is legitimately in the guarantee category. The mistake is letting a guarantee impersonate a decision — using the cap to decide completeness instead of to bound worst-case cost.

Compare: Caps vs. Hooks

Don't confuse an iteration cap with a policy hook — both are deterministic code, but they guard different things.

  • A hook (e.g. PostToolUse or an outgoing-call hook) gives 100% deterministic enforcement of a business rule: block a refund over $500, regardless of what the model wants.
  • An iteration cap bounds loop cost / runaway behavior.

Use hooks when failure has financial, legal, or safety consequences. Use a cap to keep a loop from running forever. Neither one decides whether the task is logically complete.

# Deterministic GUARANTEE via a hook -- for business rules
# (settings.json)
{
  "hooks": {
    "PostToolUse": [
      { "matcher": "process_refund",
        "command": "./block_refund_over_500.sh" }
    ]
  }
}

Picking a Cap Value

If a cap is a net and not a plan, how high should it be? High enough that healthy tasks never touch it.

  • Estimate the worst-case legitimate turn count for your task, then leave generous headroom on top.
  • If you find yourself tuning the cap to make outputs 'feel complete', stop — you've turned it back into a stop mechanism.
  • Track how often it trips. Frequent trips mean a stuck tool, a bad prompt, or a cap set too low.

The Architect's Checklist

Before you ship an agentic loop, confirm:

  • The loop terminates on stop_reason == "end_turn" — the primary, model-driven stop.
  • You inspect tool_use and append tool results to the full message history every turn.
  • You never parse text for 'done' / 'finished' as a control signal.
  • The iteration cap is generous and exists only as a safety net.
  • Hitting the cap logs, surfaces partial results, and escalates — it never masquerades as success.

Quick Check

Apply the lesson to a real design decision.

Recap

Key takeaways:

  • Completion is the model's decision, signalled by stop_reason == "end_turn". That is your primary stop.
  • An iteration cap is a safety net, never the primary stopping mechanism. Set it generously so healthy tasks never hit it.
  • Never parse text for words like 'done' to decide termination.
  • When the cap does trip, treat it as an error: log, surface partial results, escalate — don't fake success.
  • Reserve hard code for guarantees, decisions for the model. A cap bounds worst-case cost; it does not judge whether the work is finished.
เริ่มต้นได้ฟรี

เรียนรู้ Python ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
26
บทเรียน
104

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

บทเรียน “รูปแบบต่อต้าน: จำกัดจำนวนรอบโดยพลการ” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบต่อต้าน: จำกัดจำนวนรอบโดยพลการ”

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

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

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

บทเรียน “รูปแบบต่อต้าน: จำกัดจำนวนรอบโดยพลการ” ใช้เวลานานแค่ไหน

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

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

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

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

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