Intelligence is not a commodity. Stop treating it like a flat REST API and start decoupling your cognitive compute.

Published: 2026-03-10

URL: https://theagenticstack.substack.com/p/semantic-caching-and-dynamic-routing


Most multi-agent architectures look brilliant on a whiteboard and disastrous on a balance sheet. The standard approach to building agentic swarms today is fundamentally brute-force: developers route every single node in a Directed Acyclic Graph (DAG) through a frontier model like GPT-4o or Claude 3.5 Sonnet.

When your system scales from a proof-of-concept to thousands of concurrent asynchronous workflows, this architecture collapses under its own unit economics. You do not need a trillion-parameter model to convert an XML payload to JSON, nor do you need frontier intelligence to answer a question that was asked by a different user five minutes ago. Thanks for reading! Subscribe for free to receive new posts and support my work. To build financially viable enterprise AI, intelligence must be treated as a tiered compute resource.

This document outlines the architecture for an Intelligent Routing Gateway, detailing the implementation of Semantic Caching, Cognitive Routing, and Agentic Circuit Breakers.

  1. The Cognitive Load Fallacy

The core architectural flaw in modern AI systems is the assumption that all tasks require equal “cognitive” overhead. In a standard multi-agent procurement workflow, the DAG might look like this: Extraction Agent: Parses a 50-page vendor PDF to find the pricing table. Formatting Agent: Converts the extracted table into a strict JSON schema. Reasoning Agent: Compares the JSON pricing against historical company spending to recommend approval or rejection. If you use a frontier model for all three steps, you are burning capital.

Step 1 and Step 2 are deterministic, low-cognitive tasks. Step 3 is the only node that requires high-level reasoning and a massive parameter count. We must decouple the orchestration of the swarm from the compute engine executing each node.

The Orchestrator should not talk directly to an LLM provider; it must talk to an internal Routing Gateway.

  1. Layer 1: The Semantic Cache ($O(1)$ Intelligence)

The fastest and cheapest LLM call is the one you never make. Traditional caching systems (like Memcached or standard Redis) rely on exact string matching (GET "user_query"). This is useless for natural language. “What is your refund policy?” and “How do I get my money back?” are identical intents but entirely different strings.

A traditional cache will register a miss, forcing a full, expensive LLM execution. To solve this, we implement a Semantic Cache. Instead of caching the raw string, we cache the Vector Embedding of the query.

When a new request enters the routing gateway, we generate a fast, cheap embedding (using a local model like all-MiniLM-L6-v2) and perform a cosine similarity search against previous queries. If the similarity score breaches a strict confidence threshold (e.g., $\ge 0.95$), we return the cached response instantly. Implementation Architecture (Python): Python import numpy as np from sentence_transformers import SentenceTransformer from redis.commands.search.query import Query import redis class SemanticCache: def init(self, threshold=0.95):

Use a blazing fast, local embedding model (runs on CPU)

self.encoder = SentenceTransformer('all-MiniLM-L6-v2') self.redisclient = redis.Redis(host='localhost', port=6379) self.threshold = threshold def getcachedresponse(self, userprompt: str) -> str | None:

1. Convert prompt to vector (Latencies < 20ms)

queryvector = self.encoder.encode(userprompt).astype(np.float32).tobytes()

2. Perform K-Nearest Neighbors (KNN) search in Redis

Assume an index 'idx:prompts' exists with a vector field 'embedding'

q = Query("*=>[KNN 1 @embedding $vec AS score]").returnfields("response", "score").dialect(2) res = self.redisclient.ft("idx:prompts").search(q, queryparams={"vec": queryvector}) if not res.docs: return None

3. Calculate deterministic similarity

Redis returns distance; we convert to similarity

similarity = 1.0 - float(res.docs[0].score) if similarity >= self.threshold: return res.docs[0].response # Cache Hit: $0.00 cost, ~30ms latency return None # Cache Miss: Proceed to LLM routing By placing this semantic cache in front of your read-heavy agents (like documentation retrieval or policy FAQs), you can reduce frontier model API costs by up to 40% while dropping response times from seconds to milliseconds.

  1. Layer 2: Dynamic Cognitive Routing

