ข้ามไปที่เนื้อหา

Context engineering สำหรับ AI agent ระดับ production

Prompt engineering คือการเลือกคำให้ดีสำหรับ turn เดียว ส่วน context engineering กว้างกว่านั้น คือการคุมทุกอย่างที่ไหลเข้า context window ของ model ตลอดทั้งรอบที่ agent ทำงาน ทั้ง system prompt, tool definition, เอกสารที่ retrieve มา, conversation history, scratchpad note และ output ของ sub-agent Anthropic ตั้งชื่อเรื่องนี้ไว้เมื่อกันยายน 20251 เพราะเห็น agent ใน production ติดปัญหาเดิมซ้ำ ๆ คือ model ฉลาดพอแล้ว แต่ context ที่ป้อนให้ผิด

โพสต์นี้เล่าว่า context engineering คืออะไร มี 4 กลยุทธ์อะไรที่ใช้กันจริง เจอปัญหาแบบไหนบ้างตอนขึ้น production และ tool ตัวไหนเหมาะกับงานแต่ละแบบ

ทำไม prompt engineering อย่างเดียวไม่พอเมื่อเป็น agent

ถ้าเป็นงาน classification ครั้งเดียว หรือ chat แค่ turn เดียว prompt engineering ก็เอาอยู่ เขียน system prompt, test แล้ว ship ได้เลย model เห็นแค่สิ่งที่คุณเขียน output ก็ขึ้นกับสิ่งที่คุณเขียนล้วน ๆ

แต่ agent ไม่เป็นแบบนั้น Agent ที่วนอยู่ใน loop จะสร้างข้อมูลเพิ่มทุก turn:

  • Tool definition (function schema, MCP server, plugin manifest)
  • Tool result (เนื้อหาไฟล์, API response, ผล query)
  • เอกสารที่ retrieve มา (RAG chunk, ผลจาก knowledge base)
  • Conversation history (turn ก่อน ๆ, scratchpad note, output ของ sub-agent)
  • System state (task ที่ทำอยู่, plan, working memory)

Token พอกขึ้นทุก turn สุดท้ายก็จะเกิน context window ที่ model ใช้ได้จริง หรือต่อให้ยังไม่ชน limit model ก็เริ่มมองข้าม instruction ช่วงต้น ๆ ไปแล้ว อาการนี้เรียกว่า "lost in the middle" ข้อมูลของ Anthropic เองเรื่อง long-context recall บอกว่าคุณภาพเริ่มตกเมื่อเกิน ~50K token แม้แต่ Claude Sonnet 4.6 ก็หนีไม่พ้น1

Context engineering คือทางแก้ เป็นชุดกลยุทธ์ที่ใช้ตัดสินว่า อะไร จะเข้า context window, เข้า ตอนไหน และ มากแค่ไหน ให้ model ได้ข้อมูลที่ต้องใช้ตอบ turn นี้ให้ถูก ไม่ใช่โยนข้อความเก่ากองโตให้ไปคุ้ยหาเอง

4 กลยุทธ์หลัก

บทความของ Anthropic แบ่ง context engineering เป็น 4 operation1 ฟังดูเป็นระเบียบดี แต่ของจริงใน production วุ่นกว่านั้นเยอะ ผมจะไล่ทีละข้อ พร้อม tool ที่ใช้จริงและปัญหาที่แต่ละข้อแก้ได้

1. Write context: scratchpad, memory file, structured note

คืออะไร: agent เขียนข้อมูลเก็บไว้ข้างนอก แบบถาวรหรือกึ่งถาวรก็ได้ แล้วค่อยอ่านกลับมาใช้ทีหลัง ที่เก็บอาจเป็นไฟล์, vector DB, key-value cache หรือ structured note ใน conversation เองก็ได้

ใช้ตอนไหน: ตอนที่ข้อมูลที่ agent ต้องใช้ใหญ่เกินจะยัดไว้ใน context window ที่ใช้อยู่ หรือตอนที่ agent ต้องจำอะไรข้าม session

Production pattern — files-as-context:

# Agent scratchpad pattern
from pathlib import Path

class Scratchpad:
    def __init__(self, agent_id: str):
        self.path = Path(f"/tmp/agents/{agent_id}/notes.md")
        self.path.parent.mkdir(parents=True, exist_ok=True)

    def write(self, section: str, content: str):
        with self.path.open("a") as f:
            f.write(f"\n## {section}\n\n{content}\n")

    def read_recent(self, max_chars: int = 4000) -> str:
        if not self.path.exists():
            return ""
        text = self.path.read_text()
        return text[-max_chars:]  # last N chars

