惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
The GitHub Blog
The GitHub Blog
腾讯CDC
L
LangChain Blog
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
量子位
Apple Machine Learning Research
Apple Machine Learning Research
Cloudbric
Cloudbric
B
Blog RSS Feed
B
Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Vercel News
Vercel News
S
Schneier on Security
Project Zero
Project Zero
宝玉的分享
宝玉的分享
美团技术团队
MyScale Blog
MyScale Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Spread Privacy
Spread Privacy
T
Threatpost
A
Arctic Wolf
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
爱范儿
爱范儿
Recorded Future
Recorded Future
C
CERT Recently Published Vulnerability Notes
T
Threat Research - Cisco Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
SecWiki News
SecWiki News
H
Hacker News: Front Page
AWS News Blog
AWS News Blog
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tor Project blog
C
Check Point Blog
L
Lohrmann on Cybersecurity
F
Full Disclosure
TaoSecurity Blog
TaoSecurity Blog
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
The Last Watchdog
The Last Watchdog
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyond the Agentic Loop, in TypeScript: building a shopping agent with the Orchestrator pattern
Johnny Z · 2026-06-17 · via DEV Community

This post is a TypeScript implementation of the pattern described in "Beyond the Agentic Loop: The Orchestrator Pattern for Multi-Agent Systems" by Amogh Ubale (Stackademic). The original is Python with generic agents; here we keep the idea intact and re-theme it as a shopping assistant so the three execution modes have something concrete to chew on. All the design credit goes to that article — go read it first.

The cast: a handful of shopping agents

Before the pattern, the scene. The demo is a small storefront assistant backed by a
few single-purpose agents:

  • Catalog — list the categories on offer, or search products by keyword and price.
  • Inventory — check stock and availability for a product.
  • Pricing — look up the current price and any active promotions.
  • Reviews — fetch a product's rating and review highlights.
  • Order — place an order for a product.

A customer request might need just one of these, several of them at once, or a few in a
strict order — and deciding which of those shapes a request calls for is exactly what
the orchestrator is for.

The problem: the LLM as a while loop

The default way to build a multi-agent system is the agentic loop: you hand the
model a bag of tools and let it drive.

think → call a tool → observe the result → think again → call another tool → …

The LLM is both the brain and the control flow. That's wonderfully flexible, and
it's the right tool when the task is open-ended and you genuinely don't know the
steps in advance. But in production it has three nasty properties:

  • Unpredictable shape. Every "think" step is another LLM round-trip, so a three-agent task might take 3 calls or 9 — you don't know until it runs, and latency swings with it. (The article clocks a representative three-agent query at ~7 calls through the loop; the wall-clock and spend follow, but the unpredictability is the part that actually bites.)
  • Non-determinism. The same question can take a different path each time, which makes behavior hard to reason about and hard to trust with side effects — like placing an order.
  • Poor observability. "Why did it do that?" means replaying a transcript of intermingled reasoning and tool calls. There's no single place where the plan lives.

If you already know which agents exist and what they do, an open-ended reasoning loop
on every request is more freedom than the job needs.

The pattern: decide once, execute deterministically

The orchestrator's move is to separate the decision from the execution. Instead
of letting the model loop, you make exactly two LLM calls with plain,
deterministic code in between:

query ──▶ [ROUTE: LLM #1] ──▶ [EXECUTE: agents, no LLM] ──▶ [SYNTHESIZE: LLM #2] ──▶ answer

  1. Route — one LLM call whose only job is to pick which agent(s) to run.
  2. Execute — ordinary application code runs those agents. No LLM here.
  3. Synthesize — one LLM call turns the structured results into prose.

Two calls, every time, no matter how many agents run. That fixed shape is the whole
point: a plan you can inspect before anything happens, latency that doesn't depend on
the model's mood, and independent work you can fan out. (It's cheaper too — the article
puts the same query at ~2 calls instead of ~7 — but the cost isn't the headline; the
outcomes are.)

1. The registry: agents are just functions

An agent is a name, a description (for the router), a JSON-Schema for its arguments,
and an execute function. Nothing more.