If the Semantic Cache registers a miss, the request must be routed to a model. But which one? A hardcoded architecture sends everything to Claude 3.5 Sonnet. A FinOps-aware architecture inspects the payload and routes it dynamically based on the required cognitive load. We can categorize tasks into two tiers: Tier 1 (Commodity Compute): GPT-4o-mini, Claude 3 Haiku, or self-hosted Llama 3 8B. Perfect for text summarization, JSON formatting, data extraction, and basic classification. Tier 2 (Reasoning Compute): GPT-4o, Claude 3.5 Sonnet.

Reserved strictly for complex logic, multi-step planning, and generating code. To implement this, the Routing Gateway uses a Classifier Engine. The most reliable way to classify intent without adding massive latency is to use a Tier 1 model to act as the router.

It evaluates the prompt and returns a deterministic routing enum. Python from enum import Enum import openai class TargetModel(Enum): TIER1CHEAP = "gpt-4o-mini" TIER2EXPENSIVE = "gpt-4o" class RoutingGateway: def init(self, semanticcache: SemanticCache): self.cache = semanticcache self.client = openai.Client() def classifycomplexity(self, prompt: str) -> TargetModel: """Uses a cheap, fast model to route the actual request.""" routing_prompt = f""" Analyze the following task. If it requires basic extraction, formatting, or summarization, output 'CHEAP'.

If it requires complex reasoning, math, coding, or multi-step logic, output 'EXPENSIVE'. Task: {prompt} """

This routing call costs fractions of a cent and takes ~100ms

response = self.client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": routingprompt}], maxtokens=10, temperature=0.0 ) decision = response.choices[0].message.content.strip() return TargetModel.TIER2EXPENSIVE if "EXPENSIVE" in decision else TargetModel.TIER1CHEAP def execute(self, prompt: str):

Step 1: Check $O(1) Cache

cachedresult = self.cache.getcachedresponse(prompt) if cachedresult: return {"source": "cache", "data": cached_result}

Step 2: Dynamically Route

targetmodel = self.classify_complexity(prompt)

Step 3: Execute on Target Model

result = self.client.chat.completions.create( model=target_model.value, messages=[{"role": "user", "content": prompt}] )

Asynchronously update cache for future hits (omitted for brevity)

return {"source": target_model.value, "data": result.choices[0].message.content} This pattern—spending $\$0.0001$ on a router to prevent spending $\$0.05$ on a basic extraction task—compounds massively across millions of agentic executions.

  1. Layer 3: Agentic Circuit Breakers (Preventing the Infinite Loop)

The final layer of AI FinOps is disaster prevention. When you deploy autonomous agents using frameworks like LangChain, AutoGen, or CrewAI, they frequently utilize a ReAct (Reasoning + Acting) loop. The agent thinks, executes a tool, observes the result, and repeats until the goal is met. If a tool fails (e.g., an API goes down), an unconstrained agent will enter a psychotic loop: Thought: The API failed. I should try again. Action: Call API. Observation: Error 500. Thought: The API failed. I should try again.

Because the agent passes the entire conversation history back to the LLM on every iteration, the context window grows exponentially. An agent stuck in a loop for 5 minutes can silently burn hundreds of dollars in API credits. Your architecture must include Agentic Circuit Breakers.

At the Orchestrator level, you must implement strict deterministic limits for every specific traceid (the unique identifier for a workflow execution): Max Step Count: Hardcode a limit (e.g., 5 iterations). If the agent does not reach a FINISH state in 5 steps, the Orchestrator forcibly terminates the DAG and routes the state to a Dead Letter Queue for a human operator. Token Budgets: Attach a maximum token budget to the traceid.

The Routing Gateway tracks cumulative token usage in Redis. If the workflow exceeds 50,000 tokens, the Gateway rejects the next API call with an HTTP 402 Payment Required internal error, snapping the agent out of its loop. Conclusion: Compute is not a Commodity We are currently in the “mainframe” era of Generative AI. Compute is expensive, slow, and heavily centralized. If you treat a frontier LLM as a standard REST API that you can just hammer with requests indefinitely, your infrastructure will fail.

Not because it cannot scale technically, but because it cannot scale financially. Enterprise architects must stop treating AI as a black box and start treating it as a tiered memory and compute hierarchy. Implement semantic caching. Build dynamic routing gateways. Enforce hard circuit breakers. Intelligence is a resource. Architect your systems to conserve it. Thanks for reading! Subscribe for free to receive new posts and support my work.