Skip to content

Local AI research and decisions

1. The Big Picture

The system is one pipeline: client app → API gateway → agent orchestrator → local LLM, with a knowledge base and infra signals feeding into the orchestrator from the side.

Apps/interfaces (TellyBoard, Concierge, dashboards)
        |
API gateway (FastAPI + Redis + MCP servers)
        |
Agent orchestrator (LangGraph — routing, validation, retries)
        |
Local LLM inference (vLLM + Typhoon2.5-4B)

Knowledge base (vector DB + docs) -----> feeds into orchestrator
Infra signals (CDN analytics, Mikrotik) -> feeds into orchestrator

Every project OKR is an instance of this same skeleton:

Project Apps layer What the orchestrator does Side inputs
AI monitoring / CDN routing Ops dashboard Anomaly-detection agent decides reroute/alert CDN analytics feed
TellyBoard + Concierge Mobile/TV app Concierge agent answers, books, controls devices Device manuals; Mikrotik/WebRTC state
On-prem multi-agent (EKR) Internal tools Multiple agents hand off tasks, validate each other Internal docs
Self-validating manual generator Internal tools Generator agent + critic agent loop Source manuals to check against

Key point on anomaly detection specifically: the detection itself is mostly statistics (rolling z-score, seasonal decomposition), not an LLM. The LLM's role starts after something is flagged — interpreting it, deciding a response, calling the orchestrator. A separate metrics-watching service feeds the orchestrator as a new kind of input, distinct from chat messages.


2. FastAPI — what it actually is, and how a request flows through it

FastAPI is a Python library, not a separate language. Python is the language; FastAPI is the web framework used to build the API gateway. It doesn't generate text itself — it's a router that calls the LLM engine the same way it might call a database.

Why FastAPI specifically (not just any Python code): - Async-native — doesn't block on slow LLM calls, so one user's request doesn't freeze everyone else's - Built-in streaming response support — this is what produces the token-by-token "typing" effect in a chat UI - Auto-validates request/response shapes via Pydantic type hints — bad input gets rejected before reaching the model - Auto-generates interactive API docs (/docs) — useful when multiple apps (TellyBoard, Concierge, CDN dashboard) all call the same backend

The exact request lifecycle, mapped to real code: 1. Client sends raw HTTP — e.g. POST /chat with a JSON body. HTTP is just an agreed-upon text format over a network socket. 2. Uvicorn accepts the connection — the low-level server process listening on the port. Uvicorn doesn't know what /chat means or what a ChatRequest is; its only job is handing the raw request to the FastAPI app. 3. FastAPI's router matches the route — the @app.post("/chat") decorator registers "POST + /chat → this function" in an internal map. A GET /chat or POST /banana gets rejected automatically (404/405) before any custom code runs. 4. Pydantic parses and validates the body — class ChatRequest(BaseModel): message: str means FastAPI hands the raw JSON to Pydantic, which checks the message field exists and is a string, then builds a typed object that becomes the function's req argument. Malformed input never reaches the function body.


3. Engines: vLLM vs Ollama vs llama.cpp

llama.cpp Ollama vLLM
What it does Core inference engine (runs the model) Serving wrapper around llama.cpp (or MLX on v0.19+) Standalone serving engine with continuous batching
Handles concurrency No — single request No — one at a time, others queue (or spins up a full second copy of the model, costing much more memory) Yes — real batching, many requests interleaved
Setup effort Manual, more control Very low — ollama pull, ollama serve, done More flags, more configuration
API shape N/A (library) Its own: /api/generate, /api/chat OpenAI-compatible: /v1/chat/completions
Model format GGUF (quantized) GGUF (manages files for you) Typically safetensors (fp16/bf16), some quantized formats supported
Cold start N/A Fast, ~8 sec Slower, ~20+ sec (prepping batching infra)
Concurrency mental model — Strict single queue — request 2 waits behind request 1 entirely Continuous batching — pieces of many requests processed together in the same GPU pass, so multiple people's responses stream back at close to the same pace

"Single-user" clarified: this isn't about who's allowed to use it — it's about how many requests can be processed at the same time before slowing down. On Ollama, two people chatting at once feels like two people going slower, not two people at full speed. vLLM's continuous batching interleaves work instead of queuing it — that's the entire reason vLLM exists.

