SUPERBRAIN.TALK 2026 / TECH CONF
/* the world i came from */
data ─┐
features ─┤
cnn / xgboost ─┤
F1 = 0.87 ✓
/* the world that arrived */
## SYSTEM You are a careful assistant. Reason step by step. When uncertain, ask clarifying questions... ## TOOLS - search(query) - read_file(path) - call_model(...) ## STYLE Be concise. Avoid hallucinations. Cite your sources. Refuse politely when evidence is missing. ## OUTPUT { "answer": "...", "sources": [...] }
?

Things I learned building a local-only agentic AI system.

Amar Chheda
Machine Learning Engineer
Our sponsors
Act 1 · The world I came from

The world I came from.

01 / LIFECYCLE
Train. Measure. Ship.
02 / I/O
You control the inputs. You control the outputs.
03 / PERFORMANCE
A number on a leaderboard.
04 / BEHAVIOUR
Deterministic by design.
In traditional ML You own the accuracy. The system does what the math says.
Act 1 · The world I came from

Accuracy was my responsibility.

INPUT
raw data
→
CURATE
features
→
SPECIALIST MODEL
narrow task
→
OUTPUT
label / score
▸ Fine-tuned the model for my specific task.
▸ Curated the data. Defined the metrics.
▸ Understood what it could and couldn't do.
▸ The cost of being wrong: a bad F1 score.
Act 1 · The world I came from

Then the world handed us foundation models.

01 One giant model. Billions of parameters. "General" intelligence.
02 The model decides what counts as a good answer.
03 My job changes: write instructions, not code.
04 I prompt. I pray. I evaluate... differently.
"The benchmarks say it's great — but does it work for your task?"
— THE QUESTION I COULDN'T ANSWER
"To my old-school ML brain, a markdown file full of instructions and a model expected to 'figure out the rest' was both fascinating and deeply uncomfortable. So I did what I know best: I built a system to learn how it actually works."
Act 1 → Act 2 · The paradigm shift

Classical ML and the agentic LLM paradigm are different jobs.

Dimension
Classical ML
Agentic + LLM
UNIT OF WORK
One model, one narrow task
A workflow of model calls + tools
WHAT YOU BUILD
Features, loss, architecture
Prompts, retrieval, orchestration, guardrails
WHO DECIDES "GOOD"
You — the metric is the truth
The model decides — then you verify
HOW IT FAILS
A wrong number — low F1
Confident nonsense — hallucination
HOW YOU EVALUATE
Holdout set · F1 / AUC
End-to-end behaviour in a system
WHERE ACCURACY LIVES
In the weights
In the system around the model
Same engineer. New seams. The accuracy I used to own in the weights now lives in the system I build around the model.
Act 2 · The paradigm shift

Agentic AI isn't a chatbot. It's orchestrated decision-making.

input
→
retrieve
→
llm decide
→
valid?
✓ →
execute tool
✗ →
fallback
→
observe
→
output
/* not a node. a system. */
An agent perceives inputs, decides on actions, executes them, observes results.
The model is not the product. The workflow is the product.
What surprised me most Agentic AI is more like distributed systems engineering than data science.
Act 2 · The paradigm shift

Foundation models shifted the responsibility — they didn't eliminate it.

OLD WORLD
You own accuracy at the model level.
Training data. Loss curves. Hyperparameters. F1 on a holdout set.
NEW WORLD
You own accuracy at the system level.
▸ Prompt design
▸ Retrieval quality
▸ Workflow boundaries
▸ Output validation
The model is general. The system must be specific.
Act 2 · The paradigm shift

Before we shrink it — what's actually happening inside.

1
Tokenize — text → sub-word tokens, each an integer ID
↓
2
Embed — token vector (768-d) + positional encoding
↓
3
Attention ×12 — every token looks at every other (multi-head)
↓
4
MLP — per-token feed-forward, 768 → 3072 → 768
↓
5
Logits — project to a score for all 50,257 vocab tokens
↓
6
Softmax → sample — probabilities, then temperature / top-k / top-p
/* repeat for the next token. that's the whole machine. */
► Open live in the browser
poloclub.github.io/transformer-explainer
GPT-2 small · 124M params · runs entirely in-browser on ONNX
▸ Type a prompt — watch each stage update live.
▸ Hover a token — see the attention map light up.
▸ Drag temperature — watch the next-token odds shift.
Why this matters phi3:mini and llama3.1:8b are this same machine — just trained differently and scaled down to run on my laptop.
Act 2 · The paradigm shift

