0Pricing
Claude Architect · 강의

루프 및 오케스트레이션 안티 패턴

텍스트 분석에 의한 종료, 임의의 제한 및 지나치게 좁은 분해를 다룹니다

루프 및 오케스트레이션 안티 패턴은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Loops Go Wrong

The agentic loop is deceptively simple: send a request, inspect the stop_reason, run any tools, append results to history, repeat until end_turn. Yet this is exactly where production agents fail most often.

This lesson dissects three orchestration anti-patterns that recur across the Claude Certified Architect exam:

  • Text-parsing termination — stopping when the reply contains a word like "done".
  • Arbitrary iteration caps used as the primary stop mechanism.
  • Over-narrow decomposition — slicing work so finely that quality and coordination collapse.

Each looks reasonable in a demo and breaks under real traffic. Let's make the correct patterns reflexive.

The Loop Contract

Claude keeps no server-side state. Every turn you resend the full messages history. The model signals control flow through stop_reason, not through prose.

The four stop reasons you orchestrate against:

  • end_turn — the task is complete; exit the loop.
  • tool_use — run the requested tools, append results, continue.
  • max_tokens — output was truncated.
  • stop_sequence — a configured sequence was emitted.

The contract is structural. Branch on the field the API guarantees, never on the text the model happens to produce.

import anthropic

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Audit the repo and summarize risks."}]

while True:
    resp = client.messages.create(
        model="claude-opus-4-1",
        max_tokens=2048,
        tools=tools,
        messages=messages,
    )
    if resp.stop_reason == "end_turn":
        break
    # ... handle tool_use, append results, loop ...

Anti-Pattern 1: Parsing Text for "Done"

The most common termination bug: scanning the assistant's text for a completion signal.

This fails in ways that are hard to debug:

  • The model writes "I'm not done yet" — your substring match on "done" fires anyway and exits early.
  • The model finishes but phrases it as "that completes the analysis" — your check never matches and the loop spins.
  • A tool result quotes the word "finished" — false termination.

Natural language is probabilistic; control flow must be deterministic. The stop_reason field exists precisely so you never have to guess from prose.

# ANTI-PATTERN — do NOT do this
text = resp.content[0].text.lower()
if "done" in text or "finished" in text:
    break  # brittle: false positives + missed completions

The Correct Termination

Terminate on stop_reason == "end_turn". When it is tool_use, execute every requested tool, append the results as a tool_result message, and continue. The model decides when it is finished by emitting end_turn — you simply honor that signal.

This keeps the decision model-driven where it belongs. The model has the full context to judge completion; your harness only routes the structured signal.