// src/server/orchestrator/types.ts
export type ExecuteFn = (args: AgentArgs, context: AgentContext) => Promise<AgentResult>;

export interface AgentDefinition {
  agent: string;        // human name, e.g. "Catalog Agent"
  description: string;  // shown to the router LLM so it can choose this tool
  parameters: Record<string, unknown>; // JSON Schema for the args
  execute: ExecuteFn;
}

The "registry" is a plain in-process object — agents are registered by hand.
There's deliberately no Redis, no database, no HTTP self-registration. That keeps the
whole thing runnable and testable with zero infrastructure.

// src/server/orchestrator/registry.ts
export const REGISTRY: Record<string, AgentDefinition> = {
  catalog_agent__list_categories: catalogCategoriesAgent,
  catalog_agent__search_products: catalogAgent,
  inventory_agent__check_stock: inventoryAgent,
  pricing_agent__get_deals: pricingAgent,
  reviews_agent__get_reviews: reviewsAgent,
  order_agent__place_order: orderAgent,
};

toolDefinitions() projects that map into the OpenAI tool format the router sees —
each agent becomes one function tool, plus one meta-tool we'll meet shortly.

2. Route: the one decision-making LLM call

The router is given a blunt system prompt: pick tools, do not answer.

// src/server/orchestrator/router.ts
const SYSTEM_PROMPT = `You are a query router. Your ONLY job is to decide which tool(s) to call.
Rules:
- If the query needs ONE agent, call that one tool.
- If the query needs MULTIPLE INDEPENDENT agents, call all of them.
- If the query needs steps IN ORDER (a later step depends on an earlier one), call plan_execution and provide the ordered steps.
Do NOT answer the user's question — just pick tools.`;

We call the model at temperature: 0 with tool_choice: "auto", then read its tool
calls back out. The shape of that tool-call list is the execution plan — we never
ask the model to "answer," only to choose:

// src/server/orchestrator/router.ts
export async function route(query: string): Promise<RouteDecision> {
  const response = await getOpenAIClient().chat.completions.create({
    model: getConfig().ROUTER_MODEL,
    temperature: 0,
    tools: toolDefinitions(),
    tool_choice: "auto",
    messages: [
      { role: "system", content: SYSTEM_PROMPT },
      { role: "user", content: query },
    ],
  });

  const toolCalls = response.choices[0]?.message.tool_calls ?? [];

  // plan_execution present -> sequential. Take its ordered steps.
  const planCall = toolCalls.find((c) => c.function.name === PLAN_EXECUTION_TOOL);
  if (planCall) {
    const parsed = safeParseArgs(planCall.function.arguments) as {
      steps?: Array<{ tool: string; args?: AgentArgs; reason?: string }>;
    };
    const steps = (parsed.steps ?? []).map((s) => ({ tool: s.tool, args: s.args ?? {}, reason: s.reason }));
    return { mode: "sequential", steps };
  }

  const steps = toolCalls.map((c) => ({ tool: c.function.name, args: safeParseArgs(c.function.arguments) }));
  return { mode: steps.length > 1 ? "parallel" : "single", steps };
}

So the router collapses to three outcomes:

  • one tool → single
  • several tools → parallel
  • the plan_execution meta-tool → sequential

3. Execute: the heart of the pattern (no LLM)

This is where parallel and sequential actually diverge — and it's pure TypeScript,
no model involved.

// src/server/orchestrator/executor.ts
export async function* executeStream(mode: Mode, steps: PlanStep[]): AsyncGenerator<ExecEvent, AgentContext> {
  const results: AgentContext = {};

  if (mode === "parallel") {
    for (const step of steps) yield { kind: "agent_start", tool: step.tool, args: step.args };
    const settled = await Promise.all(
      steps.map(async (step) => [step.tool, await runAgent(step, {})] as const),
    );
    for (const [tool, result] of settled) {
      results[tool] = result;
      yield { kind: "agent_result", tool, result };
    }
    return results;
  }

  // single + sequential: ordered; each step sees prior results as context.
  for (const step of steps) {
    yield { kind: "agent_start", tool: step.tool, args: step.args };
    const result = await runAgent(step, results);
    results[step.tool] = result;
    yield { kind: "agent_result", tool: step.tool, result };
  }
  return results;
}

