27%

1.1 Agentic Loops

Agentic Loops คืออะไร

Agentic Loop คือ pattern พื้นฐานที่สุดของ AI Agent — เป็นการที่ Claude ทำงานวนรอบ: รับ input → คิด → เรียก tool → ได้ผลลัพธ์ → คิดต่อ → เรียก tool อีก → … จนกว่าจะเสร็จ ต่างจากการเรียก API แบบ one-shot ที่ส่ง prompt ไปแล้วได้คำตอบกลับมาทันที Agentic Loop ให้ Claude ตัดสินใจเองว่าจะทำอะไรต่อ เรียก tool อะไร และหยุดเมื่อไหร่

หัวใจของ pattern นี้คือการใช้ Messages API ร่วมกับ tool_use — เมื่อ Claude ตอบกลับมาพร้อม stop_reason: "tool_use" แปลว่ามันอยากเรียก tool ซักตัว เราต้อง execute tool นั้นแล้วส่ง result กลับไปใน message ถัดไป วนแบบนี้จนกว่า Claude จะตอบ stop_reason: "end_turn" ซึ่งหมายความว่าเสร็จแล้ว

Pattern พื้นฐาน

import anthropic

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "หาข้อมูลสภาพอากาศวันนี้ แล้วสรุปให้"}]
tools = [...]  # tool definitions

while True:
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=4096,
        tools=tools,
        messages=messages
    )

    # เก็บ response ของ Claude เข้า messages
    messages.append({"role": "assistant", "content": response.content})

    # ถ้า Claude หยุดเอง → จบ loop
    if response.stop_reason == "end_turn":
        break

    # ถ้า Claude อยากใช้ tool → execute แล้วส่ง result กลับ
    if response.stop_reason == "tool_use":
        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                result = execute_tool(block.name, block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": result
                })
        messages.append({"role": "user", "content": tool_results})

Loop Termination Conditions

การหยุด loop มีหลายกรณี:

  • end_turn — Claude ตัดสินใจเองว่าเสร็จแล้ว ไม่ต้องเรียก tool อีก
  • max_tokens — ถึง limit ที่กำหนดใน request (output ถูกตัด กลางประโยค)
  • stop_sequence — เจอ stop sequence ที่กำหนดไว้ (custom termination)
  • Max iterations — เรากำหนด loop limit เอง เช่น ไม่เกิน 20 รอบ เพื่อป้องกัน infinite loop
MAX_ITERATIONS = 25

for i in range(MAX_ITERATIONS):
    response = client.messages.create(...)
    messages.append({"role": "assistant", "content": response.content})

    if response.stop_reason == "end_turn":
        break

    if response.stop_reason == "max_tokens":
        # Output ถูกตัด — อาจต้อง handle เป็น special case
        print("Warning: response truncated")
        break

    # ... handle tool_use ...
else:
    # Loop exhausted — agent ทำงานนานเกินไป
    print("Agent exceeded max iterations")

Key Concepts

  • Tool Use Block — เมื่อ Claude ต้องการเรียก tool จะ return content block type tool_use พร้อม id, name, และ input
  • Tool Result — เราต้องส่ง result กลับไปพร้อม tool_use_id ที่ตรงกัน เพื่อให้ Claude รู้ว่า result นี้เป็นของ tool call ไหน
  • Parallel Tool Use — Claude สามารถเรียกหลาย tools พร้อมกันใน turn เดียว (multiple tool_use blocks) เราต้อง execute ทั้งหมดแล้วส่ง results กลับไปทีเดียว
  • Token Budget — ทุก iteration ใช้ tokens ทั้ง input (messages สะสม) + output ต้องคำนึงถึง cost และ context window limit

เทคนิคขั้นสูง

Streaming Agentic Loop

ใช้ streaming เพื่อให้ user เห็น output ทีละนิดระหว่างที่ agent ทำงาน:

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=4096,
    tools=tools,
    messages=messages
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            if event.delta.type == "text_delta":
                print(event.delta.text, end="")
    response = stream.get_final_message()

Guardrails ใน Loop

เพิ่ม safety checks ในแต่ละ iteration:

  • Cost guard — track total tokens used, หยุดถ้าเกิน budget
  • Time guard — ตั้ง timeout สำหรับ total elapsed time
  • Action guard — filter tool calls ที่อันตราย (เช่น ลบไฟล์ important) ถามคนก่อน

Exam Tips

  • ข้อสอบมักถามเรื่อง stop_reason ว่าแต่ละค่าหมายถึงอะไร และควร handle อย่างไร
  • จำไว้ว่า max_tokens หมายถึง output ถูกตัด ไม่ใช่ว่า Claude เสร็จแล้ว
  • Parallel tool use — Claude อาจส่ง tool_use blocks หลายอันมาพร้อมกัน ต้อง execute ทุกอันแล้วส่ง results ทั้งหมดกลับไป
  • ควรมี max iteration limit เสมอ เพื่อป้องกัน infinite loop และ cost overrun
  • tool_use_id ต้องตรงกันระหว่าง request กับ response ไม่อย่างนั้น API จะ error