Decision: vLLM, because the project's concurrency requirement (5-6+ simultaneous sessions) is structurally impossible on Ollama at any configuration or file size — it queues by design, not by a setting that can be tuned away.


4. Models: Qwen vs Typhoon

Typhoon is a Qwen3 model — SCB 10X (a Thai company) took Qwen3 and further trained it for Thai/English bilingual use, keeping Qwen3's tool-calling ability intact. Not competitors; Typhoon = Qwen3's architecture + Thai-specific training layered on top.

Qwen3 Typhoon2.5-4B
Made by Alibaba SCB 10X (Thai company)
Relationship Trained from scratch Built on top of Qwen3, further trained
Thai language quality Present, not the focus Purpose-built for Thai + English
Tool-calling Yes, native to Qwen3 Yes — inherited from Qwen3, kept intact
Size options 0.6B up to 235B+ 4B, 12B, 30B-A3B, others
Role here Base architecture underneath the pick Model actually deployed

Decision: Typhoon2.5-4B, given: - "Thai Biz" project name implies Thai language quality matters - 4B (not 8B) leaves far more memory headroom for concurrent sessions on 16GB RAM - Ships with working tool-call support in a known format ("hermes" parser style)

4B vs 8B tradeoff, stated plainly:

4B 8B
Weights (fp16) ~8GB (see section 5 — not the ~2.5GB originally assumed for a quantized version) ~16GB — would not fit alongside any KV cache on this 16GB machine at all
Single-stream speed Faster Slower (established ~33 tok/s baseline referenced for 8B class)
Reasoning/judgment quality Weaker — fine for routine chat/tool calls Stronger — better for nuance and multi-step reasoning
Best fit High-volume, routine tasks (Concierge Q&A, simple tool calls) Lower-volume, higher-stakes judgment (anomaly triage, manual-generator validation)

Known open risk: a 4B model may make weaker judgment calls on anomaly triage or content validation than an 8B model would — a deliberate tradeoff for concurrency headroom, not a hidden flaw. A two-model split (4B for routine chat, a larger model loaded separately for judgment-heavy agent decisions) is a valid future option if this becomes a real problem, since nothing stops running two models through the same vLLM setup if total memory allows it.


5. The fp16-vs-quantized surprise, and its knock-on effects

The plain Hugging Face repo (scb10x/typhoon2.5-qwen3-4b) ships full fp16 weights (~8GB), not a small quantized version — a 4B-parameter model at 2 bytes/parameter is ~8GB by definition. This was discovered only after the actual download reached ~9-10GB total instead of an assumed ~2.5-3GB.

A GGUF Q4-quantized version does exist (scb10x/typhoon2.5-qwen3-4b-gguf, ~2.5-3GB) but is built for llama.cpp/Ollama, not vLLM — GGUF is not vLLM's native format.

The real tension this creates: | Option | Result | |---|---| | Keep fp16, run in vLLM | Real concurrency (batching) but smaller KV-cache headroom (~4-6 concurrent) | | Switch to GGUF, run in Ollama | Restores memory headroom but loses concurrency entirely — Ollama queues regardless of file size |

Decision: keep the fp16 version in vLLM. A smaller file in an engine that can't do concurrency at all does not serve the actual 5-6+ concurrent requirement — vLLM with less headroom still beats Ollama with more, because Ollama's ceiling is ~1 regardless of model size.

Revised concurrency math with the real 8GB weight size: - Host budget (see section 6): ~12GB usable for vLLM - Weights: ~8GB - Left for KV cache: ~4GB - Realistic concurrent sessions: ~4-6, closely matching the original target despite the size surprise


6. Hardware: Mac Mini, 16GB RAM — the memory mechanics in detail

Unified memory: CPU and GPU share the exact same physical RAM on Apple Silicon — there is no separate, dedicated VRAM pool the way there is on an NVIDIA card. This means "GPU memory" isn't a fixed number to look up; it's a soft ceiling.

