proomt

Search

Search posts, papers, and topics

All posts

SitePoint16 min readtutorialintermediate

Build a Typed Context Compaction Gate for AI Agents

Summary

A step‑by‑step tutorial showing how to build a typed context‑compaction gate for AI agents in TypeScript using LangChain and Zod. It defines a discriminated‑union schema for keep/summarize/discard actions, implements a fast gpt‑4o‑mini classifier, validates decisions at runtime, and wires the gate as middleware in an agent loop, with testing and production‑grade tuning advice.

  • Use a Zod discriminated‑union to enforce a strict decision schema (keep, summarize, discard) for each tool output.
  • Run a cheap gpt‑4o‑mini classifier with structured output to decide the compaction action before the main LLM sees the data.
  • Validate classifier responses with `safeParse` and fall back to “keep” on malformed output to avoid accidental data loss.
  • Sample large tool outputs (head/tail) to keep classifier cost low while preserving critical information.

Long‑running AI agents that call many external tools quickly blow past token limits (800‑2,000 tokens per call). Naïve truncation discards crucial tail data; blanket summarization adds extra LLM calls. A typed compaction gate lets a cheap classifier prune or compress tool outputs before they hit th…

6/10

Related reading

  1. Building Deterministic Multi-Agent State Machines in TypeScript

    The article shows how to build a deterministic, checkpoint‑backed finite state machine engine in TypeScript for orchestrating multi‑agent AI workflows. It uses Zod for schema validation, better‑sqlite3 for atomic persistence, and a pure transition function to make workflows traceable and recoverable in serverless environments.

    SitePointsitepoint.com18 min
  2. Building Composite Model Context Protocol (MCP) Gateways in TypeScript

    Step‑by‑step tutorial showing how to build a stateless composite Model Context Protocol (MCP) gateway in TypeScript using Hono, Zod, and the MCP SDK. It covers config‑driven upstream registration, namespaced tool discovery, JSON‑RPC routing, per‑tool auth middleware, and a token‑bucket rate limiter, with concrete code snippets and design trade‑offs.

    SitePointsitepoint.com16 min
  3. Eliminating AI Code Hallucinations with TypeScript Compiler Diagnostics and TDD Loops

    The article shows how to replace raw TypeScript compiler output with a programmatic JSON feedback loop that merges diagnostics and Vitest test failures, feeding the structured data back to an LLM coding agent for self‑correction. It provides concrete code for extracting, enriching, validating, and de‑duplicating errors, and demonstrates token savings and deterministic iteration until compilation…

    SitePointsitepoint.com15 min