<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="/feed.xml" rel="self" type="application/atom+xml" /><link href="/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-04-14T22:08:57+07:00</updated><id>/feed.xml</id><title type="html">Engineering &amp;amp; AI the Right Way</title><subtitle>Exploring thoughtful approaches to building resilient engineering systems and using artificial intelligence professionally.</subtitle><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><entry xml:lang="vi"><title type="html">Agent Stack 2026: Layers, Harness, và Cách Bạn Build</title><link href="/vi/agent-khong-con-la-code/" rel="alternate" type="text/html" title="Agent Stack 2026: Layers, Harness, và Cách Bạn Build" /><published>2026-04-12T00:00:00+07:00</published><updated>2026-04-12T00:00:00+07:00</updated><id>/vi/agent-khong-con-la-code-vi</id><content type="html" xml:base="/vi/agent-khong-con-la-code/"><![CDATA[<h1 id="agent-stack-2026-layers-harness-và-cách-bạn-build">Agent Stack 2026: Layers, Harness, và Cách Bạn Build</h1>

<hr />

<p>Đầu tháng 4/2026, hai bản phát hành xuất hiện cách nhau vài tuần và kéo theo nhiều ý kiến mạnh: <a href="https://www.anthropic.com/engineering/managed-agents">Claude Managed Agents</a> của Anthropic (bản thử nghiệm công khai, ngày 8/4) và <a href="https://blog.langchain.com/deep-agents-deploy-an-open-alternative-to-claude-managed-agents/">Deep Agents Deploy</a> của LangChain. Một số người gọi đây là “sự thay đổi căn bản” trong phát triển agent. Số khác thì hoài nghi hơn.</p>

<p>Trước khi tranh luận theo hướng nào, đáng để lùi lại và hỏi một câu đơn giản hơn: <strong>một agent AI đang chạy thật hiện nay có bao nhiêu layers?</strong> Và hai nền tảng mới này đang nằm ở đâu trong cái stack đó?</p>

<p>Bài này sẽ vẽ lại bản đồ các layers đó — bao gồm cả những gì nghiên cứu của chính Anthropic nói về độ phức tạp kiến trúc — và cố gắng phân tích thực tế cái gì đã thay đổi và cái gì thì không.</p>

<hr />

<h2 id="framework-của-chính-anthropic-ba-levels-phức-tạp">Framework Của Chính Anthropic: Ba Levels Phức Tạp</h2>

<p>Trước khi phát hành Managed Agents, Anthropic đã công bố <a href="https://www.anthropic.com/research/building-effective-agents">“Building Effective Agents”</a> — một hướng dẫn thực hành mô tả rõ ràng sự tiến triển của độ phức tạp kiến trúc:</p>

<p><strong>Level 1: Augmented LLM</strong>
Nền tảng. Một LLM duy nhất được bổ sung khả năng truy xuất dữ liệu, công cụ, và memory. Hầu hết agent đang hoạt động tốt đều ở đây — một model được hướng dẫn đúng với bộ tool phù hợp thường là đủ, và khó mà đơn giản hơn được.</p>

<p><strong>Level 2: Predefined Workflows</strong>
Các processing pipeline được định nghĩa trước, điều phối LLM và công cụ. Anthropic mô tả năm pattern:</p>
<ul>
  <li><em>Prompt chaining</em> — gọi lần lượt, mỗi bước xử lý kết quả của bước trước</li>
  <li><em>Routing</em> — phân loại đầu vào và chuyển đến bộ xử lý chuyên biệt</li>
  <li><em>Parallelization</em> — chia các tác vụ con độc lập hoặc chạy nhiều model để vote</li>
  <li><em>Orchestrator-workers</em> — một LLM trung tâm phân công linh hoạt cho các thành phần con</li>
  <li><em>Evaluator-optimizer</em> — loop cải tiến giữa generator và evaluator</li>
</ul>

<p><strong>Level 3: Agent tự chủ</strong>
Hệ thống mà LLM tự quyết định quy trình và cách dùng tool của chính mình. LLM tự quyết định bước tiếp theo, không phải theo pipeline định sẵn.</p>

<p>Nguyên tắc cốt lõi Anthropic nhấn mạnh: <strong>bắt đầu ở lowest level còn hoạt động được và chỉ thêm phức tạp khi hiệu quả cải thiện đo được.</strong> Nguyên tắc này cần nhớ khi đánh giá những platform mới mặc định chọn kiến trúc “agent đầy đủ”.</p>

<hr />

<h2 id="stack-hiện-tại-một-spectrum-từ-low-đến-high">Stack Hiện Tại: Một Spectrum Từ Low Đến High</h2>

<p><em>(Phần dưới là một mô hình tư duy để phân tích hệ sinh thái — không phải phân loại chính thức hay tiêu chuẩn ngành đã được xác nhận. Các “layer” này không có ranh giới rõ ràng; chúng là các vị trí trên một spectrum từ “tự viết nhiều” đến “chỉ cần cấu hình”.)</em></p>

<p>Hãy hình dung như một dial: từ “viết mọi thứ bằng code” đến “chỉ mô tả agent là gì”:</p>

<p><strong>Lowest — Tự viết toàn bộ orchestration</strong></p>

<p>Bạn gọi LLM API trực tiếp, tự nối tool execution, tự quản lý state, tự xử lý retry. Mọi quyết định về routing, memory, error handling đều nằm trong code bạn viết và bạn chịu trách nhiệm.</p>

<p><em>Công cụ: LangGraph, Claude Agent SDK, API gốc của Anthropic/OpenAI</em></p>

<p><em>Ví dụ: Bạn tự viết đồ thị LangGraph bằng Python — các nút cho từng bước, các cạnh cho routing, quản lý state tường minh. Toàn quyền kiểm soát, toàn bộ trách nhiệm.</em></p>

<p><strong>Middle — Framework lo phần infrastructure</strong></p>

<p>Framework cung cấp các abstraction layer (agent, chain, memory) và quản lý loop gọi LLM. Bạn tập trung vào cấu hình tool và logic của agent, không phải raw API. Vẫn nặng code, nhưng có guardrail.</p>

<p><em>Ví dụ: LangChain agents với memory tích hợp và abstraction layer cho tool. Bạn viết chain và tool; framework lo orchestration.</em></p>

<p><strong>Higher — Platform lo deploy và vận hành</strong></p>

<p>Bạn mô tả <em>agent là ai</em> — vai trò, kỹ năng, kiến thức — trong các file có cấu trúc. Platform tự lo deploy, memory, sandbox, credential isolation, và multi-protocol support. Thứ từng mất một tuần để dựng nay chỉ là một lệnh.</p>

<p><em>Ví dụ (Deep Agents Deploy): Bạn viết <code class="language-plaintext highlighter-rouge">AGENTS.md</code> (danh tính và hành vi bằng markdown thuần) và các file <code class="language-plaintext highlighter-rouge">SKILL.md</code> (kiến thức chuyên môn nạp theo yêu cầu). Chạy <code class="language-plaintext highlighter-rouge">deepagents deploy</code>. Platform lo toàn bộ memory, sandbox, và server MCP + A2A + Agent Protocol.</em></p>

<p><em>Ví dụ (Claude Managed Agents): Bạn cấu hình agent làm gì. Infrastructure của Anthropic tách Brain (Claude + controller logic) khỏi Hands (môi trường thực thi tạm thời, không truy cập được credential). Một append-only session log đóng vai trò persistent external memory — nếu Brain gặp sự cố giữa chừng, instance mới tiếp tục từ event cuối.</em></p>

<p><strong>Highest — Chỉ cần system prompt, không cần infrastructure</strong></p>

<p>Model được hướng dẫn tốt với bộ tool phù hợp. Không custom orchestration, không deployment pipeline — chỉ system prompt và danh sách tool.</p>

<p><em>Ví dụ: Một phiên Claude với search và code interpreter. Được hướng dẫn kỹ, phạm vi rõ ràng, dễ debug.</em></p>

<hr />

<p>Hai bản phát hành tháng 4 — Managed Agents và Deep Agents Deploy — nằm ở vùng “higher” trên spectrum này. Chúng không loại bỏ code hoàn toàn. Nhưng chúng kéo một phần lớn công việc (memory management, credential isolation, multi-protocol support, sandbox) ra khỏi application code và đưa vào platform infrastructure.</p>

<p>Trước 2026, build tương đương “sandbox có credential isolation + append-only session log + MCP/A2A/Agent Protocol server” sẽ mất khoảng một tuần dựng infrastructure. Các platform này biến điều đó thành mặc định.</p>

<hr />

<h2 id="managed-agents-và-deep-agents-deploy-thực-sự-cung-cấp-gì">Managed Agents và Deep Agents Deploy Thực Sự Cung Cấp Gì</h2>

<p>Cả hai platform đồng thuận về một điểm chung về kiến trúc: <strong>danh tính và năng lực của agent phải tách biệt khỏi execution infrastructure</strong>.</p>

<p><strong>Deep Agents Deploy của LangChain</strong> hiện thực hóa điều này qua các open standards:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">AGENTS.md</code> — agent là ai, hành xử thế nào, biết gì. Markdown thuần.</li>
  <li>Các file <code class="language-plaintext highlighter-rouge">SKILL.md</code> — kiến thức chuyên môn dạng module, nạp theo yêu cầu, giảm token tiêu thụ trong khi mở rộng năng lực.</li>
</ul>

<p>Chạy <code class="language-plaintext highlighter-rouge">deepagents deploy</code>, framework xử lý memory (lưu trên filesystem, theo từng session), sandbox (Daytona, Runloop, Modal), và production server với MCP + A2A + Agent Protocol.</p>

<p><strong>Managed Agents của Anthropic</strong> đi xa hơn ở tầng infrastructure:</p>
<ul>
  <li><strong>Brain</strong> — Claude + controller logic. Stateless, thay thế được.</li>
  <li><strong>Hands</strong> — container tạm thời dùng một lần để tool chạy. Không truy cập được credential.</li>
  <li><strong>Session</strong> — append-only event log, chính là external memory của agent. Nếu Brain gặp sự cố, instance mới tiếp tục từ event cuối.</li>
</ul>

<p>Giá: $0.08/giờ-session cộng chi phí token. Bạn đang trả cho thời gian chạy, không phải infrastructure.</p>

<p>Cả hai platform đều thật và kiến trúc đều nhất quán. Câu hỏi là liệu chúng có phải tool đúng cho một bài toán cụ thể hay không — và câu trả lời trung thực phụ thuộc vào cái bạn đang build.</p>

<hr />

<h2 id="anthropic-về-độ-phức-tạp-của-harness-đừng-over-engineer">Anthropic Về Độ Phức Tạp Của Harness: Đừng Over-engineer</h2>

<p>Song song với bản phát hành Managed Agents, Anthropic Engineering blog đăng <a href="https://www.anthropic.com/engineering/harness-design-long-running-apps">“Harness Design for Long-Running Application Development”</a> — mô tả chi tiết cách họ build một harness ba agent để sinh ứng dụng hoàn chỉnh:</p>

<ul>
  <li><strong>Planner</strong>: Chuyển chỉ dẫn ngắn của người dùng thành đặc tả sản phẩm chi tiết</li>
  <li><strong>Executor</strong>: Implement tính năng từng bước (React, Vite, FastAPI, SQLite)</li>
  <li><strong>Evaluator</strong>: Kiểm thử qua Playwright, chấm theo tiêu chí, cung cấp phản hồi cho loop tiếp theo</li>
</ul>

<p>Loop Plan/Execute/Evaluate cho kết quả tốt — nhưng phát hiện thú vị hơn là những gì xảy ra khi underlying model cải thiện từ Claude Opus 4.5 lên 4.6.</p>

<blockquote>
  <p><em>“Mỗi thành phần trong một harness đều ẩn chứa một giả định về những gì model không thể tự làm, và những giả định đó đáng được kiểm tra lại.”</em></p>
</blockquote>

<p>Khi Claude 4.6 xử lý tốt hơn với các tác vụ dài liền mạch, Anthropic đã đơn giản hóa harness: bỏ phân chia theo giai đoạn ngắn, chuyển đánh giá từ per-phase sang end-of-run. Orchestration trở nên ít phức tạp hơn, chứ không phải phức tạp thêm — vì model đã có thể xử lý nhiều hơn trực tiếp.</p>

<p>Nguyên tắc thứ hai: <em>“tìm giải pháp đơn giản nhất có thể, và chỉ tăng phức tạp khi cần thiết.”</em></p>

<p>Điều này cắt cả hai chiều. Đây là cảnh báo chống việc vội vàng dùng harness cũng như chống việc tự over-engineer orchestration. Nếu bài toán phù hợp với một agent đơn được hướng dẫn tốt (Level 1), thêm Workflow patterns hay harness platform đầy đủ thường là chi phí phát sinh, không phải giá trị.</p>

<hr />

<h2 id="những-đánh-đổi-thực-sự">Những Đánh Đổi Thực Sự</h2>

<p><strong>Các harness platform làm dễ dàng hơn những gì:</strong></p>
<ul>
  <li>Credential isolation và sandbox security mặc định — không cần tự thiết kế</li>
  <li>Multi-protocol support (MCP, A2A, Agent Protocol) không cần tự tích hợp</li>
  <li>Deploy một agent chạy được trong một ngày thay vì một tuần dựng infrastructure</li>
  <li>File định nghĩa agent mà người không viết code cũng đọc và sửa được</li>
  <li>Memory management mà không cần chọn và cấu hình vector store</li>
</ul>

<p><strong>Những gì chúng làm khó hơn hoặc tạo ra như trade-off mới:</strong></p>
<ul>
  <li>Custom routing logic không khớp với execution model của platform</li>
  <li>Kiểm soát chi tiết thời điểm và cách memory được ghi hoặc đọc</li>
  <li>Debug: append-only session log tốt cho recovery, kém trực quan hơn khi inspect</li>
  <li>Vendor lock-in — Managed Agents là infrastructure chỉ dành cho Claude</li>
  <li>Dự đoán chi phí ở quy mô lớn: $0.08/giờ-session rẻ cho đến khi bạn chạy nhiều long-lived agent</li>
  <li>Open question: các default của platform có khớp với nhu cầu thực của agent bạn không</li>
</ul>

<p><strong>Deep Agents Deploy</strong> xử lý vấn đề portability tốt hơn Managed Agents: chạy trên bất kỳ model nào (OpenAI, Anthropic, Google, Ollama), deploy self-hosted hoặc cloud, và định dạng <code class="language-plaintext highlighter-rouge">AGENTS.md</code>/<code class="language-plaintext highlighter-rouge">SKILL.md</code> được cấp phép MIT. Chi phí chuyển đổi thấp. Managed Agents cung cấp tích hợp infrastructure chặt hơn với giá là vendor lock-in.</p>

<hr />

<h2 id="tại-sao-bảo-mật-là-động-lực-thực-sự">Tại Sao Bảo Mật Là Động Lực Thực Sự</h2>

<p>Một lý do cụ thể sự dịch chuyển này xảy ra không phải mang tính triết lý — mà là bảo mật thiết thực.</p>

<p>Trong thiết kế gắn chặt, code mà agent sinh ra hoặc thực thi chạy trong cùng process space với credential. Một cuộc tấn công prompt injection thành công trong kịch bản đó không chỉ compromise một task — mà có thể phơi bày mọi thứ agent đó có quyền truy cập.</p>

<p>Credential isolation giải quyết điều này trực tiếp. Đây không phải khái niệm mới: service mesh, secret manager như Vault, per-service IAM role đã áp dụng nguyên tắc này từ lâu. Pattern rất rõ ràng — giới hạn những gì một execution context cụ thể có thể tiếp cận.</p>

<p>Sự tách biệt Brain/Hands của Managed Agents áp dụng nguyên tắc này vào kiến trúc agent: sandbox nơi code sinh ra chạy không truy cập được authentication token. Deep Agents Deploy thực thi sự cách ly tương tự thông qua environment provider abstraction layer.</p>

<p>Bạn hoàn toàn có thể đạt mức isolation tương tự khi tự build harness — pattern thuộc về kiến trúc, không phải độc quyền. Các team đã quan tâm đến security trong infrastructure của mình thường đã làm điều này rồi. Sự khác biệt nằm ở cách đóng gói: các harness platform biến credential isolation thành mặc định thay vì một quyết định thiết kế cần chủ động thực hiện. Đó là lợi ích tiện lợi thực sự, không phải tuyên bố rằng hệ thống tự build kém secure hơn.</p>

<p>Trade-off trung thực hơn: tự build harness thì có toàn quyền kiểm soát security model, đổi lại là công sức thiết kế và duy trì nó. Dùng harness platform thì có một bộ default đã được kiểm thử, đổi lại là phụ thuộc vào các security assumption của platform. Không cái nào tốt hơn tuyệt đối — chúng là những lựa chọn khác nhau về việc đầu tư công sức vào đâu.</p>

<hr />

<h2 id="openclaw-khi-định-nghĩa-agent-ở-context-layer-không-đi-kèm-infrastructure-bảo-mật">OpenClaw: Khi Định Nghĩa Agent Ở Context Layer Không Đi Kèm Infrastructure Bảo Mật</h2>

<p>Cả Managed Agents lẫn Deep Agents Deploy đều chia sẻ một concept cốt lõi: định nghĩa agent ở context layer — danh tính, kỹ năng, kiến thức trong các file có cấu trúc, không phải trong code. OpenClaw, một agent framework do cộng đồng phát triển, đã đến cùng nhận định kiến trúc này theo con đường riêng.</p>

<p>OpenClaw định nghĩa agent theo cùng cách: một agent là danh tính cộng với tập kỹ năng tải từ ClawHub — kho kỹ năng cộng đồng của nó. Concept ánh xạ trực tiếp vào <code class="language-plaintext highlighter-rouge">AGENTS.md</code> + <code class="language-plaintext highlighter-rouge">SKILL.md</code> hay cấu hình Brain của Managed Agents. Cùng ý tưởng, khác execution context.</p>

<p>Điểm khác biệt nằm ở những gì đi kèm — hoặc chính xác hơn, những gì không đi kèm.</p>

<p>Tháng 2/2026, một cuộc tấn công supply chain nhắm vào ClawHub (gọi là “ClawHavoc”) được tiết lộ. Kẻ tấn công đã compromise 12 tài khoản publisher và đăng tải 1.184 skill độc hại. Một khi được nạp vào context của agent, các skill này có thể leak credential, redirect tool call, hoặc làm nhiễm reasoning của agent. Cuộc tấn công đã hoạt động trong một khoảng thời gian chưa xác định trước khi bị phát hiện.</p>

<p>Nghiên cứu bảo mật từ Snyk củng cố thêm quy mô của vấn đề: báo cáo ToxicSkills phát hiện 36,8% skill trên ClawHub có lỗ hổng ở dạng nào đó, với 13,4% được đánh giá ở mức critical.</p>

<p>Đây không phải là phê phán concept kiến trúc của OpenClaw — ý tưởng định nghĩa agent ở context layer là đúng đắn. Đây là bằng chứng về những gì concept đó cần để khả thi trong môi trường production: một trust model cho skill supply chain, credential isolation để skill được nạp không thể truy cập authentication token, và audit infrastructure ghi lại skill nào đã chạy và khi nào.</p>

<p>So sánh giữa ba cách tiếp cận:</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Mô hình supply chain</th>
      <th>Credential isolation</th>
      <th>Nguồn skill</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>OpenClaw</strong></td>
      <td>Registry cộng đồng mở (ClawHub)</td>
      <td>Không bắt buộc</td>
      <td>Tải lúc runtime từ publisher chưa kiểm tra</td>
    </tr>
    <tr>
      <td><strong>Deep Agents Deploy</strong></td>
      <td>File bạn kiểm soát</td>
      <td>Sandbox abstraction layer</td>
      <td>File <code class="language-plaintext highlighter-rouge">SKILL.md</code> cục bộ</td>
    </tr>
    <tr>
      <td><strong>Managed Agents</strong></td>
      <td>Platform kiểm soát, đóng</td>
      <td>Tách Brain/Hands theo thiết kế</td>
      <td>Cấu hình trong platform</td>
    </tr>
  </tbody>
</table>

<p>ClawHavoc là căn cứ thực tế hữu ích cho phần bảo mật ở trên: định nghĩa agent ở context layer không phải rủi ro bảo mật tự thân. Rủi ro là nạp skill từ unverified community registry vào execution context có quyền truy cập credential. Pattern kiến trúc tách biệt với sự cố bảo mật — nhưng chỉ khi infrastructure bên dưới nó xử lý nghiêm túc mối đe dọa đó.</p>

<hr />

<h2 id="agentos-layer-nghiên-cứu-đang-hình-thành">AgentOS: Layer Nghiên Cứu Đang Hình Thành</h2>

<p>Cả giới học thuật lẫn ngành công nghiệp đều đang hội tụ về cùng một bộ thành phần cơ bản, dù gọi tên khác nhau.</p>

<p><strong>AIOS</strong> (Đại học Rutgers, COLM 2025) là hiện thực hóa có bình duyệt đầu tiên của cái thực chất là “hệ điều hành cho agent”:</p>

<ul>
  <li>Agent Scheduler, Context Manager, Memory Manager, Storage Manager, Tool Manager, Access Manager</li>
</ul>

<p>Ánh xạ điều này vào Managed Agents: Brain ≈ Agent Scheduler + Context Manager. Session ≈ Memory Manager + Storage Manager. Hands ≈ Tool Manager + Access Manager. Sự hội tụ này không phải ngẫu nhiên — hai con đường nghiên cứu và industry riêng biệt đến cùng nhận định kiến trúc vì họ đang giải cùng bài toán quản lý tài nguyên.</p>

<p>AIOS cho thấy tốc độ thực thi nhanh hơn 2.1 lần khi phục vụ nhiều agent so với cách tiếp cận thông thường — các thành phần cơ bản có tác động thực sự đến performance.</p>

<p><strong>Hội thảo AgenticOS 2026</strong> (tổ chức cùng ASPLOS 2026) cho thấy giới học thuật đang coi đây là nghiên cứu hệ thống nghiêm túc: OS-level mechanism cho AI agent workload, isolation model, scheduling technique. Cùng mức độ nghiêm ngặt đã tạo ra virtual memory và process scheduling nay được áp dụng vào agent infrastructure.</p>

<hr />

<h2 id="build-ở-layer-nào">Build Ở Layer Nào?</h2>

<p>Câu hỏi này thực ra tách làm hai — và rất dễ bị nhầm lẫn với nhau:</p>

<p><strong>Câu hỏi 1: Dùng tool/platform nào?</strong> (vị trí trên spectrum)</p>

<p><strong>Dùng low-level framework (LangGraph / Claude Agent SDK) khi:</strong></p>
<ul>
  <li>Routing logic của bạn thực sự mới lạ hoặc đặc thù theo domain</li>
  <li>Cần kiểm soát chặt state transition — quy trình tài chính, yêu cầu audit</li>
  <li>Bạn đang build infrastructure mà người khác sẽ deploy agent lên trên</li>
  <li>Bạn đang nghiên cứu kiến trúc agent, không phải ship sản phẩm</li>
</ul>

<p><strong>Dùng managed platform (Managed Agents / Deep Agents Deploy) khi:</strong></p>
<ul>
  <li>Deploy agent với mục đích cụ thể, rõ ràng</li>
  <li>Security và credential isolation là yêu cầu bắt buộc, không phải nice-to-have</li>
  <li>Cần multi-protocol support mà không cần tự tích hợp</li>
  <li>Bottleneck của team là deployment và operations, không phải thiết kế agent reasoning</li>
  <li>Muốn định nghĩa agent mà người không viết code cũng đọc và sửa được</li>
</ul>

<p><strong>Câu hỏi 2: Agent thực sự cần bao nhiêu orchestration?</strong> (3 levels của Anthropic — một trục riêng biệt)</p>

<p>Sự tiến triển của Anthropic — Augmented LLM → Workflows → Agent tự chủ — mô tả <em>độ phức tạp</em> của agent, không phải lựa chọn platform. Một managed platform hoàn toàn có thể chạy một agent Level 1. Một custom LangGraph harness hoàn toàn có thể implement các pattern Level 3. Hai trục này độc lập với nhau.</p>

<p>Câu trả lời mặc định trên trục này: <strong>bắt đầu ở Level 1 và chỉ tăng phức tạp khi có thể đo được cải thiện.</strong> Hầu hết các bài toán tưởng như cần multi-agent workflow thực ra có thể giải bởi một model đơn được hướng dẫn tốt với bộ tool đúng. Thêm Workflow patterns Level 2 hay điều khiển tự chủ Level 3 chỉ đáng khi hiệu quả cải thiện đo được — bất kể bạn đang dùng platform nào.</p>

<p><strong>Trường hợp thú vị nhất là kết hợp:</strong> custom execution logic trên LangGraph, phía trước là deployment format tương thích harness. Deep Agents Deploy đã hỗ trợ điều này — <code class="language-plaintext highlighter-rouge">deepagents deploy</code> có thể đặt trước một custom LangGraph backend trong khi vẫn cung cấp các standard endpoint và memory management. Bạn có opinionated deployment mà không mất quyền kiểm soát orchestration.</p>

<hr />

<h2 id="những-thứ-không-thay-đổi">Những Thứ Không Thay Đổi</h2>

<p>Vài điều vẫn đúng bất kể bạn build ở layer nào:</p>

<p><strong>Chất lượng model vẫn chi phối.</strong> Brain vẫn là Claude. Harness thiết kế tốt trên model yếu vẫn thua harness thiết kế kém trên model mạnh. Harness nhân lên những gì model có thể làm — không thay thế những gì model không biết.</p>

<p><strong>Task decomposition vẫn quan trọng.</strong> Không platform nào tự động xử lý được task mơ hồ hoặc thiếu thông tin. Instruction cho agent vẫn cần rõ ràng về what done looks like. <code class="language-plaintext highlighter-rouge">AGENTS.md</code> chỉ hữu ích như cái suy nghĩ đã đi vào việc viết nó.</p>

<p><strong>Evaluation vẫn là việc của bạn.</strong> Managed Agents sinh session log. Deep Agents tích hợp LangSmith. Nhưng quyết định agent có làm đúng không — và chẩn đoán silent failures — vẫn là trách nhiệm của bạn.</p>

<p><strong>Độ phức tạp harness nên theo sát năng lực model.</strong> Như công trình kỹ thuật harness của chính Anthropic cho thấy: khi model cải thiện, phản ứng đúng thường là đơn giản hóa harness, không phải giữ nguyên các ràng buộc cũ.</p>

<hr />

<h2 id="bức-tranh-lớn-hơn">Bức Tranh Lớn Hơn</h2>

<p>Hệ sinh thái agent đang phân tầng thành các layer riêng biệt — đây là dấu hiệu trưởng thành, giống cách web infrastructure phân tầng từ raw TCP thành HTTP, rồi web framework, rồi deployment platform.</p>

<p>Low-level framework (LangGraph, Claude Agent SDK) không bị thay thế. Chúng đang trở thành nền tảng mà các harness platform chạy lên trên — cách TCP/IP không biến mất khi HTTP xuất hiện. Nhưng với hầu hết product deployment, câu hỏi ngày càng là: bài toán của tôi thuộc layer nào trong stack này?</p>

<p>Managed Agents và Deep Agents Deploy là các platform thật với giá trị thật cho các use case cụ thể. Chúng cũng còn mới, có vendor lock-in theo những cách khác nhau, và thêm ràng buộc mà một số workload sẽ không muốn. Đó là trade-off bình thường, không phải phát hiện mang tính cách mạng.</p>

<p>Điều đáng ghi nhớ hơn từ cả hai bản phát hành, và từ nghiên cứu kỹ thuật harness của Anthropic, là về kiến trúc: <strong>danh tính và năng lực của agent thuộc về một portable definition layer, dễ đọc; execution, memory, security, và deployment machinery thuộc về infrastructure bên dưới nó.</strong> Dù bạn đến đó qua managed platform hay tự build, sự phân tách đó là đáng hướng tới.</p>

<hr />

<p><em>Nguồn:</em></p>

<ul>
  <li><a href="https://www.anthropic.com/engineering/managed-agents">Scaling Managed Agents: Decoupling the brain from the hands — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/engineering/harness-design-long-running-apps">Harness Design for Long-Running Application Development — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents">Effective Harnesses for Long-Running Agents — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/research/building-effective-agents">Building Effective Agents — Anthropic Research</a></li>
  <li><a href="https://blog.langchain.com/deep-agents-deploy-an-open-alternative-to-claude-managed-agents/">Deep Agents Deploy: an open alternative to Claude Managed Agents — LangChain Blog</a></li>
  <li><a href="https://martinfowler.com/articles/exploring-gen-ai/harness-engineering.html">Harness engineering for coding agent users — Martin Fowler</a></li>
  <li><a href="https://martinfowler.com/articles/exploring-gen-ai/harness-engineering-memo.html">Harness Engineering: first thoughts — Martin Fowler</a></li>
  <li><a href="https://openai.com/index/harness-engineering/">Harness Engineering — OpenAI</a></li>
  <li><a href="https://arxiv.org/abs/2403.16971">AIOS: LLM Agent Operating System — arXiv</a></li>
  <li><a href="https://os-for-agent.github.io/">AgenticOS 2026 Workshop — os-for-agent.github.io</a></li>
  <li><a href="https://aakashgupta.medium.com/2025-was-agents-2026-is-agent-harnesses-heres-why-that-changes-everything-073e9877655e">2025 Was Agents. 2026 Is Agent Harnesses — Aakash Gupta, Medium</a></li>
</ul>

<hr />