How small language models actually get made.

01
DATA QUALITY, NOT SIZE
Phi-3 was trained "data-optimal" — heavily filtered web + synthetic textbook data. Microsoft even dropped trivia like sports scores to spend capacity on reasoning.
↗ Phi-3 Technical Report · arXiv:2404.14219, 2024
02
TOKENS ≫ PARAMETERS
Llama 3.1 8B saw ~15 trillion tokens. The model is small; the training set is enormous. You push data, not parameter count.
↗ Llama 3.1 model card · Meta, 2024
03
POST-TRAINING IS THE BEHAVIOUR
Instruction-following comes from SFT + DPO — preference data, reward models, rejection sampling — layered onto the base model.
↗ Phi-3 & Llama 3.1 post-training, 2024
04
QUANTIZE TO FIT THE LAPTOP
4-bit Q4_K_M GGUF shrinks 8B weights to ~5 GB with little quality loss. That's what Ollama serves by default.
↗ Ollama model library, 2024–25
The myth, corrected Distillation, pruning, and LoRA exist — but phi3:mini and llama3.1:8b weren't made that way. The real levers were better data and post-training.
Act 2 · The paradigm shift

The three models in Superbrain — three different origins.

phi3:mini
3.8B
MICROSOFT · 2024
▸ 3.3T tokens, "data-optimal" filtered web + synthetic
▸ SFT + DPO post-training, heavy safety red-teaming
▸ 69% MMLU — rivals GPT-3.5 at phone size
SUPERBRAIN ROLE
Classification — 4× faster than the 8B
arXiv:2404.14219
llama3.1:8b
8B
META · 2024
▸ ~15T tokens, dense decoder-only, 128K context
▸ ~1.46M H100 GPU-hours (405B sibling used 16K+ H100s)
▸ SFT + rejection sampling + DPO, synthetic data
SUPERBRAIN ROLE
Chunking · QA · digest (4-bit local)
Meta Llama 3.1, 2024
nomic-embed-text
137M
NOMIC AI · 2024
▸ Long-context BERT → contrastive → supervised FT
▸ 8192 context, 768-d vectors, fully open data
▸ Beats ada-002 & 3-small on MTEB and LoCo
SUPERBRAIN ROLE
Semantic embeddings for retrieval
arXiv:2402.01613
Act 2 · The paradigm shift

Generalist or specialist? It depends on your pipeline.

Generalist LLM
~70B+
+ Broad capability across domains
+ Complex reasoning, open-ended synthesis
− Expensive per call
− Non-deterministic on narrow tasks
Specialist SLM
~1–8B
+ Fast, cheap, predictable
+ Better F1 on your specific domain
+ Classification, extraction, routing
· Trained / fine-tuned for one task
Use both. Route tasks to the right model.
Act 2 · The paradigm shift

Latency is a system design constraint — not a UX afterthought.

Step
Model
Typical latency
Chunking strategy decision
llama3.1:8b · local
2–4 s
Topic classification
phi3:mini · local
0.5–1.5 s
Embedding generation
nomic-embed-text
50–200 ms
Grounded answer generation
llama3.1:8b · local
4–12 s
Design principle Put latency-sensitive steps on smaller models. Save the 8B for what only an 8B can do.
Act 3 · Why small language models?

Why I chose small, local models.

01
Privacy
Data never leaves your hardware.
No vendor, no logs, no compliance footnote.
02
Cost
No per-token API bill at scale.
Electricity is the only variable cost.
03
Forcing function
Small models force better system design.
The whole reason this talk exists.
04
Observability
You control every call, every log, every retry.
No black box. Full trace.
Act 3 · Why small language models?

What this has actually cost me.