Agent อ่าน notes.md ทุกครั้งที่เริ่ม turn และจดสิ่งที่เจอลงไประหว่างทำงาน ต่อให้ conversation ยาวจนล้น context window ตัว scratchpad ก็ยังอยู่ turn ใหม่แค่ดึง note ล่าสุดขึ้นมาอ่าน

Production pattern — structured memory ใน LangGraph:

from langgraph.graph import StateGraph, MessagesState
from langgraph.checkpoint.postgres import PostgresSaver

# Persistent memory across turns + sessions
graph = StateGraph(MessagesState)
graph.add_node("agent", call_model)
graph.add_node("tools", tool_node)

DB_URI = "postgresql://user:pass@localhost:5432/agent_state"
checkpointer = PostgresSaver.from_conn_string(DB_URI)

app = graph.compile(checkpointer=checkpointer)

# Each thread_id maps to a persistent conversation
config = {"configurable": {"thread_id": "user-12345"}}
result = app.invoke({"messages": [...]}, config=config)

LangGraph 1.2.9 (2026-07-10)3 เก็บ message state ทั้งหมดไว้ใน Postgres Agent หยุดไว้ก่อน แล้วอีกหลายวันค่อยกลับมาทำต่อจากจุดเดิมได้เป๊ะ "context" อยู่ใน database ไม่ได้อยู่ใน model window

ปัญหาที่แก้ได้: agent ลืมว่าเมื่อ 30 นาทีก่อนทำอะไรค้างไว้ Write context เอา state ที่ต้องอยู่นานไปเก็บไว้นอก window

2. Select context: RAG, memory recall, just-in-time loading

คืออะไร: พอ agent ต้องใช้ข้อมูลที่ไม่มีใน context ตอนนี้ ก็ไปดึงมาจากที่เก็บที่ใหญ่กว่า เช่น vector database, SQL database, MCP server หรือ filesystem

ใช้ตอนไหน: ตอนที่ข้อมูลทั้งหมดใหญ่เกินจะใส่ context ได้ (database 10M row, เอกสาร 100K ชิ้น) หรือตอนที่ข้อมูลที่ agent ต้องใช้เปลี่ยนไปทุก turn

Production pattern — LlamaIndex retrieval:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.retrievers import QueryFusionRetriever

documents = SimpleDirectoryReader("docs/").load_data()
index = VectorStoreIndex.from_documents(documents)

# Hybrid retrieval: vector + BM25 + reranking
retriever = QueryFusionRetriever(
    retrievers=[
        index.as_retriever(similarity_top_k=10),
        index.as_retriever(similarity_top_k=10),  # second retriever for BM25
    ],
    num_queries=3,        # generate 3 query variants
    use_async=True,
    similarity_top_k=5,   # final top-k after fusion
)

nodes = retriever.retrieve("How does DRA migration work?")
context = "\n\n".join(n.get_content() for n in nodes)

LlamaIndex 0.14.23 (2026-06-24)4 จัดการ embedding, hybrid retrieval และ reranking ให้หมด Agent แค่เรียก retriever.retrieve(query) ก็ได้ 5 chunk ที่ตรงกับ turn นี้ที่สุดกลับมา ไม่ต้องแบกเอกสารทั้ง corpus

Production pattern — tool-based loading:

# MCP server as context source
tools = [
    {"name": "search_docs", "description": "Search internal documentation"},
    {"name": "query_database", "description": "Run SQL against the analytics DB"},
    {"name": "fetch_file", "description": "Read a file by path"},
]

Agent เรียก fetch_file หรือ query_database เฉพาะตอนที่ต้องใช้ สิ่งที่เข้า context มีแค่ tool result ไม่ใช่ทั้ง file system หรือทั้ง database

ปัญหาที่แก้ได้: ข้อมูลที่ agent ต้องใช้ใหญ่เกิน context หรือเพิ่งจะเกี่ยวข้องตอนนี้ ทั้งที่ 10 turn ก่อนยังไม่จำเป็น

3. Compress context: summarization, trimming, compaction

คืออะไร: ย่อ context ที่มีอยู่แล้วให้เล็กลง สรุป turn เก่า ๆ ทิ้ง tool result ที่หมดประโยชน์แล้ว แล้ว compact scratchpad ของ agent

ใช้ตอนไหน: ตอนที่ context โตจนใกล้ชน limit ของ window แต่ข้อมูลยังอาจได้ใช้อยู่ ทิ้งทั้งหมดก็ไม่ได้ เลยต้องย่อให้เล็กลงแทน