Read the two branches side by side:

  • Parallel is Promise.all. The agents are independent, so they all fire at once and you pay for the slowest one, not the sum. "What's the price, rating, and stock of the iPhone 15?" becomes three lookups that have nothing to say to each other — run them together.
  • Sequential is an ordered for loop where each step receives the accumulated results as its context. That's how a later agent consumes an earlier one's output. "Find a laptop under $1000, check it's in stock, then order it" can't be parallel — the order step needs the product the search produced.

(The generator yields a small event before and after each agent. That's only so a
transport can show progress; it doesn't change the logic.)

4. plan_execution: a signal, not an agent

How does the router say "do these in order"? With a meta-tool that runs no code:

// src/server/orchestrator/registry.ts
export const PLAN_EXECUTION_TOOL = "plan_execution";
// ...its tool schema asks for { reason, steps: [{ tool, args, reason }] }

When the router selects plan_execution, the orchestrator switches to sequential
mode. The original article treats it purely as a signal and leaves the ordering and
data-passing unspecified. This repo makes one deliberate addition so the demo
actually works end-to-end: plan_execution returns the ordered steps, and the
executor threads results forward as context. The order agent then resolves the
product the search found (see resolveTargetProduct in
src/server/lib/resolve-product.ts). That's the difference between a pattern diagram
and a thing you can run.

5. Synthesize: the only creative call

Once the agents have produced structured data, a second LLM call turns it into an
answer. This is the only step with any "writing" to do, so it runs warmer and streams
its tokens out.

// src/server/orchestrator/synthesizer.ts
export async function* synthesizeStream(query: string, results: AgentContext): AsyncGenerator<string> {
  const stream = await getOpenAIClient().chat.completions.create({
    model: getConfig().SYNTH_MODEL,
    temperature: 0.7,
    stream: true,
    messages: [
      { role: "system", content: "Summarize the agent results into a clear, helpful answer." },
      { role: "user", content: `User asked: ${query}\nResults: ${JSON.stringify(results)}` },
    ],
  });
  for await (const chunk of stream) {
    const delta = chunk.choices[0]?.delta?.content;
    if (delta) yield delta;
  }
}

What this buys you

Putting the three phases together, the payoff is exactly the inverse of the loop's
pain points — and these enablements, not the price tag, are the real reason to reach
for it:

  • A plan you can trust. The decision is a single inspectable object — the RouteDecision — produced before any agent runs. You can log it, assert on it, gate it, replay it. That's what makes it safe to let an agent actually place an order.
  • Debuggability. The execute phase is deterministic, so a bug there reproduces every time instead of hiding in a different transcript on each run.
  • Parallelism for free. Independent work is a Promise.all; you didn't have to teach the model to be concurrent.
  • A testable core. Because the middle phase has no LLM in it, executeStream is an ordinary async function you can unit-test with a stub registry — no API key, no flakiness.
  • Predictable runs (the boring-but-nice one). Always two LLM calls, whether the request touches one agent or five — so latency is something you can put a number on, and the bill is lower as a side effect.

Sample queries → how they route

Query Mode Agents
what do you have? single catalog_agent__list_categories
what's the price, rating and availability of the iPhone 15? parallel pricing + reviews + inventory (at once)
find a laptop under $1000, make sure it's in stock, then order it sequential searchcheck stockorder

Same agents, same data — the router decides the shape of the run.

When the loop still wins

This isn't "orchestrator good, loop bad." The agentic loop is the right tool when the
task is genuinely exploratory: you don't know the steps ahead of time, the toolset is
open-ended, or the agent needs to re-plan mid-flight based on what it discovers. The
orchestrator trades that adaptability for predictability — and it assumes you can
enumerate your agents up front. Note too that the router here is itself a single LLM
call, so a truly novel multi-hop plan it has never seen is out of scope by design.

The article's framing is the one to keep: loop for exploration, orchestrator for
production.
If you already know your agents and you need bounded latency, parallel
execution, and debuggable runs — ask the model once, execute, synthesize. Two calls,
done.


Complete sample code

Please feel free to reach out on twitter @roamingcode