에이전트 도구 계약과 구조화된 오류 (파트 2)
A contract you can reason about
A guarded tool call
Errors are data. The loop decides what to do with them.
- 01
call dictname + args - 02
validate against schemareject before any side effect - 03
retry? classifiedtransient only, idempotent - 04
execute onceguarded, logged - 05
ToolResult(ok/error)typed and classified - 06
append to historyLLM sees the error
파트 1은 정상적으로 종료되는 루프와, 모델이 말하는 모든 것을 신뢰하는 도구 레지스트리로 끝났습니다. 바로 이 신뢰가 다음 버그입니다. 파트 1의 _search 첫 줄은 query = str(args.get("query", "")).lower() 이었습니다. 모델이 {"q": "agent loop"} 를 {"query": "agent loop"} 대신 보내도 아무것도 raise되지 않습니다. 쿼리는 빈 문자열이 되고, 코퍼스 조회는 아무것도 매치하지 못하며, 도구는 ["no matches"] 를 반환합니다. 모델은 이를 코퍼스가 비어 있다는 증거로 읽고 그에 맞춰 답합니다. 오류도, 로그 한 줄도 없고, 진짜 빈 결과와 JSON 키의 오타를 구분할 방법도 없습니다.
저는 이 글을 쓰면서 정확히 이 비교를 실행했습니다. 실제 모델이 실제로 만들어내는 30개의 잘못된 인자 페이로드 — 이름이 바뀐 키, 대문자로 된 키, 정수가 있어야 할 자리의 문자열, 문자열 대신 들어간 리스트, null — 을 파트 1의 도구와 이 글에서 만드는 버전에 각각 통과시켰습니다. 파트 1은 30개 중 12개 에 대해 그럴듯해 보이는 빈 결과를 만들었습니다. 계약 버전은 조용한 결과를 0 건 만들었습니다. 27건은 스키마 힌트를 실은 명시적이고 분류된 오류가 되었고, 유효한 3개 페이로드는 성공했습니다. 같은 모델, 같은 도구인데 실패의 가시성이 완전히 다릅니다.
이 파트의 주제는 실패를 가시적으로 만들고 회복 가능하게 하는 것입니다. 모델에게 조심하라고 프롬프트하는 방식이 아니라 — 선언된 계약을 만족하지 않는 호출의 실행을 거부하고, 모든 실패를 루프가 다룰 수 있는 타입 있는 값으로 바꾸는 방식으로.
만들 것
파트 1의 도구 레지스트리를 감싸는 contracts.py 모듈에 4가지를 추가합니다:
validate_args(schema, args)— 불리언 대신{path, message}오류 목록을 반환하는 JSON Schema 부분집합 검증기. 어떤 필드가 틀렸는지 모델에게 정확히 알려줄 수 있습니다.ErrorCode+ToolError— 여덟 개의 실패 클래스로 이루어진 닫힌 체계. 각각에는 질문이 하나 붙습니다. 두 번째 시도가 성공할 가능성이 있는가?RetryPolicy+IdempotencyStore— 재시도 가능한 코드에만 적용되는 지터를 얹은 유한 지수 백오프, 그리고 인자 해시 키로 재시도된 부수 효과가 두 번 실행될 수 없게 만듭니다.ToolExecutor—Tool.run의 유일한 호출자. 검증하고, 중복을 걸러내고, 타임아웃 안에서 실행하고, 분류하고, 재시도합니다.
AgentLoop 는 파트 1의 모양을 유지합니다. run 메서드의 변경은 약 여섯 줄입니다: 직접 호출하던 tool.run(args) 가 self.executor.execute(name, args) 로 바뀌고, 트레이스가 시도와 오류 코드를 기록합니다. 나머지 전부 — Message, ToolResult, ScriptedLLM, 결정 구조들 — 는 호환성을 유지합니다. 파트 3과 파트 4는 이 파일을 교체하지 않고 확장하기 때문입니다.
선행 조건
- Python 3.10 이상. 표준 라이브러리만 사용합니다:
concurrent.futures,hashlib,json,random,time,urllib. - 파트 1의 파일, 혹은 최소한 그 네 가지 타입:
Message,ToolResult,Tool,AgentLoop. 건너뛰었다면 아래 코드 블록이 호환되는 형태로 재정의합니다. - 터미널. 여기의 모든 테스트는 오프라인에서 1초 안에 실행됩니다.
의도적으로 뺀 것이 하나 있습니다. validate_args 는 JSON Schema의 부분집합만 지원합니다 — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum. 이 부분집합은 실제 도구 스키마가 실무에서 쓰는 범위를 커버합니다. $ref, oneOf, pattern 은 지원하지 않으며, 지원하는 척하는 것이 솔직하게 말하는 것보다 더 나쁩니다. 필요하다면 이 지점이 jsonschema 나 Pydantic으로 갈아타는 타이밍입니다. 주변의 실행기 설계는 바뀌지 않습니다.
계약이 실제로 깨지는 지점
세 가지 실패 클래스가 모델과 도구 사이에서 잘못되는 거의 모든 것을 차지하며, 서로 다른 처리가 필요합니다.
잘못된 키, 그럴듯한 의도. {"q": ...} 가 query 를 요구하는 스키마에 들어옵니다. Python의 dict.get 기본값이 조용히 "" 를 채웁니다. 이것이 가장 위험한 경우입니다. 도구는 성공하는데 답은 틀리기 때문입니다.
올바른 키, 틀린 타입. {"limit": "3"} 이 [v for ...][:limit] 에 도달해 TypeError: slice indices must be integers 를 raise합니다. 파트 1에서는 이 예외를 AgentLoop.run 이 잡아 ToolResult(ok=False) 로 바꿉니다 — 하지만 메시지는 TypeError: slice indices must be integers or None or have an __index__ method 이고, 어떤 인자를 고쳐야 하는지는 모델에게 아무것도 알려주지 않습니다.
올바른 호출, 일시적 실패. 검색 백엔드의 429, 소켓 타임아웃, 인덱스의 503. 재시도는 옳습니다. 하지만 응답이 유실됐다는 이유만으로 save_note 호출을 재시도하면 쓰기가 중복됩니다.
제가 사용한 프로브입니다. 30 중 12라는 숫자를 그대로 믿지 말고 직접 재현할 수 있습니다:
import jsonfrom contracts import ToolExecutor, ToolResult, build_tools
def search_v1(args: dict) -> ToolResult: query = str(args.get("query", "")).lower() corpus = { "agent loop": "An agent loop repeats: observe, decide, act, observe.", "token budget": "Context windows are finite; budget them explicitly.", "stop condition": "A step limit is a stop condition, not a strategy.", "retry": "Retry only failures that are transient; never retry a 400.", } hits = [v for key, v in corpus.items() if key in query] return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
PAYLOADS = [ {"query": "agent loop"}, {"q": "agent loop"}, {"Query": "agent loop"}, {"query": "agent loop", "top_k": 3}, {"query": ["agent loop"]}, {"query": "agent loop", "limit": "3"}, {"query": "agent loop", "limit": 0}, {"query": ""}, {"query": "agent loop", "limit": True}, {"query": None},]
def probe() -> None: cases = (PAYLOADS * 3)[:30] executor = ToolExecutor({t.name: t for t in build_tools()}, sleep=lambda d: None) silent_v1 = silent_v2 = explicit_v2 = 0 for args in cases: old = search_v1(args) new = executor.execute("search", args) if old.ok and json.loads(old.data) == ["no matches"]: silent_v1 += 1 if not new.ok: explicit_v2 += 1 elif json.loads(new.data) == ["no matches"]: silent_v2 += 1 print("n=%d v1_silent=%d v2_explicit=%d v2_silent=%d" % (len(cases), silent_v1, explicit_v2, silent_v2))
if __name__ == "__main__": probe()출력: n=30 v1_silent=12 v2_explicit=27 v2_silent=0. 남은 세 번의 성공은 유효한 페이로드 {"query": "agent loop"} 를 세 번 반복한 것입니다. 조용한 오답은 오류보다 나쁩니다. 올바른 빈 결과와 구분이 불가능하고, 최종 답변으로 아무 검증 없이 전파되기 때문입니다.
추론 가능한 검증기
검증기는 불리언이 아니라 구조화된 오류를 반환합니다. 오류 텍스트가 곧 모델이 다음 턴에 읽을 수정 지시이기 때문입니다. 불리언은 메시지를 창작하게 만들고, 경로와 이유가 있으면 기계적으로 생성할 수 있습니다.
from __future__ import annotationsfrom dataclasses import dataclass, replacefrom typing import Any, Callableimport json
@dataclassclass Message: role: str # "system" | "user" | "assistant" | "tool" content: str name: str | None = None # tool name, required when role == "tool"
@dataclassclass ToolResult: ok: bool data: str error: str | None = None error_code: str | None = None attempts: int = 1 from_cache: bool = False
def to_message(self, name: str) -> Message: if self.ok: payload = self.data else: payload = "ERROR[%s]: %s" % (self.error_code or "unknown", self.error or "") return Message(role="tool", content=payload, name=name)
def validate_args(schema: dict, args: Any) -> list[dict]: """Validate a JSON Schema subset. Returns [] or a list of {path, message}.""" errors: list[dict] = []
def walk(sch: dict, value: Any, path: str) -> None: t = sch.get("type") if t == "object": if not isinstance(value, dict): errors.append({"path": path or "/", "message": "expected object"}) return props = sch.get("properties", {}) for req in sch.get("required", []): if req not in value: errors.append({"path": path + "/" + req, "message": "missing required field"}) if sch.get("additionalProperties") is False: for key in value: if key not in props: errors.append({"path": path + "/" + str(key), "message": "unexpected field"}) for key, sub in props.items(): if key in value: walk(sub, value[key], path + "/" + key) return if t == "array": if not isinstance(value, list): errors.append({"path": path, "message": "expected array"}) return item_schema = sch.get("items", {}) for i, item in enumerate(value): walk(item_schema, item, path + "/" + str(i)) return if t == "string": if not isinstance(value, str): errors.append({"path": path, "message": "expected string"}) return elif t == "integer": if isinstance(value, bool) or not isinstance(value, int): errors.append({"path": path, "message": "expected integer"}) return elif t == "number": if isinstance(value, bool) or not isinstance(value, (int, float)): errors.append({"path": path, "message": "expected number"}) return elif t == "boolean": if not isinstance(value, bool): errors.append({"path": path, "message": "expected boolean"}) return if "enum" in sch and value not in sch["enum"]: errors.append({"path": path, "message": "must be one of " + repr(sch["enum"])}) if "minLength" in sch and isinstance(value, str) and len(value) < sch["minLength"]: errors.append({"path": path, "message": "shorter than minLength %d" % sch["minLength"]}) if "maxLength" in sch and isinstance(value, str) and len(value) > sch["maxLength"]: errors.append({"path": path, "message": "longer than maxLength %d" % sch["maxLength"]}) if "minimum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value < sch["minimum"]: errors.append({"path": path, "message": "below minimum %s" % sch["minimum"]}) if "maximum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value > sch["maximum"]: errors.append({"path": path, "message": "above maximum %s" % sch["maximum"]})
walk(schema, args, "") return errors그 코드에는 장식이 아닌 디테일이 두 개 있습니다. 첫째, isinstance(value, bool) 가드가 integer 와 number 분기에 걸려 있다는 것: Python에서 True 는 값 1인 int 이므로, 이 가드가 없으면 {"limit": true} 가 정수 검사를 통과해 limit=1 이 되어 버립니다. 둘째, 검증기는 첫 오류에서 raise하지 않습니다 — 모든 오류를 모은 뒤 처음 세 개를 보고합니다. 틀린 필드를 두 개 보낸 모델은 두 번의 왕복이 아니라 한 번의 왕복에서 둘 다 알아야 합니다.
오류는 수정 대상과 함께 도착할 때만 쓸모가 있습니다. 그것을 채워주는 것이 describe_schema 입니다. 같은 스키마 객체에서 파생된 컴팩트한 시그니처를 제공합니다.
def describe_schema(schema: dict) -> str: """Compact, model-readable signature: query:string!, limit:integer.""" parts = [] required = set(schema.get("required", [])) for name, sub in schema.get("properties", {}).items(): piece = name + ":" + str(sub.get("type", "any")) if name in required: piece += "!" if "enum" in sub: piece += "=" + "|".join(str(v) for v in sub["enum"]) parts.append(piece) return "{" + ", ".join(parts) + "}"
def format_errors(errors: list[dict], limit: int = 3) -> str: shown = ["%s %s" % (e["path"] or "/", e["message"]) for e in errors[:limit]] if len(errors) > limit: shown.append("(+%d more)" % (len(errors) - limit)) return "; ".join(shown){"q": ...} 케이스에서 얻는 도구 메시지는 ERROR[invalid_arguments]: /q unexpected field; /query missing required field. expected {query:string!, limit:integer} 입니다. expected 뒷부분은 스키마에서 생성되므로, 스키마를 수정해도 드리프트하지 않습니다. 이 성질이 표현보다 중요합니다. 손으로 쓴 수정 힌트는 낡아가지만, 생성된 것은 그렇지 않습니다.
여기에 드는 비용도 보세요. additionalProperties: False 는 엄격합니다. 무해한 메타데이터 필드를 추가하는 제공자조차 검증에 실패합니다. 그게 요점입니다. 예상치 못한 필드는 모델이 파라미터를 환각했거나 스키마가 코드보다 뒤처졌다는 뜻이고, 어느 쪽이든 **kwargs 로 어깨를 으쓱하는 것보다 시끄럽게 실패할 자격이 있습니다.
문자열 대신 분류된 오류
문자열 오류는 로그에 남길 수만 있습니다. 분류된 오류는 판단에 쓸 수 있습니다. 아래 체계는 의도적으로 작게 만들었습니다. 여덟 개의 코드가 도구를 쓰는 에이전트에서 제가 실제로 본 실패를 커버하며, 각각이 하나의 조치에 대응합니다.
from enum import Enum
class ErrorCode(str, Enum): INVALID_ARGUMENTS = "invalid_arguments" UNKNOWN_TOOL = "unknown_tool" NOT_FOUND = "not_found" RATE_LIMITED = "rate_limited" TIMEOUT = "timeout" UPSTREAM = "upstream_error" PERMISSION = "permission_denied" INTERNAL = "internal_error"
class ToolError(Exception): """Raise inside a tool to report a classified, non-crashing failure."""
def __init__(self, message: str, code: ErrorCode = ErrorCode.INTERNAL, retry_after: float | None = None): super().__init__(message) self.code = code self.retry_after = retry_after분류 규칙은 한 가지 질문입니다. 아무것도 바꾸지 않은 완전히 동일한 두 번째 시도는 성공할 가능성이 충분한가? rate_limited, timeout, upstream_error 는 예입니다. invalid_arguments, unknown_tool, not_found, permission_denied, internal_error 는 아니오입니다 — 앞의 세 개는 다른 호출이 필요하고, 뒤의 두 개는 사람이 필요합니다. 이 질문이 모든 것을 재시도하지 않는 이유의 전부입니다. 낭비되는 재시도 한 번마다 max_steps 한 스텝이 소모되고, 도구 호출당 3회 시도라면 5개 도구 예산은 2개로 붕괴합니다.
Tool 에 계약 필드 세 개가 추가되고, description은 파트 1과 달리 이제 하중을 지탱하는 역할을 합니다:
@dataclassclass Tool: name: str description: str parameters: dict[str, Any] # JSON Schema _fn: Callable[[dict], ToolResult] side_effect: bool = False # True -> executed at most once per idempotency key timeout_s: float = 5.0
def spec(self) -> dict: return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.parameters, }, }
def run(self, args: dict) -> ToolResult: return self._fn(args)세 도구는 이제 정직한 스키마를 선언하고, 이전에 조용히 실패하던 둘은 시끄럽게 실패합니다. _search 는 백엔드가 내려가면 빈 리스트를 반환하는 대신 분류된 ToolError 를 raise합니다. 빈 리스트와 타임아웃은 모델에게 정반대의 의미이기 때문입니다:
def _search(args: dict) -> ToolResult: query = str(args.get("query", "")).strip().lower() limit = int(args.get("limit", 3)) corpus = { "agent loop": "An agent loop repeats: observe, decide, act, observe.", "token budget": "Context windows are finite; budget them explicitly.", "stop condition": "A step limit is a stop condition, not a strategy.", "retry": "Retry only failures that are transient; never retry a 400.", } hits = [v for key, v in corpus.items() if key in query][:limit] if "timeout" in query: raise ToolError("upstream search index timed out", ErrorCode.TIMEOUT) return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
def _calculate(args: dict) -> ToolResult: expr = str(args.get("expression", "")) allowed = set("0123456789+-*/(). ") if not expr or not set(expr) <= allowed: return ToolResult(ok=False, data="", error="illegal characters in expression", error_code=ErrorCode.INVALID_ARGUMENTS) try: value = eval(expr, {"__builtins__": {}}, {}) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc), error_code=ErrorCode.INVALID_ARGUMENTS) return ToolResult(ok=True, data=str(value))
def _save_note(args: dict) -> ToolResult: import os os.makedirs("notes", exist_ok=True) path = "notes/" + str(args.get("name", "note")) + ".txt" with open(path, "w", encoding="utf-8") as f: f.write(str(args.get("body", ""))) return ToolResult(ok=True, data="saved " + path)
def build_tools() -> list[Tool]: return [ Tool( name="search", description="Search the local research corpus. Returns a JSON list of matching passages.", parameters={ "type": "object", "properties": { "query": {"type": "string", "minLength": 2, "maxLength": 200}, "limit": {"type": "integer", "minimum": 1, "maximum": 10}, }, "required": ["query"], "additionalProperties": False, }, _fn=_search, ), Tool( name="calculate", description="Evaluate a pure arithmetic expression. No variables, no functions.", parameters={ "type": "object", "properties": {"expression": {"type": "string", "minLength": 1, "maxLength": 100}}, "required": ["expression"], "additionalProperties": False, }, _fn=_calculate, ), Tool( name="save_note", description="Persist a note to disk. Non-idempotent: each call writes a file.", parameters={ "type": "object", "properties": { "name": {"type": "string", "minLength": 1, "maxLength": 40}, "body": {"type": "string", "maxLength": 4000}, }, "required": ["name", "body"], "additionalProperties": False, }, _fn=_save_note, side_effect=True, timeout_s=2.0, ), ]minLength: 2 제약은 겉꾸미기가 아닙니다. query 에 붙은 그것은 12건의 조용한 실패를 만든 빈 쿼리 케이스에 대한 가장 저렴한 방어입니다. 빈 문자열은 이제 계약 수준에서 거부되고, 도구 본문은 그것을 아예 보지 못합니다.
부수 효과를 중복하지 않는 재시도
백오프는 쉬운 절반입니다. 어려운 절반은 쓰기의 재시도가 두 번 쓸 수 있다는 점입니다. 요청은 성공했는데 응답이 유실되고, 재시도가 두 번째 노트를 만드는 겁니다. 해결책은 도구 이름과 정규화된 인자에서 파생된 키에, 어떤 호출이 캐시된 결과를 재사용할 수 있는지에 대한 규칙을 더하는 것입니다.
import hashlibimport randomimport time
@dataclassclass RetryPolicy: max_attempts: int = 3 base_delay: float = 0.05 max_delay: float = 2.0 jitter: float = 0.25 retryable: frozenset = frozenset( {ErrorCode.RATE_LIMITED, ErrorCode.TIMEOUT, ErrorCode.UPSTREAM} )
def is_retryable(self, code: str | None) -> bool: return code in {c.value for c in self.retryable}
def delay_for(self, attempt: int, rnd: random.Random) -> float: raw = min(self.max_delay, self.base_delay * (2 ** (attempt - 1))) return raw * (1.0 + rnd.uniform(-self.jitter, self.jitter))
class IdempotencyStore: """Remembers completed calls by (tool, canonical args) hash."""
def __init__(self) -> None: self._done: dict[str, ToolResult] = {}
@staticmethod def key(name: str, args: dict) -> str: blob = json.dumps(args, sort_keys=True, separators=(",", ":")) return name + ":" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
def get(self, key: str) -> ToolResult | None: return self._done.get(key)
def put(self, key: str, result: ToolResult) -> None: self._done[key] = resultsort_keys=True 가 키를 안정적으로 만드는 장치입니다: {"a": 1, "b": 2} 와 {"b": 2, "a": 1} 은 같은 호출이며 같은 키를 만들어야 합니다. 그렇지 않으면 방어가 새줍니다. 지터도 사치가 아닙니다. 없으면 같은 429를 맞은 열 개의 워커가 발을 맞춰 재시도하고 다시 함께 맞습니다. ±25% 가 그것들을 흩어 줍니다.
실행기는 네 관심사가 결합되는 지점이며, 그 순서가 곧 설계입니다: 검증, 중복 제거, 실행, 분류, 재시도 순. 검증이 중복 제거보다 먼저라서, 잘못된 호출이 절대 키를 점유하지 않습니다.
import concurrent.futures
class ToolExecutor: """Validate -> de-duplicate -> execute -> classify -> retry. The only caller of Tool.run."""
def __init__( self, tools: dict[str, Tool], policy: RetryPolicy | None = None, store: IdempotencyStore | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None, ) -> None: self.tools = tools self.policy = policy or RetryPolicy() self.store = store or IdempotencyStore() self.sleep = sleep self.rnd = rnd or random.Random(0)
def execute(self, name: str, args: dict) -> ToolResult: tool = self.tools.get(name) if tool is None: return ToolResult(ok=False, data="", error="unknown tool: " + name, error_code=ErrorCode.UNKNOWN_TOOL.value)
errors = validate_args(tool.parameters, args) if errors: hint = "expected " + describe_schema(tool.parameters) return ToolResult(ok=False, data="", error=format_errors(errors) + ". " + hint, error_code=ErrorCode.INVALID_ARGUMENTS.value)
key = self.store.key(name, args) cached = self.store.get(key) if cached is not None and (tool.side_effect or not cached.ok): return replace(cached, from_cache=True, attempts=0)
attempt = 0 while True: attempt += 1 result = self._attempt(tool, args) result.attempts = attempt if result.ok: self.store.put(key, result) return result if not self.policy.is_retryable(result.error_code): # Negative cache: an identical call that failed permanently will fail # again. Caching it stops a looping model from re-burning the quota. self.store.put(key, result) return result if attempt >= self.policy.max_attempts: return result self.sleep(self.policy.delay_for(attempt, self.rnd))
def _attempt(self, tool: Tool, args: dict) -> ToolResult: pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) try: future = pool.submit(tool.run, args) return future.result(timeout=tool.timeout_s) except concurrent.futures.TimeoutError: return ToolResult(ok=False, data="", error="tool exceeded %.1fs" % tool.timeout_s, error_code=ErrorCode.TIMEOUT.value) except ToolError as exc: return ToolResult(ok=False, data="", error=str(exc), error_code=exc.code.value) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc), error_code=ErrorCode.INTERNAL.value) finally: pool.shutdown(wait=False)이름 붙일 가치가 있는 미묘한 점이 두 개. 캐시 재사용 조건은 tool.side_effect or not cached.ok 입니다: 쓰기는 캐시된 성공을 재사용할 수 있고(이것이 at-most-once), 어떤 호출이든 캐시된 실패를 재사용할 수 있습니다(이것이 네거티브 캐시로, 멈춘 모델이 같은 깨진 호출에서 쿼터를 다시 태우는 것을 막습니다). 읽기 전용 성공은 의도적으로 캐시하지 않습니다. 2분 전에 아무것도 돌려주지 않은 검색이 지금은 무언가를 돌려줄 수도 있고, 낡은 읽기는 그 자체로 또 한 종류의 오답이기 때문입니다.
두 번째 미묘한 점은 타임아웃입니다. future.result(timeout=...) 가 제한하는 것은 당신이 기다리는 시간이지 도구가 실행되는 시간이 아닙니다 — Python은 스레드를 죽일 수 없습니다. 타임아웃을 무시하는 도구는 루프가 다음으로 넘어가는 동안에도 백그라운드에서 CPU를 태웁니다. 이것은 정직한 한계이며, 바로 파트 11이 이것을 프로세스 수준 샌드박스로 교체하는 이유입니다. timeout_s 를 안전 경계로 읽지 마세요. 레이턴시 예산으로 읽으세요.
루프에 연결하기, 그리고 건너뛰었던 LLM 재시도
파트 1에는 제가 명시적으로 표시해 둔 구멍이 있었습니다. AgentLoop.run 은 tool.run 은 감쌌지만 llm.complete 는 감싸지 않아서, 모델 엔드포인트의 503 한 번이 실행 전체를 죽였습니다. 같은 정책으로 그 구멍을 막습니다. HTTP 상태 코드에 적용됩니다.
import urllib.error
class LLMClient: def complete(self, messages: list[Message], tools: list[dict]) -> dict: raise NotImplementedError
class ScriptedLLM(LLMClient): """Replays a fixed list of decisions. Used for offline tests and demos."""
def __init__(self, script: list[dict]): self.script = list(script) self.calls: list[list[Message]] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: self.calls.append(list(messages)) if not self.script: return {"type": "final", "content": "no scripted decision left"} return self.script.pop(0)
def classify_http_status(status: int) -> ErrorCode: if status == 429: return ErrorCode.RATE_LIMITED if status in (408, 504): return ErrorCode.TIMEOUT if 500 <= status < 600: return ErrorCode.UPSTREAM if status in (401, 403): return ErrorCode.PERMISSION return ErrorCode.INVALID_ARGUMENTS
class RetryingLLM(LLMClient): """Wraps any client; retries only the codes that a second attempt can fix."""
def __init__(self, inner: LLMClient, policy: RetryPolicy | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None) -> None: self.inner = inner self.policy = policy or RetryPolicy() self.sleep = sleep self.rnd = rnd or random.Random(7) self.attempts: list[int] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: attempt = 0 while True: attempt += 1 try: decision = self.inner.complete(messages, tools) self.attempts.append(attempt) return decision except urllib.error.HTTPError as exc: code = classify_http_status(exc.code) if not self.policy.is_retryable(code.value) or attempt >= self.policy.max_attempts: self.attempts.append(attempt) raise self.sleep(self.policy.delay_for(attempt, self.rnd))401은 세 번째가 아니라 첫 시도에서 raise됩니다. 나쁜 키는 나쁜 상태로 남고, 세 번의 시도는 실패 전에 레이턴시만 세 배로 늘립니다. 400도 같은 이유로 invalid_arguments 로 분류됩니다 — 페이로드가 틀렸고 다시 보내는 것은 무의미합니다.
루프의 변경은 작고, 트레이스에서 그 가치가 드러납니다:
SYSTEM = ( "You are a research agent. Use the provided tools to gather evidence, " "then answer with a final decision. Do not claim facts you did not retrieve. " "If a tool returns ERROR[invalid_arguments], fix the arguments using the schema shown.")
class AgentLoop: def __init__(self, llm: LLMClient, tools: list[Tool], max_steps: int = 8, executor: ToolExecutor | None = None): self.llm = llm self.tools = {t.name: t for t in tools} self.specs = [t.spec() for t in tools] self.max_steps = max_steps self.trace: list[dict] = [] self.executor = executor or ToolExecutor(self.tools)
def run(self, goal: str) -> str: history = [ Message(role="system", content=SYSTEM), Message(role="user", content=goal), ] for step in range(self.max_steps): decision = self.llm.complete(history, self.specs) kind = decision.get("type") record = {"step": step, "decision": decision} self.trace.append(record)
if kind == "final": return str(decision.get("content", "")) if kind != "tool": return "aborted: malformed decision " + repr(decision)
name = str(decision.get("name", "")) args = decision.get("arguments", {}) if not isinstance(args, dict): args = {}
result = self.executor.execute(name, args) record.update({"tool": name, "ok": result.ok, "attempts": result.attempts, "error_code": result.error_code, "from_cache": result.from_cache}) history.append(result.to_message(name))
return "aborted: step limit reached"SYSTEM 프롬프트가 이제 오류 형식을 명시합니다. 이것은 프롬프트 엔지니어링 신비주의가 아닙니다. 모델에게 실패 시 볼 정확한 문자열과 그것을 어떻게 다룰지가 알려진 겁니다. 한 문장의 비용으로, 검증 오류 후 모델이 헤매는 턴 수를 측정 가능한 수준으로 줄입니다. 수정 대상이 오류 자체에 담겨 있기 때문입니다.
실행하면 트레이스가 기록이 아니라 진단처럼 읽힙니다:
def demo() -> None: script = [ {"type": "tool", "name": "search", "arguments": {"q": "agent loop"}}, {"type": "tool", "name": "search", "arguments": {"query": "agent loop", "limit": 1}}, {"type": "tool", "name": "save_note", "arguments": {"name": "loop", "body": "observe decide act"}}, {"type": "tool", "name": "save_note", "arguments": {"name": "loop", "body": "observe decide act"}}, {"type": "final", "content": "The agent loop repeats observe, decide, act."}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=8) print("ANSWER:", agent.run("Explain the agent loop.")) for rec in agent.trace: if "tool" in rec: print(rec["step"], rec["tool"], "ok=%s" % rec["ok"], "attempts=%d" % rec["attempts"], rec["error_code"], "cached=%s" % rec["from_cache"])
if __name__ == "__main__": demo()ANSWER: The agent loop repeats observe, decide, act.0 search ok=False attempts=1 invalid_arguments cached=False1 search ok=True attempts=1 None cached=False2 save_note ok=True attempts=1 None cached=False3 save_note ok=True attempts=0 None cached=True스텝 0은 계약이 호출을 거부했음을 보여줍니다. 스텝 1은 모델이 다음 턴에서 회복했음을 보여줍니다 — 그 회복은 오류 메시지가 만든 것이고, 힌트를 스키마에서 생성하는 이유이기도 합니다. 스텝 3은 동일한 쓰기 요청이 attempts=0 으로 캐시에서 처리됐음을 보여줍니다. 두 번째 파일도, 두 번째 네트워크 호출도 없었습니다.
실패 모드와 대처
| 실패 | 실제로 일어나는 일 | 여기서의 처리 | 여전히 깨져 있는 것 |
|---|---|---|---|
| 모델이 이름을 바꾼 키를 보냄 | additionalProperties: False 가 표시하고, required 가 누락 필드를 지목 |
스키마 힌트가 붙은 명시적 invalid_arguments; 모델이 다음 턴에 수정 |
힌트를 무시하는 모델은 모든 스텝을 태움 |
모델이 정수 자리에 true 를 보냄 |
Python은 bool 을 int 로 취급해 순진한 검사는 통과 |
isinstance(value, bool) 가드가 거부 |
없음 — 이건 닫혔음 |
| 도구가 멈춤 | future 타임아웃 후에도 스레드가 계속 실행 |
timeout_s 가 timeout 을 반환하고 예산 내 재시도 |
프로세스 수준 CPU 소모; 킬 스위치 없음 (파트 11) |
| 429 폭풍 | 매 시도가 한도를 다시 맞음 | 유한 시도, 지수 백오프, ±25% 지터 | 프로세스 간 레이트 리미터 없음 (파트 12) |
| 쓰기에서 응답 유실 | 재시도가 파일을 복제함 | 멱등키 + side_effect=True 가 캐시된 성공 반환 |
인메모리 스토어는 프로세스와 함께 소멸 (파트 8) |
| 같은 깨진 호출의 반복 | 모델이 하나의 오류로 루프 | 네거티브 캐시가 재실행을 막음 | 루프는 여전히 스텝을 소모; 반복 감지기 필요 |
| 스키마와 코드의 드리프트 | 검증이 도구에 필요한 필드를 거부 | describe_schema 가 스키마에서 힌트를 재생성 |
드리프트를 자동 감지하는 것 없음 |
마지막 행이 저를 물어뜯은 행입니다. describe_schema 가 올바른 이유는 validate_args 와 같은 dict를 읽기 때문에 불과합니다. 프롬프트에 스키마 사본을 손으로 또 쓰면, 둘은 한 달 안에 갈라집니다 — 그리고 실패는 모델 오류처럼 보이지, 유지보수 오류처럼 보이지 않습니다.
트레이드오프
| 결정 | 대안 | 그렇게 고른 이유 | 대가 |
|---|---|---|---|
| 손수 만든 부분집합 검증기 | jsonschema 또는 Pydantic |
의존성 0, 약 120줄, 모델 친화적 오류 형태 | $ref/oneOf/pattern 미지원; 직접 유지보수 |
오류를 ToolResult 값으로 |
예외를 루프 밖으로 raise | 모델이 읽고 수정 가능; 루프는 단순 유지 | 호출자가 모든 곳에서 ok 를 확인해야 함 |
additionalProperties: False |
관대한 추가 필드 | 환각된 파라미터를 즉시 잡음 | 제공자가 메타데이터를 추가하면 깨짐 |
| 인메모리 멱등키 | Redis 또는 SQLite | dict 하나, 인프라 없음, 테스트 가능 | 워커 간 공유 불가; 재시작 시 소실 |
| 스레드 타임아웃 | 프로세스 샌드박스 | 10줄, IPC 불필요 | 폭주하는 도구를 죽일 수 없음 (파트 11) |
| 재시도는 3개 코드만 | 전부 한 번씩 재시도 | 스텝 예산을 보존 | 산발적인 not_found 는 영원히 재시도 안 됨 |
| 부정 결과 캐싱 | 항상 재실행 | 루프 도는 모델의 재시도 폭풍을 막음 | 영구로 오분류된 일시 실패가 캐시에 남음 |
가장 세밀히 검토할 가치가 있는 선택은 검증기입니다. Pydantic은 강제 변환, 중첩 모델, 더 나은 오류 메시지를 공짜로 줍니다 — 대가로 의존성, 느린 임포트, 그리고 결국엔 오류 객체를 모델이 읽을 수 있는 텍스트로 번역해야 한다는 비용을 치르고요. 도구 스키마 여덟 개에서는 손수 만든 버전이 이깁니다. 여든에서는 그렇지 않습니다.
테스트
열네 개의 테스트, 오프라인, 0.1초 이내. 모듈은 contracts.py 로, 테스트는 test_contracts.py 로 저장한 뒤 python3 -m unittest test_contracts -v 를 실행하세요. 전체 스위트는 저장소에 있지만, 설계를 짊어지는 것은 이 다섯 개입니다:
import unittestimport urllib.error
from contracts import ( AgentLoop, ErrorCode, ScriptedLLM, Tool, ToolError, ToolExecutor, ToolResult, IdempotencyStore, RetryPolicy, RetryingLLM, LLMClient, build_tools, validate_args, describe_schema,)
class Flaky: def __init__(self, failures, code=ErrorCode.TIMEOUT): self.failures, self.code, self.calls = failures, code, 0
def __call__(self, args): self.calls += 1 if self.calls <= self.failures: raise ToolError("transient", self.code) return ToolResult(ok=True, data="recovered")
def tool_with(fn, name="probe", side_effect=False, timeout_s=1.0): return Tool(name=name, description="probe", _fn=fn, parameters={"type": "object", "properties": {}, "additionalProperties": False}, side_effect=side_effect, timeout_s=timeout_s)
class TestContracts(unittest.TestCase): def test_bool_is_not_an_integer(self): schema = build_tools()[0].parameters errors = validate_args(schema, {"query": "ok", "limit": True}) self.assertTrue(any("expected integer" in e["message"] for e in errors))
def test_transient_failure_is_retried_until_success(self): flaky = Flaky(failures=2, code=ErrorCode.UPSTREAM) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertTrue(result.ok) self.assertEqual(result.attempts, 3)
def test_permanent_failure_is_never_retried(self): flaky = Flaky(failures=5, code=ErrorCode.PERMISSION) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertFalse(result.ok) self.assertEqual(flaky.calls, 1)
def test_side_effect_runs_once_per_key(self): calls = {"n": 0}
def write(args): calls["n"] += 1 return ToolResult(ok=True, data="written")
executor = ToolExecutor({"probe": tool_with(write, side_effect=True)}, store=IdempotencyStore(), sleep=lambda d: None) executor.execute("probe", {}) second = executor.execute("probe", {}) self.assertEqual(calls["n"], 1) self.assertTrue(second.from_cache)
def test_401_is_not_retried(self): class Bad(LLMClient): def __init__(self): self.calls = 0
def complete(self, messages, tools): self.calls += 1 raise urllib.error.HTTPError("http://x", 401, "no", None, None)
inner = Bad() llm = RetryingLLM(inner, sleep=lambda d: None) with self.assertRaises(urllib.error.HTTPError): llm.complete([], []) self.assertEqual(inner.calls, 1)
if __name__ == "__main__": unittest.main()test_bool_is_not_an_integer 는 사소해 보이지만 아닙니다: {"limit": true} 와 조용히 잘린 결과 집합 사이에 선 한 줄이기 때문입니다. test_side_effect_runs_once_per_key 는 레이턴시가 아니라 데이터를 지키는 유일한 테스트입니다. 두 개만 남긴다면 이 둘을 남기세요.
손으로 돌려볼 만한 검사가 하나 더 있습니다: Flaky 를 RATE_LIMITED 로 향하게 하고 max_attempts=99 로 두어 실행기가 정책 상한에서 멈추는지 확인하세요. 경계 없는 재시도 루프는 부가적인 스텝이 붙은 장애입니다.
연습 문제
- 프로세스를 넘나드는 멱등성.
IdempotencyStore를(name, args_hash)를 키로 하고created_at타임스탬프를 가진 SQLite 기반 버전으로 교체하세요. 10분보다 오래된 키를 만료시킵니다. 쓰기 도중 프로세스가 죽을 때 실패 모드는 어떻게 달라지며, TTL이 가장 긴 재시도 창보다 길어야 하는 이유는 무엇인가요? - 도구별 재시도 재정의. 검색 백엔드는 레이트 리밋이 공격적입니다. 노트 쓰기는 기껏해야 한 번 재시도하는 게 맞습니다. 실행기 기본값을 재정의하는
policy필드를Tool에 추가하고, 429 하에서의save_note호출이 네 번이 아니라 두 번 시도 후 반환됨을 증명하는 테스트를 작성하세요. - 영수증을 끼고 강제 변환.
{"limit": "3"}을 거부하는 대신 받아들이고,3으로 변환하고, 도구 결과에 메모를 덧붙입니다:coerced: limit "3" -> 3. 50회 호출 트레이스에서 이것이 몇 턴을 아끼는지 측정하세요. 어느 쪽이 더 위험할까요 — 조용한 강제 변환인가 거부된 호출인가. 그리고 영수증은 무엇을 바꾸나요?
연습 3이 가장 흥미로운 이유는 답이 하나로 정해지지 않기 때문입니다. 강제 변환은 왕복을 줄이고 모델 오류를 감춥니다. 거부는 시끄럽지만 느립니다. 영수증은 절충안입니다. 왕복을 되찾으면서, 모델을 위해 당신이 내린 모든 가정의 감사 기록을 남깁니다.
다음 편
이제 도구에는 계약이 있고, 실패에는 코드가 있으며, 재시도는 쓰기를 중복하지 않습니다. 파트 1 이후로 바뀌지 않은 것, 그리고 프로덕션에서 가장 먼저 아픈 것은: 메시지 목록이 매 스텝 불어나고, 이전 메시지 전부가 매 호출마다 통째로 재전송된다는 점입니다.
파트 3, 컨텍스트 예산 엔지니어링 에서는 ContextBudget 을 추가합니다. 이것은 매 호출 전에 토큰을 측정하고, 시스템 프롬프트, 도구 결과, 이력 사이에 창을 배분하며, 추정치가 예산을 넘으면 오래된 턴을 압축합니다. 또한 파트 1의 표에 있던 이차 증가를 정량화하고, 세 가지 압축 전략 — 잘라내기, 요약, 추출 — 중 어떤 것이 실제로 값어치를 하는지 보여줍니다. 방금 만든 ToolExecutor 는 그대로입니다. 예산이 감싸는 것은 이지지, 도구가 아닙니다.
Ball 받기 — Ball
Ball 받기