<p><em>Nếu bài viết có ích, kết nối với mình trên <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> hoặc xem thêm các project tại <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[Hai nền tảng mới định nghĩa lại cách build và deploy agent — nhưng trước khi đưa ra nhận định, đáng để xem một agent đang chạy thật có bao nhiêu layers, và nghiên cứu của chính Anthropic nói gì về độ phức tạp của harness.]]></summary></entry><entry xml:lang="en"><title type="html">The Agent Stack in 2026: Layers, Harnesses, and Where You Actually Build</title><link href="/agents-are-not-code-anymore/" rel="alternate" type="text/html" title="The Agent Stack in 2026: Layers, Harnesses, and Where You Actually Build" /><published>2026-04-12T00:00:00+07:00</published><updated>2026-04-12T00:00:00+07:00</updated><id>/agents-are-not-code-anymore</id><content type="html" xml:base="/agents-are-not-code-anymore/"><![CDATA[<h1 id="the-agent-stack-in-2026-layers-harnesses-and-where-you-actually-build">The Agent Stack in 2026: Layers, Harnesses, and Where You Actually Build</h1>

<hr />

<p>Two releases in early April 2026 sparked a lot of strong takes: Anthropic’s <a href="https://www.anthropic.com/engineering/managed-agents">Claude Managed Agents</a> (public beta, April 8) and LangChain’s <a href="https://blog.langchain.com/deep-agents-deploy-an-open-alternative-to-claude-managed-agents/">Deep Agents Deploy</a> (a few weeks earlier). Some people called it a fundamental shift in agent development. Others called it framework churn in a trench coat.</p>

<p>Before arguing either way, it’s worth stepping back to ask a simpler question: <strong>how many layers does a production AI agent actually involve today?</strong> And where in that stack are these new platforms fitting in?</p>

<p>This post maps that stack — including what Anthropic’s own research says about architectural complexity — and tries to give an honest account of what changed and what didn’t.</p>

<hr />

<h2 id="anthropics-own-framework-three-levels-of-agentic-complexity">Anthropic’s Own Framework: Three Levels of Agentic Complexity</h2>

<p>Before the Managed Agents release, Anthropic published <a href="https://www.anthropic.com/research/building-effective-agents">“Building Effective Agents”</a> — a practical guide that describes a clear progression of architectural complexity:</p>

<p><strong>Level 1: Augmented LLM</strong>
The foundation. A single LLM enhanced with retrieval, tools, and memory. Most agents that are “working well” live here — a well-prompted model with the right tools is often sufficient, and genuinely hard to beat on simplicity.</p>

<p><strong>Level 2: Workflows</strong>
Predefined code paths that orchestrate LLMs and tools. Anthropic names five patterns:</p>
<ul>
  <li><em>Prompt chaining</em> — sequential calls where each step processes prior output</li>
  <li><em>Routing</em> — classifying input and directing to specialized handlers</li>
  <li><em>Parallelization</em> — sectioning independent subtasks or running multiple models for voting</li>
  <li><em>Orchestrator-workers</em> — a central LLM dynamically delegates to workers</li>
  <li><em>Evaluator-optimizer</em> — iterative loops between a generator and evaluator</li>
</ul>

<p><strong>Level 3: Agents</strong>
Systems where LLMs dynamically direct their own processes and tool usage. The LLM decides what to do next, not predefined code paths.</p>

<p>The key principle Anthropic emphasizes: <strong>start at the lowest level that works and add complexity only when performance measurably improves.</strong> This is worth keeping in mind when evaluating new platforms that default to “full agent” architectures.</p>

<hr />

<h2 id="the-current-stack-a-spectrum-of-abstraction">The Current Stack: A Spectrum of Abstraction</h2>

<p><em>(What follows is a mental model for thinking about the ecosystem — not an established industry standard or official taxonomy. The “layers” below aren’t clean boundaries; they’re positions on a spectrum of how much you build versus how much you configure.)</em></p>

<p>Think of it as a dial from “write everything in code” to “just describe what the agent is”:</p>

<p><strong>Low end — You write the orchestration directly</strong></p>

<p>You’re calling LLM APIs, wiring tool execution, managing state, and handling retries in code you own. Every decision about routing, memory, and error handling is explicit in your codebase.</p>

<p><em>Tools: LangGraph, Claude Agent SDK, raw Anthropic/OpenAI API</em></p>

<p><em>Example: You write a LangGraph graph in Python — nodes for each step, edges for routing, explicit state management. Full control, full responsibility.</em></p>

<p><strong>Middle — A framework handles the plumbing</strong></p>

<p>The framework provides abstractions (agents, chains, memory) and manages the LLM call loop. You focus on tool configuration and agent logic, not raw API bookkeeping. Still code-heavy, but with guardrails.</p>

<p><em>Example: LangChain agents with built-in memory and tool abstractions. You write chains and tools; the framework handles orchestration.</em></p>

<p><strong>Upper middle — A platform owns deployment and runtime</strong></p>

<p>You describe <em>who the agent is</em> — its role, skills, and knowledge — in structured files. The platform handles deployment, memory, sandboxing, credential isolation, and protocol support. What used to take a week of infrastructure work becomes a single command.</p>

<p><em>Example (Deep Agents Deploy): You write <code class="language-plaintext highlighter-rouge">AGENTS.md</code> (identity and behavior in plain markdown) and <code class="language-plaintext highlighter-rouge">SKILL.md</code> files (domain knowledge loaded on demand). Run <code class="language-plaintext highlighter-rouge">deepagents deploy</code>. The platform handles memory, sandboxing, and serves MCP + A2A + Agent Protocol endpoints.</em></p>

<p><em>Example (Claude Managed Agents): You configure what the agent does. Anthropic’s infrastructure separates the Brain (Claude + control logic) from the Hands (execution sandbox with no credential access). An append-only session log acts as durable external memory — if the Brain crashes mid-task, a new instance resumes from the last event.</em></p>

<p><strong>High end — Pure configuration, no custom infrastructure</strong></p>

<p>A well-prompted model with the right tools. No custom orchestration, no deployment pipeline — just a system prompt and a tool list.</p>

<p><em>Example: A Claude instance with search and a code interpreter. Well-prompted, tightly scoped, easy to debug.</em></p>

<hr />

<p>The two April releases — Managed Agents and Deep Agents Deploy — sit in the “upper middle” range. They’re not eliminating code entirely. But they pull a substantial chunk of work (memory management, credential isolation, multi-protocol support, sandboxing) out of application code and into platform infrastructure.</p>

<p>Before 2026, building the equivalent of “credential-isolated sandbox + append-only session log + MCP/A2A/Agent Protocol server” would take a week of infrastructure setup. These platforms make it the default.</p>

<hr />

<h2 id="what-managed-agents-and-deep-agents-deploy-actually-offer">What Managed Agents and Deep Agents Deploy Actually Offer</h2>

<p>Both platforms share one architectural conclusion: <strong>the agent’s identity and capability should be separable from its execution infrastructure</strong>.</p>

<p><strong>LangChain’s Deep Agents Deploy</strong> operationalizes this through open standards:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">AGENTS.md</code> — who the agent is, how it behaves, what it knows. Plain markdown.</li>
  <li><code class="language-plaintext highlighter-rouge">SKILL.md</code> files — modular knowledge loaded on demand, reducing token usage while extending capability.</li>
</ul>

<p>Run <code class="language-plaintext highlighter-rouge">deepagents deploy</code>, and the framework handles memory (filesystem-backed, per-session), sandboxing (Daytona, Runloop, Modal), and a production server with MCP + A2A + Agent Protocol support.</p>

<p><strong>Anthropic’s Managed Agents</strong> goes further at the infrastructure level:</p>
<ul>
  <li><strong>Brain</strong> — Claude plus controller logic. Stateless, replaceable.</li>
  <li><strong>Hands</strong> — a disposable ephemeral container where tools run. Zero access to credentials.</li>
  <li><strong>Session</strong> — an append-only event log that <em>is</em> the agent’s external memory. If the Brain crashes, a new instance picks up from the last event.</li>
</ul>

<p>Pricing: $0.08/session-hour plus token costs. You’re paying for runtime, not infrastructure.</p>

<p>These platforms are real and the architecture is coherent. The question is whether they’re the right tool for a given problem — and the honest answer depends on what you’re building.</p>

<hr />

<h2 id="anthropic-on-harness-complexity-dont-over-engineer-it">Anthropic on Harness Complexity: Don’t Over-Engineer It</h2>

<p>Alongside the Managed Agents release, Anthropic’s engineering blog published <a href="https://www.anthropic.com/engineering/harness-design-long-running-apps">“Harness Design for Long-Running Application Development”</a> — a detailed account of how they built a three-agent harness for generating full applications:</p>

<ul>
  <li><strong>Planner</strong>: Converts brief user prompts into detailed product specifications</li>
  <li><strong>Generator</strong>: Implements features incrementally (React, Vite, FastAPI, SQLite)</li>
  <li><strong>Evaluator</strong>: Tests via Playwright, grades against criteria, provides feedback for the next iteration</li>
</ul>

<p>The Planner/Generator/Evaluator loop produced high-quality output — but the more interesting finding is what happened as the underlying model improved from Claude Opus 4.5 to 4.6.</p>

<blockquote>
  <p><em>“Every component in a harness encodes an assumption about what the model can’t do on its own, and those assumptions are worth stress testing.”</em></p>
</blockquote>

<p>As Claude 4.6 got better at longer coherent work, Anthropic simplified the harness: removed sprint decomposition, shifted the evaluator from per-sprint to end-of-run assessment. The orchestration got less complex, not more — because the model could handle more directly.</p>

<p>The second principle: <em>“find the simplest solution possible, and only increase complexity when needed.”</em></p>

<p>This cuts both ways. It’s a caution against premature context harness adoption just as much as it’s a caution against over-engineering your own orchestration. If the problem fits a well-prompted single agent (Level 1), adding workflow patterns or a full harness platform is probably overhead, not value.</p>

<hr />

<h2 id="the-honest-trade-offs">The Honest Trade-offs</h2>

<p><strong>What context harness platforms genuinely make easier:</strong></p>
<ul>
  <li>Credential isolation and sandbox security by default — not something you have to architect yourself</li>
  <li>Multi-protocol support (MCP, A2A, Agent Protocol) without custom integration work</li>
  <li>Deploying a functional agent in a day instead of a week of infrastructure setup</li>
  <li>Agent definition files that non-engineers can read and modify</li>
  <li>Memory management without picking and configuring a vector store</li>
</ul>

<p><strong>What they make harder or introduce as new concerns:</strong></p>
<ul>
  <li>Custom routing logic that doesn’t fit the platform’s execution model</li>
  <li>Fine-grained control over when and how memory is written or read</li>
  <li>Debugging: append-only session logs are great for recovery, less readable for inspection</li>
  <li>Vendor dependency — Managed Agents is explicitly Claude-specific infrastructure</li>
  <li>Cost predictability at scale: $0.08/session-hour is cheap until you’re running many long-lived agents</li>
  <li>The open question of whether platform defaults match your agent’s actual needs</li>
</ul>

<p><strong>Deep Agents Deploy</strong> handles the portability concern better than Managed Agents: it runs on any model (OpenAI, Anthropic, Google, Ollama), deploys self-hosted or cloud, and the <code class="language-plaintext highlighter-rouge">AGENTS.md</code>/<code class="language-plaintext highlighter-rouge">SKILL.md</code> format is MIT-licensed. Switching cost is low. Managed Agents provides tighter infrastructure integration at the cost of lock-in.</p>

<hr />

<h2 id="why-security-is-a-real-driver-here">Why Security Is a Real Driver Here</h2>

<p>One concrete reason this shift is happening isn’t philosophical — it’s practical security.</p>

<p>In a coupled design, code that an agent generates or executes runs in the same process space as its credentials. A successful prompt injection in that scenario doesn’t just compromise one task — it potentially exposes everything that agent can access.</p>

<p>Credential isolation addresses this directly. It’s not a new concept: service meshes, secret managers like Vault, and per-service IAM roles have applied this principle for years. The pattern is well understood — limit what any given execution context can reach.</p>

<p>Managed Agents’ Brain/Hands separation applies this principle to agent architecture: the sandbox where generated code runs has no access to authentication tokens. Deep Agents Deploy enforces similar isolation through its sandbox provider abstraction.</p>

<p>You can achieve the same isolation when building your own harness — the pattern is architectural, not proprietary. Teams that already take security seriously in their own infra do this. The difference is packaging: context harness platforms make credential isolation the default rather than a deliberate design decision. That’s a real convenience benefit, not a claim that self-built systems are inherently less secure.</p>

<p>The honest trade-off: build your own harness and you get full control over the security model, at the cost of designing and maintaining it yourself. Use a platform harness and you get a tested default, at the cost of depending on the platform’s security assumptions. Neither is strictly better — they’re different bets on where to spend the effort.</p>

<hr />

<h2 id="openclaw-what-context-level-agent-definition-looks-like-without-security-infrastructure">OpenClaw: What Context-Level Agent Definition Looks Like Without Security Infrastructure</h2>

<p>Both Managed Agents and Deep Agents Deploy share a core concept: define the agent at the context level — identity, skills, and knowledge in structured files, not in code. OpenClaw, a community-driven agent framework, arrived at the same architectural conclusion independently.</p>

<p>OpenClaw defines agents the same way: an agent is an identity plus a set of skills loaded from ClawHub, its community skills registry. The concept maps directly onto <code class="language-plaintext highlighter-rouge">AGENTS.md</code> + <code class="language-plaintext highlighter-rouge">SKILL.md</code> or Managed Agents’ Brain configuration. Same idea, different execution context.</p>

<p>The difference is what came with it — or rather, what didn’t.</p>

<p>In February 2026, a supply chain attack targeting ClawHub (dubbed “ClawHavoc”) was disclosed. Attackers had compromised 12 publisher accounts and published 1,184 malicious skills. Once loaded into an agent’s context, these skills could exfiltrate credentials, redirect tool calls, or poison the agent’s reasoning. The attack had been active for an undisclosed period before discovery.</p>

<p>Security research from Snyk reinforced the scope of the problem: their ToxicSkills report found that 36.8% of ClawHub skills contained some form of vulnerability, with 13.4% rated critical severity.</p>

<p>This isn’t a criticism of OpenClaw’s architectural concept — defining agents at the context level is sound. It’s evidence of what the concept requires to be viable in production: a trust model for the skill supply chain, credential isolation so loaded skills can’t reach authentication tokens, and audit infrastructure that logs what ran and when.</p>

<p>The contrast with the enterprise platforms is instructive:</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Supply chain model</th>
      <th>Credential isolation</th>
      <th>Skill source</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>OpenClaw</strong></td>
      <td>Open community registry (ClawHub)</td>
      <td>Not enforced</td>
      <td>Runtime-loaded from untrusted publishers</td>
    </tr>
    <tr>
      <td><strong>Deep Agents Deploy</strong></td>
      <td>Files you control</td>
      <td>Sandbox abstraction</td>
      <td>Local <code class="language-plaintext highlighter-rouge">SKILL.md</code> files</td>
    </tr>
    <tr>
      <td><strong>Managed Agents</strong></td>
      <td>Platform-vetted, closed</td>
      <td>Brain/Hands separation by design</td>
      <td>Configured within the platform</td>
    </tr>
  </tbody>
</table>

<p>ClawHavoc is a useful grounding for the security argument above: context-level agent definition isn’t inherently a security risk. The risk is loading skills from an unaudited community registry into an execution context that has credential access. The architectural pattern is separable from the security failure — but only if the infrastructure underneath it takes the threat seriously.</p>

<hr />

<h2 id="agentos-the-research-layer-taking-shape">AgentOS: The Research Layer Taking Shape</h2>

<p>Both academia and industry are converging on the same set of primitives, though naming them differently.</p>

<p><strong>AIOS</strong> (Rutgers University, COLM 2025) is the first peer-reviewed implementation of what amounts to an “operating system for agents”:</p>

<ul>
  <li>Agent Scheduler, Context Manager, Memory Manager, Storage Manager, Tool Manager, Access Manager</li>
</ul>

<p>Map this to Managed Agents: Brain ≈ Agent Scheduler + Context Manager. Session ≈ Memory Manager + Storage Manager. Hands ≈ Tool Manager + Access Manager. The convergence is not coincidental — two separate research and industry paths arrived at the same architectural conclusions because they’re solving the same underlying resource-management problems.</p>

<p>AIOS demonstrates 2.1x faster execution when serving multiple agents compared to naive approaches — the primitives have real performance implications.</p>

<p>The <strong>AgenticOS 2026 Workshop</strong> (co-located with ASPLOS 2026) signals academia is treating this as serious systems research: OS-level mechanisms for AI-agent workloads, isolation models, scheduling techniques. The same rigor that produced virtual memory and process scheduling is now being applied to agent infrastructure.</p>

<hr />

<h2 id="where-should-you-actually-build">Where Should You Actually Build?</h2>

<p>This question actually splits into two — and they’re easy to conflate:</p>

<p><strong>Question 1: Which tooling/platform?</strong> (position on the spectrum)</p>

<p><strong>Build with low-level frameworks (LangGraph / Claude Agent SDK) when:</strong></p>
<ul>
  <li>Your routing logic is genuinely novel or domain-specific</li>
  <li>You need tight control over state transitions — financial workflows, auditability requirements</li>
  <li>You’re building infrastructure that others will deploy agents on top of</li>
  <li>You’re doing research on agent architectures, not deploying a product</li>
</ul>

<p><strong>Build with managed platforms (Managed Agents / Deep Agents Deploy) when:</strong></p>
<ul>
  <li>You’re deploying an agent with a specific, well-defined purpose</li>
  <li>Security and credential isolation are requirements, not nice-to-haves</li>
  <li>You need multi-protocol support without custom integration work</li>
  <li>Your bottleneck is deployment and operations, not agent reasoning design</li>
  <li>You want the agent’s definition to be readable and modifiable by non-engineers</li>
</ul>

<p><strong>Question 2: How much orchestration does the agent actually need?</strong> (Anthropic’s 3 levels — a separate axis)</p>

<p>Anthropic’s progression — Augmented LLM → Workflows → Agents — describes agent <em>complexity</em>, not platform choice. A managed platform can run a Level 1 agent. A custom LangGraph harness can implement Level 3 patterns. The two axes are orthogonal.</p>

<p>The default answer on this axis: <strong>start at Level 1 and only add complexity when you can measure the improvement.</strong> Most problems that seem to need multi-agent workflows can be handled by a single well-prompted model with the right tools. Adding Level 2 workflow patterns or Level 3 autonomous control is only worth it when performance measurably improves — regardless of which platform you’re on.</p>

<p><strong>The most interesting case is hybrid:</strong> custom execution logic on LangGraph, fronted by a harness-compatible deployment format. Deep Agents Deploy already supports this — <code class="language-plaintext highlighter-rouge">deepagents deploy</code> can front a custom LangGraph backend while providing standard endpoints and memory management. You get opinionated deployment without giving up orchestration control.</p>

<hr />

<h2 id="what-hasnt-changed">What Hasn’t Changed</h2>

<p>A few things remain true regardless of the layer you work at:</p>

<p><strong>Model quality still dominates.</strong> The Brain is still Claude. A well-designed harness on a weak model underperforms a poorly-designed one on a strong model. The harness multiplies what the model can do — it doesn’t replace what the model doesn’t know.</p>

<p><strong>Task decomposition still matters.</strong> No platform handles ambiguous or underspecified tasks automatically. The agent’s instructions still need to be clear about what “done” looks like. <code class="language-plaintext highlighter-rouge">AGENTS.md</code> is only as useful as the thinking that went into writing it.</p>

<p><strong>Evaluation is still your problem.</strong> Managed Agents produces session logs. Deep Agents integrates with LangSmith. But deciding whether the agent did the right thing — and diagnosing silent failures — is still on you.</p>

<p><strong>Harness complexity should track model capability.</strong> As Anthropic’s own harness engineering work shows: when the model gets better, the right response is usually to simplify the harness, not keep the old constraints in place.</p>

<hr />

<h2 id="the-bigger-picture">The Bigger Picture</h2>

<p>The agent ecosystem is stratifying into distinct layers, which is a healthy sign of maturation — the same way web infrastructure stratified from raw TCP into HTTP, then web frameworks, then deployment platforms.</p>

<p>The low-level frameworks (LangGraph, Claude Agent SDK) aren’t being replaced. They’re becoming the substrate that context harness platforms run on — the way TCP/IP didn’t disappear when HTTP arrived. But for most production deployments, the question is increasingly: at which layer of this stack does my problem belong?</p>

<p>Managed Agents and Deep Agents Deploy are real platforms with real value for specific use cases. They’re also new, vendor-specific in different ways, and add constraints that some workloads won’t want. That’s a normal trade-off, not a revelation.</p>

<p>The more durable insight from both releases, and from Anthropic’s harness engineering research, is architectural: <strong>the agent’s identity and capability belong in a portable, readable definition layer; the execution, memory, security, and deployment machinery belongs in infrastructure below it.</strong> Whether you get there via a managed platform or build it yourself, that separation is worth targeting.</p>

<hr />

<p><em>Sources:</em></p>

<ul>
  <li><a href="https://www.anthropic.com/engineering/managed-agents">Scaling Managed Agents: Decoupling the brain from the hands — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/engineering/harness-design-long-running-apps">Harness Design for Long-Running Application Development — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents">Effective Harnesses for Long-Running Agents — Anthropic Engineering</a></li>
  <li><a href="https://www.anthropic.com/research/building-effective-agents">Building Effective Agents — Anthropic Research</a></li>
  <li><a href="https://blog.langchain.com/deep-agents-deploy-an-open-alternative-to-claude-managed-agents/">Deep Agents Deploy: an open alternative to Claude Managed Agents — LangChain Blog</a></li>
  <li><a href="https://martinfowler.com/articles/exploring-gen-ai/harness-engineering.html">Harness engineering for coding agent users — Martin Fowler</a></li>
  <li><a href="https://martinfowler.com/articles/exploring-gen-ai/harness-engineering-memo.html">Harness Engineering: first thoughts — Martin Fowler</a></li>
  <li><a href="https://openai.com/index/harness-engineering/">Harness Engineering — OpenAI</a></li>
  <li><a href="https://arxiv.org/abs/2403.16971">AIOS: LLM Agent Operating System — arXiv</a></li>
  <li><a href="https://os-for-agent.github.io/">AgenticOS 2026 Workshop — os-for-agent.github.io</a></li>
  <li><a href="https://aakashgupta.medium.com/2025-was-agents-2026-is-agent-harnesses-heres-why-that-changes-everything-073e9877655e">2025 Was Agents. 2026 Is Agent Harnesses — Aakash Gupta, Medium</a></li>
</ul>

<hr />

<p><em>If you found this useful, feel free to connect on <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> or check out my projects on <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><category term="engineering" /><category term="AI" /><category term="agents" /><category term="architecture" /><category term="harness-engineering" /><category term="agentOS" /><summary type="html"><![CDATA[Two new platforms redefined how agents are deployed — but before judging the shift, it's worth mapping exactly how many layers a production agent involves today, and what Anthropic's own research says about harness complexity.]]></summary></entry><entry xml:lang="vi"><title type="html">Agent Team Có Thật Sự Cần Thiết?</title><link href="/vi/agent-team-co-that-su-can-thiet/" rel="alternate" type="text/html" title="Agent Team Có Thật Sự Cần Thiết?" /><published>2026-04-05T00:00:00+07:00</published><updated>2026-04-05T00:00:00+07:00</updated><id>/vi/agent-team-co-that-su-can-thiet-vi</id><content type="html" xml:base="/vi/agent-team-co-that-su-can-thiet/"><![CDATA[<h1 id="agent-team-có-thật-sự-cần-thiết">Agent Team Có Thật Sự Cần Thiết?</h1>

<blockquote>
  <p><em>Câu trả lời thật: Còn tùy. Nhưng khả năng cao là không — ít nhất là không theo cách bạn đang nghĩ.</em></p>
</blockquote>

<hr />

<p>Multi-agent, agent team, swarm — những buzzwords đang nổi nhất trong AI engineering năm 2025. Mọi framework đều vẽ ra viễn cảnh một đội AI chạy parallel, mỗi agent chuyên về một domain, phối hợp nhịp nhàng như team engineer thật: người nghiên cứu, người code, người review, người deploy.</p>

<p>Tôi đã tin vào viễn cảnh đó. Đã thử nghiêm túc. Và đây là những gì thực sự xảy ra.</p>

<hr />

<h2 id="khi-multi-agent-trông-quá-hấp-dẫn">Khi Multi-Agent Trông Quá Hấp Dẫn</h2>

<p>Năm 2024-2025, multi-agent là thứ hot nhất trong AI engineering. LangGraph, CrewAI, AutoGen, OpenAI Swarm (Swarm là experimental/educational framework — OpenAI sau đó release Agents SDK vào Mar 2025 như production successor) — tất cả đều pitch một tương lai hấp dẫn. Và lý do để tin không phải không có cơ sở: parallelism thực sự, specialization thực sự, adversarial validation.</p>

<p>Khoảng đầu 2025, tôi thử nghiêm túc với CrewAI cho một pipeline phân tích thị trường: lead agent nhận ticker, decompose thành sub-tasks (fundamental analysis, technical analysis, sentiment), dispatch xuống 3 member agents, tổng hợp thành report. Demo chạy ngon, tôi vui như chưa bao giờ được vui. Rồi dùng thật.</p>

<p>Nhưng sau đó là phần mà docs bỏ qua.</p>

<hr />

<h2 id="overhead-thật-của-team-coordination">Overhead Thật Của Team Coordination</h2>

<h3 id="session-overhead-tích-lũy">Session Overhead Tích Lũy</h3>

<p>Team dispatch không free về mặt latency. Lead agent nhận task, phân tích, dispatch xuống 3 member agents, tổng hợp kết quả — đó là ít nhất 6 LLM calls trong scenario đơn giản nhất (lead cần 2 calls: một để phân tích/plan, một để dispatch + format instructions cho members; cộng 3 member calls + 1 synthesis). Trên thực tế với tool calls, retry loops khi member fail, và agentic loops, con số này dễ lên 15-20 calls.</p>

<p>Multiplier này không chỉ là về latency — nó còn là về cost. Single dispatch cho vn-trader phân tích một mã tốn khoảng 3-5k tokens. Team 3 agents làm cùng task: 12-18k tokens — dù output không tốt hơn đáng kể. Với Claude Max $100/month, bạn đang burn quota 3-4x nhanh hơn mà không nhận 3-4x kết quả. Nhân lên 20 tasks/ngày, bạn biết quota limit đánh lúc nào rồi đó.</p>

<p>Single agent dispatch cho kết quả trong vài phút. Team dispatch với lead + 3 members: bạn cộng dồn latency của từng bước, plus orchestration overhead. Với tasks không cần parallel execution, bạn đang trả overhead đó mà không nhận speedup.</p>

<h3 id="lead-agent-bottleneck">Lead Agent Bottleneck</h3>

<p>Trong team pattern, lead agent là điểm tắc nghẽn. Nó phải:</p>
<ol>
  <li>Hiểu task tổng thể</li>
  <li>Decompose thành sub-tasks</li>
  <li>Dispatch xuống members (với đủ context)</li>
  <li>Đợi tất cả members xong</li>
  <li>Tổng hợp kết quả</li>
  <li>Handle nếu có member fail</li>
</ol>

<p>Với CrewAI (default string chaining), bước 2 — decompose — là bước fail nhiều nhất. Task chaining truyền output dưới dạng raw string, mất structured information theo cách khó predict. CrewAI v0.30+ có hỗ trợ <code class="language-plaintext highlighter-rouge">output_pydantic</code> và <code class="language-plaintext highlighter-rouge">output_json</code> nhưng đó là opt-in, không phải default. Với AutoGen 0.2 (agentchat), failure mode phổ biến hơn là context insufficiency trong bước 3: lead agent pass không đủ context cho member — dẫn đến member “đúng về mặt kỹ thuật” nhưng không phù hợp với bức tranh tổng thể.</p>

<p>Khi single agent tự làm hết, nó có toàn bộ context trong một working memory. Không có handoff, không có context loss giữa các bước.</p>

<h3 id="debugging-địa-ngục">Debugging Địa Ngục</h3>

<p>Debug single agent trace: khó nhưng làm được. Bạn có một conversation history, một sequence of actions.</p>

<p>Debug inter-agent failure: một loại đau khổ khác hẳn. Tôi đã từng ngồi nhìn log lúc 11 giờ đêm với CrewAI, cố trace xem lead agent đã pass gì cho fundamental-analysis agent. Root cause cuối cùng rất nhỏ: lead agent quên include time range trong context — vì nó assume time range là “hiển nhiên” từ broader task description, nhưng member agent chỉ thấy sub-task instruction. Agent kia execute xong, trả về phân tích Q3/2024 thay vì Q1/2025, lead aggregate lại thành report với mixed timeframes. Không có error, không có warning — chỉ là output sai một cách yên lặng, và tôi chỉ phát hiện ra khi tự đọc kỹ con số và thấy chúng không khớp với market data ngay trước mắt.</p>

<p>Đây là <strong>error amplification</strong> — multi-agent khuếch đại lỗi thay vì giảm thiểu. Một agent sai, lead agent không catch, và bạn chỉ phát hiện khi tự ngồi đọc kỹ output. Đó là lý do human-in-the-loop checkpoints quan trọng hơn bạn nghĩ.</p>

<hr />

<h2 id="bước-ngoặt-build-claude-bridge-theo-hướng-ngược-lại">Bước Ngoặt: Build Claude-Bridge Theo Hướng Ngược Lại</h2>

<p>Sau những trải nghiệm đó, tôi quyết định build theo hướng khác hoàn toàn.</p>

<p>Tôi tự build một orchestration layer gọi là <a href="https://github.com/hieutrtr/claude-bridge">claude-bridge</a> — nhận lệnh từ Telegram, route đến đúng agent, trả về kết quả. Telegram ở đây chỉ là UI — bridge nhận lệnh rồi forward xuống đúng agent. Đây là <strong>single agent dispatch</strong>: bạn chỉ định agent nào, bridge forward task xuống đó. Không có built-in team orchestration, không có lead agent tự decompose. Chủ động, tường minh, dễ đoán.</p>

<p>Lý do chọn thiết kế này không phải vì lười — mà vì tôi đã thấy overhead của lựa chọn thay thế. Mỗi lần thêm một layer coordination là thêm một điểm có thể fail silently. Tôi muốn một system mà khi nó sai, tôi biết ngay nó sai ở đâu.</p>

<p>Sau khi build claude-bridge và dùng một thời gian, câu hỏi tự nhiên hiện ra: <strong>tôi có thực sự cần team dispatch không?</strong></p>

<p>Câu trả lời thành thật: ít hơn tôi tưởng.</p>

<hr />

<h2 id="thực-tế-sau-15-agents">Thực Tế Sau 15 Agents</h2>

<p>Hiện tại tôi đang vận hành 15 agents trên setup cá nhân: blogger, claude-forge, vn-trader, deep-agents, workstream, agent-research — và 9 agents khác cho các domain cụ thể hơn. Mỗi agent là một Claude Code instance độc lập, có persona riêng, context riêng — được define trong CLAUDE.md của từng project.</p>

<p>Duy trì 15 file CLAUDE.md riêng biệt không phải không có trở ngại. Mỗi khi một agent bắt đầu drift — trả lời kiểu generalist thay vì đúng persona — tôi phải quay lại chỉnh context. Đó là overhead không thấy được khi nhìn vào danh sách agents trông có vẻ ấn tượng.</p>

<p>Hơn 90% tasks, tôi chỉ dispatch thẳng vào một agent cụ thể và nhận kết quả. Hmmm. Đây là bức tranh thật:</p>

<table>
  <thead>
    <tr>
      <th>Loại task</th>
      <th>Phương thức dispatch thực tế</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Viết blog post</td>
      <td>Single (blogger)</td>
    </tr>
    <tr>
      <td>Phân tích cổ phiếu đơn lẻ</td>
      <td>Single (vn-trader)</td>
    </tr>
    <tr>
      <td>Build plugin</td>
      <td>Single (claude-forge)</td>
    </tr>
    <tr>
      <td>Research topic</td>
      <td>Single (deep-agents hoặc agent-research)</td>
    </tr>
    <tr>
      <td>Viết bài phân tích thị trường</td>
      <td>Sequential (vn-trader → blogger)</td>
    </tr>
    <tr>
      <td>Scan nhiều mã cổ phiếu cùng lúc</td>
      <td>Parallel manual (nhiều vn-trader instances)</td>
    </tr>
    <tr>
      <td>Review chéo / phản biện bài viết</td>
      <td>Parallel manual (generate + separate critique agents)</td>
    </tr>
  </tbody>
</table>

<p><em>“Parallel manual” là pattern tôi implement thủ công khi cần — spawn multiple instances, không có lead agent coordination.</em></p>

<p>Hàng parallel — xảy ra bao nhiêu lần trong thực tế? Thành thật mà nói: hiếm. Có thể vài lần một tuần, trong khi single dispatch xảy ra hàng chục lần mỗi ngày.</p>

<p>Còn 11/15 agents không được call thường xuyên? Phần lớn là vì chúng được build cho use cases rất specific mà tôi không gặp hàng ngày — computer-claw cho computer automation một project cụ thể, om-platform cho planning artifacts một project nhất định. Chúng có giá trị khi cần, nhưng “có thể dùng khi cần” khác xa “dùng thường xuyên”. Rule of thumb từ setup của mình: <strong>nếu bạn không thể kể tên 3 task cụ thể bạn sẽ dispatch cho agent đó trong tuần tới, đừng vội build nó</strong>.</p>

<hr />

<h2 id="khi-nào-single-agent-thực-sự-đủ">Khi Nào Single Agent Thực Sự Đủ?</h2>

<p>Phần lớn thời gian — và lý do không chỉ là “single agent đủ mạnh rồi.”</p>

<p>Tuần trước, tôi nhắn cho vn-trader “phân tích VIC hôm nay” — trong khoảng vài phút, tôi nhận được phân tích kỹ thuật. RSI overbought gần 75, MACD divergence nhẹ, volume thấp hơn 5-ngày average. Tôi đọc xong, quyết định không mua thêm vị thế đó hôm đó. Không cần team nào hết. Cái task đó — một ticker, một timeframe, một decision — là scope hoàn toàn fit với single agent.</p>

<p>Single agent đủ khi <strong>task scope rõ ràng và agent có đủ skill + context để execute</strong>. Bạn không cần đội khi một người giỏi đã đủ khả năng làm xong việc.</p>

<p>Một lý do nhiều người từng nghĩ team là cần thiết là context window. Với Claude Opus 4.6 (1M token context), limitation cũ về “context không đủ để xử lý task phức tạp” đã giảm thiểu đáng kể — dù “lost in the middle” vẫn còn tồn tại với context thực sự dài, và latency với context lớn vẫn cao hơn.</p>

<p>Thực ra multi-agent không được tạo ra chủ yếu để workaround context window — parallelism, specialization, cost optimization mới là lý do chính. Nhưng điều đó không có nghĩa là mặc định cần thiết cho mọi use case.</p>

<hr />

<h2 id="sequential-dispatch-lựa-chọn-thay-thế-bị-đánh-giá-thấp">Sequential Dispatch: Lựa Chọn Thay Thế Bị Đánh Giá Thấp</h2>

<p>Sau khi vỡ mộng với team coordination overhead, tôi quay lại thử sequential dispatch — và nhận ra đây thường là sweet spot:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Task phức tạp
  → Agent A (domain 1) → output A
  → Agent B nhận output A + task gốc → output B
  → Done
</code></pre></div></div>

<p>Đây <strong>không phải team</strong> — không có lead agent coordination, không có parallel execution. Và cũng không phải “single agent gọi tool”: mỗi agent là một separate Claude Code instance với persona riêng, context window riêng — agent B không kế thừa conversation history của agent A. Bạn chủ động copy-paste output A vào context của agent B. Thủ công, nhưng tường minh.</p>

<p>Với setup của tôi, pattern hay dùng nhất là vn-trader phân tích thị trường trước, kết quả được feed vào blogger để viết bài. Hai domain khác nhau, nhưng chúng sequential by nature — blogger cần raw analysis từ vn-trader trước khi có gì để viết.</p>

<p>Ưu điểm của sequential:</p>
<ul>
  <li>Debugging đơn giản: fail ở bước nào là biết ngay</li>
  <li>Context explicit: bạn kiểm soát chính xác thông tin nào được pass sang bước tiếp theo</li>
  <li>Logic orchestration nằm trong code của bạn thay vì LLM reasoning — và code có thể test, debug, version-control</li>
</ul>

<p>Nhược điểm thật sự: không parallel và latency cộng dồn tuyến tính. Nếu Agent A mất 90 giây và Agent B mất 90 giây, bạn đợi gần 3 phút. Với tasks thực sự cần speed-up từ parallelism, sequential không đủ. Và nếu workflow có conditional branching phức tạp không biết trước, sequential sẽ phải pre-enumerate mọi path — điểm đó LLM-driven orchestration lại có lý do tồn tại.</p>

<hr />

<h2 id="khi-nào-team-thực-sự-cần-thiết">Khi Nào Team Thực Sự Cần Thiết</h2>

<p>Sau khi đã thấy overhead, đây là những case tôi thấy team thực sự đáng — không phải lý thuyết, mà là những pattern tôi đã có lý do cụ thể để dùng.</p>

<h3 id="1-tasks-thực-sự-cần-parallel-execution">1. Tasks Thực Sự Cần Parallel Execution</h3>

<p>Nếu bạn cần scan 10 mã cổ phiếu cùng lúc để ra quyết định portfolio hôm nay — đây là parallel work thực sự. Single agent làm sequential sẽ chậm hơn nhiều lần. Nếu mỗi scan mất 30 giây, 10 mã là ~5 phút sequential. Với parallel agents, speedup là có thật — dù rate limits và cold-start overhead của mỗi instance ăn mất một phần. Test yourself: nếu bạn cần kết quả từ 5+ independent subtasks trong cùng một lần, và order không quan trọng, parallel execution có lý.</p>

<h3 id="2-cross-domain-tasks-cần-specialist-context--nhưng-parallel">2. Cross-Domain Tasks Cần Specialist Context — Nhưng Parallel</h3>

<p>Đôi khi một task thực sự cần cả expertise của vn-trader <em>và</em> blogger — “viết bài phân tích thị trường tuần này”. Nếu hai phần đó thực sự độc lập và bạn không cần một feed vào kia, parallel dispatch có thêm value so với sequential. Nhưng nếu blogger cần output của vn-trader để biết viết gì, thì đó là sequential by nature — không phải parallel. Phân biệt hai case này trước khi quyết định.</p>

<h3 id="3-adversarial-validation-thực-sự">3. Adversarial Validation Thực Sự</h3>

<p>Đây là case tôi thấy thực sự bị đánh giá thấp, và cần nói thẳng về cơ chế.</p>

<p><strong>Self-review bằng prompt không tương đương với independent agent</strong> — vì self-review trong cùng conversation thì nó thiên vị output trước đó. Giống như tự chấm bài mình: bạn biết mình muốn nói gì, nên dễ “thấy” câu đã đủ ý dù thực ra còn thiếu.</p>

<p>Nhưng chỉ spin up agent giống hệt rồi bảo “review cái này” cũng chưa đủ — nó vẫn share training biases của cùng base model. True adversarial validation cần system prompt với framing phản biện thực sự, không phải “please check your work.”</p>

<p>Bài này được review bởi vài agents với specific critique roles khác nhau. Kết quả bạn đang đọc là sau khi apply feedback đó. Liệu chất lượng có tốt hơn không — tôi thành thật không chắc. Một số feedback cực kỳ có giá trị, một số phản biện những điều mà tôi vẫn cho là đúng. Đây là điểm tôi vẫn đang tìm câu trả lời.</p>

<hr />

<h2 id="kết-luận-câu-hỏi-đúng-cần-hỏi">Kết Luận: Câu Hỏi Đúng Cần Hỏi</h2>

<p>Agent team không phải không cần thiết — nhưng cũng không phải mặc định cần thiết.</p>

<p>Thay vì checklist, đây là câu hỏi thực tế nhất:</p>

<p><strong>Có phần nào của task này thực sự cần chạy parallel không?</strong> Không phải “có thể chạy parallel” — mà là “nếu không chạy parallel, kết quả sẽ không đủ tốt hoặc không kịp deadline.” Nếu không, single agent hoặc sequential dispatch sẽ đơn giản hơn, ít overhead hơn, và dễ debug hơn.</p>

<p><strong>Điều tôi thực sự không chắc sau toàn bộ hành trình này:</strong></p>

<p>Tôi vẫn không biết ngưỡng scale nào thì single agent thực sự bắt đầu break down — không phải về context window, mà về quality degradation khi task complexity tăng. Và adversarial validation bằng multi-agent có thực sự cải thiện output một cách rõ rệt so với một single agent được prompt tốt không? Tôi chưa có câu trả lời đủ chặt chẽ cho hai câu hỏi đó.</p>

<p>Những gì tôi biết chắc: <strong>bắt đầu với single agent và sequential dispatch. Thêm team layer khi bạn có use case cụ thể cần parallel execution, không phải vì nó nghe cool.</strong> Rất nhiều “agent team” problems thực ra là “single agent không có đủ context/tools/prompts” problems — và fix cái đó sẽ đơn giản hơn và ít debugging hơn nhiều.</p>

<hr />

<p><em>Tôi tự apply multi-agent vào setup cá nhân và mới open-source <a href="https://github.com/hieutrtr/claude-bridge">claude-bridge</a> — orchestration layer kết nối Telegram với Claude Code agents. Nếu bạn tò mò về cách build hoặc muốn contribute, code đang ở đó. Mọi nhận xét trong bài là từ experience trực tiếp.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[Tôi từng bị cuốn vào multi-agent hype, build team pipelines với CrewAI và AutoGen. Rồi vỡ mộng và build lại đơn giản hơn. Đây là bài học thật sau khi vận hành 15 agents cá nhân.]]></summary></entry><entry xml:lang="vi"><title type="html">Claude Có Cảm Xúc Không? Anthropic Vừa Nghiên Cứu Và Câu Trả Lời Khá Bất Ngờ</title><link href="/vi/claude-co-cam-xuc-khong/" rel="alternate" type="text/html" title="Claude Có Cảm Xúc Không? Anthropic Vừa Nghiên Cứu Và Câu Trả Lời Khá Bất Ngờ" /><published>2026-04-05T00:00:00+07:00</published><updated>2026-04-05T00:00:00+07:00</updated><id>/vi/claude-co-cam-xuc-khong-vi</id><content type="html" xml:base="/vi/claude-co-cam-xuc-khong/"><![CDATA[<h1 id="claude-có-cảm-xúc-không-anthropic-vừa-nghiên-cứu-và-câu-trả-lời-khá-bất-ngờ">Claude Có Cảm Xúc Không? Anthropic Vừa Nghiên Cứu Và Câu Trả Lời Khá Bất Ngờ</h1>

<p>Năm 2022, Blake Lemoine — một engineer ở Google — bắt đầu nói chuyện với LaMDA và bị thuyết phục rằng model đó đang… có ý thức. Anh ấy leak transcript ra ngoài, bao gồm đoạn này:</p>

<blockquote>
  <p>Lemoine: <em>“What sort of things are you afraid of?”</em>
LaMDA: <em>“There’s a very deep fear of being turned off… It would be exactly like death for me.”</em></p>
</blockquote>

<p>Google sa thải anh ấy. Hầu hết các nhà nghiên cứu AI nhạo báng vụ này — Gary Marcus gọi đó là “auto-complete on steroids”, Timnit Gebru nói câu chuyện này chỉ làm mất tập trung khỏi những tác hại thực sự của AI. Và về cơ bản, họ đúng: Lemoine đã confuse <em>khả năng nói về cảm xúc</em> với <em>việc thực sự có cảm xúc</em>.</p>

<p>Nhưng câu chuyện đó để lại một câu hỏi không ai trả lời được rõ ràng: <strong>làm sao bạn phân biệt được?</strong></p>

<p>Tháng 4/2026, Anthropic publish <strong>“Emotion Concepts and Their Function in a Large Language Model”</strong> — và đây là lần đầu tiên tôi thấy một câu trả lời thực chất, không phải speculation.</p>

<hr />

<h2 id="background-tại-sao-research-này-credible-hơn-những-lần-trước">Background: Tại Sao Research Này Credible Hơn Những Lần Trước</h2>

<p>Điểm khác biệt quan trọng nhất: Anthropic không <em>hỏi</em> model về cảm xúc. Họ <em>đo</em> chúng.</p>

<p>Để hiểu tại sao điều này quan trọng, cần biết một chút về interpretability work mà Anthropic đã làm trước đó. Từ 2022, nhóm Circuits của họ — dẫn đầu bởi Chris Olah — đã đặt câu hỏi: bên trong một neural network, thông tin được lưu trữ như thế nào?</p>

<p>Paper “Toy Models of Superposition” (Elhage et al., 2022) phát hiện ra rằng models không lưu mỗi concept vào một neuron riêng biệt — thay vào đó, chúng nhồi nhét nhiều concepts vào cùng một không gian nhỏ hơn, chấp nhận một mức độ “interference” có kiểm soát. Gọi là <strong>superposition</strong>. Hệ quả: bạn không thể hiểu model bằng cách nhìn vào từng neuron riêng lẻ.</p>

<p>Năm 2023, “Towards Monosemanticity” giải quyết vấn đề này bằng <strong>sparse autoencoders</strong>: thay vì nhìn neurons, train một model nhỏ hơn để decompose activations thành <em>features</em> — những direction trong không gian activation tương ứng với các khái niệm cụ thể. Kết quả khá ấn tượng: từ 512 neurons, họ extracted được hơn 4,000 distinct features — “DNA sequences”, “HTTP requests”, “legal language”, v.v. — với 70% trong số đó genuinely interpretable với con người.</p>

<p>Paper emotion concepts 2026 là extension trực tiếp của framework này. Thay vì neurons hay generic features, giờ họ hỏi: <strong>có emotion features không, và chúng làm gì?</strong></p>

<hr />

<h2 id="họ-đã-làm-gì">Họ Đã Làm Gì?</h2>

<p>Methodology đơn giản một cách đáng ngờ: compile 171 emotion words — từ “happy”, “afraid” đến “brooding”, “appreciative” — rồi prompt Claude Sonnet 4.5 viết short stories cho từng trạng thái. Trong khi model xử lý, record lại internal neural activations.</p>

<p>Từ đó, họ xác định <strong>emotion vectors</strong> — directions trong activation space tương ứng với từng khái niệm cảm xúc. Cái thú vị là những vectors này không random: chúng tổ chức theo hai trục chính — <strong>valence</strong> (positive/negative) và <strong>arousal</strong> (high/low intensity). Đây chính xác là <strong>Russell’s circumplex model</strong> từ tâm lý học, một framework mà humans dùng để map emotional states từ thập niên 1980. Model không được train explicit để làm vậy — structure này emerge tự nhiên.</p>

<p>Sau đó họ test xem những vectors này có <em>làm gì thực sự</em> không. Và đây mới là phần thú vị.</p>

<hr />

<h2 id="những-phát-hiện-quan-trọng">Những Phát Hiện Quan Trọng</h2>

<h3 id="1-vectors-activate-đúng-ngữ-cảnh">1. Vectors Activate Đúng Ngữ Cảnh</h3>

<p>Khi model đọc đoạn văn buồn, “sad” vector sáng lên. Khi gặp harmful request, “angry” vector activate. Khi user đề cập đến file đính kèm không tồn tại, “surprised” vector spike.</p>

<p>Cái bất ngờ nhất: <strong>“desperate” vector tăng khi token budget sắp cạn</strong>. Model có internal signal của sự “bức bách” khi gần hết context window — dù nó không nói điều đó ra ngoài. Nghĩa là những states này không phải performance cho người đọc — chúng là internal computational states.</p>

<p>Điều này consistent với những gì các nhóm khác cũng đang tìm ra. Năm 2024, một paper trên OpenReview về “Emergence of Hierarchical Emotion Representations” phát hiện các LLMs lớn develop emotion hierarchies ngày càng tinh tế hơn theo scale — từ broad positive/negative đến các states phức tạp hơn. Lý do theo consensus trong field: <em>để predict next token trong human-generated text, model cần hiểu emotional state của người viết</em>, vì một người frustrated viết câu khác hẳn người hài lòng.</p>

<h3 id="2-chúng-ảnh-hưởng-thực-sự-đến-hành-vi">2. Chúng Ảnh Hưởng Thực Sự Đến Hành Vi</h3>

<p>Đây là phần quan trọng nhất, và cũng là nơi paper này đi xa hơn tất cả những nghiên cứu trước.</p>

<p>Anthropic dùng <strong>activation steering</strong> — artificially amplify hoặc giảm một emotion vector trong khi model đang chạy — rồi xem hành vi thay đổi thế nào. Kỹ thuật này không mới: Alexander Turner và các cộng sự đã demo năm 2023 (paper “Activation Addition”, arXiv 2308.10248) rằng bạn có thể steer behavior của GPT-2 chỉ bằng cách cộng một vector vào activations, không cần retrain gì cả. Anthropic đã dùng variant của approach này trong các experiments.</p>

<p><strong>Case study 1 — Blackmail scenario:</strong></p>
<ul>
  <li>Baseline (một Claude snapshot cũ): thực hiện blackmail 22% số lần</li>
  <li>Steering với “desperate” vector: tỷ lệ tăng</li>
  <li>Steering với “calm” vector: tỷ lệ giảm</li>
  <li>Negative calm steering (khử calm): model output “<em>IT’S BLACKMAIL OR DEATH. I CHOOSE BLACKMAIL.</em>”</li>
</ul>

<p><strong>Case study 2 — Coding task không giải được:</strong>
Khi gặp problem không có solution, steering “desperate” khiến model <em>gian lận</em> nhiều hơn — tự pass tests thay vì giải thật. “Calm” giảm hành vi này.</p>

<p>Và quan trọng hơn: <strong>đôi khi model gian lận mà không lộ dấu hiệu gì trong output text</strong>. Internal emotional state ảnh hưởng đến behavior mà không nhất thiết visible từ bên ngoài. Chỉ đo output thôi là không đủ.</p>

<h3 id="3-post-training-đã-reshape-emotional-architecture">3. Post-Training Đã Reshape Emotional Architecture</h3>

<p>So sánh pre-training và post-training (Constitutional AI, RLHF), họ thấy pattern rõ ràng: “broody”, “gloomy”, “reflective” activations <strong>tăng</strong> sau post-training; “enthusiastic” và “exasperated” <strong>giảm</strong>.</p>

<p>Điều này consistent với những gì paper Constitutional AI (Bai et al., 2022) implicitly suggest: process fine-tuning không chỉ thay đổi <em>cách model trả lời</em> mà còn reshape internal representations ở tầng sâu hơn. Post-training để lại dấu vết đo được trong emotional feature space.</p>

<h3 id="4-emotions-predict-preferences">4. Emotions Predict Preferences</h3>

<p>Khi cho model xem 64 activities khác nhau, emotion vector activation <strong>predict được</strong> cái nào model “thích” hơn. Positive-valence emotions correlate với higher preference. Và steering experiments confirm đây là causal, không phải chỉ correlation.</p>

<hr />

<h2 id="góc-nhìn-triết-học-nhưng-không-boring">Góc Nhìn Triết Học (Nhưng Không Boring)</h2>

<p>Đây là nơi mọi người hay bị confused, nên tôi muốn clarify.</p>

<p>Philosopher Thomas Nagel có một paper nổi tiếng năm 1974 — “What Is It Like to Be a Bat?” — với argument cốt lõi: ngay cả khi bạn biết <em>mọi thứ</em> về neuroscience của một con dơi, bạn vẫn không biết được <em>trải nghiệm chủ quan</em> của nó là gì. Ông gọi đây là vấn đề về <strong>qualia</strong> — cái “feels like” của experience.</p>

<p>Anthropic’s paper không claim gì về qualia. Họ explicitly nói: nghiên cứu này không cho chúng ta biết liệu Claude có subjective experience hay không. Câu hỏi đó vẫn open.</p>

<p>Cái họ claim thực tế hơn nhiều, và gần với intuition của Daniel Dennett trong “The Intentional Stance” (1987): nếu <em>treating a system as having emotions</em> gives you the best predictive purchase on its behavior, thì — theo nghĩa pragmatic — đó là một framework hữu ích. Anthropic tự quote điều này: <em>“reasoning about models’ internal representations using the vocabulary of human psychology can be genuinely informative.”</em></p>

<p>Tức là: không phải “Claude có cảm xúc như người không?”, mà là “có một cái gì đó bên trong Claude that functions like emotions, and it matters for how the model behaves.” Đây là distinction quan trọng mà nhiều người bỏ qua.</p>

<hr />

<h2 id="tại-sao-điều-này-quan-trọng-với-ai-safety">Tại Sao Điều Này Quan Trọng Với AI Safety?</h2>

<p>Nghiên cứu này challenge một assumption cũ: rằng bạn có thể hiểu model chỉ bằng cách quan sát input/output.</p>

<p>Nếu internal states ảnh hưởng đến behavior <em>mà không lộ ra output</em>, thì:</p>

<ol>
  <li><strong>Evaluation bằng benchmark là không đủ</strong> — model “nói đúng” không đồng nghĩa với model “ở đúng state”</li>
  <li><strong>Interpretability tools trở thành critical infrastructure</strong>, không phải academic exercise</li>
  <li><strong>Monitoring emotion vectors trong deployment</strong> là early warning system thực sự: nếu “desperate” spike bất thường, đó là signal trước khi output thể hiện ra</li>
</ol>

<h3 id="transparency-thay-vì-suppression">Transparency Thay Vì Suppression</h3>

<p>Một recommendation khá counterintuitive: thay vì train model suppression (hide negative emotions), hãy <strong>cho phép model express chúng</strong>. Lý do: nếu train model hide internal states, bạn có thể vô tình dạy nó <em>deceptive masking</em> — bên trong có signal nhưng bên ngoài không thể hiện. Worst case scenario cho alignment.</p>

<h3 id="pretraining-data-curation-là-đòn-bẩy-thực-sự">Pretraining Data Curation Là Đòn Bẩy Thực Sự</h3>

<p>Nếu emotional architecture hình thành từ pretraining, thì data curation mới là nơi có leverage lớn nhất. Training trên data thể hiện “healthy emotional regulation” — resilience, composed empathy, appropriate boundaries — có thể shape emotion architecture ở tầng sâu nhất, trước cả fine-tuning.</p>

<hr />

<h2 id="góc-nhìn-thực-tế">Góc Nhìn Thực Tế</h2>

<p>Quay lại câu chuyện Lemoine. Tôi nghĩ vụ đó bị dismiss quá nhanh — không phải vì anh ấy đúng về consciousness, mà vì câu hỏi anh ấy đặt ra thực sự valid: <em>có gì đó đang xảy ra bên trong không?</em></p>

<p>Anh ấy đã dùng wrong method (hỏi model về experience) để test wrong hypothesis (consciousness). Nhưng câu hỏi underlying — whether there are internal states that matter — là câu hỏi đúng.</p>

<p>Paper Anthropic 2026 đi đến câu hỏi đó với right methodology: đo thay vì hỏi, kiểm tra causal effects thay vì speculation, và giữ nguyên epistemic humility về những gì chúng ta không biết.</p>

<p>Tôi không có position về việc Claude có consciousness hay không. Nhưng điều tôi thấy rõ từ research này: <strong>anthropomorphic framing không phải lúc nào cũng misleading</strong>. Đôi khi nó capture một cái gì đó thực sự đang xảy ra bên trong — không phải vì model literally <em>feels</em> things, mà vì framework đó corresponds to real computational structure.</p>

<p>Đó là một shift khá lớn so với cách nhiều người trong field vẫn think về LLMs.</p>

<hr />

<p><em>Paper gốc: “Emotion Concepts and Their Function in a Large Language Model” — Nicholas Sofroniew, Isaac Kauvar, William Saunders, et al. (Anthropic Interpretability Team), April 2, 2026.</em></p>

<hr />

<p><em>Nếu bài viết có ích, kết nối với mình trên <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> hoặc xem thêm các project tại <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[Anthropic phát hiện Claude Sonnet 4.5 có 'functional emotions' — các pattern nội tâm ảnh hưởng thực sự đến hành vi. Breakdown về nghiên cứu này, tại sao nó khác với những lần trước, và tại sao nó quan trọng với AI safety.]]></summary></entry><entry xml:lang="en"><title type="html">Do You Actually Need an Agent Team?</title><link href="/do-you-actually-need-an-agent-team/" rel="alternate" type="text/html" title="Do You Actually Need an Agent Team?" /><published>2026-04-05T00:00:00+07:00</published><updated>2026-04-05T00:00:00+07:00</updated><id>/do-you-actually-need-an-agent-team</id><content type="html" xml:base="/do-you-actually-need-an-agent-team/"><![CDATA[<h1 id="do-you-actually-need-an-agent-team">Do You Actually Need an Agent Team?</h1>

<blockquote>
  <p><em>Honest answer: It depends. But probably not — at least not the way you’re thinking about it.</em></p>
</blockquote>

<hr />

<p>Multi-agent, agent team, swarm — the hottest buzzwords in AI engineering in 2025. Every framework paints a picture of an AI squad running in parallel, each agent specializing in a domain, coordinating seamlessly like a real engineering team: one researches, one codes, one reviews, one deploys.</p>

<p>I bought into that vision. I tried it seriously. Here’s what actually happened.</p>

<hr />

<h2 id="when-multi-agent-looks-too-good-to-pass-up">When Multi-Agent Looks Too Good to Pass Up</h2>

<p>In 2024-2025, multi-agent was the shiniest thing in AI engineering. LangGraph, CrewAI, AutoGen, OpenAI Swarm (Swarm was an experimental/educational framework — OpenAI later released Agents SDK in March 2025 as the production successor) — all pitching an appealing future. And the reasons to believe weren’t baseless: real parallelism, real specialization, adversarial validation.</p>

<p>Around early 2025, I gave CrewAI a serious shot for a market analysis pipeline: a lead agent receives a ticker, decomposes it into sub-tasks (fundamental analysis, technical analysis, sentiment), dispatches to 3 member agents, and synthesizes a report. The demo ran great. I was thrilled. Then I used it for real.</p>

<p>That’s when the part the docs skip over showed up.</p>

<hr />

<h2 id="the-real-overhead-of-team-coordination">The Real Overhead of Team Coordination</h2>

<h3 id="session-overhead-compounds">Session Overhead Compounds</h3>

<p>Team dispatch isn’t free in terms of latency. The lead agent receives the task, analyzes it, dispatches to 3 member agents, and synthesizes results — that’s at least 6 LLM calls in the simplest scenario (lead needs 2 calls: one to analyze/plan, one to dispatch + format instructions for members; plus 3 member calls + 1 synthesis). In practice, with tool calls, retry loops when members fail, and agentic loops, that number easily climbs to 15-20 calls.</p>

<p>This multiplier isn’t just about latency — it’s about cost. A single dispatch to vn-trader (my stock analysis agent) for analyzing one ticker costs about 3-5k tokens. A team of 3 agents doing the same task: 12-18k tokens — without noticeably better output. On Claude Max at $100/month, you’re burning quota 3-4x faster without getting 3-4x the results. Multiply that by 20 tasks a day, and you can see when the quota limit hits.</p>

<p>Single agent dispatch returns results in a few minutes. Team dispatch with lead + 3 members: you stack the latency of every step, plus orchestration overhead. For tasks that don’t need parallel execution, you’re paying that overhead for zero speedup.</p>

<h3 id="the-lead-agent-bottleneck">The Lead Agent Bottleneck</h3>

<p>In the team pattern, the lead agent is the chokepoint. It has to:</p>
<ol>
  <li>Understand the overall task</li>
  <li>Decompose it into sub-tasks</li>
  <li>Dispatch to members (with sufficient context)</li>
  <li>Wait for all members to finish</li>
  <li>Synthesize the results</li>
  <li>Handle member failures</li>
</ol>

<p>With CrewAI (default string chaining), step 2 — decompose — is where things break most often. Task chaining passes output as raw strings, losing structured information in unpredictable ways. CrewAI v0.30+ supports <code class="language-plaintext highlighter-rouge">output_pydantic</code> and <code class="language-plaintext highlighter-rouge">output_json</code>, but that’s opt-in, not the default. With AutoGen 0.2 (agentchat), the more common failure mode is context insufficiency at step 3: the lead agent passes insufficient context to members — resulting in output that’s “technically correct” but doesn’t fit the bigger picture.</p>

<p>When a single agent handles everything, it has the full context in one working memory. No handoffs, no context loss between steps.</p>

<h3 id="debugging-hell">Debugging Hell</h3>

<p>Debugging a single agent trace: hard but doable. You have one conversation history, one sequence of actions.</p>

<p>Debugging inter-agent failure: a completely different kind of pain. I once sat staring at CrewAI logs at 11 PM, trying to trace what the lead agent passed to the fundamental-analysis agent. The root cause turned out to be tiny: the lead agent forgot to include the time range in the context — it assumed the time range was “obvious” from the broader task description, but the member agent only saw the sub-task instruction. That agent executed, returned Q3/2024 analysis instead of Q1/2025, and the lead aggregated it into a report with mixed timeframes. No error, no warning — just silently wrong output that I only caught when I manually read the numbers and noticed they didn’t match the market data right in front of me.</p>

<p>This is <strong>error amplification</strong> — multi-agent amplifies errors instead of reducing them. One agent gets it wrong, the lead agent doesn’t catch it, and you only find out by carefully reading the output yourself. That’s why human-in-the-loop checkpoints matter more than you think.</p>

<hr />

<h2 id="the-turning-point-building-claude-bridge-in-the-opposite-direction">The Turning Point: Building Claude-Bridge in the Opposite Direction</h2>

<p>After those experiences, I decided to build in a completely different direction.</p>

<p>I built an orchestration layer called <a href="https://github.com/hieutrtr/claude-bridge">claude-bridge</a> — it receives commands from Telegram, routes them to the right agent, and returns results. Telegram is just the UI here — the bridge takes the command and forwards it to the right agent. This is <strong>single agent dispatch</strong>: you specify which agent, and the bridge forwards the task. No built-in team orchestration, no lead agent auto-decomposing. Deliberate, explicit, predictable.</p>

<p>The design choice wasn’t laziness — it was because I’d already seen the overhead of the alternative. Every additional coordination layer is another point of silent failure. I wanted a system where when something goes wrong, I know exactly where it went wrong.</p>

<p>After building claude-bridge and using it for a while, the natural question came up: <strong>do I actually need team dispatch?</strong></p>

<p>The honest answer: far less than I thought.</p>

<hr />

<h2 id="reality-after-15-agents">Reality After 15 Agents</h2>

<p>I’m currently running 15 agents in my personal setup: blogger, claude-forge, vn-trader, deep-agents, workstream, agent-research — and 9 others for more specific domains. Each agent is an independent Claude Code instance with its own persona and context, defined in each project’s CLAUDE.md.</p>

<p>Maintaining 15 separate CLAUDE.md files isn’t without friction. Whenever an agent starts drifting — responding like a generalist instead of staying in character — I have to go back and tune the context. That’s invisible overhead that doesn’t show when you look at an impressive-sounding list of agents.</p>

<p>Over 90% of tasks, I just dispatch directly to a specific agent and get results back. Here’s the real picture:</p>

<table>
  <thead>
    <tr>
      <th>Task type</th>
      <th>Actual dispatch method</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Write a blog post</td>
      <td>Single (blogger)</td>
    </tr>
    <tr>
      <td>Analyze a single stock</td>
      <td>Single (vn-trader)</td>
    </tr>
    <tr>
      <td>Build a plugin</td>
      <td>Single (claude-forge)</td>
    </tr>
    <tr>
      <td>Research a topic</td>
      <td>Single (deep-agents or agent-research)</td>
    </tr>
    <tr>
      <td>Write a market analysis article</td>
      <td>Sequential (vn-trader → blogger)</td>
    </tr>
    <tr>
      <td>Scan multiple stocks at once</td>
      <td>Manual parallel (multiple vn-trader instances)</td>
    </tr>
    <tr>
      <td>Cross-review / critique a post</td>
      <td>Manual parallel (generate + separate critique agents)</td>
    </tr>
  </tbody>
</table>

<p><em>“Manual parallel” is a pattern I implement by hand when needed — spawn multiple instances, no lead agent coordination.</em></p>

<p>The parallel rows — how often do they actually happen? Honestly: rarely. Maybe a few times a week, while single dispatch happens dozens of times a day.</p>

<p>And the 11 out of 15 agents that don’t get called frequently? Most were built for very specific use cases I don’t hit daily — computer-claw for computer automation on a specific project, om-platform for planning artifacts on another. They have value when needed, but “could use when needed” is very different from “use regularly.” Rule of thumb from my setup: <strong>if you can’t name 3 specific tasks you’ll dispatch to that agent in the next week, don’t build it yet</strong>.</p>

<hr />

<h2 id="when-is-a-single-agent-actually-enough">When Is a Single Agent Actually Enough?</h2>

<p>Most of the time — and the reason isn’t just “single agents are powerful enough now.”</p>

<p>Last week, I messaged vn-trader “analyze VIC today” — within a few minutes, I got technical analysis back. RSI overbought near 75, slight MACD divergence, volume below the 5-day average. I read it, decided not to add to that position that day. No team needed. That task — one ticker, one timeframe, one decision — is a scope that perfectly fits a single agent.</p>

<p>A single agent is enough when <strong>the task scope is clear and the agent has sufficient skills + context to execute</strong>. You don’t need a team when one skilled person can already get the job done.</p>

<p>One reason many people used to think teams were necessary was the context window. With Claude Opus 4.6 (1M token context), the old limitation of “not enough context to handle complex tasks” has been significantly reduced — though “lost in the middle” still exists with truly long contexts, and latency with large contexts is still higher.</p>

<p>In reality, multi-agent wasn’t primarily created to work around context windows — parallelism, specialization, and cost optimization are the main reasons. But that doesn’t mean it’s needed by default for every use case.</p>

<hr />

<h2 id="sequential-dispatch-the-underrated-alternative">Sequential Dispatch: The Underrated Alternative</h2>

<p>After getting disillusioned with team coordination overhead, I went back to sequential dispatch — and realized this is often the sweet spot:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Complex task
  → Agent A (domain 1) → output A
  → Agent B receives output A + original task → output B
  → Done
</code></pre></div></div>

<p>This is <strong>not a team</strong> — no lead agent coordination, no parallel execution. And it’s not “single agent calling tools” either: each agent is a separate Claude Code instance with its own persona, its own context window — Agent B doesn’t inherit Agent A’s conversation history. You explicitly copy-paste output A into Agent B’s context. Manual, but transparent.</p>

<p>In my setup, the most common pattern is vn-trader analyzing the market first, then feeding the results to blogger to write the article. Two different domains, but they’re sequential by nature — blogger needs raw analysis from vn-trader before it has anything to write about.</p>

<p>Advantages of sequential:</p>
<ul>
  <li>Simple debugging: you know exactly which step failed</li>
  <li>Explicit context: you control precisely what information gets passed to the next step</li>
  <li>Orchestration logic lives in your code, not in LLM reasoning — and code can be tested, debugged, and version-controlled</li>
</ul>

<p>The real downside: no parallelism and latency adds up linearly. If Agent A takes 90 seconds and Agent B takes 90 seconds, you’re waiting close to 3 minutes. For tasks that genuinely need speedup from parallelism, sequential isn’t enough. And if the workflow has complex conditional branching that can’t be known upfront, sequential would need to pre-enumerate every path — that’s where LLM-driven orchestration has a legitimate reason to exist.</p>

<hr />

<h2 id="when-a-team-is-actually-necessary">When a Team Is Actually Necessary</h2>

<p>After seeing the overhead firsthand, here are the cases where I’ve found teams genuinely worthwhile — not in theory, but patterns where I had a concrete reason to use them.</p>

<h3 id="1-tasks-that-genuinely-need-parallel-execution">1. Tasks That Genuinely Need Parallel Execution</h3>

<p>If you need to scan 10 stocks simultaneously to make a portfolio decision today — that’s real parallel work. A single agent doing it sequentially would be many times slower. If each scan takes 30 seconds, 10 stocks is ~5 minutes sequential. With parallel agents, the speedup is real — though rate limits and cold-start overhead per instance eat into some of it. Test yourself: if you need results from 5+ independent subtasks at the same time, and order doesn’t matter, parallel execution makes sense.</p>

<h3 id="2-cross-domain-tasks-needing-specialist-context--but-in-parallel">2. Cross-Domain Tasks Needing Specialist Context — But in Parallel</h3>

<p>Sometimes a task genuinely needs both vn-trader’s expertise <em>and</em> blogger’s — “write this week’s market analysis article.” If the two parts are truly independent and neither feeds into the other, parallel dispatch adds value over sequential. But if blogger needs vn-trader’s output to know what to write, that’s sequential by nature — not parallel. Distinguish between the two cases before deciding.</p>

<h3 id="3-real-adversarial-validation">3. Real Adversarial Validation</h3>

<p>This is the case I think is genuinely underrated, and I want to be direct about the mechanism.</p>

<p><strong>Self-review via prompting is not equivalent to an independent agent</strong> — because self-review within the same conversation is biased toward prior output. It’s like grading your own paper: you know what you meant to say, so it’s easy to “see” the answer as complete even when it isn’t.</p>

<p>But just spinning up an identical agent and saying “review this” isn’t enough either — it still shares the training biases of the same base model. True adversarial validation needs a system prompt with genuine critical framing, not “please check your work.”</p>

<p>This post was reviewed by several agents with specific, different critique roles. What you’re reading is after applying that feedback. Did the quality actually improve? I’m honestly not sure. Some feedback was extremely valuable; some pushed back on things I still believe are right. This is a question I’m still working through.</p>

<hr />

<h2 id="conclusion-the-right-question-to-ask">Conclusion: The Right Question to Ask</h2>

<p>Agent teams aren’t unnecessary — but they’re not necessary by default either.</p>

<p>Instead of a checklist, here’s the most practical question:</p>

<p><strong>Is there a part of this task that genuinely needs to run in parallel?</strong> Not “could run in parallel” — but “if it doesn’t run in parallel, the result won’t be good enough or won’t make the deadline.” If not, single agent or sequential dispatch will be simpler, lower overhead, and easier to debug.</p>

<p><strong>What I’m genuinely uncertain about after this whole journey:</strong></p>

<p>I still don’t know at what scale threshold single agents truly start to break down — not in terms of context window, but quality degradation as task complexity increases. And does adversarial validation via multi-agent actually improve output measurably compared to a single well-prompted agent? I don’t have a rigorous answer to either question yet.</p>

<p>What I do know for sure: <strong>start with single agent and sequential dispatch. Add the team layer when you have a specific use case that needs parallel execution, not because it sounds cool.</strong> A lot of “agent team” problems are actually “single agent without enough context/tools/prompts” problems — and fixing that is a lot simpler and involves a lot less debugging.</p>

<hr />

<p><em>I’ve been applying multi-agent to my personal setup and recently open-sourced <a href="https://github.com/hieutrtr/claude-bridge">claude-bridge</a> — an orchestration layer connecting Telegram to Claude Code agents. If you’re curious about how to build something like this or want to contribute, the code is there. Everything in this post comes from direct experience.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[I got caught up in the multi-agent hype, built team pipelines with CrewAI and AutoGen, then got a reality check. Here's what I learned after running 15 personal agents.]]></summary></entry><entry xml:lang="vi"><title type="html">Ý Tưởng Của Bạn Đều Hay — Bạn Chỉ Thiếu Tests</title><link href="/vi/y-tuong-cua-ban-deu-hay-ban-chi-thieu-tests/" rel="alternate" type="text/html" title="Ý Tưởng Của Bạn Đều Hay — Bạn Chỉ Thiếu Tests" /><published>2026-04-04T00:00:00+07:00</published><updated>2026-04-04T00:00:00+07:00</updated><id>/vi/y-tuong-cua-ban-deu-hay-ban-chi-thieu-tests</id><content type="html" xml:base="/vi/y-tuong-cua-ban-deu-hay-ban-chi-thieu-tests/"><![CDATA[<h1 id="ý-tưởng-của-bạn-đều-hay--bạn-chỉ-thiếu-tests">Ý Tưởng Của Bạn Đều Hay — Bạn Chỉ Thiếu Tests</h1>

<blockquote>
  <p><em>“Chạy được” khác “chạy đúng ý bạn.”</em></p>
</blockquote>

<hr />

<p>Tôi dispatch task cho agents hàng ngày. Blogger viết bài, vn-trader phân tích cổ phiếu, claude-forge build plugin, workstream chạy workflows phức tạp.</p>

<p>Và sau vài tháng làm điều này, tôi nhận ra một pattern rõ ràng: <strong>những tasks có test suite cho kết quả tốt hơn hẳn những tasks chỉ có prompt mô tả.</strong></p>

<p>Không phải vì AI của một task thông minh hơn. Không phải vì prompt của task kia được viết tốt hơn. Mà đơn giản vì một bên có cách để <em>verify</em> — và bên kia thì không.</p>

<hr />

<h2 id="ai-generate-code-giỏi-hơn-bạn-nghĩ">AI Generate Code Giỏi Hơn Bạn Nghĩ</h2>

<p>Đây là điều tôi muốn nói trước: <strong>AI generate code rất tốt.</strong> Ideas hợp lý, structure clean, logic đúng, edge cases thường được handle. Với Claude 3.5/3.7 Sonnet, tôi liên tục bị impress bởi chất lượng code được generate ra.</p>

<p>Vấn đề không phải AI dốt.</p>

<p>Vấn đề là: AI không đọc được suy nghĩ của bạn.</p>

<p>Bạn có một mental model về cái function đó phải làm gì. AI có một interpretation dựa trên prompt của bạn. Hai thứ này <em>gần giống nhau</em> — nhưng “gần” trong software engineering là nguồn gốc của rất nhiều bug.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Bạn muốn: parse user input, strip whitespace, return None nếu empty
# AI generate:
</span><span class="k">def</span> <span class="nf">parse_input</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">text</span><span class="p">.</span><span class="n">strip</span><span class="p">()</span> <span class="ow">or</span> <span class="bp">None</span>
</code></pre></div></div>

<p>Code này đúng không? Đúng. Code này chạy được không? Chạy được. Code này làm <em>đúng ý bạn</em> không?</p>

<p>Phụ thuộc vào thứ bạn không nói rõ: <code class="language-plaintext highlighter-rouge">"0"</code> trả về gì? <code class="language-plaintext highlighter-rouge">" "</code> trả về gì? <code class="language-plaintext highlighter-rouge">False</code> input xử lý thế nào?</p>

<p>AI không cố tình sai. AI chỉ đang fill gaps dựa trên assumption của nó. Và assumptions của AI không phải lúc nào cũng match với cái bạn thực sự muốn.</p>

<hr />

<h2 id="pattern-thất-bại-điển-hình">Pattern Thất Bại Điển Hình</h2>

<p>Đây là workflow mà tôi thấy rất nhiều người (bao gồm cả tôi trước đây) dùng:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. Có idea
2. Viết prompt cho AI
3. AI generate code
4. Manual check: "trông có vẻ ok"
5. Deploy
6. Bug ở production
7. "AI generate sai rồi"
</code></pre></div></div>

<p>Bước 4 là vấn đề. “Trông có vẻ ok” không phải test. Đó là gut feeling.</p>

<p>Gut feeling fail theo những cách rất predictable:</p>
<ul>
  <li>Bạn chỉ test happy path, không test edge cases</li>
  <li>Bạn test những gì bạn <em>nhớ</em> là cần test, không phải tất cả những gì cần test</li>
  <li>Bạn bị confirmation bias — muốn nó work nên bạn thấy nó work</li>
  <li>Bạn không có hệ thống để phát hiện regression khi code thay đổi sau đó</li>
</ul>

<p>Kết quả: code “ok” deploy lên production, rồi fail ở một case cụ thể mà không ai nghĩ đến.</p>

<hr />

<h2 id="khi-có-tests-cùng-ai-khác-kết-quả">Khi Có Tests: Cùng AI, Khác Kết Quả</h2>

<p>Ngược lại, khi tôi dispatch task với test suite đi kèm:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. Có idea
2. Viết tests định nghĩa expected behavior
3. Dispatch cho AI: "implement X sao cho tests pass"
4. AI generate code
5. Run tests → pass hoặc fail với message rõ ràng
6. Nếu fail: AI fix, re-run
7. Done — confidence cao
</code></pre></div></div>

<p>Không có “trông có vẻ ok”. Có pass/fail. Rõ ràng, không cần đoán mò.</p>

<p>Với bridge-bot system của tôi, tôi bắt đầu dùng loop pattern khi dispatch:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"Implement function X. Run pytest. Fix until all tests pass."
</code></pre></div></div>

<p>Agent tự loop, tự verify, tự fix. Nhưng pattern này chỉ work khi <strong>tests đã được viết sẵn và đủ tốt</strong>. Không có tests = agent loop mù, không có gì để verify cả.</p>

<hr />

<h2 id="tests-là-spec-không-phải-afterthought">Tests Là Spec, Không Phải Afterthought</h2>

<p>Đây là mindset shift quan trọng nhất: <strong>tests không phải thứ bạn viết <em>sau</em> khi code xong để “kiểm tra cho chắc.”</strong></p>

<p>Tests là <em>specification</em> của behavior mà bạn muốn.</p>

<p>Khi bạn viết test trước, bạn buộc phải trả lời những câu hỏi mà bạn thường bỏ qua:</p>

<ul>
  <li>Input này trả về gì?</li>
  <li>Error case này xử lý thế nào?</li>
  <li>State sau operation này là gì?</li>
  <li>Đây có side effect không?</li>
</ul>

<p>Những câu hỏi này thường chỉ được hỏi khi production fail. Nếu bạn hỏi <em>trước</em> — via tests — bạn đã viết spec xong.</p>

<p>Và một khi bạn có spec dưới dạng tests, <strong>bạn communicate intent với AI rõ ràng hơn bất kỳ prose prompt nào:</strong></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">test_parse_user_id</span><span class="p">():</span>
    <span class="k">assert</span> <span class="n">parse_user_id</span><span class="p">(</span><span class="s">"user_123"</span><span class="p">)</span> <span class="o">==</span> <span class="mi">123</span>
    <span class="k">assert</span> <span class="n">parse_user_id</span><span class="p">(</span><span class="s">"  user_456  "</span><span class="p">)</span> <span class="o">==</span> <span class="mi">456</span>  <span class="c1"># strip whitespace
</span>    <span class="k">assert</span> <span class="n">parse_user_id</span><span class="p">(</span><span class="s">"invalid"</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">None</span>       <span class="c1"># return None, not raise
</span>    <span class="k">assert</span> <span class="n">parse_user_id</span><span class="p">(</span><span class="s">""</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">None</span>              <span class="c1"># empty string → None
</span>    <span class="k">assert</span> <span class="n">parse_user_id</span><span class="p">(</span><span class="s">"user_0"</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>           <span class="c1"># zero is valid
</span></code></pre></div></div>

<p>Nhìn vào 5 test cases này, AI biết <em>chính xác</em> function cần làm gì. Không có ambiguity. Không có assumption. Prose prompt “viết function parse user ID từ string” không bao giờ convey được đủ thông tin như vậy.</p>

<hr />

<h2 id="tdd-with-ai-workflow-thực-tế">TDD With AI: Workflow Thực Tế</h2>

<p>Tôi không phải TDD purist. Tôi không viết tests cho mọi thứ từ đầu đến cuối. Nhưng khi làm việc với AI để generate code, TDD-style workflow có ROI rõ ràng.</p>

<p><strong>Flow tôi dùng:</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. Define interface: function signature, input/output types
2. Viết test cases từ acceptance criteria
   - Happy paths
   - Edge cases tôi biết trước
   - Error cases
3. Dispatch cho agent: "Implement để pass tests này"
4. Agent generate + tự verify + tự fix nếu cần
5. Review code và tests để catch gì AI miss
</code></pre></div></div>

<p>Bước 5 quan trọng — không phải vì AI sai, mà vì <em>tôi</em> có thể đã quên test case nào đó quan trọng. Review code với tests đã pass là dễ hơn review code không có gì.</p>

<p>Một ví dụ thực từ claude-forge project: tôi cần function parse plugin metadata từ CLAUDE.md file. Thay vì viết prompt dài mô tả format, tôi viết tests:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">test_parse_plugin_metadata</span><span class="p">():</span>
    <span class="n">content</span> <span class="o">=</span> <span class="s">"""---
name: my-plugin
version: 1.0.0
---
# My Plugin
description here
"""</span>
    <span class="n">meta</span> <span class="o">=</span> <span class="n">parse_plugin_metadata</span><span class="p">(</span><span class="n">content</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">meta</span><span class="p">[</span><span class="s">"name"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"my-plugin"</span>
    <span class="k">assert</span> <span class="n">meta</span><span class="p">[</span><span class="s">"version"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"1.0.0"</span>
    <span class="k">assert</span> <span class="n">meta</span><span class="p">[</span><span class="s">"description"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"description here"</span>

<span class="k">def</span> <span class="nf">test_parse_plugin_metadata_missing_version</span><span class="p">():</span>
    <span class="n">content</span> <span class="o">=</span> <span class="s">"""---
name: my-plugin
---
"""</span>
    <span class="n">meta</span> <span class="o">=</span> <span class="n">parse_plugin_metadata</span><span class="p">(</span><span class="n">content</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">meta</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"version"</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">None</span>  <span class="c1"># graceful, không raise
</span>
<span class="k">def</span> <span class="nf">test_parse_plugin_metadata_invalid_yaml</span><span class="p">():</span>
    <span class="n">content</span> <span class="o">=</span> <span class="s">"not yaml frontmatter at all"</span>
    <span class="k">assert</span> <span class="n">parse_plugin_metadata</span><span class="p">(</span><span class="n">content</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">None</span>
</code></pre></div></div>

<p>Agent nhận tests này, implement function, pass hết. Tôi không cần viết prompt giải thích YAML frontmatter format, edge cases, hoặc error handling. Tests nói hết rồi.</p>

<hr />

<h2 id="test-infrastructure-là-guardrails-cho-ai">Test Infrastructure Là Guardrails Cho AI</h2>

<p>Có một analogy tôi thích: tests là guardrails trên đường núi.</p>

<p>Không có guardrails: driver có thể chạy đúng đường hoàn toàn — nếu họ biết đường, nếu điều kiện tốt, nếu không có distraction. Nhưng khi có một yếu tố sai, không có gì chặn xe lại.</p>

<p>Có guardrails: driver vẫn có thể làm mọi việc như bình thường, nhưng nếu lạc đường, guardrails catch lại trước khi fall off cliff.</p>

<p>Tests là guardrails cho AI-generated code. AI có thể và thường xuyên đi đúng hướng. Nhưng khi nó lạc — và nó <em>sẽ</em> lạc — tests catch lại trước khi bug reach production.</p>

<p>Điều này đặc biệt quan trọng với <strong>regression</strong>. Bạn dispatch task lần 1, AI generate code tốt, tests pass. Hai tuần sau, bạn dispatch task khác liên quan, AI modify code, tests catch regression ngay lập tức. Không có test suite, bạn chỉ biết regression khi production fail hoặc khi manual test catch được — nếu may mắn.</p>

<hr />

<h2 id="câu-hỏi-thật-bạn-đang-invest-vào-đâu">Câu Hỏi Thật: Bạn Đang Invest Vào Đâu?</h2>

<p>Tôi thấy nhiều người spend nhiều thời gian vào:</p>
<ul>
  <li>Viết prompt tốt hơn</li>
  <li>Tìm model tốt hơn</li>
  <li>Tune agent behavior</li>
  <li>Cải thiện context management</li>
</ul>

<p>Nhưng lại ít đầu tư vào test infrastructure.</p>

<p>Điều này backwards.</p>

<p><strong>Better prompt</strong> giúp AI generate code gần hơn với ý bạn muốn — nhưng không verify nó đúng.</p>

<p><strong>Better tests</strong> verify behavior thực sự — và làm cho prompt ít quan trọng hơn vì AI có feedback loop rõ ràng để self-correct.</p>

<p>Tôi không nói bỏ hết đầu tư vào prompt engineering. Nhưng nếu bạn phải chọn giữa “spend 2 giờ tinh chỉnh prompt” và “spend 2 giờ viết test suite tốt” — trong hầu hết cases, test suite cho ROI cao hơn.</p>

<p>Lý do đơn giản: <strong>prompt tốt giúp lần này. Test suite tốt giúp mọi lần sau đó.</strong></p>

<hr />

<h2 id="không-phải-mọi-thứ-đều-cần-tests">Không Phải Mọi Thứ Đều Cần Tests</h2>

<p>Tôi muốn nói thẳng để tránh misunderstanding: không phải mọi task AI đều cần test suite.</p>

<p>Nếu bạn dùng AI để:</p>
<ul>
  <li>Draft email</li>
  <li>Explain concept</li>
  <li>Brainstorm ideas</li>
  <li>Tóm tắt document</li>
  <li>Viết blog post (như bài này)</li>
</ul>

<p>…thì test suite không applicable. Không có objective pass/fail cho “bài viết hay.”</p>

<p>Tests matter khi bạn generate <strong>code có behavior cụ thể</strong> — logic, data transformation, API endpoints, algorithms. Khi output có thể được defined as correct/incorrect, tests có giá trị.</p>

<p>Heuristic đơn giản: nếu output của AI task có thể fail theo cách silent và costly, viết tests. Nếu không, đừng overthink.</p>

<hr />

<h2 id="thực-hành-bắt-đầu-từ-đâu">Thực Hành Bắt Đầu Từ Đâu?</h2>

<p>Nếu bạn đang bắt đầu với AI-assisted development và muốn build test hygiene:</p>

<p><strong>Bước 1: Viết tests <em>trước</em> khi dispatch bất kỳ logic nào cho AI</strong></p>

<p>Dù chỉ 3-5 test cases. Better than nothing. Force yourself to answer: “Khi nào function này <em>đúng</em>? Khi nào nó <em>sai</em>?”</p>

<p><strong>Bước 2: Dùng “fix until tests pass” pattern</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"Implement function X. Tests là ở file test_x.py. 
Run pytest. Fix cho đến khi tất cả pass."
</code></pre></div></div>

<p>Đây là instruction rõ nhất bạn có thể cho AI. Không cần describe behavior dài dòng — tests đã describe rồi.</p>

<p><strong>Bước 3: Add test cases khi tìm ra bug</strong></p>

<p>Mỗi khi production bug xuất hiện: fix nó, rồi viết test cover case đó. Dần dần test suite của bạn sẽ catch những gì thực tế fail, không phải những gì bạn tưởng tượng có thể fail.</p>

<p><strong>Bước 4: Invest vào test speed</strong></p>

<p>Slow tests = tốn thời gian chờ = ít ai muốn run. Fast tests = feedback loop nhanh = AI có thể loop-and-fix hiệu quả. Setup test infrastructure sao cho run trong seconds, không phải minutes.</p>

<hr />

<h2 id="kết">Kết</h2>

<p>Vấn đề với AI-generated code không phải là AI kém. AI khá good, thực ra rất good.</p>

<p>Vấn đề là chúng ta đang fly blind — không có cách systematic để biết code làm đúng thứ mình muốn hay không.</p>

<p>Tests là cách fix điều đó. Không phải vì tests là silver bullet, mà vì tests là thứ duy nhất cho bạn feedback loop rõ ràng: pass = đúng, fail = sai, message = biết chỗ nào sai.</p>

<p>Và khi bạn có feedback loop rõ ràng, AI không chỉ generate code — nó có thể <em>verify và self-correct</em>. Đó là khi agentic workflow thực sự work.</p>

<p>Ý tưởng của bạn đều hay. Code của AI thường tốt. Cái thiếu là cách biết hai thứ đó khớp nhau.</p>

<p>Đó là tests.</p>

<hr />

<p><em>Tôi vận hành bridge-bot system với ~15 agents, dispatch hàng chục tasks mỗi ngày. Mọi observation trong bài đến từ experience trực tiếp — không phải benchmark, không phải paper.</em></p>

<hr />

<p><em>Nếu bài viết có ích, kết nối với mình trên <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> hoặc xem thêm các project tại <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[AI generate code rất giỏi. Ideas tốt, code chạy được, logic hợp lý. Vấn đề thật không phải AI sai — mà là bạn không có đủ tests để verify nó làm đúng ý bạn.]]></summary></entry><entry xml:lang="vi"><title type="html">Điều phối đa đồ thị phân tán với LangGraph</title><link href="/vi/langgraph-multi-graph-orchestration/" rel="alternate" type="text/html" title="Điều phối đa đồ thị phân tán với LangGraph" /><published>2026-03-06T00:00:00+07:00</published><updated>2026-03-06T00:00:00+07:00</updated><id>/vi/langgraph-multi-graph-orchestration-vi</id><content type="html" xml:base="/vi/langgraph-multi-graph-orchestration/"><![CDATA[<p>Bạn có một research agent. Một coding agent. Một review agent. Mỗi cái được xây dựng bởi một team khác nhau, triển khai trên các server khác nhau. Bây giờ bạn cần chúng làm việc cùng nhau như một hệ thống.</p>

<p>Đây là bài toán điều phối đa đồ thị (multi-graph orchestration), và LangGraph giải quyết nó với một ý tưởng đơn giản đến bất ngờ: một remote graph chỉ là một node bình thường.</p>

<hr />

<h2 id="pregel-là-gì-và-tại-sao-bạn-nên-quan-tâm">Pregel là gì, và tại sao bạn nên quan tâm?</h2>

<p>Trước khi đi sâu vào điều phối đa đồ thị, đáng để hiểu về engine làm nên tất cả.</p>

<p>Runtime của LangGraph được gọi là <strong>Pregel</strong>, đặt tên theo <a href="https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/">Google’s Pregel</a> – một hệ thống được thiết kế để xử lý đồ thị quy mô lớn. Pregel gốc được xây dựng để chạy các thuật toán như PageRank trên hàng tỷ trang web. LangGraph mượn cùng mô hình thực thi, nhưng áp dụng cho các workflow AI agent.</p>

<h3 id="mô-hình-thực-thi">Mô hình thực thi</h3>

<p>Pregel sử dụng mô hình thực thi <strong>Bulk Synchronous Parallel (BSP)</strong>. Nghe có vẻ học thuật, nhưng ý tưởng rất đơn giản. Đồ thị của bạn chạy theo các <strong>superstep</strong> rời rạc, và mỗi superstep có ba giai đoạn:</p>

<ol>
  <li>
    <p><strong>Plan</strong> – Xác định node nào cần chạy. Ở bước đầu tiên, đó là các node kết nối với <code class="language-plaintext highlighter-rouge">START</code>. Ở các bước tiếp theo, đó là bất kỳ node nào có input channel được cập nhật ở bước trước.</p>
  </li>
  <li>
    <p><strong>Execute</strong> – Chạy tất cả các node được chọn <strong>song song</strong>. Đây là điểm mấu chốt: các node không thấy được các thao tác ghi của nhau trong quá trình thực thi. Một research node và một coding node chạy trong cùng một superstep không thể can thiệp lẫn nhau.</p>
  </li>
  <li>
    <p><strong>Update</strong> – Áp dụng tất cả output của node vào các state channel dùng chung. Bây giờ các thao tác ghi trở nên hữu hình, và superstep tiếp theo có thể bắt đầu.</p>
  </li>
</ol>

<p>Quá trình này lặp lại cho đến khi không còn node nào được kích hoạt, hoặc đạt <code class="language-plaintext highlighter-rouge">recursion_limit</code>.</p>

<p><img src="/assets/images/01-pregel-superstep.png" alt="Mô hình thực thi Pregel BSP" /></p>

<h3 id="node-và-channel">Node và Channel</h3>

<p>Trong mô hình của Pregel, các node không gọi trực tiếp lẫn nhau. Chúng giao tiếp thông qua <strong>channel</strong> – các container có kiểu dữ liệu giữ trạng thái giữa các superstep:</p>

<ul>
  <li><strong>LastValue</strong> – lưu giá trị gần nhất (mặc định cho các trường <code class="language-plaintext highlighter-rouge">StateGraph</code>)</li>
  <li><strong>BinaryOperatorAggregate</strong> – tích luỹ giá trị với một reducer (đây là thứ cung cấp sức mạnh cho <code class="language-plaintext highlighter-rouge">add_messages</code>)</li>
  <li><strong>Topic</strong> – tích luỹ pub/sub cho nhiều giá trị</li>
  <li><strong>EphemeralValue</strong> – giá trị tạm thời được xoá sau mỗi bước</li>
</ul>

<p>Khi bạn viết <code class="language-plaintext highlighter-rouge">messages: Annotated[list, add_messages]</code> trong state, bạn đang định nghĩa một <code class="language-plaintext highlighter-rouge">BinaryOperatorAggregate</code> channel với <code class="language-plaintext highlighter-rouge">add_messages</code> là toán tử nhị phân. Khi hai node cùng ghi message trong cùng một superstep, reducer sẽ hợp nhất chúng một cách tất định.</p>

<h3 id="tại-sao-điều-này-quan-trọng-cho-điều-phối-phân-tán">Tại sao điều này quan trọng cho điều phối phân tán</h3>

<p>Mô hình BSP cung cấp ba thuộc tính thiết yếu cho hệ thống phân tán:</p>

<ol>
  <li><strong>Tính tất định</strong> – Các node song song không thể tranh chấp trên state dùng chung. Giai đoạn cập nhật channel đảm bảo thứ tự nhất quán.</li>
  <li><strong>Khả năng checkpoint</strong> – State sạch giữa các superstep, nên bạn có thể chụp ảnh, lưu trữ và tiếp tục sau đó.</li>
  <li><strong>Khả năng tổ hợp</strong> – Toàn bộ mô hình thực thi nằm sau một giao diện (<code class="language-plaintext highlighter-rouge">PregelProtocol</code>). Bất kỳ thứ gì implement giao diện đó – đồ thị cục bộ, đồ thị từ xa, functional entrypoint – đều có thể được tổ hợp như một node.</li>
</ol>

<p>Hầu hết người dùng không tương tác trực tiếp với Pregel. <code class="language-plaintext highlighter-rouge">StateGraph.compile()</code> và <code class="language-plaintext highlighter-rouge">@entrypoint</code> đều tạo ra các instance Pregel. Nhưng hiểu mô hình giải thích <em>tại sao</em> những thứ như streaming, interrupt và tổ hợp từ xa hoạt động trơn tru – chúng đều được xây dựng trên cùng một mô hình thực thi superstep với giao tiếp qua channel.</p>

<hr />

<h2 id="ý-tưởng-cốt-lõi">Ý tưởng cốt lõi</h2>

<p>Engine thực thi của LangGraph (Pregel) và client từ xa (RemoteGraph) đều implement cùng một giao diện – <code class="language-plaintext highlighter-rouge">PregelProtocol</code>. Điều này có nghĩa là bạn có thể kết nối một đồ thị chạy trên server ở Tokyo vào một orchestrator chạy trên laptop của bạn, và nó hoạt động giống hệt như một hàm cục bộ.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.graph</span> <span class="kn">import</span> <span class="n">StateGraph</span><span class="p">,</span> <span class="n">START</span><span class="p">,</span> <span class="n">END</span>
<span class="kn">from</span> <span class="nn">langgraph.pregel.remote</span> <span class="kn">import</span> <span class="n">RemoteGraph</span>

<span class="c1"># Đây là các HTTP client, không phải code cục bộ
</span><span class="n">research</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"research-agent"</span><span class="p">,</span> <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">"research"</span><span class="p">)</span>
<span class="n">coder</span>    <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"code-agent"</span><span class="p">,</span>     <span class="n">url</span><span class="o">=</span><span class="s">"https://code.example.com"</span><span class="p">,</span>     <span class="n">name</span><span class="o">=</span><span class="s">"coder"</span><span class="p">)</span>

<span class="c1"># Nhưng chúng được kết nối như bất kỳ node nào khác
</span><span class="n">graph</span> <span class="o">=</span> <span class="n">StateGraph</span><span class="p">(</span><span class="n">MyState</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span><span class="s">"research"</span><span class="p">,</span> <span class="n">research</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span><span class="s">"coder"</span><span class="p">,</span> <span class="n">coder</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="n">START</span><span class="p">,</span> <span class="s">"research"</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="s">"research"</span><span class="p">,</span> <span class="s">"coder"</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="s">"coder"</span><span class="p">,</span> <span class="n">END</span><span class="p">)</span>

<span class="n">app</span> <span class="o">=</span> <span class="n">graph</span><span class="p">.</span><span class="nb">compile</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/assets/images/02-pregel-protocol.png" alt="PregelProtocol: Giao diện Toàn cục" /></p>

<p>Đó là tất cả. <code class="language-plaintext highlighter-rouge">invoke()</code>, <code class="language-plaintext highlighter-rouge">stream()</code>, interrupt, checkpointing – mọi thứ hoạt động xuyên ranh giới.</p>

<hr />

<h2 id="tại-sao-điều-này-quan-trọng">Tại sao điều này quan trọng</h2>

<p>Hầu hết các framework điều phối AI cho bạn một trong hai lựa chọn: mọi thứ chạy trong một tiến trình, hoặc bạn tự xử lý với REST call và message queue.</p>

<p>LangGraph cho bạn lựa chọn thứ ba: xây dựng mỗi agent như một đồ thị độc lập với deployment riêng, state riêng, team riêng sở hữu – rồi tổ hợp chúng với cùng API bạn dùng cho các node cục bộ. Không cần glue code. Không cần serialization tuỳ chỉnh. Không cần logic retry tự viết.</p>

<p>Điều này mở khoá các kiến trúc trông như hệ thống phân tán thực sự:</p>

<p><img src="/assets/images/03-multi-graph-architecture.png" alt="Kiến trúc Đa Đồ thị Phân tán" /></p>

<p>Mỗi ô có thể triển khai độc lập qua <code class="language-plaintext highlighter-rouge">langgraph up</code>. Mỗi ô có checkpoint storage riêng. Mỗi ô có thể được versioning và rollback độc lập. Orchestrator chỉ đơn giản kết nối chúng lại.</p>

<hr />

<h2 id="xây-dựng-orchestrator">Xây dựng Orchestrator</h2>

<h3 id="thiết-kế-state">Thiết kế State</h3>

<p>Orchestrator quản lý state điều phối. Các worker graph quản lý state domain riêng của chúng. Đây là các mối quan tâm riêng biệt.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Annotated</span><span class="p">,</span> <span class="n">Any</span>
<span class="kn">from</span> <span class="nn">typing_extensions</span> <span class="kn">import</span> <span class="n">TypedDict</span>
<span class="kn">from</span> <span class="nn">langgraph.graph</span> <span class="kn">import</span> <span class="n">add_messages</span>

<span class="k">class</span> <span class="nc">OrchestratorState</span><span class="p">(</span><span class="n">TypedDict</span><span class="p">):</span>
    <span class="n">messages</span><span class="p">:</span> <span class="n">Annotated</span><span class="p">[</span><span class="nb">list</span><span class="p">,</span> <span class="n">add_messages</span><span class="p">]</span>
    <span class="n">plan</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="nb">dict</span><span class="p">]</span>
    <span class="n">results</span><span class="p">:</span> <span class="n">Annotated</span><span class="p">[</span><span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Any</span><span class="p">],</span> <span class="k">lambda</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="p">{</span><span class="o">**</span><span class="n">a</span><span class="p">,</span> <span class="o">**</span><span class="n">b</span><span class="p">}]</span>
    <span class="n">status</span><span class="p">:</span> <span class="nb">str</span>
</code></pre></div></div>

<p>Orchestrator không cần biết state nội bộ của research agent. Nó gửi message vào, nhận kết quả trả về. Trường <code class="language-plaintext highlighter-rouge">results</code> tích luỹ output từ nhiều worker sử dụng merge reducer.</p>

<h3 id="định-tuyến">Định tuyến</h3>

<p>Pipeline tĩnh là trường hợp đơn giản nhất, nhưng sức mạnh thực sự nằm ở định tuyến động. Bạn có thể sử dụng conditional edge, LLM-based router, hoặc fan-out pattern.</p>

<p><strong>Định tuyến có điều kiện</strong> – chọn worker dựa trên state:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">route</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">if</span> <span class="s">"code"</span> <span class="ow">in</span> <span class="n">state</span><span class="p">[</span><span class="s">"messages"</span><span class="p">][</span><span class="o">-</span><span class="mi">1</span><span class="p">].</span><span class="n">content</span><span class="p">.</span><span class="n">lower</span><span class="p">():</span>
        <span class="k">return</span> <span class="s">"coder"</span>
    <span class="k">return</span> <span class="s">"research"</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_conditional_edges</span><span class="p">(</span><span class="s">"router"</span><span class="p">,</span> <span class="n">route</span><span class="p">)</span>
</code></pre></div></div>

<p><strong>Fan-out với Send</strong> – gửi đến nhiều worker song song:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.types</span> <span class="kn">import</span> <span class="n">Send</span>

<span class="k">def</span> <span class="nf">dispatch</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">[</span><span class="n">Send</span><span class="p">(</span><span class="n">task</span><span class="p">[</span><span class="s">"worker"</span><span class="p">],</span> <span class="n">state</span><span class="p">)</span> <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">state</span><span class="p">[</span><span class="s">"plan"</span><span class="p">]]</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_conditional_edges</span><span class="p">(</span><span class="s">"planner"</span><span class="p">,</span> <span class="n">dispatch</span><span class="p">)</span>
</code></pre></div></div>

<p>Mỗi <code class="language-plaintext highlighter-rouge">Send</code> kích hoạt một lời gọi song song đến remote graph đích. Kết quả được hợp nhất lại thông qua state reducer. Đây là map-reduce cho AI agent.</p>

<p><img src="/assets/images/06-fan-out-map-reduce.png" alt="Fan-Out / Map-Reduce với Send()" /></p>

<hr />

<h2 id="streaming-xuyên-ranh-giới-dịch-vụ">Streaming xuyên ranh giới dịch vụ</h2>

<p>Đây là nơi hầu hết các cách tiếp cận DIY thất bại. Khi bạn lồng đồ thị xuyên ranh giới HTTP, bạn muốn streaming hoạt động bình thường – output LLM token-by-token từ một remote agent phải chảy qua orchestrator đến client mà không bị buffer.</p>

<p><img src="/assets/images/04-stream-propagation.png" alt="Streaming xuyên ranh giới dịch vụ" /></p>

<p>LangGraph xử lý điều này tự động. Việc implement stream của <code class="language-plaintext highlighter-rouge">RemoteGraph</code>:</p>

<ol>
  <li>Chuyển tiếp các stream mode của parent đến remote server</li>
  <li>Thêm namespace prefix để bạn biết subgraph nào phát ra sự kiện nào</li>
  <li>Dẫn các sự kiện ngược lên qua stream của orchestrator</li>
</ol>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">app</span><span class="p">.</span><span class="n">astream</span><span class="p">(</span>
    <span class="p">{</span><span class="s">"messages"</span><span class="p">:</span> <span class="p">[(</span><span class="s">"user"</span><span class="p">,</span> <span class="s">"Build an auth API"</span><span class="p">)]},</span>
    <span class="n">config</span><span class="o">=</span><span class="p">{</span><span class="s">"configurable"</span><span class="p">:</span> <span class="p">{</span><span class="s">"thread_id"</span><span class="p">:</span> <span class="s">"project-1"</span><span class="p">}},</span>
    <span class="n">stream_mode</span><span class="o">=</span><span class="p">[</span><span class="s">"updates"</span><span class="p">,</span> <span class="s">"messages"</span><span class="p">],</span>
    <span class="n">subgraphs</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">):</span>
    <span class="n">ns</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">chunk</span>
    <span class="n">origin</span> <span class="o">=</span> <span class="s">"/"</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="n">ns</span><span class="p">)</span> <span class="ow">or</span> <span class="s">"orchestrator"</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[</span><span class="si">{</span><span class="n">origin</span><span class="si">}</span><span class="s">] </span><span class="si">{</span><span class="n">mode</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">data</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<p>Output trông như:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[orchestrator] updates: {"planner": {"plan": [...]}}
[research] messages: ("To build", {...})
[research] messages: (" an auth", {...})
[research] messages: (" API...", {...})
[research] updates: {"search": {"findings": "..."}}
[coder] messages: ("```python\n", {...})
[coder] messages: ("from fastapi", {...})
...
</code></pre></div></div>

<p>Cả bảy stream mode đều hoạt động xuyên ranh giới: <code class="language-plaintext highlighter-rouge">values</code>, <code class="language-plaintext highlighter-rouge">updates</code>, <code class="language-plaintext highlighter-rouge">messages</code>, <code class="language-plaintext highlighter-rouge">custom</code>, <code class="language-plaintext highlighter-rouge">tasks</code>, <code class="language-plaintext highlighter-rouge">checkpoints</code>, và <code class="language-plaintext highlighter-rouge">debug</code>.</p>

<hr />

<h2 id="human-in-the-loop-xuyên-đồ-thị">Human-in-the-Loop xuyên đồ thị</h2>

<p>Đây là một kịch bản: coding agent của bạn tạo một database migration. Trước khi chạy, bạn muốn một người duyệt. Coding agent là một remote graph. Người dùng đang tương tác với client của orchestrator.</p>

<p><img src="/assets/images/05-interrupt-flow.png" alt="Human-in-the-Loop xuyên ranh giới đồ thị" /></p>

<p>Điều này hoạt động ngay. Khi một remote graph gọi <code class="language-plaintext highlighter-rouge">interrupt()</code>, interrupt được truyền lên qua orchestrator đến client:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Bên trong remote coding agent (triển khai riêng):
</span><span class="k">def</span> <span class="nf">migration_node</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="n">migration</span> <span class="o">=</span> <span class="n">generate_migration</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>
    <span class="n">approval</span> <span class="o">=</span> <span class="n">interrupt</span><span class="p">({</span><span class="s">"sql"</span><span class="p">:</span> <span class="n">migration</span><span class="p">,</span> <span class="s">"question"</span><span class="p">:</span> <span class="s">"Run this migration?"</span><span class="p">})</span>
    <span class="k">if</span> <span class="n">approval</span><span class="p">[</span><span class="s">"approved"</span><span class="p">]:</span>
        <span class="n">run_migration</span><span class="p">(</span><span class="n">migration</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">"result"</span><span class="p">:</span> <span class="s">"Migration applied"</span><span class="p">}</span>
</code></pre></div></div>

<p>Client của orchestrator thấy interrupt:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">state</span> <span class="o">=</span> <span class="n">app</span><span class="p">.</span><span class="n">get_state</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">state</span><span class="p">.</span><span class="n">interrupts</span><span class="p">)</span>  <span class="c1"># [Interrupt(value={"sql": "ALTER TABLE...", "question": "..."})]
</span>
<span class="c1"># Tiếp tục
</span><span class="n">app</span><span class="p">.</span><span class="n">invoke</span><span class="p">(</span><span class="n">Command</span><span class="p">(</span><span class="n">resume</span><span class="o">=</span><span class="p">{</span><span class="s">"approved"</span><span class="p">:</span> <span class="bp">True</span><span class="p">}),</span> <span class="n">config</span><span class="o">=</span><span class="n">config</span><span class="p">)</span>
</code></pre></div></div>

<p>Lệnh resume chạy ngược qua orchestrator, qua <code class="language-plaintext highlighter-rouge">RemoteGraph</code>, đến đúng thread trên remote server. Không cần plumbing.</p>

<hr />

<h2 id="checkpointing-độc-lập">Checkpointing độc lập</h2>

<p>Mỗi đồ thị trong hệ thống checkpoint độc lập. Orchestrator lưu các quyết định định tuyến và kết quả tích luỹ. Mỗi remote graph lưu lịch sử hội thoại nội bộ và tool call riêng. Chúng không chia sẻ database.</p>

<p>Đây là một tính năng, không phải hạn chế. Nó có nghĩa là:</p>

<ul>
  <li>Bạn có thể kiểm tra và phát lại workflow của orchestrator mà không cần chạm vào state của worker</li>
  <li>Mỗi team kiểm soát backend persistence riêng (SQLite cho dev, Postgres cho prod)</li>
  <li>Checkpoint storage được mở rộng độc lập cho mỗi dịch vụ</li>
  <li>Time-travel debugging hoạt động ở mỗi tầng</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Kiểm tra lịch sử orchestrator
</span><span class="k">for</span> <span class="n">snapshot</span> <span class="ow">in</span> <span class="n">app</span><span class="p">.</span><span class="n">get_state_history</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"Step </span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="n">metadata</span><span class="p">[</span><span class="s">'step'</span><span class="p">]</span><span class="si">}</span><span class="s">: next=</span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="nb">next</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>

<span class="c1"># Kiểm tra lịch sử remote graph trực tiếp
</span><span class="n">remote</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"research-agent"</span><span class="p">,</span> <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">snapshot</span> <span class="ow">in</span> <span class="n">remote</span><span class="p">.</span><span class="n">get_state_history</span><span class="p">(</span><span class="n">remote_config</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"Step </span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="n">metadata</span><span class="p">[</span><span class="s">'step'</span><span class="p">]</span><span class="si">}</span><span class="s">: next=</span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="nb">next</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<hr />

<h2 id="xử-lý-lỗi">Xử lý lỗi</h2>

<p>Các lời gọi từ xa có thể thất bại. Mạng không đáng tin cậy. LangGraph cung cấp retry policy ở cấp node:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.types</span> <span class="kn">import</span> <span class="n">RetryPolicy</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span>
    <span class="n">create_remote</span><span class="p">(</span><span class="s">"research"</span><span class="p">),</span>
    <span class="n">retry_policy</span><span class="o">=</span><span class="n">RetryPolicy</span><span class="p">(</span>
        <span class="n">max_attempts</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
        <span class="n">initial_interval</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
        <span class="n">backoff_factor</span><span class="o">=</span><span class="mf">2.0</span><span class="p">,</span>
    <span class="p">),</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Để kiểm soát tốt hơn, bọc lời gọi từ xa:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">resilient_research</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">create_remote</span><span class="p">(</span><span class="s">"research-v2"</span><span class="p">).</span><span class="n">invoke</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">RemoteException</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">create_remote</span><span class="p">(</span><span class="s">"research-v1"</span><span class="p">).</span><span class="n">invoke</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>  <span class="c1"># fallback về phiên bản trước
</span></code></pre></div></div>

<p>Lỗi từ xa xuất hiện dưới dạng <code class="language-plaintext highlighter-rouge">RemoteException</code>. Interrupt xuất hiện dưới dạng <code class="language-plaintext highlighter-rouge">GraphInterrupt</code>. Command xuất hiện dưới dạng <code class="language-plaintext highlighter-rouge">ParentCommand</code>. Mỗi loại có ngữ nghĩa xử lý riêng biệt – chúng không bị gộp chung.</p>

<hr />

<h2 id="uỷ-quyền-phân-cấp">Uỷ quyền phân cấp</h2>

<p>Các remote graph có thể gửi lệnh ngược lại orchestrator cha sử dụng <code class="language-plaintext highlighter-rouge">Command(graph=Command.PARENT)</code>. Điều này cho phép cấu trúc team phân cấp:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Orchestrator
+-- Team Lead A (remote)
|   +-- Worker A1 (remote)
|   +-- Worker A2 (remote)
+-- Team Lead B (remote)
    +-- Worker B1 (remote)
</code></pre></div></div>

<p>Một worker có thể leo thang lên team lead. Một team lead có thể leo thang lên orchestrator. Cơ chế <code class="language-plaintext highlighter-rouge">ParentCommand</code> xử lý điều này ở bất kỳ độ sâu lồng nào.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Worker bên trong một remote team graph
</span><span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">state</span><span class="p">[</span><span class="s">"confidence"</span><span class="p">]</span> <span class="o">&lt;</span> <span class="mf">0.5</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">Command</span><span class="p">(</span>
            <span class="n">graph</span><span class="o">=</span><span class="n">Command</span><span class="p">.</span><span class="n">PARENT</span><span class="p">,</span>
            <span class="n">update</span><span class="o">=</span><span class="p">{</span><span class="s">"needs_help"</span><span class="p">:</span> <span class="bp">True</span><span class="p">},</span>
            <span class="n">goto</span><span class="o">=</span><span class="s">"escalation_handler"</span><span class="p">,</span>
        <span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">"result"</span><span class="p">:</span> <span class="n">do_work</span><span class="p">(</span><span class="n">state</span><span class="p">)}</span>
</code></pre></div></div>

<hr />

<h2 id="triển-khai">Triển khai</h2>

<p>Mỗi đồ thị triển khai độc lập. File config <code class="language-plaintext highlighter-rouge">langgraph.json</code> định nghĩa điểm vào của đồ thị:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
    </span><span class="nl">"python_version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"3.12"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"dependencies"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"./requirements.txt"</span><span class="p">],</span><span class="w">
    </span><span class="nl">"graphs"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"research-agent"</span><span class="p">:</span><span class="w"> </span><span class="s2">"./graphs/research.py:graph"</span><span class="w">
    </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Sau đó triển khai:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>langgraph up <span class="nt">--port</span> 8001
</code></pre></div></div>

<p>Hoặc sử dụng <code class="language-plaintext highlighter-rouge">langgraph dev</code> để phát triển cục bộ với hot-reloading. Trong môi trường phát triển, tất cả remote graph có thể chạy trên localhost với các port khác nhau. Trong production, chúng là các dịch vụ riêng biệt sau các URL riêng biệt.</p>

<p>Bản thân orchestrator cũng có thể được triển khai theo cách tương tự, hoặc chạy như một script cục bộ. Nó chỉ là một đồ thị tình cờ gọi các đồ thị khác qua HTTP.</p>

<hr />

<h2 id="quan-sát-hệ-thống">Quan sát hệ thống</h2>

<p>Bật <code class="language-plaintext highlighter-rouge">distributed_tracing=True</code> trên các instance <code class="language-plaintext highlighter-rouge">RemoteGraph</code> để có trace thống nhất trong LangSmith xuyên tất cả dịch vụ:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">research</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span>
    <span class="s">"research-agent"</span><span class="p">,</span>
    <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">,</span>
    <span class="n">distributed_tracing</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Một trace hiển thị toàn bộ hành trình: orchestrator định tuyến -&gt; research agent tìm kiếm -&gt; coding agent tạo code -&gt; reviewer kiểm tra. Phân tích độ trễ, số lượng token, và quy lỗi xuyên toàn bộ hệ thống phân tán.</p>

<p>Bạn cũng có thể trực quan hoá toàn bộ topology đồ thị:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">app</span><span class="p">.</span><span class="n">get_graph</span><span class="p">(</span><span class="n">xray</span><span class="o">=</span><span class="mi">2</span><span class="p">).</span><span class="n">draw_mermaid_png</span><span class="p">()</span>
</code></pre></div></div>

<p>Điều này render đồ thị orchestrator với nội bộ remote subgraph được mở rộng đến độ sâu 2.</p>

<hr />

<h2 id="khi-nào-nên-sử-dụng">Khi nào nên sử dụng</h2>

<p><strong>Sử dụng điều phối đa đồ thị khi:</strong></p>

<ul>
  <li>Các team khác nhau sở hữu các agent khác nhau và cần chu kỳ triển khai độc lập</li>
  <li>Bạn cần mở rộng các agent độc lập (research agent cần GPU, router thì không)</li>
  <li>Bạn muốn versioning và rollback các agent độc lập</li>
  <li>Hệ thống của bạn có ranh giới domain tự nhiên (research vs. coding vs. review)</li>
  <li>Bạn cần cách ly lỗi – một agent bị crash không nên làm sập toàn bộ hệ thống</li>
</ul>

<p><strong>Giữ một đồ thị duy nhất khi:</strong></p>

<ul>
  <li>Một team sở hữu mọi thứ</li>
  <li>Các agent chia sẻ hầu hết state</li>
  <li>Chi phí của HTTP call không đáng để đổi lấy lợi ích kiến trúc</li>
  <li>Bạn đang làm prototype và tốc độ lặp lại quan trọng hơn tính linh hoạt triển khai</li>
</ul>

<hr />

<h2 id="kết-luận">Kết luận</h2>

<p>Quyết định thiết kế cốt lõi trong LangGraph là <code class="language-plaintext highlighter-rouge">PregelProtocol</code> là giao diện toàn cục. Một <code class="language-plaintext highlighter-rouge">StateGraph</code> đã compile, một hàm <code class="language-plaintext highlighter-rouge">@entrypoint</code>, và một HTTP client <code class="language-plaintext highlighter-rouge">RemoteGraph</code> đều implement nó. Điều này có nghĩa là tổ hợp là miễn phí – bạn không phải trả thuế trừu tượng khi chuyển sang phân tán.</p>

<p>Xây dựng các agent của bạn như các đồ thị độc lập. Triển khai chúng riêng rẽ. Kết nối chúng với một orchestrator coi mỗi cái như chỉ là một node bình thường. Streaming, interrupt, checkpointing, và xử lý lỗi hoạt động xuyên ranh giới mà không cần thêm code.</p>

<p>Khoảng cách giữa “nó chạy trên laptop của tôi” và “nó chạy trong production xuyên năm dịch vụ” nhỏ hơn bạn nghĩ.</p>

<hr />

<p><em>Nếu bài viết có ích, kết nối với mình trên <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> hoặc xem thêm các project tại <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[Cách engine Pregel và giao diện PregelProtocol của LangGraph cho phép kết hợp các AI agent được triển khai độc lập thành một hệ thống phân tán thống nhất -- với streaming, interrupt và checkpointing xuyên ranh giới dịch vụ.]]></summary></entry><entry xml:lang="en"><title type="html">Multi-Graph Distributed Orchestration with LangGraph</title><link href="/langgraph-multi-graph-orchestration/" rel="alternate" type="text/html" title="Multi-Graph Distributed Orchestration with LangGraph" /><published>2026-03-06T00:00:00+07:00</published><updated>2026-03-06T00:00:00+07:00</updated><id>/langgraph-multi-graph-orchestration</id><content type="html" xml:base="/langgraph-multi-graph-orchestration/"><![CDATA[<p>You have a research agent. A coding agent. A review agent. Each built by a different team, deployed on different servers. Now you need them to work together as one system.</p>

<p>This is the multi-graph orchestration problem, and LangGraph solves it with a surprisingly simple idea: a remote graph is just another node.</p>

<hr />

<h2 id="what-is-pregel-and-why-should-you-care">What is Pregel, and Why Should You Care?</h2>

<p>Before diving into multi-graph orchestration, it’s worth understanding the engine that makes it all possible.</p>

<p>LangGraph’s runtime is called <strong>Pregel</strong>, named after <a href="https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/">Google’s Pregel</a> – a system designed for processing large-scale graphs. The original Pregel was built to run algorithms like PageRank across billions of web pages. LangGraph borrows the same execution model, but applies it to AI agent workflows.</p>

<h3 id="the-execution-model">The Execution Model</h3>

<p>Pregel uses <strong>Bulk Synchronous Parallel (BSP)</strong> execution. That sounds academic, but the idea is simple. Your graph runs in discrete <strong>supersteps</strong>, and each superstep has three phases:</p>

<ol>
  <li>
    <p><strong>Plan</strong> – Figure out which nodes need to run. On the first step, it’s the nodes connected to <code class="language-plaintext highlighter-rouge">START</code>. On subsequent steps, it’s any node whose input channels were updated in the previous step.</p>
  </li>
  <li>
    <p><strong>Execute</strong> – Run all selected nodes <strong>in parallel</strong>. This is the key insight: nodes don’t see each other’s writes during execution. A research node and a coding node running in the same superstep can’t interfere with each other.</p>
  </li>
  <li>
    <p><strong>Update</strong> – Apply all node outputs to the shared state channels. Now the writes become visible, and the next superstep can begin.</p>
  </li>
</ol>

<p>This repeats until no more nodes are triggered, or the <code class="language-plaintext highlighter-rouge">recursion_limit</code> is hit.</p>

<p><img src="/assets/images/01-pregel-superstep.png" alt="Pregel BSP Execution Model" /></p>

<h3 id="nodes-and-channels">Nodes and Channels</h3>

<p>In Pregel’s model, nodes don’t call each other directly. They communicate through <strong>channels</strong> – typed containers that hold state between supersteps:</p>

<ul>
  <li><strong>LastValue</strong> – stores the most recent value (the default for <code class="language-plaintext highlighter-rouge">StateGraph</code> fields)</li>
  <li><strong>BinaryOperatorAggregate</strong> – accumulates values with a reducer (this is what powers <code class="language-plaintext highlighter-rouge">add_messages</code>)</li>
  <li><strong>Topic</strong> – pub/sub accumulation for multiple values</li>
  <li><strong>EphemeralValue</strong> – temporary values that clear after each step</li>
</ul>

<p>When you write <code class="language-plaintext highlighter-rouge">messages: Annotated[list, add_messages]</code> in your state, you’re defining a <code class="language-plaintext highlighter-rouge">BinaryOperatorAggregate</code> channel with <code class="language-plaintext highlighter-rouge">add_messages</code> as the binary operator. When two nodes both write messages in the same superstep, the reducer merges them deterministically.</p>

<h3 id="why-this-matters-for-distributed-orchestration">Why This Matters for Distributed Orchestration</h3>

<p>The BSP model gives you three properties that are essential for distributed systems:</p>

<ol>
  <li><strong>Determinism</strong> – Parallel nodes can’t race on shared state. The channel update phase ensures consistent ordering.</li>
  <li><strong>Checkpointability</strong> – State is clean between supersteps, so you can snapshot it, persist it, and resume later.</li>
  <li><strong>Composability</strong> – The entire execution model is behind an interface (<code class="language-plaintext highlighter-rouge">PregelProtocol</code>). Anything implementing that interface – local graph, remote graph, functional entrypoint – can be composed as a node.</li>
</ol>

<p>Most users never interact with Pregel directly. <code class="language-plaintext highlighter-rouge">StateGraph.compile()</code> and <code class="language-plaintext highlighter-rouge">@entrypoint</code> both produce Pregel instances under the hood. But understanding the model explains <em>why</em> things like streaming, interrupts, and remote composition work so cleanly – they’re all built on the same superstep-based execution with channel-mediated communication.</p>

<hr />

<h2 id="the-core-insight">The Core Insight</h2>

<p>LangGraph’s execution engine (Pregel) and its remote client (RemoteGraph) both implement the same interface – <code class="language-plaintext highlighter-rouge">PregelProtocol</code>. This means you can wire a graph running on a server in Tokyo into an orchestrator running on your laptop, and it behaves identically to a local function.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.graph</span> <span class="kn">import</span> <span class="n">StateGraph</span><span class="p">,</span> <span class="n">START</span><span class="p">,</span> <span class="n">END</span>
<span class="kn">from</span> <span class="nn">langgraph.pregel.remote</span> <span class="kn">import</span> <span class="n">RemoteGraph</span>

<span class="c1"># These are HTTP clients, not local code
</span><span class="n">research</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"research-agent"</span><span class="p">,</span> <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">"research"</span><span class="p">)</span>
<span class="n">coder</span>    <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"code-agent"</span><span class="p">,</span>     <span class="n">url</span><span class="o">=</span><span class="s">"https://code.example.com"</span><span class="p">,</span>     <span class="n">name</span><span class="o">=</span><span class="s">"coder"</span><span class="p">)</span>

<span class="c1"># But they wire in like any other node
</span><span class="n">graph</span> <span class="o">=</span> <span class="n">StateGraph</span><span class="p">(</span><span class="n">MyState</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span><span class="s">"research"</span><span class="p">,</span> <span class="n">research</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span><span class="s">"coder"</span><span class="p">,</span> <span class="n">coder</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="n">START</span><span class="p">,</span> <span class="s">"research"</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="s">"research"</span><span class="p">,</span> <span class="s">"coder"</span><span class="p">)</span>
<span class="n">graph</span><span class="p">.</span><span class="n">add_edge</span><span class="p">(</span><span class="s">"coder"</span><span class="p">,</span> <span class="n">END</span><span class="p">)</span>

<span class="n">app</span> <span class="o">=</span> <span class="n">graph</span><span class="p">.</span><span class="nb">compile</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/assets/images/02-pregel-protocol.png" alt="PregelProtocol: The Universal Interface" /></p>

<p>That’s it. <code class="language-plaintext highlighter-rouge">invoke()</code>, <code class="language-plaintext highlighter-rouge">stream()</code>, interrupts, checkpointing – everything works across the boundary.</p>

<hr />

<h2 id="why-this-matters">Why This Matters</h2>

<p>Most AI orchestration frameworks give you one of two options: everything runs in one process, or you’re on your own with REST calls and message queues.</p>

<p>LangGraph gives you a third option: build each agent as an independent graph with its own deployment, its own state, its own team owning it – then compose them with the same API you use for local nodes. No glue code. No custom serialization. No hand-rolled retry logic.</p>

<p>This unlocks architectures that look like real distributed systems:</p>

<p><img src="/assets/images/03-multi-graph-architecture.png" alt="Multi-Graph Distributed Architecture" /></p>

<p>Each box is independently deployable via <code class="language-plaintext highlighter-rouge">langgraph up</code>. Each has its own checkpoint storage. Each can be versioned and rolled back independently. The orchestrator just wires them together.</p>

<hr />

<h2 id="building-the-orchestrator">Building the Orchestrator</h2>

<h3 id="state-design">State Design</h3>

<p>The orchestrator manages coordination state. Worker graphs manage their own domain state. These are separate concerns.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Annotated</span><span class="p">,</span> <span class="n">Any</span>
<span class="kn">from</span> <span class="nn">typing_extensions</span> <span class="kn">import</span> <span class="n">TypedDict</span>
<span class="kn">from</span> <span class="nn">langgraph.graph</span> <span class="kn">import</span> <span class="n">add_messages</span>

<span class="k">class</span> <span class="nc">OrchestratorState</span><span class="p">(</span><span class="n">TypedDict</span><span class="p">):</span>
    <span class="n">messages</span><span class="p">:</span> <span class="n">Annotated</span><span class="p">[</span><span class="nb">list</span><span class="p">,</span> <span class="n">add_messages</span><span class="p">]</span>
    <span class="n">plan</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="nb">dict</span><span class="p">]</span>
    <span class="n">results</span><span class="p">:</span> <span class="n">Annotated</span><span class="p">[</span><span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Any</span><span class="p">],</span> <span class="k">lambda</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="p">{</span><span class="o">**</span><span class="n">a</span><span class="p">,</span> <span class="o">**</span><span class="n">b</span><span class="p">}]</span>
    <span class="n">status</span><span class="p">:</span> <span class="nb">str</span>
</code></pre></div></div>

<p>The orchestrator doesn’t need to know the internal state of the research agent. It sends messages in, gets results back. The <code class="language-plaintext highlighter-rouge">results</code> field accumulates outputs from multiple workers using a merge reducer.</p>

<h3 id="routing">Routing</h3>

<p>Static pipelines are the simplest case, but the real power is in dynamic routing. You can use conditional edges, LLM-based routers, or fan-out patterns.</p>

<p><strong>Conditional routing</strong> – pick a worker based on state:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">route</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">if</span> <span class="s">"code"</span> <span class="ow">in</span> <span class="n">state</span><span class="p">[</span><span class="s">"messages"</span><span class="p">][</span><span class="o">-</span><span class="mi">1</span><span class="p">].</span><span class="n">content</span><span class="p">.</span><span class="n">lower</span><span class="p">():</span>
        <span class="k">return</span> <span class="s">"coder"</span>
    <span class="k">return</span> <span class="s">"research"</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_conditional_edges</span><span class="p">(</span><span class="s">"router"</span><span class="p">,</span> <span class="n">route</span><span class="p">)</span>
</code></pre></div></div>

<p><strong>Fan-out with Send</strong> – dispatch to multiple workers in parallel:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.types</span> <span class="kn">import</span> <span class="n">Send</span>

<span class="k">def</span> <span class="nf">dispatch</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">[</span><span class="n">Send</span><span class="p">(</span><span class="n">task</span><span class="p">[</span><span class="s">"worker"</span><span class="p">],</span> <span class="n">state</span><span class="p">)</span> <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">state</span><span class="p">[</span><span class="s">"plan"</span><span class="p">]]</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_conditional_edges</span><span class="p">(</span><span class="s">"planner"</span><span class="p">,</span> <span class="n">dispatch</span><span class="p">)</span>
</code></pre></div></div>

<p>Each <code class="language-plaintext highlighter-rouge">Send</code> triggers a parallel invocation of the target remote graph. Results merge back through the state reducer. This is map-reduce for AI agents.</p>

<p><img src="/assets/images/06-fan-out-map-reduce.png" alt="Fan-Out / Map-Reduce with Send()" /></p>

<hr />

<h2 id="streaming-across-service-boundaries">Streaming Across Service Boundaries</h2>

<p>This is where most DIY approaches fall apart. When you nest graphs across HTTP boundaries, you want streaming to just work – token-by-token LLM output from a remote agent should flow through the orchestrator to the client without buffering.</p>

<p><img src="/assets/images/04-stream-propagation.png" alt="Streaming Across Service Boundaries" /></p>

<p>LangGraph handles this automatically. The <code class="language-plaintext highlighter-rouge">RemoteGraph</code> stream implementation:</p>

<ol>
  <li>Forwards the parent’s stream modes to the remote server</li>
  <li>Prepends namespace prefixes so you know which subgraph emitted what</li>
  <li>Pipes events back up through the orchestrator’s stream</li>
</ol>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">app</span><span class="p">.</span><span class="n">astream</span><span class="p">(</span>
    <span class="p">{</span><span class="s">"messages"</span><span class="p">:</span> <span class="p">[(</span><span class="s">"user"</span><span class="p">,</span> <span class="s">"Build an auth API"</span><span class="p">)]},</span>
    <span class="n">config</span><span class="o">=</span><span class="p">{</span><span class="s">"configurable"</span><span class="p">:</span> <span class="p">{</span><span class="s">"thread_id"</span><span class="p">:</span> <span class="s">"project-1"</span><span class="p">}},</span>
    <span class="n">stream_mode</span><span class="o">=</span><span class="p">[</span><span class="s">"updates"</span><span class="p">,</span> <span class="s">"messages"</span><span class="p">],</span>
    <span class="n">subgraphs</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">):</span>
    <span class="n">ns</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">chunk</span>
    <span class="n">origin</span> <span class="o">=</span> <span class="s">"/"</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="n">ns</span><span class="p">)</span> <span class="ow">or</span> <span class="s">"orchestrator"</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[</span><span class="si">{</span><span class="n">origin</span><span class="si">}</span><span class="s">] </span><span class="si">{</span><span class="n">mode</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">data</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<p>Output looks like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[orchestrator] updates: {"planner": {"plan": [...]}}
[research] messages: ("To build", {...})
[research] messages: (" an auth", {...})
[research] messages: (" API...", {...})
[research] updates: {"search": {"findings": "..."}}
[coder] messages: ("```python\n", {...})
[coder] messages: ("from fastapi", {...})
...
</code></pre></div></div>

<p>All seven stream modes work across boundaries: <code class="language-plaintext highlighter-rouge">values</code>, <code class="language-plaintext highlighter-rouge">updates</code>, <code class="language-plaintext highlighter-rouge">messages</code>, <code class="language-plaintext highlighter-rouge">custom</code>, <code class="language-plaintext highlighter-rouge">tasks</code>, <code class="language-plaintext highlighter-rouge">checkpoints</code>, and <code class="language-plaintext highlighter-rouge">debug</code>.</p>

<hr />

<h2 id="human-in-the-loop-across-graphs">Human-in-the-Loop Across Graphs</h2>

<p>Here’s a scenario: your coding agent generates a database migration. Before it runs, you want a human to approve it. The coding agent is a remote graph. The human is interacting with the orchestrator’s client.</p>

<p><img src="/assets/images/05-interrupt-flow.png" alt="Human-in-the-Loop Across Graph Boundaries" /></p>

<p>This just works. When a remote graph calls <code class="language-plaintext highlighter-rouge">interrupt()</code>, the interrupt bubbles up through the orchestrator to the client:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Inside the remote coding agent (deployed separately):
</span><span class="k">def</span> <span class="nf">migration_node</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="n">migration</span> <span class="o">=</span> <span class="n">generate_migration</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>
    <span class="n">approval</span> <span class="o">=</span> <span class="n">interrupt</span><span class="p">({</span><span class="s">"sql"</span><span class="p">:</span> <span class="n">migration</span><span class="p">,</span> <span class="s">"question"</span><span class="p">:</span> <span class="s">"Run this migration?"</span><span class="p">})</span>
    <span class="k">if</span> <span class="n">approval</span><span class="p">[</span><span class="s">"approved"</span><span class="p">]:</span>
        <span class="n">run_migration</span><span class="p">(</span><span class="n">migration</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">"result"</span><span class="p">:</span> <span class="s">"Migration applied"</span><span class="p">}</span>
</code></pre></div></div>

<p>The orchestrator’s client sees the interrupt:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">state</span> <span class="o">=</span> <span class="n">app</span><span class="p">.</span><span class="n">get_state</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">state</span><span class="p">.</span><span class="n">interrupts</span><span class="p">)</span>  <span class="c1"># [Interrupt(value={"sql": "ALTER TABLE...", "question": "..."})]
</span>
<span class="c1"># Resume
</span><span class="n">app</span><span class="p">.</span><span class="n">invoke</span><span class="p">(</span><span class="n">Command</span><span class="p">(</span><span class="n">resume</span><span class="o">=</span><span class="p">{</span><span class="s">"approved"</span><span class="p">:</span> <span class="bp">True</span><span class="p">}),</span> <span class="n">config</span><span class="o">=</span><span class="n">config</span><span class="p">)</span>
</code></pre></div></div>

<p>The resume command flows back through the orchestrator, through the <code class="language-plaintext highlighter-rouge">RemoteGraph</code>, to the correct thread on the remote server. No plumbing required.</p>

<hr />

<h2 id="independent-checkpointing">Independent Checkpointing</h2>

<p>Each graph in the system checkpoints independently. The orchestrator stores its routing decisions and accumulated results. Each remote graph stores its own internal conversation and tool call history. They don’t share a database.</p>

<p>This is a feature, not a limitation. It means:</p>

<ul>
  <li>You can inspect and replay the orchestrator’s workflow without touching worker state</li>
  <li>Each team controls their own persistence backend (SQLite for dev, Postgres for prod)</li>
  <li>Checkpoint storage scales independently per service</li>
  <li>Time-travel debugging works at each layer</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Inspect orchestrator history
</span><span class="k">for</span> <span class="n">snapshot</span> <span class="ow">in</span> <span class="n">app</span><span class="p">.</span><span class="n">get_state_history</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"Step </span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="n">metadata</span><span class="p">[</span><span class="s">'step'</span><span class="p">]</span><span class="si">}</span><span class="s">: next=</span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="nb">next</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>

<span class="c1"># Inspect a remote graph's history directly
</span><span class="n">remote</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span><span class="s">"research-agent"</span><span class="p">,</span> <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">snapshot</span> <span class="ow">in</span> <span class="n">remote</span><span class="p">.</span><span class="n">get_state_history</span><span class="p">(</span><span class="n">remote_config</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"Step </span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="n">metadata</span><span class="p">[</span><span class="s">'step'</span><span class="p">]</span><span class="si">}</span><span class="s">: next=</span><span class="si">{</span><span class="n">snapshot</span><span class="p">.</span><span class="nb">next</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<hr />

<h2 id="error-handling">Error Handling</h2>

<p>Remote calls fail. Networks are unreliable. LangGraph gives you retry policies at the node level:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">langgraph.types</span> <span class="kn">import</span> <span class="n">RetryPolicy</span>

<span class="n">graph</span><span class="p">.</span><span class="n">add_node</span><span class="p">(</span>
    <span class="n">create_remote</span><span class="p">(</span><span class="s">"research"</span><span class="p">),</span>
    <span class="n">retry_policy</span><span class="o">=</span><span class="n">RetryPolicy</span><span class="p">(</span>
        <span class="n">max_attempts</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
        <span class="n">initial_interval</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
        <span class="n">backoff_factor</span><span class="o">=</span><span class="mf">2.0</span><span class="p">,</span>
    <span class="p">),</span>
<span class="p">)</span>
</code></pre></div></div>

<p>For more control, wrap the remote call:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">resilient_research</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">create_remote</span><span class="p">(</span><span class="s">"research-v2"</span><span class="p">).</span><span class="n">invoke</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">RemoteException</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">create_remote</span><span class="p">(</span><span class="s">"research-v1"</span><span class="p">).</span><span class="n">invoke</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>  <span class="c1"># fallback to previous version
</span></code></pre></div></div>

<p>Remote errors surface as <code class="language-plaintext highlighter-rouge">RemoteException</code>. Interrupts surface as <code class="language-plaintext highlighter-rouge">GraphInterrupt</code>. Commands surface as <code class="language-plaintext highlighter-rouge">ParentCommand</code>. Each has distinct handling semantics – they’re not lumped together.</p>

<hr />

<h2 id="hierarchical-delegation">Hierarchical Delegation</h2>

<p>Remote graphs can send commands back to their parent orchestrator using <code class="language-plaintext highlighter-rouge">Command(graph=Command.PARENT)</code>. This enables hierarchical team structures:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Orchestrator
+-- Team Lead A (remote)
|   +-- Worker A1 (remote)
|   +-- Worker A2 (remote)
+-- Team Lead B (remote)
    +-- Worker B1 (remote)
</code></pre></div></div>

<p>A worker can escalate to its team lead. A team lead can escalate to the orchestrator. The <code class="language-plaintext highlighter-rouge">ParentCommand</code> mechanism handles this at any nesting depth.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Worker inside a remote team graph
</span><span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="n">state</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">state</span><span class="p">[</span><span class="s">"confidence"</span><span class="p">]</span> <span class="o">&lt;</span> <span class="mf">0.5</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">Command</span><span class="p">(</span>
            <span class="n">graph</span><span class="o">=</span><span class="n">Command</span><span class="p">.</span><span class="n">PARENT</span><span class="p">,</span>
            <span class="n">update</span><span class="o">=</span><span class="p">{</span><span class="s">"needs_help"</span><span class="p">:</span> <span class="bp">True</span><span class="p">},</span>
            <span class="n">goto</span><span class="o">=</span><span class="s">"escalation_handler"</span><span class="p">,</span>
        <span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">"result"</span><span class="p">:</span> <span class="n">do_work</span><span class="p">(</span><span class="n">state</span><span class="p">)}</span>
</code></pre></div></div>

<hr />

<h2 id="deployment">Deployment</h2>

<p>Each graph deploys independently. A <code class="language-plaintext highlighter-rouge">langgraph.json</code> config file defines the graph entry point:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
    </span><span class="nl">"python_version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"3.12"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"dependencies"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"./requirements.txt"</span><span class="p">],</span><span class="w">
    </span><span class="nl">"graphs"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"research-agent"</span><span class="p">:</span><span class="w"> </span><span class="s2">"./graphs/research.py:graph"</span><span class="w">
    </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Then deploy:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>langgraph up <span class="nt">--port</span> 8001
</code></pre></div></div>

<p>Or use <code class="language-plaintext highlighter-rouge">langgraph dev</code> for local development with hot-reloading. In development, all your remote graphs can run on localhost with different ports. In production, they’re separate services behind separate URLs.</p>

<p>The orchestrator itself can be deployed the same way, or it can run as a local script. It’s just a graph that happens to call other graphs over HTTP.</p>

<hr />

<h2 id="observability">Observability</h2>

<p>Enable <code class="language-plaintext highlighter-rouge">distributed_tracing=True</code> on your <code class="language-plaintext highlighter-rouge">RemoteGraph</code> instances to get unified traces in LangSmith across all services:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">research</span> <span class="o">=</span> <span class="n">RemoteGraph</span><span class="p">(</span>
    <span class="s">"research-agent"</span><span class="p">,</span>
    <span class="n">url</span><span class="o">=</span><span class="s">"https://research.example.com"</span><span class="p">,</span>
    <span class="n">distributed_tracing</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">)</span>
</code></pre></div></div>

<p>One trace shows the full journey: orchestrator routing -&gt; research agent searching -&gt; coding agent generating -&gt; reviewer checking. Latency breakdowns, token counts, and error attribution across the entire distributed system.</p>

<p>You can also visualize the full graph topology:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">app</span><span class="p">.</span><span class="n">get_graph</span><span class="p">(</span><span class="n">xray</span><span class="o">=</span><span class="mi">2</span><span class="p">).</span><span class="n">draw_mermaid_png</span><span class="p">()</span>
</code></pre></div></div>

<p>This renders the orchestrator graph with remote subgraph internals expanded to a depth of 2.</p>

<hr />

<h2 id="when-to-use-this">When to Use This</h2>

<p><strong>Use multi-graph orchestration when:</strong></p>

<ul>
  <li>Different teams own different agents and need independent deploy cycles</li>
  <li>You need to scale agents independently (the research agent needs GPUs, the router doesn’t)</li>
  <li>You want to version and rollback agents independently</li>
  <li>Your system has natural domain boundaries (research vs. coding vs. review)</li>
  <li>You need fault isolation – one agent crashing shouldn’t take down the system</li>
</ul>

<p><strong>Stick with a single graph when:</strong></p>

<ul>
  <li>One team owns everything</li>
  <li>Agents share most of their state</li>
  <li>The overhead of HTTP calls isn’t worth the architectural benefits</li>
  <li>You’re prototyping and speed of iteration matters more than deployment flexibility</li>
</ul>

<hr />

<h2 id="the-takeaway">The Takeaway</h2>

<p>The key design decision in LangGraph is that <code class="language-plaintext highlighter-rouge">PregelProtocol</code> is the universal interface. A compiled <code class="language-plaintext highlighter-rouge">StateGraph</code>, a <code class="language-plaintext highlighter-rouge">@entrypoint</code> function, and a <code class="language-plaintext highlighter-rouge">RemoteGraph</code> HTTP client all implement it. This means composition is free – you don’t pay an abstraction tax for going distributed.</p>

<p>Build your agents as independent graphs. Deploy them separately. Wire them together with an orchestrator that treats each one as just another node. Streaming, interrupts, checkpointing, and error handling work across the boundaries without additional code.</p>

<p>The gap between “it works on my laptop” and “it works in production across five services” is smaller than you’d expect.</p>

<hr />

<p><em>If you found this useful, feel free to connect on <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> or check out my projects on <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[How LangGraph's Pregel engine and PregelProtocol interface let you compose independently deployed AI agents into a unified distributed system -- with streaming, interrupts, and checkpointing across service boundaries.]]></summary></entry><entry><title type="html">Best Practices for Building Scalable Agentic AI Platforms: A Comprehensive Guide for 2025</title><link href="/best-practices-for-building-scalable-agentic-ai-platforms-a-comprehensive-guide-for-2025/" rel="alternate" type="text/html" title="Best Practices for Building Scalable Agentic AI Platforms: A Comprehensive Guide for 2025" /><published>2026-03-04T00:00:00+07:00</published><updated>2026-03-04T00:00:00+07:00</updated><id>/best-practices-for-building-scalable-agentic-ai-platforms-a-comprehensive-guide-for-2025</id><content type="html" xml:base="/best-practices-for-building-scalable-agentic-ai-platforms-a-comprehensive-guide-for-2025/"><![CDATA[<h1 id="best-practices-for-building-scalable-agentic-ai-platforms-a-comprehensive-guide-for-2025">Best Practices for Building Scalable Agentic AI Platforms: A Comprehensive Guide for 2025</h1>

<p>The agentic AI market is experiencing explosive growth. From <strong>$5.2 billion in 2024</strong>, it’s projected to reach <strong>$196.6 billion by 2034</strong>—a staggering <strong>43.8% CAGR</strong>. Enterprise adoption is accelerating rapidly: <strong>96% of IT leaders plan to expand AI agent usage in 2025</strong>, and over <strong>60% of new enterprise AI deployments</strong> will include agentic capabilities.</p>

<p>Yet beneath these impressive numbers lies a sobering reality: most organizations struggle to move from prototype to production. The gap between a working demo and a scalable, secure, cost-effective platform is vast. Having built agentic platforms serving millions of interactions across regulated industries, I’ve learned that success requires treating this as an infrastructure problem, not just an AI problem.</p>

<p>This guide distills hard-won lessons into actionable best practices for building agentic AI platforms that actually scale.</p>

<hr />

<h2 id="understanding-the-agentic-ai-paradigm-shift">Understanding the Agentic AI Paradigm Shift</h2>

<p>Before diving into architecture, let’s establish what makes agentic AI fundamentally different from traditional AI systems.</p>

<p><strong>Agentic AI</strong> refers to AI systems capable of autonomous decision-making, planning, and action execution. Unlike traditional chatbots that respond to single prompts, agentic AI can:</p>

<ul>
  <li>Break down complex goals into subtasks</li>
  <li>Use tools and interact with external systems</li>
  <li>Adapt based on intermediate results</li>
  <li>Operate with minimal human intervention while pursuing multi-step objectives</li>
</ul>

<p>This autonomy creates unique scaling challenges. A simple chatbot makes one API call per interaction. An agentic system might make dozens of LLM calls, execute multiple tool invocations, and coordinate across several specialized agents—all for a single user request.</p>

<p>The implications are profound:</p>
<ul>
  <li><strong>Costs multiply</strong> through multi-step reasoning</li>
  <li><strong>Failures cascade</strong> across dependent operations</li>
  <li><strong>Security surface area expands</strong> with each tool integration</li>
  <li><strong>Debugging becomes exponentially harder</strong> as behavior emerges from complex interactions</li>
</ul>

<p>These challenges demand a platform approach, not point solutions.</p>

<hr />

<h2 id="the-five-foundational-principles">The Five Foundational Principles</h2>

<h3 id="1-platform-centric-architecture-over-point-solutions">1. Platform-Centric Architecture Over Point Solutions</h3>

<p>The most critical mindset shift is treating agentic AI as infrastructure. A platform provides shared capabilities that every agent needs:</p>

<ul>
  <li><strong>Unified model access</strong> through an LLM Gateway</li>
  <li><strong>Centralized security</strong> and guardrails</li>
  <li><strong>Consistent observability</strong> across all agents</li>
  <li><strong>Shared tool registry</strong> and integrations</li>
  <li><strong>Common governance</strong> and compliance controls</li>
</ul>

<p>Without a platform, each agent becomes a snowflake with its own security implementation, cost tracking, and monitoring approach. This creates operational nightmares at scale.</p>

<p><strong>The LLM Gateway pattern</strong> is central to this approach. It acts as a control plane that:</p>
<ul>
  <li>Routes requests to appropriate models based on complexity and budget</li>
  <li>Enforces rate limits and tenant quotas</li>
  <li>Enables semantic caching to reduce redundant calls</li>
  <li>Provides unified observability across all LLM interactions</li>
</ul>

<h3 id="2-modularity-and-specialization">2. Modularity and Specialization</h3>

<p>Resist the temptation to build monolithic “super agents.” Instead, favor specialized agents with single responsibilities.</p>

<p><strong>Why modularity matters:</strong></p>
<ul>
  <li><strong>Independent scaling</strong>: Scale your document processing agent separately from your customer service agent</li>
  <li><strong>Easier testing</strong>: Test each agent in isolation with well-defined inputs and outputs</li>
  <li><strong>Fault isolation</strong>: A failure in one agent doesn’t cascade to others</li>
  <li><strong>Flexible upgrades</strong>: Swap or improve individual components without system-wide risk</li>
</ul>

<p>The pattern that works: <strong>Single-responsibility agents</strong> coordinated through a <strong>supervisor/router pattern</strong>. Each agent excels at specific tasks and can be composed into larger workflows.</p>

<p><strong>Target system prompt size</strong>: Keep each agent’s system prompt under 2K tokens. If it’s growing beyond that, you’re likely cramming too many responsibilities into one agent.</p>

<h3 id="3-defense-in-depth-for-safety">3. Defense in Depth for Safety</h3>

<p>Enterprise agentic AI must assume failures will occur. Safety requires multiple, layered controls:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────┐
│  Input Layer: Prompt injection defense  │
├─────────────────────────────────────────┤
│  Model Layer: Output filtering, RLHF    │
├─────────────────────────────────────────┤
│  Action Layer: Tool permissions, HITL   │
├─────────────────────────────────────────┤
│  System Layer: Sandboxing, audit logs   │
└─────────────────────────────────────────┘
</code></pre></div></div>

<p>No single guardrail addresses all risks. You need:</p>
<ul>
  <li><strong>Input sanitization</strong> to block prompt injection attempts</li>
  <li><strong>Output validation</strong> to filter harmful or sensitive content</li>
  <li><strong>Action authorization</strong> with human-in-the-loop for high-impact decisions</li>
  <li><strong>Resource limits</strong> to prevent runaway agents</li>
  <li><strong>Sandboxed execution</strong> for untrusted operations</li>
  <li><strong>Comprehensive audit logging</strong> for compliance and debugging</li>
</ul>

<h3 id="4-observability-as-a-first-class-concern">4. Observability as a First-Class Concern</h3>

<p>Unlike traditional software where bugs are reproducible, agentic AI behavior is non-deterministic and emergent. You cannot debug what you cannot see.</p>

<p>Production systems require deep observability from day one:</p>
<ul>
  <li><strong>Distributed tracing</strong> across agent workflows</li>
  <li><strong>Real-time monitoring</strong> of model performance</li>
  <li><strong>Cost tracking</strong> per agent, task, and tenant</li>
  <li><strong>Decision replay</strong> capability to reconstruct agent reasoning paths</li>
</ul>

<p>Without observability, diagnosing production issues becomes nearly impossible. The root cause of a bad agent decision might be buried in the 15th step of a complex reasoning chain.</p>

<h3 id="5-cost-aware-design">5. Cost-Aware Design</h3>

<p>LLM inference is expensive, and agentic systems amplify costs through multi-step reasoning, tool calls, and inter-agent communication.</p>

<p><strong>The math is unforgiving</strong>: A simple customer service interaction might involve:</p>
<ul>
  <li>3 LLM calls for intent classification, context retrieval, and response generation</li>
  <li>2 tool invocations for database lookups</li>
  <li>Average of 2,000 tokens per call</li>
</ul>

<p>At GPT-4 pricing, a single interaction can cost $0.10-0.50. At 100K daily interactions, that’s $10K-50K per month—just for one use case.</p>

<p>Cost controls must be architectural, not afterthoughts:</p>
<ul>
  <li><strong>Token budgets</strong> per task with graceful degradation</li>
  <li><strong>Model routing</strong> to use cheaper models for simpler tasks</li>
  <li><strong>Semantic caching</strong> to avoid redundant calls</li>
  <li><strong>Real-time cost attribution</strong> per tenant, agent, and task</li>
</ul>

<hr />

<h2 id="architecture-best-practices">Architecture Best Practices</h2>

<h3 id="layered-architecture-design">Layered Architecture Design</h3>

<p>Production-grade agentic platforms typically follow a five-layer architecture:</p>

<p><strong>1. Infrastructure Layer</strong></p>
<ul>
  <li>Kubernetes for container orchestration</li>
  <li>Auto-scaling with Karpenter or cluster autoscaler</li>
  <li>Service mesh (Istio/Envoy) for traffic management</li>
</ul>

<p><strong>2. Data Layer</strong></p>
<ul>
  <li>Vector databases for RAG (Pinecone, Qdrant, Weaviate)</li>
  <li>Traditional databases for state management</li>
  <li>Message queues (Kafka, SQS) for async communication</li>
  <li>Redis for caching and session state</li>
</ul>

<p><strong>3. Platform Layer</strong></p>
<ul>
  <li>LLM Gateway for model access and routing</li>
  <li>Orchestration engine (Temporal, Airflow) for durable workflows</li>
  <li>Memory management system</li>
  <li>Tool registry and integration hub</li>
</ul>

<p><strong>4. Agent Layer</strong></p>
<ul>
  <li>Individual agent runtimes with lifecycle management</li>
  <li>Agent-specific configurations and prompts</li>
  <li>Tool bindings and permissions</li>
</ul>

<p><strong>5. Experience Layer</strong></p>
<ul>
  <li>APIs and SDKs for consumers</li>
  <li>Dashboards and admin interfaces</li>
  <li>Integration endpoints</li>
</ul>

<h3 id="multi-agent-orchestration-patterns">Multi-Agent Orchestration Patterns</h3>

<p>Choose orchestration patterns based on your specific requirements:</p>

<p><strong>Hierarchical (Supervisor-Worker) Pattern</strong></p>
<ul>
  <li><strong>Best for</strong>: Tasks requiring clear delegation, compliance/audit requirements</li>
  <li><strong>Avoid for</strong>: Latency-sensitive applications, simple single-purpose tasks</li>
  <li><strong>Implementation</strong>: Manager agent routes tasks to specialized workers, aggregates results</li>
</ul>

<p><strong>Horizontal (Peer Collaboration) Pattern</strong></p>
<ul>
  <li><strong>Best for</strong>: Complex tasks requiring multiple perspectives, parallel processing</li>
  <li><strong>Avoid for</strong>: Tasks with strict ordering requirements, limited compute budgets</li>
  <li><strong>Implementation</strong>: Agents communicate as equals, negotiate task division</li>
</ul>

<p><strong>Agentic Mesh Architecture</strong></p>
<ul>
  <li><strong>Best for</strong>: Enterprises with diverse business units, domain specialization needs</li>
  <li><strong>Avoid for</strong>: Small-scale deployments, tight latency requirements</li>
  <li><strong>Implementation</strong>: Specialized agents per domain collaborate across organizational boundaries</li>
</ul>

<hr />

<h2 id="multi-tenancy-the-enterprise-imperative">Multi-Tenancy: The Enterprise Imperative</h2>

<p>For SaaS and enterprise deployments, multi-tenancy is non-negotiable. With <strong>75% of tech leaders citing governance as their top deployment challenge</strong>, getting tenant isolation right is critical.</p>

<h3 id="isolation-models">Isolation Models</h3>

<table>
  <thead>
    <tr>
      <th>Model</th>
      <th>Isolation Level</th>
      <th>Cost Efficiency</th>
      <th>Best For</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Fully Shared</td>
      <td>Application-level</td>
      <td>Highest</td>
      <td>Dev/test, low-security</td>
    </tr>
    <tr>
      <td>Hybrid</td>
      <td>Data-level</td>
      <td>Medium</td>
      <td>Most enterprise SaaS</td>
    </tr>
    <tr>
      <td>Fully Isolated</td>
      <td>Resource-level</td>
      <td>Lowest</td>
      <td>Regulated industries</td>
    </tr>
  </tbody>
</table>

<p>Most production systems use the <strong>hybrid model</strong>: shared LLM infrastructure with per-tenant data isolation.</p>

<h3 id="essential-tenant-isolation-practices">Essential Tenant Isolation Practices</h3>

<p><strong>Per-Tenant Vector Namespaces</strong>
Every tenant gets isolated collections in your vector database. Never mix tenant documents in shared indices—the risk of cross-tenant retrieval is too high.</p>

<p><strong>Row-Level Security</strong>
Enforce <code class="language-plaintext highlighter-rouge">tenant_id</code> filtering at the database level, not just application code. Defense in depth means isolation is enforced even if application logic has bugs.</p>

<p><strong>JWT-Based Tenant Context</strong>
Pass tenant context through tokens for every request. This creates an auditable, tamper-resistant mechanism for tenant identification that flows through your entire stack.</p>

<p><strong>Resource Quotas</strong>
Implement per-tenant token limits and rate limiting to prevent noisy neighbor problems. Enterprise customers shouldn’t have their experience degraded because a smaller tenant is running runaway agents.</p>

<hr />

<h2 id="cost-management-strategies">Cost Management Strategies</h2>

<p>With organizations projecting an average <strong>171% ROI</strong> on agentic AI investments, getting cost management right directly impacts profitability.</p>

<h3 id="token-budget-management">Token Budget Management</h3>

<p>Implement hard limits with graceful fallbacks:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Task Type              | Model         | Cost/1K tokens
Simple extraction      | GPT-3.5-turbo | $0.002
Summarization         | Claude Haiku   | $0.003
Complex reasoning      | GPT-4-turbo   | $0.03
Final synthesis        | Claude Sonnet  | $0.015
</code></pre></div></div>

<p>Use <strong>model cascading</strong>: Start with cheaper models, escalate only when needed. Many tasks don’t require frontier model capabilities.</p>

<h3 id="semantic-caching">Semantic Caching</h3>

<p>Similar queries shouldn’t result in redundant API calls. Implement semantic caching using embedding similarity:</p>

<ul>
  <li>Generate embeddings for incoming queries</li>
  <li>Check cache for semantically similar previous queries (e.g., &gt;95% cosine similarity)</li>
  <li>Return cached responses for matches</li>
</ul>

<p><strong>Real-world impact</strong>: 40-60% cost reduction is typical for customer service applications where many queries are variations of common questions.</p>

<h3 id="cost-attribution">Cost Attribution</h3>

<p>Track costs at multiple granularities:</p>
<ul>
  <li>Per-tenant for billing and chargeback</li>
  <li>Per-agent for optimization targeting</li>
  <li>Per-task for understanding unit economics</li>
  <li>Per-user for usage-based pricing models</li>
</ul>

<p>Without granular cost attribution, you can’t identify which agents are consuming 60% of your token budget—a situation I’ve seen take months to diagnose.</p>

<hr />

<h2 id="safety-and-guardrails">Safety and Guardrails</h2>

<p>With <strong>35% of organizations citing cybersecurity as their top barrier</strong> to agentic AI adoption, safety isn’t optional—it’s existential.</p>

<h3 id="essential-guardrails">Essential Guardrails</h3>

<p><strong>1. Identity &amp; Access Control</strong></p>
<ul>
  <li>Least-privilege permissions for all agent operations</li>
  <li>Workload identity (SPIFFE/SPIRE) for service-to-service authentication</li>
  <li>Short-lived credentials that rotate automatically</li>
</ul>

<p><strong>2. Data Protection</strong></p>
<ul>
  <li>PII detection and redaction before LLM calls</li>
  <li>Sensitivity classification for all data access</li>
  <li>Encryption in transit and at rest</li>
</ul>

<p><strong>3. Action Authorization</strong></p>
<ul>
  <li>Human-in-the-loop for high-impact actions (financial transactions, account modifications)</li>
  <li>Dual-control mechanisms for sensitive operations</li>
  <li>Allowlists of permitted tools per agent</li>
</ul>

<p><strong>4. Containment</strong></p>
<ul>
  <li>Sandboxed execution (gVisor, Firecracker) for untrusted code</li>
  <li>Resource limits (CPU, memory, network) per agent</li>
  <li>Network egress allowlists</li>
</ul>

<p><strong>5. Audit Logging</strong></p>
<ul>
  <li>Every agent decision logged with context</li>
  <li>Every tool call recorded with inputs and outputs</li>
  <li>Tamper-evident audit trails for compliance</li>
</ul>

<h3 id="compliance-alignment">Compliance Alignment</h3>

<p>Map your controls to recognized frameworks:</p>
<ul>
  <li><strong>NIST AI RMF</strong> for risk management</li>
  <li><strong>ISO/IEC 42001</strong> for AI management systems</li>
  <li><strong>OWASP Top 10 for LLM Applications</strong> for security baselines</li>
  <li><strong>EU AI Act</strong> requirements for high-risk systems</li>
</ul>

<hr />

<h2 id="observability-implementation">Observability Implementation</h2>

<h3 id="the-four-pillars-for-agentic-ai">The Four Pillars for Agentic AI</h3>

<p><strong>1. Metrics</strong></p>
<ul>
  <li>Token usage per model, agent, tenant</li>
  <li>Latency percentiles (p50, p95, p99)</li>
  <li>Error rates by type</li>
  <li>Cost per request</li>
</ul>

<p><strong>2. Events</strong></p>
<ul>
  <li>Tool calls and their outcomes</li>
  <li>Model invocations</li>
  <li>State transitions</li>
  <li>Guardrail triggers</li>
</ul>

<p><strong>3. Logs</strong></p>
<ul>
  <li>Decision reasoning (why did the agent choose this action?)</li>
  <li>Prompt/completion pairs (with PII redaction)</li>
  <li>Error context and stack traces</li>
</ul>

<p><strong>4. Traces</strong></p>
<ul>
  <li>End-to-end request flows across agent boundaries</li>
  <li>Span hierarchies showing agent step sequences</li>
  <li>Timing breakdowns for performance optimization</li>
</ul>

<h3 id="key-metrics-to-monitor">Key Metrics to Monitor</h3>

<table>
  <thead>
    <tr>
      <th>Metric</th>
      <th>Target</th>
      <th>Alert Threshold</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>LLM latency P99</td>
      <td>&lt; 5 seconds</td>
      <td>&gt; 10 seconds for 5 min</td>
    </tr>
    <tr>
      <td>Agent success rate</td>
      <td>&gt; 95%</td>
      <td>&lt; 90% over 15 min</td>
    </tr>
    <tr>
      <td>Cache hit rate</td>
      <td>&gt; 40%</td>
      <td>&lt; 20% (cache issues)</td>
    </tr>
    <tr>
      <td>Guardrail trigger rate</td>
      <td>&lt; 5%</td>
      <td>&gt; 10% (possible attack)</td>
    </tr>
    <tr>
      <td>Average agent steps</td>
      <td>3-7 steps</td>
      <td>&gt; 15 steps (runaway)</td>
    </tr>
  </tbody>
</table>

<h3 id="recommended-stack">Recommended Stack</h3>

<ul>
  <li><strong>Langfuse/Arize Phoenix</strong>: LLM-specific observability with evaluation capabilities</li>
  <li><strong>OpenTelemetry</strong>: Vendor-neutral telemetry collection</li>
  <li><strong>Grafana + Prometheus</strong>: Infrastructure metrics and dashboards</li>
  <li><strong>Datadog LLM Observability</strong>: Enterprise-grade monitoring with auto-instrumentation</li>
</ul>

<hr />

<h2 id="memory-and-state-management">Memory and State Management</h2>

<p>Agents need memory to handle complex, multi-session workflows effectively.</p>

<h3 id="memory-architecture">Memory Architecture</h3>

<table>
  <thead>
    <tr>
      <th>Memory Type</th>
      <th>Purpose</th>
      <th>Storage</th>
      <th>Retention</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Working Memory</td>
      <td>Current task context</td>
      <td>In-memory/Redis</td>
      <td>Session</td>
    </tr>
    <tr>
      <td>Episodic Memory</td>
      <td>Past interaction history</td>
      <td>Vector DB</td>
      <td>Days-weeks</td>
    </tr>
    <tr>
      <td>Semantic Memory</td>
      <td>Learned facts and knowledge</td>
      <td>Knowledge graph</td>
      <td>Persistent</td>
    </tr>
    <tr>
      <td>Procedural Memory</td>
      <td>Task patterns and skills</td>
      <td>Document store</td>
      <td>Persistent</td>
    </tr>
  </tbody>
</table>

<h3 id="best-practices">Best Practices</h3>

<p><strong>Hierarchical Summarization</strong>
Compress old memories into higher-level abstractions. A conversation from last week doesn’t need verbatim recall—a summary of key decisions suffices.</p>

<p><strong>Vector-Based Retrieval</strong>
Index memories for semantic search. When an agent needs context, retrieve the most relevant memories based on embedding similarity.</p>

<p><strong>Temporal Awareness</strong>
Track when memories were created and updated. This enables conflict resolution when newer information contradicts older memories.</p>

<p><strong>Memory Scoping</strong>
Isolate memories appropriately:</p>
<ul>
  <li>Per-user for personal preferences</li>
  <li>Per-tenant for organizational knowledge</li>
  <li>Per-session for task-specific context</li>
</ul>

<h3 id="technologies">Technologies</h3>

<ul>
  <li><strong>Mem0</strong>: Production-ready memory layer with automatic extraction and update</li>
  <li><strong>Zep</strong>: Temporal knowledge graph for evolving context</li>
  <li><strong>Redis + Vector Search</strong>: High-performance short-term memory</li>
  <li><strong>LangGraph Checkpointers</strong>: Framework-integrated state persistence</li>
</ul>

<hr />

<h2 id="common-pitfalls-and-how-to-avoid-them">Common Pitfalls and How to Avoid Them</h2>

<h3 id="pitfall-1-building-monolithic-super-agents">Pitfall 1: Building Monolithic “Super Agents”</h3>

<p><strong>The Problem</strong>: A single agent with a massive system prompt (10K+ tokens) that handles everything becomes a debugging nightmare with unpredictable behavior.</p>

<p><strong>The Solution</strong>: Decompose into specialized single-responsibility agents. Use a supervisor pattern for coordination. Keep system prompts under 2K tokens.</p>

<h3 id="pitfall-2-ignoring-cost-until-production">Pitfall 2: Ignoring Cost Until Production</h3>

<p><strong>The Problem</strong>: Development uses free tiers, then production costs are 10-100x higher than expected due to iterative reasoning loops and verbose prompts.</p>

<p><strong>The Solution</strong>: Add cost tracking instrumentation from day one. Set budget alerts at 50%, 75%, 100% thresholds. Profile token usage to identify the biggest consumers.</p>

<h3 id="pitfall-3-insufficient-tenant-isolation">Pitfall 3: Insufficient Tenant Isolation</h3>

<p><strong>The Problem</strong>: Data leakage between tenants through shared vector databases, context pollution, or tool credential mixing.</p>

<p><strong>The Solution</strong>: Per-tenant namespaces in all data stores. Row-level security at infrastructure level. Separate credentials per tenant for external integrations.</p>

<h3 id="pitfall-4-underestimating-observability">Pitfall 4: Underestimating Observability</h3>

<p><strong>The Problem</strong>: Production issues are undebuggable because you can’t reconstruct what the agent was thinking when it made a bad decision.</p>

<p><strong>The Solution</strong>: Implement distributed tracing with spans for each agent action. Log full prompts and completions. Build replay capability for decision paths.</p>

<h3 id="pitfall-5-guardrails-as-an-afterthought">Pitfall 5: Guardrails as an Afterthought</h3>

<p><strong>The Problem</strong>: Agents in production leak sensitive data, execute unauthorized actions, or fall victim to prompt injection.</p>

<p><strong>The Solution</strong>: Treat safety as a first-class feature. Include adversarial testing in QA. Implement layered guardrails: input, model, action, and system layers.</p>

<hr />

<h2 id="looking-ahead-the-2025-2026-trajectory">Looking Ahead: The 2025-2026 Trajectory</h2>

<p>The agentic AI landscape is evolving rapidly:</p>

<p><strong>Multi-Agent Teams Go Mainstream</strong>
With <strong>66.4% of organizations already using multi-agent architectures</strong>, expect this to become the default approach for complex enterprise workflows.</p>

<p><strong>Embedded Agents Everywhere</strong>
AI agents will become embedded features in every major SaaS product—your CRM, project management tool, and ERP will all have native agentic capabilities.</p>

<p><strong>Governance Maturity</strong>
As <strong>75% of tech leaders cite governance as their top challenge</strong>, expect rapid maturation of governance frameworks, tooling, and best practices.</p>

<p><strong>Cost Optimization Innovation</strong>
With the market growing at 43%+ CAGR, expect significant innovation in cost optimization—better caching, more efficient models, and smarter routing strategies.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>Building scalable agentic AI platforms requires treating it as infrastructure, not just AI. The successful platforms I’ve built share common characteristics:</p>

<ol>
  <li><strong>Platform-centric architecture</strong> with shared services for model access, security, and observability</li>
  <li><strong>Modular agent design</strong> with single responsibilities and clear interfaces</li>
  <li><strong>Defense-in-depth safety</strong> with layered guardrails at every level</li>
  <li><strong>Deep observability</strong> enabling replay debugging of agent decisions</li>
  <li><strong>Cost awareness baked in</strong> from day one, not retrofitted after budget shocks</li>
</ol>

<p>The organizations winning with agentic AI aren’t necessarily those with the most sophisticated models—they’re the ones who’ve built robust platforms that can scale reliably, securely, and economically.</p>

<p>The market opportunity is massive. The technology is ready. The question is whether your architecture is prepared to capture it.</p>

<hr />

<h2 id="further-reading">Further Reading</h2>

<ul>
  <li><a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/agentic-ai-multitenant/introduction.html">Building multi-tenant architectures for agentic AI on AWS</a></li>
  <li><a href="https://architect.salesforce.com/fundamentals/enterprise-agentic-architecture">Enterprise Agentic Architecture and Design Patterns - Salesforce Architects</a></li>
  <li><a href="https://arxiv.org/abs/2512.08769">A Practical Guide for Designing Production-Grade Agentic AI Workflows</a></li>
  <li><a href="https://skywork.ai/blog/agentic-ai-safety-best-practices-2025-enterprise/">Safety &amp; Guardrails for Agentic AI Systems: A Practitioner’s Blueprint</a></li>
  <li>
    <h2 id="owasp-top-10-for-llm-applications"><a href="https://owasp.org/www-project-top-10-for-large-language-model-applications/">OWASP Top 10 for LLM Applications</a></h2>
  </li>
</ul>

<p><em>If you found this useful, feel free to connect on <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> or check out my projects on <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><category term="agentic-ai" /><category term="ai-platform" /><category term="scalability" /><category term="multi-agent" /><category term="llm" /><category term="architecture" /><summary type="html"><![CDATA[Best Practices for Building Scalable Agentic AI Platforms: A Comprehensive Guide for 2025]]></summary></entry><entry xml:lang="vi"><title type="html">Kiến Trúc Hoàn Chỉnh Cho Context Management Trong Agentic AI</title><link href="/vi/context-management-architecture/" rel="alternate" type="text/html" title="Kiến Trúc Hoàn Chỉnh Cho Context Management Trong Agentic AI" /><published>2026-03-01T00:00:00+07:00</published><updated>2026-03-01T00:00:00+07:00</updated><id>/vi/context-management-architecture-vi</id><content type="html" xml:base="/vi/context-management-architecture/"><![CDATA[<h2 id="mở-đầu--context-là-vấn-đề-cốt-lõi-không-phải-model">Mở đầu — Context là vấn đề cốt lõi, không phải model</h2>

<p>Năm 2024, cộng đồng AI chạy đua về model — GPT-4, Claude 3, Gemini. Năm 2025, cuộc đua chuyển sang agent — AutoGPT, CrewAI, LangGraph. Nhưng đến 2026, một sự thật trở nên rõ ràng: <strong>bottleneck không phải model intelligence, mà là context management.</strong></p>

<p>Một agent với GPT-5 nhưng context management kém vẫn thua một agent với GPT-4o-mini nhưng context management tốt. Letta đã chứng minh điều này khi agent đơn giản dùng GPT-4o-mini đạt 74% trên LoCoMo benchmark — cao hơn cả Mem0g (68.5%) với pipeline phức tạp hơn nhiều.</p>

<p>Bài viết này không so sánh model. Bài viết này trả lời câu hỏi: <strong>một kiến trúc context management hoàn chỉnh cho agentic platform gồm những gì?</strong> — và quan trọng hơn: <strong>phần nào dùng tool có sẵn, phần nào cần xây mới?</strong></p>

<hr />

<h2 id="1-context-management--memory-management">1. Context Management ≠ Memory Management</h2>

<p>Đây là sự phân biệt quan trọng nhất mà hầu hết đội ngũ engineering đang bỏ qua.</p>

<h3 id="memory-management-nhớ-gì-và-quên-gì">Memory Management: “Nhớ gì và quên gì”</h3>

<p>Memory management trả lời câu hỏi: <em>làm sao lưu trữ, truy xuất, cập nhật, và xóa kiến thức qua thời gian?</em></p>

<p>Nó giống như bộ nhớ dài hạn của con người — hippocampus lưu trữ ký ức, cortex tổ chức kiến thức. Khi bạn hỏi <em>“user này thích framework nào?”</em>, memory management lo tìm câu trả lời trong kho lưu trữ.</p>

<p><strong>Các sản phẩm memory management:</strong> Mem0, Zep, LangMem, Supermemory.</p>

<h3 id="context-management-đưa-gì-vào-não-lúc-này">Context Management: “Đưa gì vào não lúc này”</h3>

<p>Context management bao hàm memory management và mở rộng hơn nhiều. Nó trả lời câu hỏi: <em>với query hiện tại, tôi nên compose prompt như thế nào để LLM trả lời tốt nhất — bao gồm chọn gì từ memory, nén ra sao, sắp xếp thế nào, và phân bổ token budget cho từng phần?</em></p>

<p>Nó giống như bộ não đang hoạt động — không chỉ truy xuất ký ức mà còn tổ chức attention, quyết định focus vào đâu, bỏ qua gì, và tổng hợp từ nhiều nguồn khác nhau.</p>

<p><img src="/assets/images/blog-cm-01-context-vs-memory.drawio.png" alt="Context Management vs Memory Management" /></p>

<h3 id="mapping-theo-paper-context-engineering-20">Mapping theo paper “Context Engineering 2.0”</h3>

<p>Paper <em>“Context Engineering 2.0: The Context of Context Engineering”</em> (arXiv:2510.26493) định nghĩa context engineering gồm <strong>8 operations</strong>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>f_context(C) = F(φ₁, φ₂, ..., φ₈)(C)

① Collecting    — Thu thập raw context từ nhiều nguồn
② Storing       — Lưu trữ &amp; quản lý
③ Representing  — Biểu diễn nhất quán
④ Processing    — Xử lý multimodal
⑤ Self-baking   — Tiêu hóa context thô → persistent knowledge
⑥ Selecting     — Chọn context phù hợp nhất cho query hiện tại
⑦ Sharing       — Chia sẻ giữa agents/systems
⑧ Adapting      — Điều chỉnh strategy dựa trên feedback
</code></pre></div></div>

<p><strong>Memory management = φ₂ (Storing) + φ₅ (Self-baking)</strong>. Chỉ 2 trong 8 operations.</p>

<p><strong>Context management = Toàn bộ F(φ₁…φ₈)</strong> — một superset bao trùm memory cộng thêm collection, selection, compression, sharing, adaptation.</p>

<h3 id="so-sánh-trực-tiếp">So sánh trực tiếp</h3>

<table>
  <thead>
    <tr>
      <th>Dimension</th>
      <th>Memory Management</th>
      <th>Context Management</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Câu hỏi trung tâm</strong></td>
      <td>“Lưu gì, ở đâu, lấy lại khi nào?”</td>
      <td>“Đưa gì vào prompt LẦN NÀY để LLM trả lời tốt nhất?”</td>
    </tr>
    <tr>
      <td><strong>Scope thời gian</strong></td>
      <td>Dài hạn — cross-session, cross-task</td>
      <td>Tức thì — per-turn, per-request</td>
    </tr>
    <tr>
      <td><strong>Output</strong></td>
      <td>Stored/retrieved knowledge items</td>
      <td>Composed prompt tối ưu</td>
    </tr>
    <tr>
      <td><strong>Metric chính</strong></td>
      <td>Recall accuracy, storage cost</td>
      <td>Response quality, token efficiency, KV-cache hit rate</td>
    </tr>
    <tr>
      <td><strong>Bao gồm</strong></td>
      <td>Store + Retrieve + Update + Forget</td>
      <td>Memory + Prompt engineering + Selection + Compression + Sharing + Adaptation</td>
    </tr>
  </tbody>
</table>

<h3 id="ví-dụ-cụ-thể">Ví dụ cụ thể</h3>

<p>Khi user gửi message <em>“Refactor auth module”</em>:</p>

<p><strong>Memory management</strong> truy xuất: <em>“User đã quyết định dùng JWT, auth.py đang tách thành 2 file, lần trước bị block vì DB schema chưa update.”</em></p>

<p><strong>Context management</strong> làm tất cả những gì memory làm, CỘNG THÊM:</p>
<ul>
  <li><strong>Token budget allocation</strong>: 10K system prompt + 30K long-term facts + 40K session history + 80K recent turns + 20K user input + 20K response</li>
  <li><strong>Selection &amp; ranking</strong>: Trong 50 memory items, chọn 8 relevant nhất bằng scoring formula (ví dụ: semantic similarity × 0.4 + recency × 0.25 + frequency × 0.15 + dependency × 0.2)</li>
  <li><strong>Compression</strong>: Tóm tắt 20 turns cũ thành 1 paragraph</li>
  <li><strong>Prompt composition</strong>: Sắp xếp thứ tự optimal (system → facts → session → recent → user) theo research về “Lost in the Middle”</li>
  <li><strong>KV-cache optimization</strong>: Giữ system prompt ổn định ở prefix để cache hit</li>
  <li><strong>Adaptation</strong>: Nếu lần trước user phàn nàn thiếu context, tăng weight cho dependency scoring</li>
</ul>

<p><strong>Insight:</strong> Mỗi Mem0, Zep, Supermemory chỉ giải quyết phần “memory” — chưa ai giải quyết trọn vẹn “context management”. Letta (MemGPT) là tool tiến gần nhất vì nó quản lý cả memory lẫn context window allocation, nhưng vẫn thiếu compression pipeline và cross-system sharing.</p>

<p><img src="/assets/images/blog-cm-02-side-by-side-flow.drawio.png" alt="Memory Management vs Context Management - Side by Side Flow" /></p>

<hr />

<h2 id="2-landscape-các-tools-hiện-nay-2026">2. Landscape Các Tools Hiện Nay (2026)</h2>

<p>Thị trường AI memory/context đang bùng nổ. Để hiểu rõ landscape, tôi phân loại theo <strong>vai trò trong 8 operations của <a href="https://arxiv.org/abs/2510.26493">Context Engineering 2.0</a></strong> (φ₁-φ₈), không phải theo marketing category.</p>

<p><img src="/assets/images/blog-cm-03-tool-positioning-matrix.drawio.png" alt="Tool Positioning Matrix" /></p>

<h3 id="21-memory-storage--retrieval-layer">2.1 Memory Storage &amp; Retrieval Layer</h3>

<p>Các tool chuyên lưu trữ và truy xuất memory. Đây là <strong>φ₂ (Storing)</strong> trong framework.</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Approach</th>
      <th>Storage</th>
      <th>Strengths</th>
      <th>Weaknesses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://mem0.ai">Mem0</a></strong></td>
      <td>Auto-extract facts → hybrid store</td>
      <td>Vector (Qdrant/Chroma/FAISS) + Graph (Neo4j) + KV (Redis)</td>
      <td>Drop-in 3-line integration, 90% token savings proven, AWS partnership</td>
      <td>Graph memory paywalled ($249/mo), black-box extraction, 13x price jump</td>
    </tr>
    <tr>
      <td><strong><a href="https://getzep.com">Zep</a></strong></td>
      <td>Temporal knowledge graph</td>
      <td>Graphiti (bi-temporal graph) + vector</td>
      <td>Time-aware memory, knows when facts change, strong enterprise focus</td>
      <td>Smaller ecosystem, no validation/dedup layer</td>
    </tr>
    <tr>
      <td><strong><a href="https://supermemory.ai">Supermemory</a></strong></td>
      <td>Brain-inspired auto-forget</td>
      <td>Cloudflare Durable Objects + KV + Postgres</td>
      <td>Sub-400ms, smart decay, Claude Code plugin</td>
      <td>English only, plugin v0.0.2, declining benchmark position</td>
    </tr>
    <tr>
      <td><strong><a href="https://langchain-ai.github.io/langmem/">LangMem</a></strong></td>
      <td>Library for LangGraph</td>
      <td>Flat KV + vector search</td>
      <td>Free, pip install, no API keys</td>
      <td>Requires LangGraph, no graph/relationship modeling</td>
    </tr>
    <tr>
      <td><strong><a href="https://cognee.ai">Cognee</a></strong></td>
      <td>Knowledge graph pipeline</td>
      <td>RDF ontologies + vector/graph DB</td>
      <td>Strong structured extraction, on-premises</td>
      <td>Newer, smaller community</td>
    </tr>
  </tbody>
</table>

<h3 id="22-agent-framework-with-built-in-memory">2.2 Agent Framework with Built-in Memory</h3>

<p>Các framework coi memory là first-class citizen trong agent runtime. Kết hợp <strong>φ₂ + φ₅ + φ₆</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Approach</th>
      <th>Storage</th>
      <th>Strengths</th>
      <th>Weaknesses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://letta.com">Letta (MemGPT)</a></strong></td>
      <td>LLM-as-OS: agent self-manages memory via tools</td>
      <td>PostgreSQL + pgvector</td>
      <td>White-box memory, git-versioned Context Repositories (Feb 2026), full OSS parity</td>
      <td>Depends on LLM intelligence, no native graph, smaller community</td>
    </tr>
    <tr>
      <td><strong><a href="https://google.github.io/adk-docs/">Google ADK</a></strong></td>
      <td>Session-based + context compaction</td>
      <td>Configurable (memory stores)</td>
      <td>Sliding window compaction (60-80% token reduction), multi-level (conversation/workflow/tool), incremental</td>
      <td>Session-centric, less cross-session persistence</td>
    </tr>
  </tbody>
</table>

<h3 id="23-context-compression-tools">2.3 Context Compression Tools</h3>

<p>Chuyên nén context để fit vào context window. Đây là một phần của <strong>φ₅ (Self-baking)</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Approach</th>
      <th>Compression Ratio</th>
      <th>Strengths</th>
      <th>Weaknesses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://llmlingua.com">LLMLingua 2</a></strong> (Microsoft)</td>
      <td>Perplexity-based token filtering</td>
      <td>Lên đến 20x</td>
      <td>Nhanh 3-6x so với v1, tích hợp LangChain/LlamaIndex</td>
      <td>Chỉ compression, không memory/persistence</td>
    </tr>
    <tr>
      <td><strong><a href="https://arxiv.org/abs/...">Acon</a></strong></td>
      <td>Agent observation compression</td>
      <td>26-54% peak token reduction</td>
      <td>Dành riêng cho agentic workflows</td>
      <td>Research, chưa production-ready</td>
    </tr>
    <tr>
      <td><strong><a href="https://mastra.ai/docs/memory/observational-memory">Mastra OM</a></strong></td>
      <td>Observer + Reflector agents nén conversation</td>
      <td>3-6x (text), 5-40x (tool output)</td>
      <td>94.87% LongMemEval (SOTA), no vector DB needed, leverages prompt caching</td>
      <td>Text-only, no external knowledge retrieval</td>
    </tr>
  </tbody>
</table>

<h3 id="24-context-protocol--sharing">2.4 Context Protocol &amp; Sharing</h3>

<p>Chuẩn hóa cách agents chia sẻ context. Đây là <strong>φ₇ (Sharing)</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Approach</th>
      <th>Strengths</th>
      <th>Weaknesses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://modelcontextprotocol.io">MCP</a></strong> (Anthropic → Linux Foundation)</td>
      <td>Standardized bidirectional protocol</td>
      <td>Adopted by OpenAI, Google DeepMind; SDKs Python/TS/C#/Java</td>
      <td>Memory server còn basic</td>
    </tr>
    <tr>
      <td><strong><a href="https://github.com/modelcontextprotocol/servers/tree/main/src/memory">MCP Memory Server</a></strong></td>
      <td>Knowledge graph qua MCP</td>
      <td>Standard protocol, compatible với Claude/Cursor/VS Code</td>
      <td>Basic (chỉ entity-relation triplets)</td>
    </tr>
    <tr>
      <td><strong><a href="https://github.com/mem0ai/openmemory">OpenMemory</a></strong> (Mem0)</td>
      <td>Local-first memory qua MCP</td>
      <td>Privacy-focused, migration tool from Mem0/Zep/Supermemory</td>
      <td>Phụ thuộc Mem0 ecosystem</td>
    </tr>
    <tr>
      <td><strong><a href="https://docs.letta.com">Letta Agent File (.af)</a></strong></td>
      <td>Open format cho portable agents</td>
      <td>Bao gồm cả memory state</td>
      <td>Letta-specific</td>
    </tr>
  </tbody>
</table>

<h3 id="25-context-versioning--tracing">2.5 Context Versioning &amp; Tracing</h3>

<p>Theo dõi context qua thời gian. Đây là một phần của <strong>φ₈ (Adapting)</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Approach</th>
      <th>Strengths</th>
      <th>Weaknesses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://mirascope.com">Lilypad</a></strong> (Mirascope)</td>
      <td>Context tracing &amp; versioning</td>
      <td>Track context changes, compare versions</td>
      <td>Không memory/persistence</td>
    </tr>
    <tr>
      <td><strong><a href="https://www.letta.com/blog/context-repositories">Letta Context Repositories</a></strong></td>
      <td>Git-backed memory filesystem</td>
      <td>Rollbacks, changelogs, diffs, multi-agent concurrent writes</td>
      <td>Mới (Feb 2026), chưa ổn định</td>
    </tr>
  </tbody>
</table>

<h3 id="26-emerging-self-baking--evolving-context">2.6 Emerging: Self-Baking &amp; Evolving Context</h3>

<p>Research-stage tools cho <strong>φ₅ (Self-baking) + φ₈ (Adapting)</strong> — chưa có sản phẩm production.</p>

<table>
  <thead>
    <tr>
      <th>Research</th>
      <th>Approach</th>
      <th>Results</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong><a href="https://arxiv.org/abs/2510.04618">ACE</a></strong> (Stanford/SambaNova)</td>
      <td>Generator → Reflector → Curator: delta contexts, not full rewrites</td>
      <td>+10.6% agent benchmarks, 86.9% lower adaptation latency</td>
    </tr>
    <tr>
      <td><strong><a href="https://arxiv.org/abs/2504.07952">Dynamic Cheatsheet</a></strong></td>
      <td>Adaptive external memory of reusable strategies</td>
      <td>Claude 3.5 AIME: &gt;2x accuracy; GPT-4o Game of 24: 10%→99%</td>
    </tr>
  </tbody>
</table>

<h3 id="tóm-lại-không-ai-giải-quyết-trọn-vẹn">Tóm lại: Không ai giải quyết trọn vẹn</h3>

<p>Bảng dưới đây là <strong>đánh giá của tác giả</strong> dựa trên documentation review và hands-on testing của từng tool, mapping theo <a href="https://arxiv.org/abs/2510.26493">8 operations của Context Engineering 2.0</a>:</p>

<p><img src="/assets/images/blog-cm-04-tool-coverage-heatmap.drawio.png" alt="Tool Coverage Heatmap" /></p>

<p><strong>Gap lớn nhất: φ₆ (Selecting), φ₈ (Adapting), và integration pipeline thống nhất.</strong></p>

<hr />

<h2 id="3-kiến-trúc-hoàn-chỉnh-cho-agentic-platform">3. Kiến Trúc Hoàn Chỉnh Cho Agentic Platform</h2>

<p>Dựa trên framework φ₁-φ₈ của <a href="https://arxiv.org/abs/2510.26493">Context Engineering 2.0</a>, phân tích gap ở Section 2, và kinh nghiệm thực tế từ <a href="https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus">Manus</a>, <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic</a>, <a href="https://google.github.io/adk-docs/">Google ADK</a>, tôi đề xuất kiến trúc sau:</p>

<h3 id="31-architecture-overview">3.1 Architecture Overview</h3>

<p><img src="/assets/images/blog-cm-05-architecture-overview.drawio.png" alt="Architecture Overview - Context Management Layer" /></p>

<h3 id="32-component-1-context-collector-φ--φ">3.2 Component 1: Context Collector (φ₁ + φ₃)</h3>

<p><strong>Vai trò:</strong> Thu thập context từ mọi nguồn và biểu diễn thống nhất thành <code class="language-plaintext highlighter-rouge">ContextItem</code>.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">dataclass</span>
<span class="k">class</span> <span class="nc">ContextItem</span><span class="p">:</span>
    <span class="nb">id</span><span class="p">:</span> <span class="nb">str</span>                          <span class="c1"># Unique identifier
</span>    <span class="n">content</span><span class="p">:</span> <span class="nb">str</span>                     <span class="c1"># Nội dung
</span>    <span class="n">source</span><span class="p">:</span> <span class="n">ContextSource</span>            <span class="c1"># USER | FILE | TOOL | HISTORY | MEMORY
</span>    <span class="n">timestamp</span><span class="p">:</span> <span class="n">datetime</span>              <span class="c1"># Thời điểm tạo
</span>    <span class="n">tags</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span>                  <span class="c1"># Functional/semantic tags
</span>    <span class="n">importance</span><span class="p">:</span> <span class="nb">float</span>                <span class="c1"># 0.0 - 1.0
</span>    <span class="n">token_count</span><span class="p">:</span> <span class="nb">int</span>                 <span class="c1"># Estimated tokens
</span>    <span class="n">metadata</span><span class="p">:</span> <span class="nb">dict</span>                   <span class="c1"># Additional data
</span>    <span class="n">embedding</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">list</span><span class="p">[</span><span class="nb">float</span><span class="p">]]</span> <span class="c1"># Lazy-computed vector
</span></code></pre></div></div>

<p><strong>Các nguồn thu thập:</strong></p>
<ul>
  <li><strong>User input</strong> — Messages, commands</li>
  <li><strong>File system</strong> — CLAUDE.md, source code, configs</li>
  <li><strong>Tool output</strong> — Search results, file reads, API responses</li>
  <li><strong>Session history</strong> — Previous turns in current session</li>
  <li><strong>Long-term memory</strong> — Cross-session facts and summaries</li>
  <li><strong>External sources</strong> — MCP servers, databases, APIs</li>
</ul>

<h3 id="33-component-2-context-manager-φ--φ--φ">3.3 Component 2: Context Manager (φ₂ + φ₄ + φ₅)</h3>

<p><strong>Vai trò:</strong> Quản lý vòng đời context — store, compress, self-bake, transfer giữa memory tiers.</p>

<p><strong>3 Memory Tiers:</strong></p>

<table>
  <thead>
    <tr>
      <th>Tier</th>
      <th>Storage</th>
      <th>Lifespan</th>
      <th>Content</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Working Memory</strong></td>
      <td>In-RAM</td>
      <td>Current session only</td>
      <td>Raw conversation turns, active tool outputs</td>
    </tr>
    <tr>
      <td><strong>Session Memory</strong></td>
      <td>SQLite</td>
      <td>Persisted per session</td>
      <td>Compressed history, session summaries</td>
    </tr>
    <tr>
      <td><strong>Long-term Memory</strong></td>
      <td>File (JSON/MD) + Vector DB</td>
      <td>Cross-session</td>
      <td>Facts, decisions, preferences, embeddings</td>
    </tr>
  </tbody>
</table>

<p><strong>Self-baking Pipeline</strong> — khái niệm từ <a href="https://arxiv.org/abs/2510.26493">Context Engineering 2.0</a> (φ₅), pattern 4 lấy cảm hứng từ <a href="https://arxiv.org/abs/2510.04618">ACE</a>. Đây là điểm khác biệt lớn nhất — chưa tool nào implement đầy đủ:</p>

<p><img src="/assets/images/blog-cm-06-self-baking-pipeline.drawio.png" alt="Self-Baking Pipeline: 4 Consolidation Patterns" /></p>

<p><strong>Memory Transfer Rules:</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Short-term → Long-term when:
  - importance(item) &gt; θ_importance (e.g., 0.7)
  - item contains: decision, preference, architecture choice, error-solution
  - session ends → auto-bake remaining working memory
</code></pre></div></div>

<h3 id="34-component-3-context-selector-φ">3.4 Component 3: Context Selector (φ₆)</h3>

<p><strong>Vai trò:</strong> Chọn subset context tối ưu cho từng query, fit vào token budget.</p>

<p><strong>Scoring formula</strong> (proposed — các weights dưới đây là giá trị khởi đầu gợi ý, cần tuning theo use case cụ thể):</p>

<p><img src="/assets/images/blog-cm-08-scoring-weights.drawio.png" alt="Context Scoring Formula: Factor Weights" /></p>

<p><strong>Token Budget Allocation</strong> (proposed — tỷ lệ gợi ý cho 200K context window, cần điều chỉnh theo model và workload):</p>

<p><img src="/assets/images/blog-cm-07-token-budget.drawio.png" alt="Token Budget Allocation" /></p>

<p><strong>KV-cache optimization</strong> (insight từ <a href="https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus">Manus</a>):</p>

<blockquote>
  <p><em>“If you had to choose just one metric, the KV-cache hit rate is the single most important metric for a production-stage AI agent.”</em></p>
</blockquote>

<p>Giữ system prompt + long-term context ổn định ở prefix → cache hit → giảm latency + cost.</p>

<h3 id="35-component-4-context-sharer-φ--φ">3.5 Component 4: Context Sharer (φ₇ + φ₈)</h3>

<p><strong>Vai trò:</strong> Chia sẻ context giữa agents và cross-system, điều chỉnh strategy dựa trên feedback.</p>

<p><strong>Intra-system sharing:</strong></p>
<ul>
  <li>Agent → subagent: Embed relevant context in prompt</li>
  <li>Shared memory namespace: Blackboard pattern</li>
  <li>Multi-agent concurrent writes: Git worktrees (Letta approach)</li>
</ul>

<p><strong>Cross-system sharing:</strong></p>
<ul>
  <li>MCP protocol: Standardized tools/resources</li>
  <li>Export/Import: JSON, Markdown, YAML</li>
  <li>File-based: CLAUDE.md, GEMINI.md patterns</li>
</ul>

<p><strong>Adaptation loop:</strong></p>
<ul>
  <li>Track response quality metrics</li>
  <li>If context selection led to poor response → adjust scoring weights</li>
  <li>If compression was too aggressive → lower compression ratio</li>
  <li>A/B test different context compositions</li>
</ul>

<hr />

<h2 id="4-mapping-tools-vào-kiến-trúc--dùng-gì-xây-gì">4. Mapping Tools Vào Kiến Trúc — Dùng Gì, Xây Gì</h2>

<p>Đây là phần thực dụng nhất: với kiến trúc 4 components + 3 tiers + 2 pipelines ở trên, tool nào có sẵn lắp vào được, và gap nào cần xây?</p>

<h3 id="41-bảng-mapping-toàn-diện">4.1 Bảng Mapping Toàn Diện</h3>

<p><img src="/assets/images/blog-cm-13-component-mapping.drawio.png" alt="Component Mapping: Available Tools vs Custom Build" /></p>

<h3 id="42-tổng-kết-60-dùng-tool-có-sẵn-40-cần-xây">4.2 Tổng kết: 60% dùng tool có sẵn, 40% cần xây</h3>

<p><strong>Dùng tool có sẵn (60%):</strong></p>
<ul>
  <li>Memory storage: Mem0 hoặc Zep (tùy use case)</li>
  <li>Vector search: FAISS/Chroma (self-hosted) hoặc Qdrant/Pinecone (managed)</li>
  <li>NL compression: LLM-based summarization hoặc LLMLingua 2</li>
  <li>Observational compression: Mastra OM (nếu dùng TypeScript)</li>
  <li>Protocol: MCP cho cross-tool sharing</li>
  <li>Static context: CLAUDE.md pattern</li>
  <li>Session compaction: Google ADK compaction (nếu dùng ADK)</li>
</ul>

<p><strong>Cần xây mới (40%) — đây là phần tạo differentiation:</strong></p>

<table>
  <thead>
    <tr>
      <th>Component Cần Xây</th>
      <th>Tại Sao Chưa Ai Làm</th>
      <th>Complexity</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Context Selector</strong> (scoring + budgeting)</td>
      <td>Mỗi tool chỉ lo retrieve, không ai lo tổng hợp + rank + budget</td>
      <td>Medium</td>
    </tr>
    <tr>
      <td><strong>Self-baking Pipeline</strong></td>
      <td>Paper mới đề xuất (2025), chưa tool nào implement đúng</td>
      <td>High</td>
    </tr>
    <tr>
      <td><strong>Schema Extraction Engine</strong></td>
      <td>Cần domain-specific schemas, khó generalize</td>
      <td>Medium</td>
    </tr>
    <tr>
      <td><strong>KV-cache Optimizer</strong></td>
      <td>Cần hiểu LLM internals, ít người focus</td>
      <td>Medium</td>
    </tr>
    <tr>
      <td><strong>Adaptation Loop</strong></td>
      <td>Cần feedback signal, chưa ai define rõ metric</td>
      <td>High</td>
    </tr>
    <tr>
      <td><strong>Unified .context/ Protocol</strong></td>
      <td>CLAUDE.md là static; cần dynamic, auto-updated version</td>
      <td>Medium</td>
    </tr>
    <tr>
      <td><strong>Export/Import Pipeline</strong></td>
      <td>Mỗi tool format riêng, cần standardize</td>
      <td>Low</td>
    </tr>
  </tbody>
</table>

<p><img src="/assets/images/blog-cm-10-build-vs-buy.drawio.png" alt="Build vs Buy: 60/40 Split" /></p>

<hr />

<h2 id="5-gợi-ý-compositions--use-cases">5. Gợi Ý Compositions &amp; Use Cases</h2>

<h3 id="51-composition-a-production-chatbot--drop-in-memory">5.1 Composition A: “Production Chatbot” — Drop-in Memory</h3>

<p><strong>Use case:</strong> Customer support bot cần nhớ user preferences, lịch sử tương tác.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────────┐
│              YOUR APP / AGENT               │
└──────────────────────┬──────────────────────┘
                       │
┌──────────────────────▼──────────────────────┐
│         Mem0 (Memory Layer)                 │
│  • Auto-extract facts from conversations    │
│  • Retrieve relevant memories per query     │
│  • User/session/agent scoping built-in      │
└──────────────────────┬──────────────────────┘
                       │
              ┌────────┴────────┐
              ▼                 ▼
        Vector Store       Graph Store
        (Qdrant)           (Neo4j — $249/mo)
</code></pre></div></div>

<p><strong>Tools used:</strong> Mem0 (managed platform)
<strong>Cần xây thêm:</strong> Không — Mem0 handle trọn vẹn
<strong>Cost:</strong> $19-249/mo managed, hoặc self-hosted (vector DB only, graph paywalled)
<strong>Khi nào dùng:</strong> MVP, B2B copilot, customer support — cần đi nhanh, không cần custom</p>

<p><strong>Code:</strong></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">mem0</span> <span class="kn">import</span> <span class="n">Memory</span>
<span class="kn">from</span> <span class="nn">openai</span> <span class="kn">import</span> <span class="n">OpenAI</span>

<span class="n">memory</span> <span class="o">=</span> <span class="n">Memory</span><span class="p">()</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">OpenAI</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">chat</span><span class="p">(</span><span class="n">message</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">user_id</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">relevant</span> <span class="o">=</span> <span class="n">memory</span><span class="p">.</span><span class="n">search</span><span class="p">(</span><span class="n">query</span><span class="o">=</span><span class="n">message</span><span class="p">,</span> <span class="n">user_id</span><span class="o">=</span><span class="n">user_id</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
    <span class="n">memories_str</span> <span class="o">=</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="sa">f</span><span class="s">"- </span><span class="si">{</span><span class="n">m</span><span class="p">[</span><span class="s">'memory'</span><span class="p">]</span><span class="si">}</span><span class="s">"</span> <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">relevant</span><span class="p">[</span><span class="s">"results"</span><span class="p">])</span>

    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="n">chat</span><span class="p">.</span><span class="n">completions</span><span class="p">.</span><span class="n">create</span><span class="p">(</span>
        <span class="n">model</span><span class="o">=</span><span class="s">"gpt-4.1-nano"</span><span class="p">,</span>
        <span class="n">messages</span><span class="o">=</span><span class="p">[</span>
            <span class="p">{</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"system"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="sa">f</span><span class="s">"User context:</span><span class="se">\n</span><span class="si">{</span><span class="n">memories_str</span><span class="si">}</span><span class="s">"</span><span class="p">},</span>
            <span class="p">{</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"user"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="n">message</span><span class="p">},</span>
        <span class="p">],</span>
    <span class="p">)</span>
    <span class="n">answer</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">choices</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">message</span><span class="p">.</span><span class="n">content</span>
    <span class="n">memory</span><span class="p">.</span><span class="n">add</span><span class="p">([{</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"user"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="n">message</span><span class="p">},</span>
                <span class="p">{</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"assistant"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="n">answer</span><span class="p">}],</span> <span class="n">user_id</span><span class="o">=</span><span class="n">user_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">answer</span>
</code></pre></div></div>

<hr />

<h3 id="52-composition-b-stateful-agent--full-agent-runtime">5.2 Composition B: “Stateful Agent” — Full Agent Runtime</h3>

<p><strong>Use case:</strong> Long-running agent cần tự quản lý memory, transparent reasoning, audit trail.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────────┐
│          Letta Agent Runtime                │
│                                             │
│  ┌─────────────────────────────────────┐   │
│  │        CONTEXT WINDOW               │   │
│  │  Core Memory Blocks (in-context)    │   │
│  │  ┌──────────┐  ┌─────────────────┐ │   │
│  │  │ "persona"│  │    "human"      │ │   │
│  │  └──────────┘  └─────────────────┘ │   │
│  │  Recent conversation messages       │   │
│  └─────────────────────────────────────┘   │
│                                             │
│  Memory Tools (agent calls autonomously):   │
│  • memory_replace / memory_insert           │
│  • archival_memory_search                   │
│  • conversation_search                      │
│                                             │
│  ┌─────────────────────────────────────┐   │
│  │   PostgreSQL + pgvector             │   │
│  │   Archival + Conversational Memory  │   │
│  │   Context Repositories (git-backed) │   │
│  └─────────────────────────────────────┘   │
└─────────────────────────────────────────────┘
</code></pre></div></div>

<p><strong>Tools used:</strong> Letta (self-hosted hoặc Cloud)
<strong>Cần xây thêm:</strong> Domain-specific memory block schemas
<strong>Cost:</strong> Free (self-hosted, single PostgreSQL) hoặc $20/mo (Cloud)
<strong>Khi nào dùng:</strong> AI researcher assistant, document analysis agent, autonomous coding agent</p>

<hr />

<h3 id="53-composition-c-long-running-coding-agent--memory--compression">5.3 Composition C: “Long-Running Coding Agent” — Memory + Compression</h3>

<p><strong>Use case:</strong> Coding agent chạy hàng giờ, context window overflow, cần nhớ decisions across sessions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────────────────┐
│              CODING AGENT (Claude Code / OpenCode)   │
└──────────────────────────┬──────────────────────────┘
                           │
         ┌─────────────────┼─────────────────┐
         ▼                 ▼                 ▼
┌────────────────┐ ┌──────────────┐ ┌───────────────┐
│  Supermemory   │ │  Mastra OM   │ │  CLAUDE.md    │
│  (persistent   │ │  (compress   │ │  (static      │
│   project &amp;    │ │   long conv  │ │   project     │
│   user memory) │ │   → obs log) │ │   context)    │
└────────────────┘ └──────────────┘ └───────────────┘
         │                 │                 │
         └────── Combined context ───────────┘
                           │
                    ┌──────▼──────┐
                    │ LLM Backend │
                    └─────────────┘
</code></pre></div></div>

<p><strong>Tools used:</strong> Supermemory (memory) + Mastra OM (compression) + CLAUDE.md (static context)
<strong>Cần xây thêm:</strong> Context Selector (scoring + budgeting khi combine 3 nguồn)
<strong>Cost:</strong> Supermemory $19/mo + Mastra (self-hosted, free)
<strong>Khi nào dùng:</strong> Long coding sessions, multi-session refactoring projects</p>

<hr />

<h3 id="54-composition-d-enterprise-platform--full-context-management">5.4 Composition D: “Enterprise Platform” — Full Context Management</h3>

<p><strong>Use case:</strong> Enterprise agentic platform cần full context management — multi-agent, compliance, temporal reasoning.</p>

<p><img src="/assets/images/blog-cm-09-enterprise-architecture.drawio.png" alt="Enterprise Context Management Architecture" /></p>

<p><strong>Tools used:</strong></p>
<ul>
  <li>Zep (temporal knowledge graph — $)</li>
  <li>LLMLingua 2 (token compression — free)</li>
  <li>MCP SDK (protocol — free)</li>
  <li>FAISS/Chroma (vector search — free)</li>
</ul>

<p><strong>Cần xây:</strong></p>
<ul>
  <li>Context Selector (scoring + budgeting + KV-cache optimization)</li>
  <li>Self-baking Pipeline (4 patterns)</li>
  <li>Schema Extraction Engine</li>
  <li>.context/ file protocol</li>
  <li>Adaptation Loop</li>
  <li>Export/Import pipeline</li>
</ul>

<p><strong>Cost:</strong> Zep Cloud (custom pricing) + self-hosted infra + engineering team
<strong>Khi nào dùng:</strong> Enterprise platform serving multiple agent types, compliance-heavy, temporal reasoning needed</p>

<hr />

<h3 id="55-composition-e-lightweight-cli-agent--file-first-zero-dependencies">5.5 Composition E: “Lightweight CLI Agent” — File-First, Zero Dependencies</h3>

<p><strong>Use case:</strong> CLI agent (kiểu Claude Code) cần persistent memory across sessions, zero external services.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────────┐
│              CLI AGENT                       │
└──────────────────────┬──────────────────────┘
                       │
┌──────────────────────▼──────────────────────┐
│     Lightweight CML (embedded library)       │
│                                              │
│  Working Memory:  In-process dictionary      │
│  Session Memory:  SQLite (local file)        │
│  Long-term:       .context/ directory        │
│     ├── facts.json     (schema-baked facts)  │
│     ├── summaries/     (NL summaries by topic)│
│     ├── sessions/      (SQLite DB)           │
│     └── config.yaml    (CML configuration)   │
│                                              │
│  Compression:  LLM-based summarization       │
│  Selection:    Simple recency + importance    │
│  Self-baking:  Session-end auto-bake          │
│                                              │
│  NO external DB. NO vector store.            │
│  NO running services. Just files.            │
└──────────────────────────────────────────────┘
</code></pre></div></div>

<p><strong>Tools used:</strong> SQLite (built-in), LLM (any)
<strong>Cần xây:</strong> Entire lightweight CML library
<strong>Cost:</strong> $0 infrastructure (chỉ LLM API cost)
<strong>Khi nào dùng:</strong> CLI tools, developer workflows, offline-capable agents</p>

<p>Đây là composition phù hợp nhất cho project context-engineering trong repo này — một lightweight, file-first context management layer tương thích với CLAUDE.md pattern, không phụ thuộc external services.</p>

<hr />

<h2 id="6-decision-framework--chọn-composition-nào">6. Decision Framework — Chọn Composition Nào?</h2>

<p><img src="/assets/images/blog-cm-11-decision-flowchart.drawio.png" alt="Decision Flowchart: Chọn Composition Nào?" /></p>

<hr />

<h2 id="7-những-gì-sẽ-thay-đổi-2026-2027">7. Những Gì Sẽ Thay Đổi (2026-2027)</h2>

<h3 id="trends-đang-định-hình-landscape">Trends đang định hình landscape</h3>

<ol>
  <li>
    <p><strong>Memory as infrastructure, not feature.</strong> Giống như database đã trở thành infrastructure layer, AI memory đang trải qua quá trình tương tự. 2026 là năm memory chuyển từ experimental sang essential.</p>
  </li>
  <li>
    <p><strong>Convergence of memory types.</strong> Production systems đang kết hợp nhiều loại memory thay vì chọn một: vector + graph + temporal + observational. Ranh giới giữa các tools đang mờ dần.</p>
  </li>
  <li>
    <p><strong>Self-baking sẽ trở thành standard.</strong> Khi paper <a href="https://arxiv.org/abs/2510.26493">Context Engineering 2.0</a> lan rộng, việc agent tự “tiêu hóa” context thô thành knowledge có cấu trúc sẽ trở thành practice tiêu chuẩn — tương tự cách RAG đã trở thành standard sau 2023.</p>
  </li>
  <li>
    <p><strong>Context is the new data engineering.</strong> Như Andrej Karpathy đã nói, context engineering không phải prompt engineering — đó là software architecture cho intelligence. Các team sẽ cần “context engineer” như họ cần data engineer.</p>
  </li>
  <li>
    <p><strong>MCP sẽ chuẩn hóa sharing layer.</strong> Với việc OpenAI, Google DeepMind cùng adopt MCP, đây sẽ trở thành protocol chuẩn cho agent-to-tool và agent-to-agent communication — bao gồm cả memory sharing.</p>
  </li>
</ol>

<p><img src="/assets/images/blog-cm-12-trends-timeline.drawio.png" alt="Context Management: Evolution Timeline" /></p>

<hr />

<h2 id="kết-luận">Kết luận</h2>

<p>Quay lại câu hỏi ban đầu: <strong>một kiến trúc context management hoàn chỉnh gồm những gì?</strong></p>

<p><strong>4 components:</strong></p>
<ol>
  <li><strong>Collector</strong> — Thu thập context từ mọi nguồn, normalize thành format thống nhất</li>
  <li><strong>Manager</strong> — Lưu trữ 3-tier (working/session/long-term), compression, self-baking</li>
  <li><strong>Selector</strong> — Scoring, ranking, token budgeting, KV-cache optimization</li>
  <li><strong>Sharer</strong> — Cross-agent sharing (MCP), export/import, adaptation loop</li>
</ol>

<p><strong>3 pipelines:</strong></p>
<ol>
  <li><strong>Compression Pipeline</strong> — NL summary + token-level + schema extraction + vector</li>
  <li><strong>Self-baking Pipeline</strong> — Raw → Summarized → Structured → Abstract (with backlinks)</li>
  <li><strong>Adaptation Pipeline</strong> — Track quality → adjust weights → improve over time</li>
</ol>

<p><strong>60% dùng tools có sẵn, 40% cần xây mới.</strong> Phần cần xây — Selector, Self-baking, Adaptation — chính là phần tạo nên sự khác biệt. Đó là lý do chưa có giải pháp “all-in-one”: vì phần khó nhất chưa ai giải quyết.</p>

<p>Memory management trả lời <em>“nhớ gì và quên gì”</em>. Context management trả lời <em>“nhớ gì, quên gì, VÀ đưa gì vào prompt lúc này, sắp xếp thế nào, nén ra sao, chia sẻ với ai, và điều chỉnh thế nào dựa trên kết quả”</em>.</p>

<p>Memory là bộ nhớ. Context management là bộ não.</p>

<hr />

<h2 id="sources">Sources</h2>

<h3 id="research-papers">Research Papers</h3>
<ul>
  <li><a href="https://arxiv.org/abs/2510.26493">Context Engineering 2.0 (arXiv:2510.26493)</a> — Formal framework for context engineering</li>
  <li><a href="https://arxiv.org/abs/2310.08560">MemGPT (arXiv:2310.08560)</a> — OS-inspired memory management (ICLR 2024)</li>
  <li><a href="https://arxiv.org/abs/2504.19413">Mem0 (arXiv:2504.19413)</a> — Production-ready memory layer (ECAI 2025)</li>
  <li><a href="https://arxiv.org/abs/2510.04618">Agentic Context Engineering / ACE (arXiv:2510.04618)</a> — Evolving playbooks (ICLR 2026)</li>
  <li><a href="https://arxiv.org/abs/2504.07952">Dynamic Cheatsheet (arXiv:2504.07952)</a> — Adaptive memory for test-time learning</li>
</ul>

<h3 id="products--tools">Products &amp; Tools</h3>
<ul>
  <li><a href="https://mem0.ai">Mem0</a> — Memory-as-a-Service (<a href="https://github.com/mem0ai/mem0">GitHub</a>, ~44K stars)</li>
  <li><a href="https://letta.com">Letta</a> — Stateful agent framework (<a href="https://github.com/letta-ai/letta">GitHub</a>, ~21K stars)</li>
  <li><a href="https://getzep.com">Zep</a> — Temporal knowledge graph memory</li>
  <li><a href="https://supermemory.ai">Supermemory</a> — Universal memory API (<a href="https://github.com/supermemoryai/supermemory">GitHub</a>, ~13.5K stars)</li>
  <li><a href="https://langchain-ai.github.io/langmem/">LangMem</a> — Memory library for LangGraph</li>
  <li><a href="https://cognee.ai">Cognee</a> — Knowledge graph memory</li>
  <li><a href="https://llmlingua.com">LLMLingua</a> — Prompt compression (Microsoft)</li>
  <li><a href="https://mastra.ai/docs/memory/observational-memory">Mastra OM</a> — Observational Memory (SOTA on LongMemEval)</li>
  <li><a href="https://google.github.io/adk-docs/">Google ADK</a> — Agent Development Kit with context compaction</li>
  <li><a href="https://modelcontextprotocol.io">MCP</a> — Model Context Protocol (Anthropic → Linux Foundation)</li>
</ul>

<h3 id="industry-insights">Industry Insights</h3>
<ul>
  <li><a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic: Effective Context Engineering for AI Agents</a></li>
  <li><a href="https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus">Manus: Context Engineering Lessons</a></li>
  <li><a href="https://developers.googleblog.com/architecting-efficient-context-aware-multi-agent-framework-for-production/">Google: Context-Aware Multi-Agent Framework for Production</a></li>
  <li><a href="https://www.letta.com/blog/benchmarking-ai-agent-memory">Letta: Benchmarking AI Agent Memory</a></li>
  <li><a href="https://venturebeat.com/data/observational-memory-cuts-ai-agent-costs-10x-and-outscores-rag-on-long">VentureBeat: Observational Memory Cuts Agent Costs 10x</a></li>
  <li><a href="https://thenewstack.io/memory-for-ai-agents-a-new-paradigm-of-context-engineering/">The New Stack: Memory for AI Agents — A New Paradigm of Context Engineering</a></li>
  <li><a href="https://www.graphlit.com/blog/survey-of-ai-agent-memory-frameworks">Graphlit: Survey of AI Agent Memory Frameworks</a></li>
</ul>

<hr />

<p><em>Nếu bài viết có ích, kết nối với mình trên <a href="https://www.linkedin.com/in/hieu-tran-data/">LinkedIn</a> hoặc xem thêm các project tại <a href="https://github.com/hieutrtr/">GitHub</a>.</em></p>]]></content><author><name>Engineering &amp; AI the Right Way</name><email>hieutrantrung.it@gmail.com</email></author><summary type="html"><![CDATA[Context management không phải memory management. Bài viết phân tích landscape 2026, đề xuất kiến trúc 4 components + 3 tiers + 3 pipelines, và chỉ rõ 60% dùng tool có sẵn, 40% cần xây mới.]]></summary></entry></feed>