How the ceiling is actually calculated: macOS exposes a Metal API call, recommendedMaxWorkingSetSize, returning roughly how much of total system memory is safe to hand to GPU-side work — typically 75-90% of total RAM, not a fixed published constant. MLX (and vllm-metal on top of it) queries this once, at server startup, and treats that single snapshot as the memory budget for the entire session.

Static, not dynamic: this is captured once at launch and does not update while the server runs. Opening other memory-hungry apps after the server starts doesn't cause it to back off — it's still working from the number it captured at launch. Two real failure modes follow from this: - Starting the server on an idle machine (generous headroom reported), then opening other apps later — real available memory drops below what the KV cache pool assumed, risking swapping. Once macOS starts swapping to virtual memory, performance doesn't degrade gracefully — one real-world example dropped from ~10 tok/s to 0.28 tok/s. - Starting the server under heavy load — under-allocates, leaving real capacity unused for no reason.

Practical rule: always (re)start the model server with the Mac already in its normal working state (VM running, usual apps open) — not on a freshly rebooted, empty machine — since the number it captures at that moment is binding for the whole session.

RAM tiers and what fits (Apple Silicon in general):

RAM What fits comfortably
8GB 3B-7B models at Q4 only
16GB (this machine) 7B-8B comfortably; with fp16 8GB weights specifically, ~4GB left for KV cache
24GB Up to ~13B, or 8B with more headroom
32GB+ 30B-class becomes usable

Chip matters as much as RAM amount: base M4 and M4 Pro can both come in a 32GB configuration, but bandwidth differs sharply — base M4 ~120GB/s vs M4 Pro ~273GB/s. More RAM on the base chip buys concurrency headroom only (same per-token speed); the same RAM on M4 Pro raises both the concurrency ceiling and the raw throughput ceiling, since it isn't fighting the same bandwidth cap.


7. Mac Mini vs NUC vs GPU server — per-workload verdicts

Workload Best fit Why
LLM inference (Gemma/Qwen/Typhoon) Mac Mini Integrated-GPU NUCs are ~10x slower for this; unified memory + MLX is a genuinely good fit
WebRTC/mediasoup/cast broker NUC (Linux) Native environment; matches eventual production deployment
k3s orchestration NUC (Linux) k3s is Linux-native; running it on Mac needs a VM layer with no native equivalent
200+ concurrent production serving Cloud/dedicated GPU (A100/H100) Both consumer hardware and Mac's unified memory hit real ceilings well before 200

Same-engine (llama.cpp) benchmark, Mac vs Linux GPU, 8B class model, Q4:

Hardware Tokens/sec
Mac Mini M4 ~33
RTX 4070 ~52
RTX 4090 ~104

The gap is pure memory-bandwidth difference: M4 ~120-546GB/s (chip-dependent) vs RTX 4090 ~1TB/s — same code, same quantization, same everything else. One caveat cutting the other way: for models too large to fit in a consumer GPU's VRAM at all, Apple's unified memory can still run them (slower per token) where a 24GB RTX 4090 simply can't load them — Apple trades speed for capacity, NVIDIA trades capacity for speed.

Ollama backend upgrade, same hardware: Ollama switched its Apple Silicon backend from llama.cpp to Apple's own MLX framework in v0.19 (March 2026) — roughly tripled decode speed in one tested case (43 → 130 tok/s on a Mac Mini M4 Pro). Free speed gain from just updating Ollama, no hardware change — though the practical setup here moved to vllm-metal directly rather than Ollama, so this specific fact is more of a "know it exists" than something actively used.


8. Architecture: vLLM native, k3s in a UTM VM

Decision: vLLM runs directly on macOS — it needs direct Metal/MLX GPU access, which a Linux VM generally does not get passed through to it (a Linux VM running vLLM inside it would likely fall back to CPU-only, losing all batching/speed benefits). k3s runs inside a UTM Linux VM, hosting FastAPI, Redis, and mediasoup.