Processed so far · 33 articles · 676 chunks · live DB
Model · job
Input
Output
phi3:mini classify
366,881
26,040
llama3.1:8b QA·digest
26,523
1,107
nomic-embed embed
257,814
—
TOTAL
651,218
27,147
678,365 tokens, counted with tiktoken straight from Postgres.
Claude Opus 5.5 · cloud $3.15
651,218 in × $4/M + 27,147 out × $20/M
Ollama, local · my laptop $0.00
electricity only · no per-token meter
↗ Claude Opus 5.5 API pricing · anthropic.com, 2026
The honest point $3.15 is nothing. But it's zero on my hardware, it stays zero as I scale, and not one token left the machine.
Act 3 · Why small language models?

NVIDIA's case: small models are the future of agentic AI.

General NLP benchmark
Llama-3 70B
82
Phi-3 mini
53
SmolLM2
48
LLMs win by a wide margin.
Berkeley function-calling leaderboard
Llama-3 70B
79
Phi-3 mini
77
SmolLM2
75
SLMs go toe-to-toe.
Agents make many sequential calls. Cost and latency compound at every step.
▸SLMs match or beat LLMs on tool-use and structured output.
▸Models cited: Phi-3, Nemotron, SmolLM2, DeepSeek, Llama 3.3.
▸Evaluate on agentic benchmarks — not general NLP.
Citation arXiv:2506.02153 · NVIDIA, 2025
Act 3 · Why small language models?

The open-weights moment.

Llama 2
7B / 13B
2023 H1
Mistral 7B
grouped-query
2023 H2
Phi-3 mini
3.8B · runs on a laptop
2024 Q1
Llama 3.1 8B
128k context
2024 Q3
Qwen2.5 / Gemma 2
strong tool use
2025 Q1
Llama 3.3 / Phi-4
competitive at 7B
2025 Q4
Before
You needed cloud APIs for anything useful.
After
An instruction-following model runs on my laptop. This is what made Superbrain possible.
Act 3 · Why small language models?

It's not SLMs versus LLMs. It's SLMs and LLMs — orchestrated.

CONDUCTOR
LLM
rare · high-level
SLM
classify
SLM
extract
SLM
route
SLM
embed
/ frequent · precise /
LLMs: complex synthesis, nuanced reasoning, one-shot creative work.
SLMs: classification, routing, structured extraction, high-volume repetition.
3×
projected adoption of task-specific models vs LLMs.
Gartner via InfoWorld, by 2027
Act 3 · Why small language models?

Small models are a forcing function for better system design.

01
Prompts must be precise.
BEFORE
"classify this article"
AFTER
role + task + schema + fallback
02
Boundaries must be explicit.
BEFORE
"figure it out"
AFTER
one decision, one schema, per step
03
Outputs must be validated.
BEFORE
parse free text. hope.
AFTER
structured JSON or fail loudly
04
Fallbacks must be engineered.
BEFORE
rely on model cleverness
AFTER
deterministic default path
Act 3 · Why small language models?

Division of labour.

SENIOR ADVISOR
LLM
TEAM
routine classify
phi3:mini
TEAM
structured extract
phi3:mini
TEAM
high-volume route
nomic-embed
The key design question
"How do I route and compose multiple model sizes?"
90%
cost reduction on high-volume repetitive tasks by switching routine work to SLMs.
InfoWorld, 2024 — "Rethinking enterprise AI architecture"
Act 4 · What I built — Superbrain

Superbrain at a glance.

☁ Cloud RAG stack — managed
Managed ingest + embeddings API
↓
Pinecone / Weaviate · managed vector DB
↓
Claude Opus 5.5 · retrieve + generate
↓
Vendor dashboard · metrics
Fast to start. Every layer is someone else's black box.
⚡ SLM · Superbrain — local only
REST API · Telegram bot · CLI · Scheduler
↓
FastAPI async · ingestion · QA · digest
↓
Ollama · llama3.1:8b · phi3:mini · nomic-embed
↓
PostgreSQL 16 · pgvector · tsvector · jsonb
Every layer is yours. Every call is logged. Zero cloud AI dependency.
The tradeoff Cloud gives you a running system in an afternoon. Local gives you ownership of every layer — and forces you to understand each one.
Act 4 · What I built — Superbrain

User flow — ingest, ask, and what gets logged.