Production pattern — turn-level summarization:

from langchain_core.messages import HumanMessage, SystemMessage, RemoveMessage

def summarize_old_messages(state):
    messages = state["messages"]
    if len(messages) <= 10:
        return state  # nothing to compress yet

    # Keep last 6 verbatim, summarize the rest
    old = messages[:-6]
    recent = messages[-6:]

    summary_prompt = [
        SystemMessage(content="Summarize this conversation in 500 tokens or less. Preserve: decisions made, files touched, errors encountered, current task state."),
        HumanMessage(content="\n".join(m.content for m in old if isinstance(m.content, str)))
    ]
    summary = chat_model.invoke(summary_prompt)

    # Replace old messages with the summary
    return {"messages": [RemoveMessage(id=m.id) for m in old] + [
        SystemMessage(content=f"Earlier conversation summary: {summary.content}")
    ] + recent}

ตั้งให้รันทุก N turn (ทุก 10 หรือ 20 turn แล้วแต่ traffic) conversation history จะไม่โตเกินขอบเขต และ agent ก็ยังรู้ว่าก่อนหน้านี้เกิดอะไรขึ้นบ้าง

Production pattern — tool result trimming:

def trim_tool_results(messages, max_chars=2000):
    for msg in messages:
        if msg.type == "tool":
            content = msg.content if isinstance(msg.content, str) else str(msg.content)
            if len(content) > max_chars:
                msg.content = content[:max_chars] + f"\n... [{len(content)-max_chars} chars truncated]"
    return messages

Tool output ยาว ๆ อย่าง log file 50K บรรทัด หรือ JSON response 10MB ต้องตัดให้สั้นก่อนจะไปรก context ผลเต็มยังเก็บอยู่ใน tool execution store ส่วนที่ model เห็นเป็นแค่ฉบับย่อ

Production pattern — context caching ในแง่ compression:

Prompt caching ของ Anthropic ให้คุณ mark ส่วนที่ cache ได้2 ฝั่ง provider จะเก็บ prefix ส่วนนั้นไว้ข้ามการเรียก รอบถัดไปจ่ายเฉพาะ token ใหม่ที่เพิ่มเข้ามา ตรงนี้สิ่งที่ลดลงคือ ค่าใช้จ่าย ไม่ใช่จำนวน token context ยังขนาดเท่าเดิม แต่จ่ายแค่ครั้งเดียว ไม่ต้องจ่ายซ้ำทุกครั้งที่เรียก

ปัญหาที่แก้ได้: context อืดไปด้วยข้อมูลเก่าที่ agent ยังต้องอ้างถึงอยู่

4. Isolate context: sub-agent, scope, sandbox

คืออะไร: หั่นปัญหา context ก้อนใหญ่ออกเป็นหลาย context เล็ก ๆ ที่แยกขาดจากกัน sub-agent หรือ sub-task แต่ละตัวได้ context window ของตัวเอง แล้วส่งกลับไปให้ parent เฉพาะ output ที่จำเป็น

ใช้ตอนไหน: ตอนที่ context ก้อนเดียวรับทุกอย่างไม่ไหว หรือแต่ละส่วนของ task ต้องใช้ข้อมูลคนละแบบ (และไม่ต้องเห็นข้อมูลของส่วนอื่น)

Production pattern — multi-agent ด้วย LangGraph:

from langgraph.graph import StateGraph, Send
from typing import TypedDict

class ResearchState(TypedDict):
    query: str
    sub_results: list[str]
    final_answer: str

def dispatch_research(state):
    # Spawn 3 sub-agents, each with their own context
    return [
        Send("research_subagent", {"topic": "pricing", "query": state["query"]}),
        Send("research_subagent", {"topic": "features", "query": state["query"]}),
        Send("research_subagent", {"topic": "competitors", "query": state["query"]}),
    ]

def research_subagent(state):
    # Each sub-agent has its own ~50K-token context
    # It only sees its topic + the original query
    return {"sub_results": [run_research(state["topic"], state["query"])]}

def synthesize(state):
    # Parent only sees the 3 sub-results (~5K tokens)
    # Not the full research sub-agent contexts
    return {"final_answer": synthesize_results(state["sub_results"])}

graph = StateGraph(ResearchState)
graph.add_node("synthesize", synthesize)
graph.add_conditional_edges("synthesize", dispatch_research, ["research_subagent"])
graph.add_node("research_subagent", research_subagent)
graph.add_edge("research_subagent", "synthesize")
app = graph.compile()

