สร้าง AI Agent Loop ตั้งแต่เริ่มต้น (Part 1)
คำอธิบายเกี่ยวกับ AI agent ส่วนใหญ่หยุดอยู่แค่แผนภาพ: กล่องที่เขียนว่า LLM, ลูกศรไปยังกล่องที่เขียนว่า Tools และ loop ที่ลากรอบๆ มัน ภาพนั้นไม่ผิด แต่มันซ่อนทุกการตัดสินใจที่สำคัญจริงๆ ว่าใน context ที่ step 4 มีอะไรอยู่กันแน่? จะเกิดอะไรขึ้นเมื่อโมเดลขอใช้ tool ที่ไม่มีอยู่? คุณจะหยุด Agent ที่ตัดสินใจว่าจะเดินหน้าตลอดไปได้อย่างไร? คำถามเหล่านี้แหละคือจุดที่ agent จริงๆ สำเร็จหรือล้มเหลว
บทเรียนนี้สร้าง agent loop ที่เล็กที่สุดเท่าที่จะยังซื่อสัตย์อยู่ได้ ไม่มี framework ไม่มี SDK ไม่ต้องใช้ API key เมื่อจบ คุณจะได้ loop ที่รันได้ เรียกใช้ tools ฟื้นตัวจากการตัดสินใจที่ผิดรูป เคารพงบประมาณของ step และให้ trace ที่คุณตรวจสอบได้ ทุกตอนถัดไปของซีรีส์นี้ล้วนต่อยอดจากไฟล์นี้เป๊ะๆ ดังนั้นจงอ่านโค้ด อย่ากวาดสายตาผิวๆ
สิ่งที่คุณจะสร้าง
research-agent ที่มีจุดเข้าถึงเพียงจุดเดียวคือ AgentLoop.run(goal) ซึ่งคืนคำตอบสุดท้าย Part 1 ให้ความสามารถสี่อย่าง:
- message model แบบมี type เพื่อให้ context มีโครงสร้างชัดเจน แทนที่จะเป็น strings ต่อกัน
- tool registry ที่ซึ่ง tools เป็นที่เดียวที่อนุญาตให้เกิด side effects
- decision cycle ที่แปลงคำตอบของโมเดลให้เป็น tool call หรือคำตอบสุดท้าย
- stop conditions และ error recovery เพื่อให้โมเดลที่สับสนไม่สามารถค้างหรือทำให้ process พังได้
โค้ดจงใจไม่พึ่ง dependency ใดๆ LLM คือ interface ที่ inject ได้ และ implementation เริ่มต้นคือตัวแทนแบบ scripted ที่ deterministic หมายความว่าคุณสามารถรันและทดสอบ loop ทั้งหมดแบบออฟไลน์ แล้วค่อยสลับเป็น HTTP client จริงในภายหลังโดยไม่ต้องแตะ loop
สิ่งที่ต้องมีก่อน
- Python 3.10 หรือใหม่กว่า (โค้ดใช้
str | Noneunion syntax และ dataclasses) - ไม่มีแพ็กเกจจากภายนอก ทุกอย่างใช้ standard library
- คุ้นเคยกับ JSON และ Python เบื้องต้น คุณไม่จำเป็นต้องรู้จัก agent framework ใดๆ
- นี่คือ Part 1 ของซีรีส์ ไม่มีโค้ดเก่าที่ต้องดึงมา Part 2 จะแทนที่ tool functions แบบ ad-hoc ตรงนี้ด้วย validated contracts และ Part 3 จะเพิ่ม context budget
หมายเหตุเรื่องขอบเขต: tool calculate ด้านล่างใช้ eval ร่วมกับชุดอักขระที่จำกัด นี่เป็นทางลัดเพื่อการสอน ไม่ใช่เขตความปลอดภัย Part 11 จะแทนที่มันด้วย sandbox จริง การปล่อยให้เวอร์ชันที่ไม่ปลอดภัยเห็นอยู่เป็นความตั้งใจ — มันให้ failure mode ที่จับต้องได้ให้เราแก้ในภายหลัง แทนที่จะแกล้งทำเป็นว่าปัญหาไม่มี
กายวิภาคของ loop ไม่ใช่แผนภาพ
agent loop คือ state machine ที่มี state เดียว คือรายการของ messages แต่ละรอบทำสามอย่าง:
- Observe — ส่งรายการ messages ปัจจุบันให้โมเดล พร้อมกับ tool specifications
- Decide — แปลงคำตอบให้เป็นการตัดสินใจที่มีโครงสร้าง จะเรียก tool หรือจบ
- Act — ถ้าเป็น tool call ให้รันมันแล้วต่อผลลัพธ์เป็น message ใหม่ ถ้าเป็นคำตอบสุดท้ายให้คืนค่า
ทางเลือกด้านออกแบบที่สำคัญคือโมเดลไม่เคยรันอะไรเลย มันแค่ปล่อยคำอธิบายของการกระทำ ส่วน loop เป็นเจ้าของการรัน ขอบเขตเพียงเส้นเดียวนี้แหละที่ทำให้ permissions, logging, retries และ budgets ทำได้จริง — ทั้งหมดอยู่ฝั่ง loop ไม่ใช่ใน prompt
ทางเลือกที่สองคือ ผลลัพธ์ของ tools กลับเข้าไปในรายการ messages นี่คือเหตุผลที่ loop ลู่เข้าสู่จุดจบ: แต่ละ step เห็นสิ่งที่การกระทำก่อนหน้าผลิตออกมา โมเดลจึงแก้ตัวเองได้ ถ้าคุณทิ้งผลลัพธ์ คุณก็ไม่มี agent ดอก คุณมีแค่ one-shot classifier ที่มี step เพิ่มขึ้นมา
นี่คือ message model สังเกตว่า role="tool" มี name ด้วย เพราะเมื่อมี tools หลายตัว โมเดลต้องรู้ว่าผลลัพธ์อันไหนเป็นของ call ไหน
from __future__ import annotationsfrom dataclasses import dataclassfrom 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
def to_message(self, name: str) -> Message: payload = self.data if self.ok else "ERROR: " + (self.error or "unknown") return Message(role="tool", content=payload, name=name)ToolResult ทำงานมากกว่าที่ดูภายนอก ทุก tool ไม่ว่าสำเร็จหรือล้มเหลว คืนรูปแบบเดียวกัน ความสม่ำเสมอนี้แหละที่ทำให้ loop จัดการ errors แบบทั่วไปได้ — มันไม่จำเป็นต้องรู้เลยว่า tool ไหนพังและเพราะอะไร สังเกตอีกอย่างว่าความล้มเหลวกลายเป็น content ไม่ใช่ exceptions: error string ถูกต่อเข้าประวัติเพื่อให้โมเดลอ่านแล้วปรับตัวได้ การกลืน error จะซ่อนมัน ส่วนการ raise จะฆ่า run ทิ้ง
tools คือที่เดียวที่เกิด side effects
tool ในที่นี้คือชื่อหนึ่ง คำอธิบายหนึ่ง JSON Schema สำหรับ arguments และ callable หนึ่งตัว เมธอด spec() สร้างคำอธิบายที่ส่งให้โมเดล จงทำให้สองสิ่งนี้ตรงกัน: คำอธิบายที่คลุมเครือทำให้เกิดการเรียกผิดบ่อยกว่าโมเดลที่อ่อนแอเสียอีก
@dataclassclass Tool: name: str description: str parameters: dict[str, Any] # JSON Schema _fn: Callable[[dict], ToolResult]
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)tools ที่เป็นรูปธรรมสองตัวสำหรับ research agent ของเรา search tool คือตัวแทนแบบ deterministic ของ retrieval backend ส่วน calculator ประเมินนิพจน์เลขคณิต ทั้งคู่คืน ToolResult ไม่ใช่ค่าดิบ และทั้งคู่ไม่ print หรือแก้ global state
def _search(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.", } hits = [v for key, v in corpus.items() if key in query] 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") try: value = eval(expr, {"__builtins__": {}}, {}) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc)) return ToolResult(ok=True, data=str(value))
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", "description": "keywords to look for"}}, "required": ["query"], }, _fn=_search, ), Tool( name="calculate", description="Evaluate a pure arithmetic expression. No variables, no functions.", parameters={ "type": "object", "properties": {"expression": {"type": "string", "description": "e.g. 17 * (3 + 4)"}}, "required": ["expression"], }, _fn=_calculate, ), ]whitelist อักขระใน _calculate คือเรื่องความปลอดภัยทั้งหมดสำหรับตอนนี้ และมันบางมาก มันบล็อก __import__ และการเข้าถึง attribute แต่ไม่จำกัด runtime: นิพจน์อย่าง 9**9**9 เป็นอักขระที่ถูกต้องทั้งนั้น และจะเผา CPU อย่างสบายใจ เราจะแทนที่ด้วย parser ที่เหมาะสมและ timeout ใน Part 11 การโชว์มันตอนนี้ก็เพื่อทำให้ข้อจำกัดวัดได้ ไม่ใช่คงไว้แค่เชิงนามธรรม
ตัว loop เอง
LLM คือ interface ที่มีเมธอดเดียวคือ complete(messages, tools) มันคืน dict ธรรมดา ซึ่งเราถือเป็นการตัดสินใจ การนิยาม interface ที่แคบคือสิ่งที่ทำให้ loop ทดสอบได้: tests ด้านล่าง inject โมเดลแบบ scripted แล้วตรวจพฤติกรรมของ loop โดยไม่มี network และไม่มีความไม่แน่นอน
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)รองรับการตัดสินใจสองรูปแบบ: {"type": "tool", "name": ..., "arguments": {...}} และ {"type": "final", "content": ...} client จริงจะแปลงคำตอบแบบ function-calling ของโมเดลให้เป็นรูปแบบนี้เป๊ะๆ การทำให้ loop ขึ้นกับรูปแบบนี้ ไม่ใช่ response format ของ vendor รายใดรายหนึ่ง คือสิ่งที่ให้คุณเปลี่ยน providers ได้โดยไม่แตะ control flow
มาดู loop กัน อ่าน guards เหล่านี้ให้ละเอียด มันคือเนื้อหาสาระของบทเรียน
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.")
class AgentLoop: def __init__(self, llm: LLMClient, tools: list[Tool], max_steps: int = 8): 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] = []
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) self.trace.append({"step": step, "decision": decision})
kind = decision.get("type") 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 = {}
tool = self.tools.get(name) if tool is None: # Do not crash. Turn the mistake into context so the model can recover. result = ToolResult(ok=False, data="", error="unknown tool: " + name) else: try: result = tool.run(args) except Exception as exc: # A tool raising is a bug, not a reason to end the run. result = ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc))
history.append(result.to_message(name))
return "aborted: step limit reached"การตัดสินใจสี่อย่างตรงนี้ควรพูดให้ชัด เพราะแต่ละจุดคือที่ที่ implementations แบบ naïve พัง:
max_stepsคือเพดานที่แข็งกร้าว ถ้าไม่มีมัน โมเดลที่ขอ tools ไม่หยุดจะรันไปจนกว่าจะมีอะไรจากภายนอก timeout แปดคือค่าตั้งต้น agents ใน production มักตั้ง token budget ด้วย (Part 3)- tools ที่ไม่รู้จักกลายเป็น error messages ไม่ใช่ exceptions โมเดลจะถูกบอกใน context ของมันเองว่ามันขอสิ่งที่ไม่มีอยู่ ในทางปฏิบัติ message เดียวแบบนี้มักพอให้มันเลือก tool ที่ถูกต้องใน step ถัดไป
- exceptions ของ tool ถูกจับและแปลง ด้วยกลไกเดียวกัน tool ที่พังทำให้แค่หนึ่ง step อ่อนลง แทนที่จะฆ่า process
- ทุกการตัดสินใจถูกบันทึกใน
traceก่อนถูกรัน นี่ให้บันทึกที่เล่นซ้ำได้กับคุณ Part 9 เปลี่ยนมันเป็น structured tracing ส่วน Part 10 ใช้เป็น evaluation fixture
loop ไม่ต่อ message แบบ assistant สำหรับ tool calls หลาย implementations ทำแบบนั้น การละเว้นเป็นการทำให้ง่ายลงโดยตั้งใจสำหรับ Part 1: การตัดสินใจอยู่ใน trace อยู่แล้ว และการข้ามมันเลี่ยงการทำซ้ำ argument payloads ขนาดใหญ่ลงใน context Part 3 จะกลับมาทบทวนเรื่องนี้เมื่อเราเริ่มจัดงบ tokens
ตัวอย่าง end-to-end ที่รันได้
สคริปต์นี้รันได้โดยไม่มี network และไม่มี key มันใช้โมเดลแบบ scripted ที่ค้นหาก่อนแล้วค่อยตอบ
def demo() -> None: script = [ {"type": "tool", "name": "search", "arguments": {"query": "agent loop"}}, {"type": "final", "content": "An agent loop repeats: observe, decide, act, observe."}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5) answer = agent.run("Explain the agent loop in one sentence.") print("ANSWER:", answer) print("TRACE:", json.dumps(agent.trace, indent=2))
if __name__ == "__main__": demo()ผลลัพธ์ที่คาดไว้ (ตัดย่อ):
ANSWER: An agent loop repeats: observe, decide, act, observe.TRACE: [ {"step": 0, "decision": {"type": "tool", "name": "search", "arguments": {"query": "agent loop"}}}, {"step": 1, "decision": {"type": "final", "content": "An agent loop repeats: observe, decide, act, observe."}}]สังเกตว่า step 1 เห็นผลลัพธ์การค้นหาที่ step 0 ต่อเข้าไป นั่นแหละคือเส้นทาง feedback: การตัดสินใจครั้งที่สองเกิดขึ้นกับประวัติที่มี output ของ tool อยู่ อยากได้หลักฐานให้ดู agent.llm.calls[1] — มันมี message role="tool" พร้อมข้อความที่ดึงมา นี่คือกลไกเบื้องหลังการแก้ตัวเอง และมันไม่มีค่าใช้จ่ายเกินกว่าการต่อสมาชิกลงในรายการ
ต่อโมเดลจริงโดยไม่แตะ loop
โมเดลแบบ scripted พิสูจน์ control flow แต่ production ต้องการโมเดลจริง integration ทั้งหมดควรอยู่ใน subclass ของ LLMClient — ถ้าคุณพบว่าตัวเองกำลังแก้ AgentLoop เพื่อรองรับ provider แสดงว่า abstraction กำลังรั่ว งานของ adapter นี้คือแปล HTTP response แบบเฉพาะ vendor ให้เป็นการตัดสินใจสองรูปแบบที่ loop เข้าใจอยู่แล้ว
import urllib.request
class HTTPClient(LLMClient): """Minimal adapter for an OpenAI-compatible chat endpoint.""" def __init__(self, base_url: str, api_key: str, model: str, timeout: float = 20.0): self.base_url, self.api_key, self.model, self.timeout = base_url, api_key, model, timeout
def complete(self, messages: list[Message], tools: list[dict]) -> dict: payload = { "model": self.model, "messages": [{"role": m.role, "content": m.content, **({"name": m.name} if m.name else {})} for m in messages], "tools": tools, "tool_choice": "auto", } req = urllib.request.Request( self.base_url.rstrip("/") + "/chat/completions", data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json", "Authorization": "Bearer " + self.api_key}, method="POST", ) with urllib.request.urlopen(req, timeout=self.timeout) as resp: body = json.load(resp) choice = body["choices"][0]["message"] calls = choice.get("tool_calls") or [] if not calls: return {"type": "final", "content": choice.get("content") or ""} call = calls[0]["function"] try: args = json.loads(call.get("arguments") or "{}") except json.JSONDecodeError: args = {} return {"type": "tool", "name": call["name"], "arguments": args}ใน adapter นั้นมีรายละเอียดสามอย่างที่พลาดได้ง่ายและควรเอ่ยชื่อ หนึ่ง tool_choice: "auto" ให้โมเดลตอบตรงๆ เมื่อไม่ต้องการ tool การบังคับให้เรียก tool จะทำให้คำถามง่ายๆ วน loop ไปเปล่าๆ สอง arguments มาถึงในรูป JSON string ไม่ใช่ object — ทุก provider ทำแบบนี้ และการลืม parse มันจะได้ agent ที่พังแบบแอบแฝง ซึ่งเรียก tools ด้วย arguments ว่างตลอด สาม arguments string ที่ผิดรูปจะถูกจับและลดทอนเป็น {} แล้ว loop จะรัน tool ด้วย defaults แทนที่จะยุติ สำหรับเวอร์ชันที่ตรวจ schema ของการเช็กนี้โดยตรง ดู Part 2
พารามิเตอร์ timeout คือแนวป้องกันแรกต่อ request ที่ค้าง แต่จงสังเกตสิ่งที่มันไม่ทำ: มันไม่ retry และมันไม่แยกแยะ 429 (rate limit, retry หลังพัก) ออกจาก 401 (key ผิด, ห้าม retry เด็ดขาด) การจัดหมวดความล้มเหลวเหล่านี้คือสิ่งที่ Part 2 เพิ่มเข้ามาพอดี ตอนนี้ timeout จะ raise ออกจาก complete และ loop ไม่ได้ จับมัน — AgentLoop.run คุม tool.run ไม่ใช่ llm.complete นี่เป็นช่องโหว่จริง ไม่ใช่การตกหล่นในเนื้อความ จงห่อ self.llm.complete ด้วย try/except ก่อนส่งไฟล์นี้ขึ้นจริง
ติดตามว่าจริงๆ แล้ว context โตยังไง
loop เรียบง่ายพอที่เราจะคิดต้นทุนได้ตรงเป๊ะ ลองดู run ที่มี tool calls สองครั้ง และสมมติว่าประมาณสี่อักขระต่อหนึ่ง token context ที่ส่งให้โมเดลในแต่ละ step คือ:
| Step | Messages ใน history |
tokens โดยประมาณ | ทำไมถึงโต |
|---|---|---|---|
| 0 | system (42) + user (18) | ~15 | สถานะเริ่มต้น |
| 1 | + tool result 1 | ~95 | search คืนข้อความหนึ่งชุด |
| 2 | + tool result 2 | ~180 | call ที่สอง, output ยาวขึ้น |
| 3 | + final decision | ~200 | คำตอบถูกสร้างขึ้น |
ทุก message ก่อนหน้าถูกส่งซ้ำทั้งหมดในทุก call ดังนั้น run ห้า step จึงไม่ได้มีต้นทุนห้าเท่าของหนึ่ง call — มันใช้ 1 + 2 + 3 + 4 + 5 = 15 message-units ของ input ต้นทุน input token เป็น quadratic กับจำนวน step ไม่ใช่เชิงเส้น นี่คือเหตุผลเดียวที่พบบ่อยที่สุดที่ agent ซึ่งทำงานใน demo กลายเป็นแพงใน production และมันจะมองไม่เห็นจนกว่าคุณจะวัดมัน
ผลที่ตามมามีสองอย่าง การย่อ output ของ tools คุ้มสองเท่า เพราะทุกผลลัพธ์ถูกอ่านซ้ำในทุก step ถัดมา และการต่อ blobs ขนาดใหญ่ตั้งแต่ต้นมีต้นทุนสูงเกินสัดส่วน Part 3 นำเสนอ ContextBudget ที่จำกัดการโตนี้และบีบอัด turns เก่า การวัดข้างต้นคือ baseline ที่มันต้องเอาชนะ ถ้าคุณระบุต้นทุน token ต่อ step ได้ไม่ชัดเจนเท่าตารางนี้ แสดงว่าคุณยังควบคุมต้นทุนของ agent ไม่ได้
รูปแบบความล้มเหลวและวิธีจัดการ
| ความล้มเหลว | สิ่งที่เกิดขึ้นจริง | การจัดการใน loop นี้ | สิ่งที่ Part 1 ยังแก้ไม่ได้ |
|---|---|---|---|
| โมเดลขอ tool ที่ไม่มีอยู่ | self.tools.get(name) คืน None |
ต่อ message ERROR: unknown tool แล้วเดินหน้า |
โมเดลที่ทำพลาดซ้ำจะเผา steps หมด |
| tool raise exception | Exception แพร่ออกจาก tool.run |
จับ แปลงเป็น ToolResult(ok=False) เดินหน้า |
ไม่มี retry ไม่มี circuit breaker (Part 2) |
การตัดสินใจผิดรูป (ไม่มี type, ประเภท arguments ผิด) |
Parser จัดหมวดไม่ได้ | คืน abort string ทันที | ไม่มี schema validation ของ arguments (Part 2) |
| ขอ tool ไม่รู้จบ | loop วนต่อไปเรื่อยๆ | เพดาน max_steps คืน abort |
ไม่มี budget ด้าน token หรือต้นทุน (Part 3) |
| context โตไม่มีขอบเขต | ทุก step ต่อ message เข้าไป | ยังไม่มี | ไม่มีการสรุปย่อหรือ pruning (Part 3, Part 4) |
tool เลขคณิตถูกใช้ในทางที่ผิด (9**9**9) |
whitelist อักขระอนุญาต, CPU พุ่ง | ไม่มี | ไม่มี sandbox หรือ timeout (Part 11) |
รูปแบบสอดคล้องกันคือ แปลงความล้มเหลวให้เป็นข้อมูลที่ loop ใช้เหตุผลได้ และคงขอบเขตที่แข็งกร้าวไว้กับการวน สิ่งที่ตารางนี้ยังบอกอีกอย่างคือ Part 1 เป็นแค่โครง จากความกังวลจริงใน production แปดอย่าง มีหกอย่างถูกเลื่อนออกไปอย่างชัดเจน บทเรียนที่อ้างเป็นอย่างอื่นจะกำลังโกหกเรื่องความยากอยู่
ข้อแลกเปลี่ยน
| การตัดสินใจ | ทางเลือกอื่น | ทำไมเราถึงเลือกแบบนี้ | ต้นทุน |
|---|---|---|---|
| โมเดลปล่อยการตัดสินใจมีโครงสร้าง, loop เป็นคนรัน | ให้โมเดลเรียก functions ตรงๆ | มีที่เดียวไว้บังคับ permissions, logging, budgets | ต้อง parse และมี decision schema ที่เสถียร |
| errors ของ tool กลายเป็น messages | raise แล้วหยุด | โมเดลฟื้นตัวได้ใน step ถัดไป | โมเดลที่ติดหล่มอาจวนกับ error เดิม |
max_steps คงที่ |
ไม่จำกัด, ให้โมเดลหยุดเอง | รับประกันการจบ | งานยาวที่ชอบด้วยกฎถูกตัดกลางคัน |
| Scripted LLM หลัง interface | เรียก API จริงใน tests | deterministic, ออฟไลน์, เร็ว | ไม่ได้ทดสอบการ parse response จริง |
ข้าม message assistant สำหรับ tool calls |
ต่อทุก turn | context เล็กลง, ประวัติง่ายขึ้น | บาง providers คาดหวังโครงสร้าง turn เต็ม |
| standard library ไร้ dependency | ใช้ agent framework | ทุกบรรทัดมองเห็นและแก้ได้ | คุณต้องสร้างชิ้นส่วนที่ขาดเอง |
แถวสุดท้ายคือข้อแลกเปลี่ยนที่แท้จริงของซีรีส์นี้ทั้งหมด Frameworks ให้ retries, tracing และ memory ตั้งแต่วันแรก แต่มันก็ตัดสินเรื่องเหล่านั้นให้คุณด้วย การสร้างตั้งแต่ต้นใช้เวลา สิ่งที่ได้คืนคือคุณอธิบายพฤติกรรมทุกอย่างในระบบได้ สำหรับ agent ใน production นั่นมักคุ้มค่า
การทดสอบ
tests เหล่านี้ต้องการแค่ python3 บันทึกโค้ดข้างบนเป็น agent_loop.py และอันถัดไปเป็น test_agent_loop.py แล้วรัน python3 -m unittest test_agent_loop -v
import unittestfrom agent_loop import AgentLoop, ScriptedLLM, ToolResult, _calculate, build_tools
class TestAgentLoop(unittest.TestCase): def test_normal_path_returns_final_answer(self): script = [ {"type": "tool", "name": "search", "arguments": {"query": "agent loop"}}, {"type": "final", "content": "done"}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5) self.assertEqual(agent.run("q"), "done") self.assertEqual(len(agent.llm.calls), 2) self.assertTrue(any(m.role == "tool" for m in agent.llm.calls[1]))
def test_unknown_tool_does_not_crash(self): script = [ {"type": "tool", "name": "ghost", "arguments": {}}, {"type": "final", "content": "recovered"}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5) self.assertEqual(agent.run("q"), "recovered") self.assertIn("unknown tool", agent.llm.calls[1][-1].content)
def test_step_limit_is_enforced(self): script = [{"type": "tool", "name": "search", "arguments": {"query": "loop"}}] * 20 agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=3) self.assertEqual(agent.run("q"), "aborted: step limit reached") self.assertEqual(len(agent.trace), 3)
def test_malformed_arguments_are_normalised(self): script = [ {"type": "tool", "name": "calculate", "arguments": "not-a-dict"}, {"type": "final", "content": "handled"}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5) self.assertEqual(agent.run("q"), "handled")
def test_calculator_rejects_attribute_access(self): self.assertFalse(_calculate({"expression": "__import__('os')"}).ok) self.assertTrue(_calculate({"expression": "17 * (3 + 4)"}).ok) self.assertEqual(_calculate({"expression": "17 * (3 + 4)"}).data, "119")
if __name__ == "__main__": unittest.main()ห้า tests แต่ละตัวเล็ง guard หนึ่งตัวจากตารางความล้มเหลว ถ้า test_unknown_tool_does_not_crash ล้มเหลว แปลว่าเส้นทาง recovery พัง ถ้า test_step_limit_is_enforced ล้มเหลว แปลว่าคุณอาจมี loop ไม่รู้จบ นี่คือสองสมบัติที่ผมจะปฏิเสธไม่ยอมส่งขึ้นจริงถ้าไม่มี
แบบฝึกหัด
- เพิ่ม tool
finishแทนที่จะใช้ประเภทการตัดสินใจfinalจงทำให้การจบเป็น tool ชื่อfinishที่รับanswerstring แก้runให้การเรียกมันจบ loop แล้วอัปเดต tests ออกแบบไหนที่จำกัดด้วย schema ได้ง่ายกว่า? - ใส่ retry counter ถ้า tool เดียวกันถูกเรียกสามครั้งด้วย arguments เหมือนกันและประวัติไม่เปลี่ยนแปลงอย่างอื่น จง abort พร้อมข้อความเฉพาะ คุณต้องเก็บ state ตรงไหนใน loop และมันทำอะไรกับโครงสร้าง
trace? - สลับเป็น client จริง เขียน subclass ของ
LLMClientที่เรียก HTTP chat endpoint แล้วแปลงคำตอบแบบ function-calling ให้เป็นการตัดสินใจสองรูปแบบของเรา จงปล่อยAgentLoopไว้ไม่เปลี่ยน — ถ้าคุณต้องแก้มัน แสดงว่าขอบเขต interface ของคุณอยู่ผิดที่
แบบฝึกหัดข้อ 3 นี่แหละที่พิสูจน์สถาปัตยกรรม loop ไม่ควรสนใจว่าโมเดลตัวไหนเป็นคนให้การตัดสินใจ
ต่อไปคืออะไร
ตอนนี้คุณมี loop ที่จบได้ เรียก tools และฟื้นตัวจากการตัดสินใจที่แย่ มันก็มีช่องโหว่ชัดเจนเหมือนกัน: arguments ของ tool ไม่ถูกตรวจสอบ, errors เป็น strings ไร้โครงสร้าง และ tool ที่ล้มเหลวชั่วคราวไม่เคยถูก retry
Part 2, Agent tool contracts and structured errors แทนที่ Tool dataclass ที่หลวมด้วย contracts ที่ตรวจสอบแล้ว ได้แก่ argument schemas ที่เช็กก่อนรัน, หมวด error แบบมี type, retry policy ที่แยกความล้มเหลวชั่วคราวออกจากถาวร และ idempotency keys เพื่อให้ retry ไม่ทำให้ side effect ซ้ำ AgentLoop จากไฟล์นี้ยังอยู่ครบ — เราต่อยอดมัน ไม่ได้เขียนใหม่ นั่นแหละคือประเด็นของการสร้างขอบเขตก่อน
Get Ball — Ball
Get Ball