INGEST — user drops a link, text or PDFClientTelegram · RESTCLI · URL/text/PDFJob queuedingestion_jobs rowBackgroundTaskCrawlhttpx → Spidertext extractorDedupcanonical URLSHA-256 of textChunk agentllama3.1:8b pickssemantic·recursive·fixed (tiktoken)Embednomic-embed-text768-d, 1 batch callStorePostgres+pgvectorchunks · tsvectorClassifyphi3:miniinteger-index topicASK — user messages a question (or pastes a URL: intent=summarize_url skips recall, reads that article's chunks directly)QuestionTelegram · POST /qaone or many asksAnalyselfm2.5-thinking1.2b: intent, query,keywords + HyDEHybrid recallpgvector cosine ×2(query + HyDE)+ BM25 ts_rank_cdRecall floorboth legs weak→ topic not in KBRRF fusionreciprocal rankfusion → pool of 12Rerank gatephi3:mini, 1 callper passage; ≥0.5kept as evidenceAnswerllama3.1:8b · DSPygrounded, [n] citesReplyanswer + citationsTelegram / APIRefuse safelyno evidence, or reranker failed → fail closed, never guessOBSERVABILITY — every stage leaves a rowwrite path ▸structlog + request_idJSON logs; X-Request-IDbound to every linemodel_call_logsevery LLM call: model,prompt, response, ms,retries, statusquery_logsquestion, answer, abortreason, stage latencies,retrieval_trace JSONBingestion_jobsstate per job; trace at/observability/jobs/{id} /traceInMemoryMetricscounters + p50/p95/p99qa_aborted_*_totalGrafana :3000 — provisioned dashboard, plain SQL over the same Postgresingestion status · LLM latency + failures · QA abort rate · LLM call inspector (prompt/response) · retrieval trace (vector vs BM25 hits)SQL panels read these tablesClient / outputBackend stepLocal model / tokenizerPostgresLLM gatewayGate / observability
Act 4 · What I built — Superbrain

Components — models, tokenizers, Postgres, observability.

FASTAPI APP — async, ports & adapters (domain / application / infrastructure)OLLAMA — local models, nothing leaves the machineOBSERVABILITYTelegram botwebhook via ngrokREST clients/ingestion /qa /topicsCLIsuperbrain commandsSchedulerdaily digest 07:00 UTCAPI routersingestion · qa · topicsdigests · observability · healthUse casesIngest · ClassifyAskQuestion · DigestMiddlewareRequestIDMiddlewarestructlog contextvars → JSONQA pipelineanalyse → recall → rerank → answerDSPy signatures per stageRetrievalVectorRetriever · BM25 repoRRF fusion (k, pool 12)Chunkerssemantic · recursive · fixedchunk agent picks per articlePorts → adaptersLLMPort · EmbeddingPort · CrawlerPort · ChunkerPort · repositoriesTokenizerstiktoken cl100k_base (fixed 512/64)NLTK punkt (semantic, 400 tok)LLMPriorityQueuesingle worker · P1 QAP2 ingestion · P3 backgroundPrioritizedLLMLLMPort wrapper per priorityshared queue, no GPU thrashOllamaLLM · LLMPortLMlogs every call; DSPy bridgerun_coroutine_threadsafellama3.1:8bchunk strategy · QAanswer · digestphi3:miniclassificationrerank (pointwise)lfm2.5-thinking:1.2bquery analysisintent + HyDEnomic-embed-text768-d embeddingsvector(768) in pgvectorPostgreSQL 16 + pgvectorproduct: articles · chunks (embedding vector(768) + tsvector FTS) · topics · article_topic_matches · digest_runs/itemsobservability: ingestion_jobs · model_call_logs · query_logs (JSONB retrieval_trace)logsSQLAlchemy asyncstructlog JSONrequest_id on every linestage + gate decisionsInMemoryMetricscounters + p50/p95/p99qa_aborted_*_total/observability APImetrics · model-callsquery-logs · jobs/{id}/traceevals/runWhy Postgres for it all?Same store as the product:one SQL dashboard, no extrainfra, every prompt replayable.Grafana 11 :3000provisioned dashboardSQL panels on PostgresLLM call inspectorClient / outputBackend stepLocal model / tokenizerPostgresLLM gatewayGate / observability
Act 4 · What I built — Superbrain

Three local models. Four agentic roles.

☁ Cloud API — what you get free
One API endpoint. Claude Opus 5.5 handles chunking decisions, classification, QA, and digest summaries. No model routing needed. No latency tradeoffs to manage per task.
model = "claude-opus-5-5"
chunking → opus-5.5
classify → opus-5.5
qa → opus-5.5
digest → opus-5.5
# one model, every task
⚡ SLM · Superbrain — what we built
Explicit routing. Right model for the right job. phi3:mini on classification saved 4× latency over llama3.1:8b for the same task.
Model
Role(s)
llama3.1:8b
chunking · QA · digest
phi3:mini
classification 4× faster
nomic-embed
semantic embeddings
The principle Don't pick one model. Route. Send each task to the right size of model. The interesting design problem isn't which model — it's how they talk to each other.
Act 4 · What I built — Superbrain

The chunking strategy agent — LLM-as-decision-maker.

☁ Cloud frameworks — what you get free
LangChain and LlamaIndex provide 7+ chunking strategies with automatic selection. RecursiveCharacterTextSplitter, MarkdownNodeParser, SemanticSplitter — pick one, done.
LangChain / LlamaIndex
RecursiveCharacterTextSplitter(
chunk_size=512
)
# no LLM call needed
↗ Chunking Techniques with LangChain & LlamaIndex — lancedb.com, 2024
⚡ SLM · Superbrain — what we built
Ask llama3.1:8b to pick the strategy. Closed action space — 3 valid values. Every call has a fallback if JSON is malformed.
# closed action space
"""Output JSON only:
{"strategy": "semantic"|"recursive"|"fixed"}
Article (first 2000 chars): ..."""

try:
    strategy = json.loads(resp)["strategy"]
    assert strategy in {"semantic","recursive","fixed"}
except:
    strategy = "fixed"  # deterministic fallback
The principle Design for failure. Every LLM call needs a fallback. The pipeline never blocks on a bad model response.
Act 4 · What I built — Superbrain

Classification by integer index — hallucination prevention by design.

☁ Cloud API — what you get free
OpenAI Structured Outputs enforce schema at the API level. Enum values are valid by construction. No markdown fences, no wrong shapes, no coercion needed.
response_format=TopicMatch
# Pydantic schema enforced
# confidence always valid enum
# no parsing surprises
↗ Structured Outputs — developers.openai.com, 2024
⚡ SLM · Superbrain — what we built
Pass topics as integers, not UUID strings. The model can't invent an ID that wasn't in the prompt. Invalid integers are silently dropped by the parser.
[1] AI & Machine Learning
[2] DeepSeek R1
[3] Small Language Models
↓ phi3:mini ↓
[{"topic_id": 1}, {"topic_id": 99}]
↓ parser ↓
1 → ML ✓ kept
99 → no match ✗ dropped silently
The principle Structure the prompt so hallucination is physically impossible, not just statistically unlikely. Without structured output APIs, you engineer the constraint yourself.
Act 4 · What I built — Superbrain

Grounded QA with evidence gating.

☁ Cloud API — what you get free
OpenAI Assistants API: managed RAG as a service. Upload files, it handles embedding, chunking, retrieval, and generation. One API call returns a grounded answer.
assistants.create(tools=[retrieval])
threads.messages.create(question)
→ grounded answer with citations
# pipeline: invisible
↗ RAG and Semantic Search for GPTs — help.openai.com, 2024
⚡ SLM · Superbrain — what we built
Every step explicit. Every gate intentional. An honest "I don't know" beats a confident wrong answer.
question → embed (nomic-embed-text)
↓
vector · top-20
BM25 · top-20
↓
RRF fusion → top-10
↓
cosine score ≥ 0.6?
✗ abort
✓ generate
validate chunk IDs · drop hallucinated
The principle Build the gate, not just the generator. The LLM can only cite what you gave it — and only if you gave it enough.
Act 4 · What I built — Superbrain

Reciprocal rank fusion — when vector and keyword disagree.

☁ Cloud vector stores — what you get free
Pinecone hybrid search merges dense and sparse vectors in one API call. Server-side normalization. No RRF formula to implement, no Postgres to query twice.
index.query(
vector=dense_vec,
sparse_vector=bm25_vec,
alpha=0.5
)
# fusion: someone else's problem
↗ Hybrid Search — docs.pinecone.io, 2024
⚡ SLM · Superbrain — what we built
Postgres does both — pgvector for cosine, tsvector for BM25. RRF implemented in Python. Two lines of math. No separate vector database.
VECTOR
#1 chunk_A
#2 chunk_B
#3 chunk_C
+
BM25
#1 chunk_D
#2 chunk_E
#3 chunk_A
=
FUSED
chunk_A .0323
chunk_B .0164
chunk_D .0164
score(c) = ∑ 1 / (60 + ranki)
Why this matters A chunk that appears in both rankings gets a real boost. Vector finds meaning. BM25 finds keywords. Postgres handles both — no separate vector database.
Act 4 · Continued · The honest part
Let me tell you about the
things that broke.
Every failure in this section made the system more trustworthy than the version that worked on the first try.
01
The model we planned to use wasn't ready.
02
When the model talked back in formats we didn't ask for.
03
The async session that closed before we were done with it.
04
The architecture that worked on GPT-4o and fell apart on everything else.
Act 4 · What actually broke

The model we planned to use wasn't ready.

☁ Cloud API — what you get free
Model availability is invisible. Swap one string. New model, same call. If Claude Opus 5.5 isn't ready, you use Claude Haiku. No Ollama build to wait for. No compatibility to verify.
# swap a string, done
model = "lfm2-7b"
model = "claude-haiku-4-5"
# always available, always stable
⚡ SLM · Superbrain — what we hit
LiquidAI's LFM2-7B was the planned digest model. Efficient, purpose-built. Ollama-compatible build wasn't stable at ship time.
PLANNED
LFM2-7B via Ollama
smaller · efficient
SHIPPED
llama3.1:8b
already working · trusted
// docs/ARCHITECTURE.md
swap to lfm2-7b when available
# comment still in the source
The lesson Build to what ships today. Local model availability is a real constraint — "available soon" is not a production contract.
Act 4 · What actually broke

When phi3:mini talked back.

☁ Cloud API — what you get free
OpenAI Structured Outputs: schema enforced at the API layer. Required fields always present, enum values always valid, no markdown fences. Contract is the SDK.
✓ confidence always "high" | "medium" | "low"
✓ JSON always bare — no fences
✓ Shape always the array you asked for
↗ Structured Outputs — developers.openai.com, 2024
⚡ SLM · Superbrain — what we hit
[{"confidence": "very_high"}]  # not defined
```json [...]```              # markdown fences
{"matches": [...]}           # wrong shape
FIX 1 Unknown confidence → coerce to "low"
FIX 2 Strip ```json ... ``` before parse
FIX 3 Detect {"matches": [...]} → extract array
The reframe The model wasn't broken. The contract was missing. Every fix was tightening the prompt — not patching the model.
Act 4 · What actually broke

The session that wouldn't stay open.

☁ Cloud API — what you get free
Stateless HTTP calls. No connection lifecycle. No session to manage. A cloud LLM call is just a POST request — it's complete when the response arrives. No async context managers to reason about.
# at 7am UTC, APScheduler fires
resp = await anthropic.messages(...)
# always works
# no lifecycle to manage
⚡ SLM · Superbrain — what we hit
ATTEMPT 1 · session at startup
7am: InvalidRequestError
session already closed
ATTEMPT 2 · factory at job time
async with ... exits early
DetachedInstanceError inside execute()
ATTEMPT 3 · closure in main.py ✓
session lives for entire pipeline run
fresh session per execution
The lesson Small models don't cause all your bugs. Async does. Every "it should work this way" assumption is a potential midnight debugging session.
Act 4 · What actually broke

GPT-4o taught us the wrong architecture.

☁ The architecture spike · GPT-4o
One prompt.
Beautiful citations.
Nothing hallucinated.
— no evidence gate needed
— no SOURCES format required
— no chunk ID validation
— just worked
"wow this is easy"
⚡ Same prompt · llama3.1:8b
✗ Cited chunk IDs it invented
✗ Confident answers on thin evidence
✗ SOURCES format was inconsistent
✗ No way to tell signal from hallucination
THREE ADDITIONS REQUIRED
+ Evidence sufficiency gate (abort if weak)
+ SOURCES line with chunk IDs in prompt
+ ID validation against evidence set
more trustworthy than GPT-4o ever was
GPT-4o's cleverness was hiding architectural gaps. The smaller model forced me to close them.
Act 5 · Lessons learned

LESSON 01 · Agentic AI is orchestration, not autonomy.

☁ Cloud API — what you get free
Function calling and tool use baked into the API. The model decides which tool, when, in what order. Multi-step reasoning in one round trip. Vague orchestration? The model recovers.
POST /v1/chat/completions
tools: [search, classify, write]
→ model decides everything
⚡ SLM · Superbrain — what we built
SLMs cannot recover from vague orchestration. The code owns the graph. Each step is bounded, explicit, validated.
input · validate schema
↓
retrieve · top-k · gate on score
↓
llm decide · JSON schema only
↓ valid? → fallback if not
act · log · observe
The insight The "agentic" part isn't the LLM being clever. It's the orchestration logic around the LLM being correct. SLMs made this impossible to skip.
Act 5 · Lessons learned

LESSON 02 · The prompt is the contract.

☁ Cloud API — what you get free
GPT-4 infers intent from vague prompts. Returns structured data even without an explicit schema. Tolerates drift. Fails gracefully. You don't notice the contract is missing.
"Classify this article."

# GPT-4 figures it out anyway.
# Returns something reasonable.
# The contract is invisible.
⚡ SLM · Superbrain — what we built
phi3:mini failed immediately on every missing constraint. Three real failures before the classifier worked.
confidence: very_high   # not defined
```json                  # markdown fences
{"matches": [...]}       # wrong shape

# Fix: role + task + schema + fallback
"""Output JSON array only:
[{"topic_id": <int>,
  "confidence": "high"|"med"|"low"}]
Return [] if no match."""
The rule Every prompt specifies: role · task · output schema · fallback behaviour. The model wasn't broken — the contract was missing.
Act 5 · Lessons learned

LESSON 03 · Constraints are features in disguise.

☁ Cloud API — what you get free
One GPT-4 call handles chunking strategy, extraction, and classification in a single round trip. Multi-step reasoning, one prompt. Explicit stages are optional.
one prompt →
chunk + extract + classify
"opaque · expensive · usually works"
⚡ SLM · Superbrain — what we built
phi3:mini cannot do multi-step reasoning in one prompt. Forced explicit stages. Each one independently debuggable and observable.
chunk
strategy
→
extract
+ embed
→
classify
JSON
→
validate
+ persist
debuggable · observable · reliable
"If your system only works with a powerful model, you haven't built a system — you've built a prompt."
— THE THING I WISH I'D KNOWN ON DAY ONE
Act 5 · Lessons learned

LESSON 04 · You need real observability — not just logs.

☁ Cloud API — what you get free
Vendor dashboard: token usage, cost, p50/p95 latency, error rate by model. Aggregates are automatic. But the vendor sees your model calls — not your pipeline.
console.anthropic.com/usage
tokens_used: 4.2M
cost_this_month: $312
avg_latency: 1.4s
# your pipeline: still a black box
↗ Grafana + OpenRouter — grafana.com/blog, 2026
⚡ SLM · Superbrain — what we built
No vendor dashboard. Built Grafana panels from scratch over Postgres. Without it, we couldn't see the Ollama queue flooding during reclassification.
LLM call log · model · template · latency · status
QA trace · retrieval latency · abort reason
pipeline health · p50/p95/p99 · fallback rate
→ revealed: 128 background calls blocking /ask
The hard rule Without it, you're guessing. With it, you can improve. Build the metrics surface alongside the feature — not after the incident.
Act 5 · Lessons learned

LESSON 05 · Retrieval quality is answer quality.

☁ Cloud API — what you get free
GPT-4 reasons over weak context and still produces plausible answers. Bad retrieval is masked by fluency. You need eval harness scores — not user complaints — to notice.
context: 3 weakly-relevant chunks
→ GPT-4: plausible-sounding answer
# failure is quiet
# you need eval to catch it
⚡ SLM · Superbrain — what we built
llama3.1:8b fails loudly with bad context — invented chunk IDs, hallucinated sources. Made retrieval problems impossible to ignore. We fixed retrieval.
+ Hybrid retrieval: vector + BM25
+ RRF fusion across both
+ Per-chunk embeddings, not per-article
+ Postgres FTS index on chunk content
· Prompt tweaks — barely moved the needle
· Larger generation model — didn't either
The budget rule Spend 80% of your QA improvement budget on retrieval. The LLM can only cite what you gave it. Garbage in, hallucination out.
Act 5 · Lessons learned

LESSON 06 · Shared resources need explicit scheduling.

☁ Cloud API — what you get free
Auto-scales transparently. Thousands of concurrent requests distributed across infrastructure. You never think about queuing or request priority. It's someone else's problem.
/ask → 800ms
128 background jobs → all fine
# concurrency: someone else's problem
↗ "Local LLMs Handle Concurrency" — mljourney.com, 2026
↗ "Ollama: Laptop to Cluster" — bentoml.com, 2025
⚡ SLM · Superbrain — what we built
Single Ollama process. 8 reclassification jobs × 16 articles = 128 background calls. /ask blocked for 5 minutes. Grafana showed us why.
P1 · /ask QA — interactive · jumps queue
P2 · ingestion — user-triggered background
P3 · classification · digest — fully background
asyncio.PriorityQueue · single worker · FIFO within tier
The lesson A local model is a single-threaded resource. Design your queue discipline before you ship background work — not after your user waits 5 minutes for an answer.
Act 5 · Lessons learned

LESSON 07 · Gate on relevance — cosine score isn't relevance.

☁ Cloud API — the problem still exists
Cloud LLMs are fluent — plausible-sounding answers even with weak retrieval. The failure is quiet. You need eval scores, not user complaints, to catch it. The gate is available to you — you just don't feel forced to build it.
Q: "my car broke down"
top_chunk_score: 0.31
→ fluent answer. confidently wrong.
↗ "Better RAG: Similarity with Threshold" — M. Lee, Medium, 2025
⚡ SLM · Superbrain — what the trace taught us
We gated on cosine ≥ 0.6. Then the trace showed off-topic queries scoring 0.60–0.63 — overlapping real matches at 0.66–0.76. Cosine is recall, not relevance.
v1 · if cosine ≥ 0.6 → answer ← junk slips through
v2 · phi3 scores each chunk's relevance to the query
gate on the rerank score → off-topic chunks drop out
The catch The reranker is itself a small model — and ours sometimes returned JSON with // comments. Invalid JSON → it silently fell back to the unfiltered list. Small models need defensive parsing, graceful degradation, and the trace to catch the fallback.
Act 6 · Takeaways

A mental model for local-first agentic AI.

LAYER 1
Entry points
API · Bot · CLI · Scheduler — how the world reaches you
↓
LAYER 2
Orchestration
bounded flows with explicit contracts — input → schema → fallback
↓
LAYER 3
LLM calls
right model for the task · validated output — small unless you must
↓
LAYER 4
Retrieval
hybrid · vector + BM25 · RRF fusion — the answer's quality lives here
↓
LAYER 5
Storage
Postgres · relational + vector + FTS, one store — no separate vector DB
Act 6 · Takeaways

LLM or SLM — a checklist.

Question
Answer
Pick
Is the task repetitive and high-volume?
YES
→ SLM
Does it require structured output?
YES
→ SLM
Is latency under 2 s required?
YES
→ SLM
Does it need nuanced multi-step reasoning?
YES
→ LLM
One-off creative or synthesis task?
YES
→ LLM
Combining both in a pipeline?
ALWAYS
→ orchestrate
Act 6 · Takeaways

Three things I'd tell past me.

01
Design your prompts before you write a line of code.
The prompt is the spec.
02
Pick the smallest model that works for each step.
Use the big model only where it earns its cost.
03
Build the eval harness first, not last.
You cannot improve what you do not measure.
Act 6 · Takeaways

The new paradigm requires new engineering muscles, not new magic.

Agentic AI is still engineering.

It just has different seams.
Feedback QR code
Resources
SUPERBRAIN · REPO
github.com/amar-chheda/SuperBrain
NVIDIA · SLM PAPER
arxiv.org/pdf/2506.02153
INFOWORLD · SLM ARCHITECTURE
infoworld.com/article/4160404
LOCAL RUNTIME
ollama.ai
Amar Chheda
Machine Learning Engineer
thank you.