프로그래밍 방식의 사전 조건
코드에서 신원을 확인하기 전까지 환불을 차단합니다
프로그래밍 방식의 사전 조건은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Refund That Should Never Fire
Picture a customer support agent with a process_refund tool. The model is smart, but it is also probabilistic. Roughly 9 times out of 10 it follows your instruction to verify the customer first. The tenth time, under an unusual prompt or a confusing conversation, it refunds an unverified stranger.
For a financial action, a 90% success rate is a liability, not a feature. This lesson is about closing that 10% gap with a programmatic precondition: a deterministic code-level gate that blocks the refund until identity is verified — every single time.
Prompts Persuade, Code Guarantees
There are two ways to enforce a rule in an agent:
- Prompt guidance — "Always verify the customer before refunding." This is ~90% reliable. The model decides whether to comply.
- Programmatic enforcement — a hook or code check that runs deterministically. This is 100% reliable. The model cannot override it.
The exam rule of thumb: when failure has financial, legal, or safety consequences, you do not trust a prompt. You reserve hard code for guarantees, and let the model make the open-ended decisions.
What 'Precondition' Actually Means
A programmatic precondition is a fact that must be established in verified state before a sensitive action is allowed to proceed. For our case: the refund is blocked until get_customer has returned a record with a verified identity.
This is not the model promising it checked. It is your code observing the actual tool results and refusing to run process_refund unless the verification fact is genuinely present. The guarantee comes from the data, not from the model's narration.
The Agentic Loop, Recapped
To gate a tool you must know where in the loop to intervene. Each turn: you send the full message history, inspect stop_reason, and if it is tool_use you run the requested tool, append the result, and loop again until end_turn.
The precondition lives in that "run the requested tool" step. When the model asks for process_refund, your code inspects accumulated state before executing it. The model proposes; your code disposes.
stop_reason = response.stop_reason # 'tool_use' | 'end_turn' | ...
for block in response.content:
if block.type == "tool_use":
# Intercept here, BEFORE executing the tool
result = dispatch_tool(block.name, block.input, state)
tool_results.append(result)
# Loop continues until stop_reason == 'end_turn'Tracking Verification State
The precondition needs a source of truth. Keep a small server-side state object that records what has actually been established this conversation — not what the model said it did.
When get_customer returns, your dispatcher reads the real payload and sets a flag only if the record is genuinely verified. This state is the gatekeeper's evidence.
state = {"customer_id": None, "identity_verified": False}
def handle_get_customer(tool_input, state):
record = lookup_customer(tool_input["query"])
if record and record["identity_status"] == "verified":
state["customer_id"] = record["id"]
state["identity_verified"] = True
return recordThe Gate Itself
Now wire the precondition. When the model requests process_refund, your code checks state["identity_verified"] first. If the fact is not established, you do not call the refund backend — you return a structured tool result telling the model why it was blocked and what to do next.
Crucially, you return this as a normal tool result the model can read and act on, not a thrown exception that crashes the loop.
def handle_process_refund(tool_input, state):
if not state["identity_verified"]:
return {
"isError": True,
"errorCategory": "permission",
"isRetryable": False,
"message": "Refund blocked: identity not verified. "
"Call get_customer and verify the ID first."
}
return refund_backend.process(tool_input) # only reachable when verifiedWhy a Structured Error Beats a Crash
A generic failure like "Operation failed" blocks recovery — the model cannot tell why it failed or what to do next. A structured error enables intelligent routing.
Include: isError: true, an errorCategory (transient / validation / business / permission), isRetryable, a human-readable message, and ideally the attempted action. Here the category is permission and isRetryable is false until the precondition is satisfied — so the model knows to go verify first rather than blindly retry the refund.
Hooks: Enforcement Outside the Tool
The dispatcher check above is one form of precondition. The exam also expects you to know hooks for the same job. An outgoing-call hook intercepts a tool invocation and can block a policy-violating action — for example, a refund over $500, or any refund on an unverified account.
Hooks are 100% deterministic; prompts are ~90% probabilistic. A PostToolUse hook can also intercept a tool result before the model ever sees it. Either way, the guarantee is enforced in code the model cannot talk its way around.
Layering the Two Conditions
Real policy is often compound: block the refund unless identity is verified AND the amount is within the allowed threshold. Both checks are deterministic preconditions; neither belongs in a prompt.
The verification check guards who; the threshold check guards how much. A violation of either returns a structured, actionable result — escalate to a human for the threshold case, or send the model back to verify for the identity case.
def handle_process_refund(tool_input, state):
if not state["identity_verified"]:
return blocked("permission", "Verify identity via get_customer first.")
if tool_input["amount"] > 500:
return blocked("business",
"Amount exceeds $500 policy limit. Use escalate_to_human.")
return refund_backend.process(tool_input)Don't Confuse This With Iteration Caps
A precondition is a correctness guarantee — it ensures a specific fact holds before a specific action. Do not confuse it with the loop's safety net.
- You still terminate on
stop_reason, never by parsing text for words like "done" or "verified". - Iteration caps are a safety net against runaway loops, never the primary stop mechanism — and never the way you enforce business policy.
The precondition is surgical: it gates one action on one verified fact, deterministically, while the model keeps driving the conversation.
Real-Time Means No Batch API
One more architectural trap. A verification precondition is a blocking, time-sensitive check — the refund cannot proceed until it resolves in the live conversation.
That rules out the Message Batches API: it is 50% cheaper but has a window of up to 24 hours, no latency SLA, and no multi-turn tool calling. Batch is for overnight audits and reports, never for an inline guard a customer is waiting on. Run preconditions synchronously in the agentic loop.
Quick Check: Enforcing the Refund Rule
A solutions architect must guarantee that process_refund never executes for a customer whose identity has not been verified by get_customer. The action carries financial and legal risk. Which design meets the requirement?
Recap: Gate It in Code
Key takeaways for programmatic preconditions:
- Money, legal, safety → deterministic. Prompts are ~90%; hooks and code preconditions are 100%.
- Gate on verified facts, not narration. Track real state from
get_customer; blockprocess_refunduntilidentity_verifiedis true. - Intercept in the loop. Check before executing the tool the model requested; use a hook to block policy violations like refunds over $500.
- Fail with structure. Return
isError,errorCategory,isRetryable, and a clear message so the model can recover. - Stay synchronous. Terminate on
stop_reason, never iteration caps or text parsing — and never the Batch API for blocking checks.
자주 묻는 질문
“프로그래밍 방식의 사전 조건” 강의는 무료인가요?
네 — “프로그래밍 방식의 사전 조건” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
“프로그래밍 방식의 사전 조건”에서 뭘 배우나요?
코드에서 신원을 확인하기 전까지 환불을 차단합니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Claude Architect을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“프로그래밍 방식의 사전 조건” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- PostToolUse 및 발신 호출 훅
- 결정적 강제 적용과 프롬프트
- 프로그래밍 방식의 사전 조건
- 구조화된 인계 프로토콜