research_subagent แต่ละตัวรันใน context window ของตัวเอง มี scratchpad, retrieval call และ tool result แยกกัน parent agent ไม่เคยเห็นข้างในของ sub-agent เลย เห็นแค่ summary สุดท้ายที่ส่งกลับมา Anthropic ก็อธิบาย multi-agent research ใน production agent ของตัวเองไว้แบบนี้1

Production pattern — context isolation ผ่าน MCP:

# Per-task MCP server scope
async with mcp_session("research-tools") as session:
    tools = await session.list_tools()
    # Only research tools are visible to this sub-agent
    result = await agent.run(query, tools=tools)

Agent เห็นเฉพาะ tool ที่โหลดไว้ใน MCP session ของตัวเอง sub-agent ฝั่ง finance ได้ finance tool ส่วน sub-agent ฝั่ง code ได้ code tool tool ของอีกฝั่งไม่อยู่ใน scope เลยไม่มีทางปนกัน

ปัญหาที่แก้ได้: task ทั้งก้อนใหญ่เกินกว่าจะอยู่ใน context window เดียวโดยที่ model ยังคิดต่อเนื่องได้

หน้าตาของปัญหาจริงใน production

พอใช้งานจริง สิ่งที่เจอบ่อยกว่าตัวกลยุทธ์คือ failure mode พวกนี้:

Lost-in-the-middle model รับ 80K token แต่ใส่ใจแค่ 20K แรกกับ 5K ท้าย อาการ: ลืม system prompt หรือลืม task ตั้งต้น วิธีแก้: ใช้ write context เก็บ state สำคัญไว้นอก window หรือ compress ให้หนักมือขึ้น

Tool result bloat tool call ครั้งเดียวได้ JSON กลับมา 50K อาการ: turn ถัด ๆ ไปช้าและแพง model หา field เดียวที่ต้องใช้ไม่เจอ วิธีแก้: trim tool result ให้หนักมือ หรือเขียนผลเต็มลงไฟล์แล้วส่งให้ model แค่ path

Retrieval pollution retriever คืนมา 10 chunk แต่ไม่เกี่ยวเลย 8 อัน อาการ: model hallucinate จาก context ที่มีแต่ noise วิธีแก้: ทำ retrieval ให้แม่นขึ้น (hybrid + reranking) ใช้ chunk เล็กลง หรือให้ model คัดกรองเองหลัง retrieve

Context thrashing ได้ context ใหม่ทีไร model ก็รื้อ plan ใหม่ทุก turn อาการ: agent วนไปวนมาไม่ไปไหน วิธีแก้: แยก context ของ planner ออกจาก context ของ executor planner ไม่จำเป็นต้องเห็นทุก tool result

Stale scratchpad agent จดอะไรไว้ใน note เมื่อ 50 turn ก่อน แต่ตอนนี้ข้อมูลนั้นผิดไปแล้ว อาการ: agent ทำงานตาม state ที่ตกยุค วิธีแก้: ใส่ timestamp ใน note สรุปใหม่เป็นระยะ หรือให้ agent เช็ก note ก่อนใช้

Cascading sub-agent sub-agent ทุกตัวส่ง output เต็ม ๆ กลับมาที่ parent จน window ของ parent ล้น อาการ: context ของ parent เต็มทั้งที่ทำ "isolation" ไว้แล้ว วิธีแก้: ให้ sub-agent ส่งกลับแค่ summary ไม่ใช่ transcript ทั้งหมด

Observability สำหรับ context engineering

วัดไม่ได้ก็แก้ไม่ได้ ถ้าจะทำ context engineering ใน production ต้อง log สิ่งเหล่านี้ทุก turn:

  • Token count — input token, output token, cache hit/miss
  • ส่วนผสมของ context — แต่ละส่วนมาจาก system prompt, tool, retrieval, history, scratchpad อย่างละเท่าไหร่
  • Retrieval stat — retrieve อะไรมาบ้าง และอันไหนได้ใช้จริงใน response
  • จำนวน tool call — แยกต่อ turn, ต่อ agent, ต่อ sub-agent
  • การ spawn sub-agent — spawn ตอนไหน เพราะอะไร กี่ตัว และส่งอะไรกลับมา

Langfuse 3.218.0 (2026-07-16)5 ทำได้ครบทุกข้อกับ LangChain และ LangGraph แบบไม่ต้อง config เพิ่ม ถ้าอยากได้ตัว open-source ก็มี OpenLLMetry กับ Arize Phoenix

ตัวอย่าง Langfuse instrumentation แบบสั้นที่สุด:

from langfuse import Langfuse
from langfuse.langchain import CallbackHandler

