Route Small Talk to a Cheap Model, and Never Embed the Same Message Twice
An AI agent should not send "thanks" to the same frontier model, with the same long system prompt, that it uses to write a sales proposal. The fix has three parts that work together: a semantic router that sends simple conversation to a fast, cheap, non-reasoning model and keeps real work on the selected model; a single embedding service so a message's vector is computed once per turn and shared by every component that needs it; and a prompt layout that keeps stable content at the top so the provider's prompt cache actually hits.
I'm Mahmoud Zalt, an AI systems architect who has spent 16 years building production software, and these days most of that is spent on Sista AI work where the model bill is part of the architecture.
Everything below comes from building and operating Sistava, a platform where agents (AI employees) chat with real people all day. None of it is clever. All of it is the kind of cost that hides in plain sight until you trace a single turn end to end.
Where the Money Hides in a Single Turn
Trace one ordinary turn of a production agent and count the paid calls. In our case, before these fixes, a message could pay for: a routing decision, the main model call on a large system prompt, a vector search over trained documents, a vector search over conversation memory, and a later check on whether the conversation went well. Several of those needed the meaning of the same user message, and each computed it on its own.
None of this showed up as a bug. Answers were correct. The waste was structural: every new feature that needed a vector added its own embedding client, and every new piece of dynamic context was appended wherever it was convenient in the prompt. The lesson I took from it: cost is a property of the turn, not of any one component, so you have to design it at the level of the turn.
Semantic Routing: Small Talk to the Cheap Lane
The router runs once per turn, before the main model, and picks one of two lanes: chat (a cheap model) or work (the agent's selected model). It does not re-run on every step of the agent loop. The decision ladder:
- Empty message: chat, free.
- Whole message is an obvious greeting or acknowledgement: an anchored, multilingual pattern ("hi", "thanks", "merci", "salam", a thumbs up) goes to chat with no embedding at all. These are the highest frequency turns, so skipping the vector here is most of the saving, and it is safe because the pattern is anchored at both ends: "hi, can you analyze this" does not match.
- Long input: if the message or its approval context is longer than 2,000 characters, it goes to work with a zero-cost routing receipt. Never classify a truncated brief.
- Everything else: embed the complete input and pick the nearest route by meaning. Chat must score at least 0.35 cosine similarity to win; anything weaker keeps the selected model.
- Any error: work. A wrong chat ships weak output; a wrong work only costs a little more. Fail toward quality.
How the semantic router scores
Each route has a list of example utterances, embedded once per worker process at startup in one call. A query is embedded once, compared with every utterance, and each route's score is the mean of its top 3 similarities. The pattern is borrowed from the open-source semantic-router idea; we did not take the library, because it capped Python versions below ours and we needed none of its threshold tuning or vector database features for two routes. Coverage is widened by adding a phrase to a route's utterances, never a regex.
This replaced two earlier versions: a keyword regex classifier, then the regex plus a tiny LLM tie-breaker for the ambiguous middle. Semantic matching is cheaper than the tie-breaker call and handles paraphrases and other languages that word lists miss.
Bare approvals inherit the work they approve
"Yes, do it now" carries no task of its own. Its lane depends on what it approves. We learned this from an incident: a bare "yes" approving a full sales playbook routed to the cheap lane because, on its own, it looks like chat. Now an approval-shaped message triggers one indexed read of the last assistant message, and the router embeds the previous turn and the approval together, so approving heavy work escalates to the selected model. It is escalation only: reshape requests like "make it shorter" and plain greetings are not treated as approvals and keep their savings.
Turn it off when it cannot save money
If the selected model already costs the same as the cheap lane or less, routing only adds an embedding call and can at best move a turn sideways. So the router checks, live on every turn, whether the selected model is strictly pricier than the cheap lane, and steps aside if not. Change the agent's model and it re-evaluates on the next message.
Choosing the cheap model
The cheap lane has three requirements: fast, cheap, and non-reasoning. A reasoning model burns thinking tokens on "hi", which defeats the point. It also has to be strong enough to reshape a previous reply when asked; the smallest model we tested was too weak for that. We currently use a small Flash-class model with a large context window and tool support, and the assembled prompt is size-gated before the call.
Measure Net Benefit, Not Credits Saved
A router has its own cost, so "credits saved" on its own is a vanity number. Every non-greeting turn bills its one embedding call. Our embedding endpoint returns no usage, so tokens are counted locally with the provider's tokenizer against the exact request; if the tokenizer fails, we write a zero-charge audit row rather than estimate from character counts.
On the savings side, each cheap-lane call records, at route time, the measured cost difference from the model it replaced. The dashboard then reports lane split, router cost, credits saved, and net benefit on exactly the same turns. Older records without that field are excluded. Never reconstruct historical savings from today's model prices; it produces a number that looks precise and is not.
One Owner for Embeddings: Memo, Single-Flight, Redis
The second leak was embeddings. We found that up to four components embedded the same user message in the same turn, each with its own client and billing: the router, the trained-document search (with its own Redis cache that never saw the router's vector), the conversation memory search, and a follow-up classifier that runs after the turn. Each call is cheap. Together they added one to two avoidable network round trips to the prompt assembly path and duplicate charges for the same text.
The fix was to give embeddings exactly one owner, an embedding service that every caller goes through. Query lookups follow a fixed order:
- Per-turn memo. A dict held in a context variable, opened at the start of the agent turn before the work fans out, so every task spawned by the turn shares it.
- Single-flight. Concurrent callers asking for the same key await one in-flight request instead of each firing their own.
- Redis. Key
v1:embeddings:t:{tenant}:{model}:{dims}:{sha256(normalized text)}, a one-hour TTL, tenant-scoped, and fail-open, so a Redis outage costs money, not availability. - Provider. Only now is a real call made.
Billing stays with each caller's existing cost tracking, but the service reports whether usage was actually paid, and a caller records a charge only for a real provider call. A memo, single-flight or Redis hit is never billed.
Document embedding is uncached on purpose. The document store already skips re-embedding by comparing chunk hashes (an identical re-ingest makes zero embedding calls; one edited section makes one), and router utterance indexes are process singletons. Caching them again would only spend Redis memory.
| Measured with a fake provider | Before | After |
|---|---|---|
| Router, document search and memory search embedding the same text in one turn | 3 provider calls | 1 |
| A normal turn (memory search uses an enriched query, which is different text) | 3 provider calls | 2 |
| A repeat of the same text within the hour (tools, retries, resumed turns) | paid again | free |
Two lessons I would give any team. First, Redis alone does not fix this: parallel callers in the same turn miss the cache together and each pays. The per-turn memo plus single-flight is what makes the same turn free. Second, enforce the single owner with a test. We added a guard test that fails if any module other than the service constructs an embedding client or calls an embeddings API directly. Run against the old code, it reported 9 violations. A shared paid primitive needs one owner from its second caller on, not its fourth.
A Prompt Layout the Cache Can Actually Hit
The biggest single line item for most agents is the main model call, and most of its input is a long system prompt that barely changes. Every major provider caches the longest stable prefix of a prompt, top down. One changed byte invalidates the cache for everything below it. So a value's volatility decides its vertical position:
- Top, universal: bytes identical for every agent of a template: behaviour, safety, voice, the skills catalogue, the tool framework, platform docs.
- Middle, per agent: name, persona, duties, company profile, team roster, custom instructions.
- Below the conversation, dynamic: the clock, live credits, schedule values, retrieved knowledge and memory, appended as a trailing message after the last conversation message.
The trap that cost us the most time: there is no cache line inside the system message. The system message is one object at the head of the prefix. Appending a dynamic block to its bottom still puts that block above every conversation message, so changing it re-bills the rest of the system message and the whole history underneath. We measured a single changed "credits left right now" line taking a thread from 32,768 cached tokens to 0. Another time, a schedule countdown sitting above a 34.4k token skills catalogue made caching look broken. The only position that costs nothing is after the last message.
A few more rules that held up:
- Order is the lever for every provider. OpenAI caches the stable prefix automatically, with no markers. Anthropic uses explicit cache breakpoints, added at send time, still prefix based. Order for both the same way.
- An affinity key is not a cache. A cache routing key sends requests toward a cache owner; it never makes different prompt bytes share a prefix.
- Make trailing blocks deterministic. If several middlewares append dynamic blocks, their order must be fixed, and a byte-stability test should prove two identical turns produce identical prefixes.
- Verify with cached token counts from your traces, not by searching the prompt for cache markers.
The Same Idea Applies to Memory Writes
Small talk is not only cheap to answer, it is free to forget. The memory layer skips greetings and acknowledgements before they reach the extraction pipeline, while never skipping approvals. In our memory eval, extraction calls spent on small talk went from 21 per run to 0, without losing any fact-bearing turn. I wrote about that, and about scoping memory per person, in agent memory should belong to the person, not the chat. Note the two decisions stay separate: a casual "I'm vegetarian, by the way" is routed to the cheap lane for the reply and still saved to memory.
Where This Falls Short
- The router is a heuristic. Borderline reshape requests can go cheap. If a workspace wants every reply on the selected model, it should be one switch to turn routing off.
- Savings depend on traffic shape. A team that only sends long briefs has little small talk to route; a chatty team sees much more.
- Similarity floors drift when you change the embedding model or add utterances. Re-audit real decisions after either change.
- Prompt caching is the provider's policy. Retention time and discount vary by provider and model, so the layout guarantees the opportunity, not the price.
Takeaways
- Route once per turn, by meaning, and fail toward quality. Free pattern match for obvious greetings, an embedding for the rest, a conservative floor, and escalation for approvals.
- Give every paid primitive one owner. Memo, single-flight, then a tenant-scoped cache, and a guard test that keeps it that way.
- Place prompt content by volatility. Stable on top, per agent in the middle, everything dynamic after the last message.
If your agent's bill grows faster than its usage, a turn-level cost review usually finds these three in an afternoon. It is a standard part of my agent development work, and every pattern here runs in production at Sistava.
Frequently Asked Questions
What is semantic routing for LLM agents?
It decides which model handles a message by comparing the message's embedding with example utterances for each route, instead of matching keywords. It catches paraphrases and other languages, and escalates a real request even when it follows a greeting.
Is an LLM classifier better than embeddings for routing?
For two routes, not in our experience. A small LLM tie-breaker cost more than one embedding call per turn and added latency. Embedding similarity with a conservative floor and a fail-safe default was cheaper and handled more languages.
How do I stop paying for the same embedding twice?
Route every embedding through one service. Look up a per-turn memo first, then deduplicate in-flight requests, then a tenant-scoped Redis cache keyed by a hash of the normalized text, and only then call the provider. Bill only real provider calls.
Why is my prompt cache hit rate so low?
Usually because something that changes every turn, like a clock, a balance or a countdown, sits above stable content. Providers cache the longest unchanged prefix, so move dynamic values after the last conversation message.
Which model should handle small talk?
A fast, cheap, non-reasoning model that is still strong enough to rewrite a previous reply on request. Reasoning models waste thinking tokens on greetings.