Physical Mac Mini
│
├── macOS host (native, direct Metal/MLX GPU access)
│   └── vLLM serving Typhoon2.5-4B  →  port 8001
│
└── UTM VM (Linux, runs k3s)
    ├── FastAPI backend (pod)
    ├── Redis (pod)
    ├── mediasoup / streaming service (pod)
    └── MCP servers (pod)
        │
        └── reach vLLM via the macOS host's gateway IP
            (e.g. http://<UTM_GATEWAY_IP>:8001), NOT localhost —
            localhost inside the VM means the VM itself

Finding the gateway IP (UTM Shared Network mode, commonly <UTM_GATEWAY_IP> but must be confirmed per-machine):

ip route | grep default   # run inside the VM

Kubernetes resource limits apply only inside the VM — to FastAPI, Redis, and mediasoup pods. vLLM is not a pod and is not under Kubernetes' control at all; its memory is set via its own environment variables on the host (VLLM_METAL_MEMORY_FRACTION), calculated against the host's own remaining memory after the VM's fixed allocation is carved off (e.g. 32GB total − 16GB to the VM = 16GB host-side, minus macOS overhead, leaving ~12GB for vLLM).


9. Concurrency scaling — real-world reference benchmarks

  • Single RTX 3090, Llama 3.1 8B via vLLM: served 100 concurrent users simultaneously at ~12.88 tok/s each (human reading speed) — proof one consumer GPU handles far more than intuition suggests, since not every registered user is actively generating text at the same instant. "Concurrent" specifically means active prompt+response pairs inside the inference engine, not total logged-in users.
  • Dual A100 40GB, tensor-parallel: stable for 200-300 concurrent users on 14B-32B class models, no bottleneck detected.
  • 4x A100, 70B model: 2,200 tokens/sec at 256 concurrent users — 2.3x faster than Text Generation Inference, 3.1x faster than vanilla PyTorch serving.
  • Smaller models batch better: a 0.6B model showed 3.7x throughput scaling at 16 concurrent requests vs an 8B model's 2.6x — part of why the 4B pick helps concurrency beyond just its smaller memory footprint alone.

The three real levers for more concurrency, in priority order: 1. vLLM config first — check --gpu-memory-utilization / VLLM_METAL_MEMORY_FRACTION isn't left at an overly conservative default; this is free. 2. Model size/quantization second — a smaller or quantized model frees VRAM without spending money. 3. GPU hardware last — only add VRAM (bigger/more GPUs) once the first two are already maxed out; jumping straight to new hardware often masks an under-configured setup.


10. Cost reference (for the eventual Phase 8 GPU decision)

Path Cost
Mac Mini M4, 16GB (current) ~$799 one-time
Mac Mini M4 Pro, 48GB ~$1,799 one-time
DIY Linux + RTX 4090 build ~$2,200 upfront + ~$770-900/yr electricity if run 24/7
Cloud GPU rental (RTX 4090 class) ~$0.13-0.36/hr
Dedicated monthly GPU hosting ~$630-820/month, unmetered
Data-center GPU cloud (A100/H100/H200) ~$2-8/hr — adds up fast for 24/7 workloads

Breakeven rule of thumb: owning beats renting once usage crosses roughly 4-6 hours/day sustained over about two years; below that, renting wins by a wide margin.

Guidance: stay on the Mac Mini through Phases 1-7. Use rented cloud GPU for early load-testing at real scale before committing capital. Check Mashup's own internal GPU allocation before assuming public cloud pricing applies at all — internal infra cost allocation may bypass this calculation entirely.


11. Open items / not yet resolved

  • Whether Typhoon2.5-4B's reasoning quality is adequate for higher-stakes agent decisions (anomaly triage, manual-generator validation) — untested; revisit if problems surface in Phase 5+.
  • No AWQ/GPTQ quantized version of this exact model confirmed to exist yet — would restore more concurrency headroom if found, without giving up vLLM's batching.
  • Tool-calling behavior on the vllm-metal plugin specifically is unconfirmed — the standalone binary's CLI lacks the --tool-call-parser / --enable-auto-tool-choice flags that mainline vllm serve has; mainline vLLM does not build on this machine (see installation guide), so this needs a direct test against the model's raw output format instead of relying on a built-in parser flag.
  • Real concurrency ceiling on this exact machine has not yet been benchmarked with a proper load test — all concurrency figures above are estimates from external research and internal math, not measurements taken on this specific setup.
  • Total physical RAM (32GB assumed at one point for the host-vs-VM split math) should be reconfirmed against the actual machine spec.