while True:
    resp = client.messages.create(
        model="claude-opus-4-1", max_tokens=2048,
        tools=tools, messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "end_turn":
        break

    if resp.stop_reason == "tool_use":
        results = run_requested_tools(resp.content)
        messages.append({"role": "user", "content": results})

Anti-Pattern 2: The Cap as Primary Stop

The next trap is treating an iteration cap as the way you stop. You write for _ in range(5) and call it orchestration.

The problem is intent. A cap that is your primary stop means:

  • Tasks that legitimately need 7 tool calls are silently truncated mid-investigation.
  • Tasks that finish in 2 calls still appear "capped" in your telemetry, hiding real behavior.
  • You have no signal distinguishing completed from ran out of budget.

The model's end_turn must remain the decision point. The cap is something else entirely.

# ANTI-PATTERN — cap IS the stop mechanism
for _ in range(5):
    resp = client.messages.create(...)
    run_tools(resp)
# loop exits by exhaustion, not because the task is done

Caps as a Safety Net

Iteration caps are valid — but only as a safety net against runaway loops, never as the primary termination logic. The reflex from the fact sheet: decisions are model-driven; reserve hard code for guarantees.

So the cap sits around the model-driven loop. end_turn is how you normally exit. The cap only fires in the pathological case, and when it does you treat that as an error condition worth logging and escalating — not a normal exit.

MAX_ITERS = 25  # safety net, not the plan
for i in range(MAX_ITERS):
    resp = client.messages.create(...)
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason == "end_turn":
        break          # normal, model-driven exit
    handle_tools(resp)
else:
    log.error("hit safety cap without end_turn")
    escalate(messages)  # treat as anomaly, not success

When Guarantees DO Belong in Code

"Model-driven" does not mean "never use hard code." Reserve deterministic code for genuine guarantees — places where a probabilistic decision is unacceptable.

Examples from the exam's anti-pattern catalog:

  • A hook blocking a refund over $500 — deterministic enforcement, ~100% reliable, versus a prompt at ~90%.
  • A programmatic precondition: block process_refund until get_customer has returned a verified ID.

The line is clear: route open-ended decisions to the model; encode policy and safety in code. Caps belong to the latter only as a backstop.

Anti-Pattern 3: Over-Narrow Decomposition

Multi-agent systems use a hub-and-spoke shape: a coordinator decomposes, delegates, aggregates, routes, and handles errors. The orchestration failure here is slicing the work too finely.

Over-narrow decomposition spawns a subagent per trivial step. The costs compound:

  • Coordination overhead dwarfs the actual work.
  • Each subagent loses context — subagents do not inherit the coordinator's conversation history.
  • Cross-cutting judgment that needs a whole-picture view gets fragmented across isolated agents.

Decompose by meaningful unit of work, not by individual operation.

Context Must Be Passed Explicitly

Because subagents start with a blank history, the coordinator must pass all needed context explicitly in each subagent prompt. Over-narrow decomposition makes this worse: more agents means more boundaries where context is dropped and more prompts to keep in sync.

Note also that multiple Task calls in a single response run in parallel, and the coordinator's allowedTools must include "Task". Parallelism is a reason to decompose at the right granularity — independent, self-contained units — not to shatter one coherent task into fragments that each need the same shared context re-injected.

AgentDefinition(
    name="file_reviewer",
    description="Reviews a single source file for local correctness issues.",
    system_prompt=(
        "You review ONE file in isolation.\n"
        # subagent has NO coordinator history — pass everything it needs:
        "Project conventions: {conventions}\n"
        "File under review: {file_path}\n"
        "Known constraints: {constraints}\n"
    ),
    allowed_tools=["Read", "Grep"],  # least privilege
)

The Right Granularity: Code Review

Code review is the canonical example of correct decomposition — and it shows the difference from over-narrow slicing.

The right structure is a per-file local pass followed by a separate cross-file integration pass. A single-pass multi-file review dilutes attention; one agent juggling everything misses both local bugs and integration issues.

The wrong over-narrow extreme is the opposite error: a subagent per function or per line, none of which can see enough to judge correctness. Decompose into passes that each have a coherent scope — file-level, then integration-level — not into fragments below the level at which judgment is possible.

Fixed vs Adaptive Decomposition

One more lever prevents both over- and under-decomposition: match the strategy to the problem shape.

  • Fixed pipelines / prompt chaining for known, sequential steps — extract, then validate, then format.
  • Adaptive decomposition for open-ended investigations where the next step depends on what was just found.

Forcing a fixed pipeline onto an open-ended research task pushes you toward brittle over-narrow stages; using adaptive decomposition for a deterministic three-step transform adds needless coordination. Choose deliberately, and let the model drive the steps it should own while code owns the steps that must be guaranteed.

Quick Check: Loop Termination

An architect's agent loop calls tools across several turns. Pick the orchestration that matches the certification's reliability guidance.

Recap: Orchestrate on Signals, Decompose with Intent

Three reflexes to carry into the exam and into production:

  • Terminate on stop_reason. Exit on end_turn; never parse text for "done". The model owns the completion decision; you route its structured signal.
  • Caps are a safety net, not a plan. Keep a generous cap to catch runaways, treat hitting it as an anomaly, and reserve hard code for real guarantees (hooks, preconditions).
  • Decompose at the right grain. Hub-and-spoke with coherent units — per-file then cross-file passes, not a subagent per line. Pass all context explicitly, and match fixed vs adaptive strategy to the problem.

Get these three right and most loop-and-orchestration distractors on the exam fall away.

자주 묻는 질문

“루프 및 오케스트레이션 안티 패턴” 강의는 무료인가요?

네 — “루프 및 오케스트레이션 안티 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

“루프 및 오케스트레이션 안티 패턴”에서 뭘 배우나요?

텍스트 분석에 의한 종료, 임의의 제한 및 지나치게 좁은 분해를 다룹니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Claude Architect을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“루프 및 오케스트레이션 안티 패턴” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 루프 및 오케스트레이션 안티 패턴
  2. 도구 및 오류 안티 패턴
  3. 프롬프트 및 검토 안티 패턴
  4. 에스컬레이션 및 지표 안티 패턴
← Claude Architect(으)로 돌아가기