langfuse = Langfuse(
    public_key="pk-...",
    secret_key="sk-...",
    host="https://cloud.langfuse.com"
)

handler = CallbackHandler()

result = app.invoke(
    {"messages": [HumanMessage(content="Research DRA migration")]},
    config={
        "callbacks": [handler],
        "configurable": {"thread_id": "user-12345"}
    }
)

รันเสร็จแล้ว Langfuse จะแสดงส่วนผสมของ token, retrieval call, tool call และ latency แยกเป็นราย turn ดูตรงนี้แหละถึงจะรู้ว่า context ของ agent ยังปกติดี หรือเริ่มมีอาการ lost-in-the-middle ก่อตัวแล้ว

สิ่งที่ผมยังยืนยันไม่ได้

  • ตัวเลข token ที่ Claude Sonnet 4.6 / Opus 4.6 เริ่มจำ context ได้แย่ลง Anthropic ให้แนวทางไว้กว้าง ๆ ว่า recall เริ่มตกเมื่อเกิน ~50K token1 แต่จุดที่ร่วงจริงขึ้นกับ task และโครงสร้าง prompt
  • Reranking ดีกว่า vector search เปล่า ๆ ทุกกรณีหรือเปล่า reranking กินทั้ง latency และเงิน benchmark ที่เผยแพร่ (BEIR, TREC) ชี้ว่าช่วยได้กับ query สั้น ๆ แต่กับ query ยาวที่เจาะจงอาจแย่ลงหรือไม่ต่างกัน และ trade-off curve ก็ขึ้นกับ corpus ของคุณ
  • Token ที่ multi-agent ใช้จริงใน production Anthropic บอกว่า multi-agent research ใช้ token มากกว่า chat ปกติเยอะ ตัวเลขจาก research agent ของเขาเองอยู่ราว 4× แต่ตัวคูณนี้แปรผันตาม architecture และ task1 ถ้า design แตกงานไปให้ researcher หลายตัวทำแบบ parallel ตัวคูณอาจพุ่งสูงกว่านั้นมาก
  • การ scope MCP server แยกขาดได้จริงไหม MCP session แยกชื่อ tool ออกจากกันได้จริง แต่ state ที่อยู่นอก session (file system, network) ยังใช้ร่วมกันอยู่ ถ้าไม่ได้ทำ sandbox แยกไว้ชัด ๆ
  • คำแนะนำ "ให้ sub-agent ส่ง summary กลับ" ทุกคนแนะนำแบบนี้ แต่ผมยังหา benchmark ที่บอกว่า summary ควรยาวแค่ไหนเมื่อเทียบกับขนาด context ของ parent ไม่เจอ

Summary

  • Context engineering คือขั้นถัดจาก prompt engineering เป็นการคุมว่าอะไรจะเข้า model window ตลอดทั้งรอบที่ agent ทำงาน
  • 4 operation: write (scratchpad, memory), select (RAG, tool), compress (summarization, trimming), isolate (sub-agent, scope)
  • Failure mode: lost-in-the-middle, tool result bloat, retrieval pollution, context thrashing, stale scratchpad, cascading sub-agent
  • ต้องวัดผล token count, retrieval stat, จำนวน tool call, การ spawn sub-agent ถ้าไม่มี observability ก็เท่ากับจูนแบบปิดตา
  • Tooling ปี 2026: LangGraph 1.2.9 สำหรับ graph state, LlamaIndex 0.14.23 สำหรับ retrieval, Langfuse 3.218.0 สำหรับ observability และ prompt caching ของ Anthropic ช่วยลดค่าใช้จ่ายเมื่อ prefix ซ้ำกัน

จาก "เขียน prompt ให้ดี" มาเป็น "จัดการ context ให้ดี" นี่แหละคือเส้นแบ่งระหว่าง demo กับ agent ที่ขึ้น production ได้ และ 4 operation นี้คือเครื่องมือที่ใช้ข้ามเส้นนั้น


มีคำถามหรืออยากคุยต่อ? ติดต่อผมได้ทาง LinkedIn, X หรือ email


  1. Anthropic Engineering, "Effective context engineering for AI agents" (29 ก.ย. 2025), https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents ↩↩↩↩↩↩

  2. Anthropic, "Prompt caching," https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching ↩

  3. LangGraph v1.2.9 (2026-07-10), https://github.com/langchain-ai/langgraph/releases ↩

  4. LlamaIndex v0.14.23 (2026-06-24), https://github.com/run-llama/llama_index/releases ↩

  5. Langfuse v3.218.0 (2026-07-16), https://github.com/langfuse/langfuse/releases ↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.