Last December, for this same advent calendar, I built a conversational expense assistant. You'd message a Telegram bot "Spent 250 on lunch" or "What did I spend last month?", and it would save the expense or answer the question. It worked. But every single message went to Claude 3.5 Sonnet on AWS Bedrock first, just to decide which of the two you meant.
Looking back, it was a pricey assistant. An expense assistant gets two kinds of messages: recording a payment or asking about past spending. To act on either, it needs three answers:
- What you want to do.
- Which category the expense belongs to.
- When the expense was made.
Each answer is one word picked from a pre-determined list, and I was paying a large model, per token, to pick the right option each time.
So this year I rebuilt that selection flow using the decision model Laya. A small model that doesn't generate text answers first, and an LLM is called only when that model isn't sure. The routing runs as an Elastic workflow in Kibana, Elasticsearch stores and answers, and the whole thing runs on your laptop with one command.
The full code is available here.
What changed from last year:
| Last year | This year | |
|---|---|---|
| Deciding what a message means | Claude 3.5 Sonnet, for every message | A small decision model (Laya) first, Claude Haiku 5.5 only when it's unsure |
| Running the steps | n8n | An Elastic workflow, inside Kibana |
| Answering spending questions | An agent picking ES|QL tools in Agent Builder | A fixed ES|QL template, no model |
| Setup | Colab notebook, Cloudflare Tunnel, AWS credentials | ./start.sh on your laptop |
I gave up a few things to get there. There's no Telegram bot or voice notes this time, and a fixed template answers fewer kinds of questions than an agent can.
By the end, you'll have:
- a chat page where you can record expenses and ask about them,
- a workflow in Kibana that shows, for every message, which model decided and why,
- a small test that compares the router with three LLMs on 200 labeled messages.
Limitations
There's one catch, and I'll say it up front: on my laptop, the small model was rarely enough to save money against a small LLM. It does save a lot against a large one. The test section has the numbers for both.
The idea also builds on the Let the big model think, let the small model work article on Elasticsearch Labs, which splits the work between two LLMs.
How the pieces connect
Follow the numbers in the diagram to trace one message from start to finish. The architecture contains five components:
- Chat page and app. A small web page hosted locally at http://localhost:8080. For each message, the app starts the workflow and reads the result from Elasticsearch.
- The workflow. Elastic Workflows lets you write automation as YAML steps that Kibana runs one after another: HTTP calls, Elasticsearch queries and AI prompts encapsulated using conditional logic. The whole router is one workflow called
finance-router. Steps make their decisions with Liquid templates. - Laya. Laya is an open-source decision model. It picks one option per question and gives a probability for each option. Unlike an LLM, it doesn't generate text. It runs in its own container.
- Claude Haiku 5.5. A small LLM, called only when Laya is unsure. The workflow reaches it through an inference endpoint, which puts an external model behind an Elasticsearch API. It's an OpenAI-compatible inference endpoint, not the Elastic Inference Service, pointed at OpenRouter, a service that serves many LLMs behind one API key.
- Elasticsearch. Stores the expenses, answers spending questions with ES|QL (Elasticsearch Query Language), and logs every decision in a
router-logindex.
The rest of the post walks through them in that order.
Three questions for every message
This is everything the assistant needs to know about a message:
| Question | Options |
|---|---|
| intent | save a purchase, look up spending, something else |
| category | coffee, groceries, dining, transport, travel, housing, shopping, entertainment, health, all |
| period | today, this week, last week, this month, last month, this year, all time, not applicable |
None of them needs a sentence written. An LLM can answer them, but you pay per token, you wait for generation, and then you parse what it wrote back into one of your options.
So the router has two tiers. Tier one picks an answer for each question and gives a probability. If every probability is high enough, the workflow acts on those answers. If not, it asks the LLM.
Tier one: Laya answers first (and fast)
You might have heard of Jev. It's a hosted decision model: you send it text and a few typed questions with applicable options, and it sends back answers with probabilities.
Laya is an open-source model built for the same job. Its server, laya-serve, accepts the same POST /v1/systemone requests as Jev, so a client written for Jev works by changing the base URL. And because it's open, it runs in a container alongside Elasticsearch, with no API key.
Laya is built on the ModernBERT-large encoder. An encoder is a model that reads text and scores it. You send it the message and a set of choice questions, with a few words describing each option. It returns a choice and a probability for every option.
This is what the workflow's first step, laya (an http step), sends, cut down to one of the three questions:
POST /v1/systemone
{
"model": "english",
"state": "how much did I spend on coffee last month?",
"questions": {
"intent": {
"type": "choice",
"instructions": "What does the user want to do with this message?",
"criteria": {
"index": "save this purchase to my expenses",
"search": "look up my past spending",
"other": "something else: greeting, help, reminder, budget or general question"
}
}
}
}
And this is the answer:
intent search 0.7349 (index 0.2007, other 0.0644)
category coffee 0.9395
period last_month 0.9869
usage input_tokens 277, output_tokens 0
Look at the last line. Laya read 277 tokens and wrote none. There's no generated text to parse: each answer is already one of your options, with a probability the gate can check.
In this stack it runs as a CPU container (laya-serve), so you pay for a machine by the hour, not per token. In my test, one container handled about 4,500 decisions an hour, and each one took 0.8 s at the median (1.3 s on an earlier run, so treat Laya's speed as a range), against about 2.0 s for every LLM I tried. A message Laya passes on waits for both models, about 2.8 s in total.
Tier two: when Laya isn't sure
The first step in the workflow, laya, is a plain http step that posts the request above to laya-serve. The next step, laya_gate, decides whether to trust the answers.
The gate is written in Liquid. Liquid is a template language that Elastic Workflows uses for any code inside {{ }} or {% %}. Typical operations include reading a previous step's output, comparing values, and building strings. Our workflow reads Laya's probabilities and returns laya only when every probability the message needs is at or above the threshold, the min_probability input (0.7 by default), and llm otherwise. A switch step then sends the message one way or the other.
This is the whole workflow, top to bottom. Steps marked ... are cut down, but the gate is shown in full:
name: Finance router (Laya first, LLM fallback)
triggers:
- type: manual
inputs:
- name: text
- name: min_probability # the threshold, 0.7 by default
steps:
# Tier one: ask Laya
- name: laya
type: http
with:
url: "{{ consts.layaUrl }}" # laya-serve, POST /v1/systemone
method: POST
body:
model: english
state: "{{ inputs.text }}"
questions:
... # intent, category and period
# The gate: trust Laya, or ask the LLM?
- name: laya_gate
type: data.set
with:
laya_route: |-
{%- assign a = steps.laya.output.data.answers -%}
{%- assign p_intent = a.intent.probabilities[a.intent.choice] -%}
{%- assign p_category = a.category.probabilities[a.category.choice] -%}
{%- assign p_period = a.period.probabilities[a.period.choice] -%}
{%- assign ok = true -%}
{%- if p_intent < inputs.min_probability -%}{%- assign ok = false -%}{%- endif -%}
{%- if a.intent.choice != "other" and p_category < inputs.min_probability -%}{%- assign ok = false -%}{%- endif -%}
{%- if a.intent.choice == "search" and p_period < inputs.min_probability -%}{%- assign ok = false -%}{%- endif -%}
{%- if ok -%}laya{%- else -%}llm{%- endif -%}
- name: decide
type: switch
expression: "{{ variables.laya_route }}"
cases:
- match: laya
steps:
- name: use_laya # take Laya's three labels as they are
type: data.set
with:
intent: "{{ steps.laya.output.data.answers.intent.choice }}"
... # category and period the same way
decided_by: laya
default:
# Tier two: only for messages Laya is unsure about
- name: llm_classify
type: ai.prompt
connector-id: "{{ consts.fallbackLlm }}" # Claude Haiku 5.5
with:
prompt: ... # asks for the three labels as plain JSON
temperature: 0
... # pull the JSON out of the reply and parse it
- name: use_llm
type: data.set
with:
... # intent, category, period from the JSON
decided_by: llm
# Only known labels go further, whichever tier decided
- name: check_labels
type: data.set
with:
labels_ok: ... # "yes" if intent, category and period are all known options
# Act on the intent
- name: act
type: switch
expression: "{%- if variables.labels_ok == 'yes' -%}{{ variables.intent }}{%- else -%}invalid{%- endif -%}"
cases:
- match: index
steps:
... # data.regexExtract x4: currency sign, cents, "for 9.40", any number
- name: amount # data.set: the first of them that matched
- name: merchant # ai.prompt: one short LLM call
- name: merchant_name # "none" or a failed call becomes "unknown"
- name: save_expense
type: elasticsearch.index
with:
index: expenses
refresh: wait_for
document:
"@timestamp": "{{ now | date: '%s%L' }}"
amount: "${{ variables.amount | remove: ',' | plus: 0 }}"
currency: USD
merchant: "{{ variables.merchant_name }}"
category: "{{ variables.category }}"
description: "{{ inputs.text }}"
source: router
...
- match: search
steps:
- name: build_query # Liquid fills a fixed ES|QL template
- name: run_query # elasticsearch.esql.query
...
default:
- name: other_answer # "I can record an expense or answer questions..."
# Log every decision
- name: log
type: elasticsearch.index
with:
index: router-log
refresh: wait_for
document:
"@timestamp": "{{ now | date: '%s%L' }}"
text: "{{ inputs.text }}"
intent: "{{ variables.intent }}"
category: "{{ variables.category }}"
period: "{{ variables.period }}"
decided_by: "{{ variables.decided_by }}"
labels_ok: "{{ variables.labels_ok }}"
answer: "{{ variables.answer }}"
workflow_execution_id: "{{ execution.id }}" # the app finds the result by this ID
The complete workflow, with every step, is available at tools/workflows/finance-router.yaml. It's a template: the setup container fills in the questions, the endpoints and the threshold, then loads it into Kibana.
The gate only checks the answers a message needs. The period matters only for a spending question, and the category doesn't matter for "something else". Without that, a purchase would go to the LLM just because Laya wasn't sure about a time period the purchase never uses.
Two messages from the running stack, with the default threshold of 0.7:
- "how much did I spend on coffee last month?" passes. Laya gives search 0.73, coffee 0.94 and last month 0.99, so no LLM is called.
- "I paid $1,000 for coffee at Starbucks" doesn't. Laya gets the category right (coffee, 0.87) but is only 0.43 sure it's a purchase. So the workflow asks Claude Haiku 5.5, which reads 469 tokens and writes 29.
The fallback is an ai.prompt step pointed at an Elasticsearch inference endpoint. I used an OpenAI-compatible inference service with its URL set to OpenRouter. That way, any model on OpenRouter can be the fallback without code changes, and the test script calls Sonnet, Haiku and Llama through the same kind of endpoint the workflow uses.
Acting on the answer
Whichever tier decided, the workflow now has three labels. A check_labels step first makes sure each one is a known option, because an LLM can answer with anything, and a label outside the lists gets the "something else" reply. A second switch, on the intent, does the work:
- Save a purchase. Regexes pull out the amount, most specific match first ("bought 2 lattes for 9.40" saves 9.40, not 2), a short
ai.promptcall gets the merchant name, and anelasticsearch.indexstep writes the expense. If there's no amount, nothing is saved and the assistant asks for one. - Look up spending. Liquid fills the category and period into a fixed ES|QL template, and an
elasticsearch.esql.querystep runs it. - Something else. A polite "I can record an expense or answer questions about your spending."
The merchant name is the one place a purchase always calls an LLM. Laya can pick from a list, but it can't copy text out of a message, and merchant names aren't a list.
For the coffee question, the template produces this query:
FROM expenses
| WHERE @timestamp >= DATE_TRUNC(1 month, NOW()) - 1 month AND @timestamp < DATE_TRUNC(1 month, NOW())
| WHERE category == "coffee"
| STATS total = ROUND(SUM(amount), 2), payments = COUNT(*)
The answer is filled in from the result: "You spent 101.02 USD on coffee (last month), 17 payments." No model wrote the query or the answer. That's on purpose: a fixed template can only produce queries you've already read. And because check_labels only lets known categories and periods through, that holds even when the LLM decided.
The last step logs every message to router-log, with decided_by: laya or decided_by: llm. That's how you check in Kibana how much of your traffic each tier actually handles.
A quick test on my laptop
I tested this assistant using a run of 200 messages on my laptop. Note that this is not a benchmark. The 87 purchases, 82 spending questions and 31 other messages are all generated manually. Thirty of them are reworded versions of another message, to check whether a classifier changes its answer when only the wording changes.
It checks only the three labels, not the full workflow, so saving and querying are excluded from the test. And the router rows aren't a separate run: for each threshold, I took Laya's answer where it was sure enough and Haiku's answer where it wasn't, and a message passed on to Haiku counts both models' time.
"All correct" means intent, category and period were all right. Costs are per 1M decisions at OpenRouter list prices on 20th November 2026. For Laya, it's the machine's cost, $0.10 an hour, spread over the roughly 4,500 decisions an hour measured. That assumes the machine is busy all month; with less traffic, the same machine costs more per decision. The router rows add the LLM's cost for the messages Laya passed on. Treat all of it as a rough check, and test with your own messages before you trust any of it.
| Classifier | All correct | Changed answer on a reworded message | Cost per 1M decisions |
|---|---|---|---|
| Claude Sonnet 4.6 | 99.0% | 0% | $1,401 |
| Claude Haiku 5.5 | 98.0% | 0% | $60 |
| Llama 3.1 8B | 37.0% | 23% | $8 |
| Laya alone, CPU | 55.0% | 37% | $22, if the machine is busy all month |
| Router, threshold 0.7 | 97.5% | 3% | $78 |
| Router, threshold 0.5 | 86.5% | 7% | $63 |
That's the Benchmark tab of the chat page in the repo, not an Elastic feature: it charts the test results, and it switches to your own numbers once you run the test.
What the numbers suggest:
- Moving off a large model is the biggest saving. Haiku 5.5 alone is within one point of Sonnet 4.6 at about 1/23 of the cost. The router at 0.7 is about 18 times cheaper than Sonnet.
- Against a cheap small LLM, Laya on CPU doesn't pay. Laya's probabilities are low. At 0.7, the router still sends 94% of messages to the LLM, so you pay for Laya and Haiku on almost everything: $78 against $60 for Haiku alone. It's slower too: about 2.8 s against 2.0 s. At 0.5 it sends 67.5% and costs $63, but accuracy drops to 86.5%.
- Laya's cost is mostly fixed. One container at $0.10 an hour costs about $73 a month, whether it sees ten messages or the three million or so it can handle. Sonnet costs about $0.0014 per decision, so $73 buys roughly 52,000 Sonnet decisions ($73 ÷ $0.0014). Below that, the machine costs more than just asking Sonnet, even if Laya answered every message on its own, which it didn't. Against Haiku, the same math gives about 1.2 million.
How I described each option mattered more than I expected
The first Laya run was much worse. I had described the "other" option as "neither records an expense nor asks about spending". An encoder matches words, and that description has both "expense" and "spending" in it. In a 36-message sample, 35 purchases went to "other".
Rewriting every option as a short, positive phrase in the user's voice ("save this purchase to my expenses") lifted intent accuracy from 42% to 75% on a 24-message check. I stopped tuning there, so I wouldn't fit the labels to my own test messages.
The same wording then broke Llama 3.1 8B. It started answering with the descriptions instead of the option names, and a router can't use "save this purchase to my expenses" as a label. That's most of its 37%. So label wording is a setting per model, not a constant.
When not to use this
Honestly, for a lot of setups you shouldn't build this.
- You're already on a small LLM. If Haiku-class classification is affordable for you, a CPU encoder in front of it adds cost and one more thing to run. That's what my numbers show.
- Your volume is low. The encoder's machine costs about $73 a month even at ten messages. That's what about 52,000 Sonnet decisions cost, so below that, just ask the LLM.
- You need text out of the message, not a choice. Merchant names, dates, free-form notes: an encoder can't copy them out, so you'll call an LLM anyway.
It earns its place when you send a lot of simple classification to a large model, or when you can run the encoder on hardware you're already paying for.
What would change the numbers
These results come from Laya on the CPU inside Docker, which is the worst case for an encoder. It isn't steady either: on the same laptop, Laya took 1.3 s per decision on one run and 0.8 s on another. A GPU would raise throughput and cut the fixed cost per decision. A separate threshold per question would help too. Category and period were between 0.87 and 0.99 in both examples above, so they could stay on tier one while only intent escalates.
The pattern itself doesn't depend on Laya. The gate is a dozen lines of Liquid around an http step, so any classifier that returns probabilities can take Laya's place, and any model behind an inference endpoint can be the fallback.
Running Laya on a GPU with a threshold per question is my next experiment.
Try it yourself
Everything above runs locally: Elasticsearch and Kibana 9.5.6, Laya, a one-time setup container and the chat page.
Prerequisites:
- Docker with about 8 GB of memory and 5 GB of free disk
- An OpenRouter API key. A few dollars of credit is plenty, and running the full test costs well under $1. Without a key, Laya still routes and the LLM steps are skipped.
- For the first setup only, an OpenRouter management key. Setup uses it to create three presets that hold settings such as temperature 0, and OpenRouter only allows that with a management key.
bash(built in on macOS and Linux; use WSL or Git Bash on Windows)
You can pull the project locally using the following steps:
git clone https://github.com/Som23Git/two-tier-router-orchestration.git
cd two-tier-router-orchestration
./start.sh
On the first run, start.sh writes passwords and an encryption key to .env, asks for your OpenRouter API key and management key, picks free ports if 9200, 5601 or 8080 are taken, starts the stack and opens the chat page. The cluster uses the self-generated 30-day trial license, because Workflows and the AI steps need it.
Once it's up:
- Send a purchase and a spending question at http://localhost:8080. Each answer shows which tier decided, Laya's probabilities, the tokens used and an estimated cost.
- Follow the Kibana link under any answer to see every workflow step with its input and output (monitoring workflow executions).
- Lower the threshold slider and resend the Starbucks message until
decided_byflips fromllmtolaya. Then check whether the labels are still right. - Run the same test on your machine with
docker compose run --rm bench. The Benchmark tab in the chat page switches to your results. - Change the option wording in
tools/labels.py, rundocker compose up setup, and run the test again. When you're done,docker compose downstops everything and keeps your data.docker compose down -vdeletes all resources, including the trial.
Check out the README for the full walkthrough and any troubleshooting guidance.
Over to you
I'd like to hear from you:
- Have you used an encoder or another non-generative model as a first tier? Where did you set the threshold?
- Would you put this gate somewhere else, for example in front of an Agent Builder agent?
- If you run the test on a GPU or with your own labels, please post your numbers here.
Clone the repo, push the threshold slider down until Laya starts getting things wrong, and see what the gate is protecting you from. Issues and pull requests welcome.
References
Elastic Workflows
- Elastic Workflows overview
- Get started with Elastic Workflows
- Workflows cheat sheet
- Templating with Liquid in Workflows and the Liquid filters reference
- Step types used in this post:
http,switch,data.*,ai.prompt,elasticsearch.*, and the full step types reference - Manual triggers, which is how the app starts the workflow with
inputs - Monitor workflow executions
Elasticsearch
- ES|QL reference
- Inference API overview
- Create an OpenAI inference endpoint, used here as an OpenAI-compatible endpoint pointed at OpenRouter
- Manage your license in a self-managed cluster, for the 30-day trial
Models and services
- Introducing System One models and Jev and the TypeSafe models docs
- Laya model card on Hugging Face
- ModernBERT-large on Hugging Face
- OpenRouter quickstart
Related reading


