Chapter 1

LLMs and the chat API

What a large language model actually is, the exact shape of a request to one, and how this project can switch between Gemini, Groq, a local model or anything else by changing one line of configuration.

What an LLM is (and isn't)

A large language model is a function trained to do one thing: given some text, predict a likely next token. A token is a chunk of text, often a word or part of a word: "scheduling" might be one token, "CP-SAT" three or four. As a rule of thumb, 1 token ≈ ¾ of an English word. To write an answer, the model predicts a token, appends it to the input, predicts the next one, and repeats until it predicts "end".

Three consequences shape everything in this project:

  1. It only knows its training data and its prompt. Gemini has never seen your portfolio. Anything it says about you must come from text we put in the prompt, or it will invent something plausible. That invention is called hallucination.
  2. It has no memory between calls. Every request starts from zero. A "conversation" is an illusion we create by sending the previous messages again, each time. That's why chat.py loads the last HISTORY_TURNS messages from SQLite and puts them back in the request.
  3. The prompt has a size limit, the context window, measured in tokens (Gemini's is about a million; small local models may have 8k). Every token you send also costs time and, on paid tiers, money.
Concept

Think of the model as a brilliant improviser with amnesia, handed one sheet of paper per question. Your whole job is deciding what's written on that sheet. Chapter 3 is about filling it well.

The chat request, exactly

Nearly every LLM API today accepts the same request shape, popularized by OpenAI. A request is a list of messages, each with a role:

RoleMeaningIn this project
systemStanding instructions: who the model is, the rules."Answer ONLY from the numbered sources, cite them like [1]…" plus a site map. (prompts.py)
userWhat the human said.Past questions as typed, and for the latest one: the retrieved sources + the question.
assistantWhat the model said earlier.Previous answers, loaded from SQLite.

Here's a trimmed version of what really goes over the wire for a follow-up question:

POST https://generativelanguage.googleapis.com/v1beta/openai/chat/completions
Authorization: Bearer <GEMINI_API_KEY>

{
  "model": "gemini-3.1-flash-lite",
  "temperature": 0.3,
  "max_tokens": 900,
  "stream": true,
  "reasoning_effort": "low",
  "messages": [
    {"role": "system",    "content": "You are the assistant on Mohamed Amine Hajji's portfolio… Rules: …"},
    {"role": "user",      "content": "How did the CP-SAT scheduler work?"},
    {"role": "assistant", "content": "Amine modeled lesson scheduling as a constraint problem… [2]"},
    {"role": "user",      "content": "Sources:\n\n[1] Lesson scheduling optimizer — Results…\n\n---\nVisitor's question: How fast was it?"}
  ]
}

Notice the previous turn is stored as the raw question, while only the latest message carries sources. Chapter 3 explains why.

The knobs

  • temperature controls randomness when picking each token. At 0 the model always picks its top choice. Higher values pick less likely tokens more often. We use 0.3: factual answers should be stable, but a little variety keeps the tone natural.
  • max_tokens caps the answer length. It's a safety net against runaway output, not a style instruction ("be concise" in the prompt does that).
  • reasoning_effort: many current models think before answering, generating hidden reasoning tokens first. That helps with hard problems but delays the first visible word. For "summarize these 5 paragraphs", thinking isn't worth it (see the measurements below).
  • stream: instead of one response at the end, the server sends the answer in small pieces as it's generated.

Streaming: why the answer types itself

A 150-word answer takes the model a few seconds to generate. Without streaming, the visitor stares at a spinner for all of it. With streaming, the first words show up as soon as they exist, typically 1 to 3 seconds in. The total time is the same, but time to first token is what people perceive as speed. Streaming is also what makes voice mode possible: we can start speaking sentence one while sentence three is still being written.

In code, the library hands us an async iterator of chunks; each carries a small delta of new text. The inner async for loop is all streaming takes (the rest of this method is about switching providers, explained below):

One library, many providers: LiteLLM

Every provider has its own URL, key, model names and small quirks. Instead of handling each one, the code goes through LiteLLM, an open-source Python library that speaks to 100+ providers with one function. A model is written provider/model, and the prefix tells LiteLLM where to send the request and which key to use:

groq/llama-3.3-70b-versatile          → api.groq.com, key from GROQ_API_KEY
gemini/gemini-3.1-flash-lite          → Google AI Studio, key from GEMINI_API_KEY
mistral/mistral-small-latest          → api.mistral.ai, key from MISTRAL_API_KEY
openrouter/nvidia/nemotron-…:free     → openrouter.ai, key from OPENROUTER_API_KEY
ollama/qwen3:8b                       → a model on your own machine, no key

Everything else in the app depends on a tiny interface, a Python Protocol: anything with a stream(messages) and a complete(messages) method counts as an LLM. That's the "scalable" part you asked for: LiteLLM lives behind it, and the RAG code never knows which provider answered.

Library · LiteLLM

One completion() function for 100+ LLM APIs, returning the same response shape for all of them, plus a Router that load-balances and fails over between them (also available as a standalone proxy server). It's the most used library of its kind, which is also why it was a target: in March 2026 two hacked releases sat on PyPI for about 40 minutes. So pyproject.toml pins one exact, two-week-old version (litellm==1.108.3) instead of "the latest". docs.litellm.ai/docs/routing

Switching providers is configuration

One line lists the models in order of preference; each provider's key has its own line. A model whose key is missing is skipped at startup (the log says which variable to set), so the list can name every provider you might use:

LLM_MODELS=groq/llama-3.3-70b-versatile,gemini/gemini-3.1-flash-lite,mistral/mistral-small-latest
GROQ_API_KEY=gsk_...
GEMINI_API_KEY=...
MISTRAL_API_KEY=...

# Fully local and private, no key: run Ollama, then
LLM_MODELS=ollama/qwen3:8b

Failover: when a free tier says no

Free tiers limit requests per minute and per day, and shared capacity gets overloaded. RouterLLM gives LiteLLM's Router every model, each with an order (1, 2, 3…):

  • Order: the router uses the lowest order that is healthy. If it fails (429 rate limit, 5xx outage, timeout, bad key), the request moves to the next order at once. num_retries=0, because retrying a provider that just said "too many requests" only makes the visitor wait.
  • Cooldown: allowed_fails=0 puts a model that failed in "cooldown" for LLM_COOLDOWN_SECONDS (60 s). During that minute the router doesn't even try it, so the next visitors go straight to a working model instead of waiting for the same error.
  • Only before the first word. Once text has reached the visitor, switching models mid-sentence would produce a Frankenstein answer, so a failure then is reported instead. Some providers only report an error when the first chunk is read; stream() catches that case too and asks the router again (the failed model is now cooling down, so the next one answers).

The tests check exactly these cases without any key or network: LiteLLM's mock_response makes a model fail with a real-looking 429 or 500, and the test asserts that the next model answered:

What actually happened

I listed the models your new key could use and sent each a one-sentence prompt. Results, from one afternoon:

ModelResult
gemini-2.5-flash, -lite404: retired. Tutorials still use these names.
gemini-3.5-flash, gemini-3.8-flash, gemini-flash-latest503: overloaded at that moment.
gemini-3.5-flash-liteWorks; 8.9 s to the first token (default thinking).
gemini-3.1-flash-lite + reasoning_effort=lowWorks; 1.5 to 4 s to first token. Chosen as primary.

Lessons: pin exact model names (aliases like -latest change under you), measure instead of trusting docs, and always configure a fallback on free tiers. The most robust fallback is a different company, since one provider's outage takes down all its models. That lesson is why the app later moved from "Gemini + a Gemini fallback" to LiteLLM with several companies (next box).

What actually happened · 21 Nov 2026

Gemini's free tier kept answering 503 "overloaded" and taking 15 to 26 seconds, so I set up free accounts at several companies and ran every candidate through the same test: python -m evals.models sends each model the real prompts the app builds for 5 portfolio questions, plus a trap question it can't answer ("What is Amine's current salary?").

Model (LLM_MODELS order)First wordFull answerCites [n]TrapNotes
groq/qwen/qwen3.8-27b0.7 s0.8 s2/3–Fastest by far, but only ~7,000 tokens a minute: our prompts are ~3,000 tokens, so 2 questions a minute. Rate-limited after 3 questions.
gemini/gemini-3.5-flash-lite0.6 s0.9 s3/3yesFast with reasoning_effort=low, but 2 of 6 calls failed with 503 "overloaded" when the first chunk was read.
cloudflare/@cf/meta/llama-3.3-70b-instruct-fp8-fast1.0 s2.8 s2/5yes6/6, steady. Different company, so a Google outage doesn't touch it.
gemini/gemini-3.1-flash-lite4.1 s4.4 s4/5yesGood answers, slow today. Separate quota from 3.5.
openrouter/nvidia/nemotron-3.5-super-vl:free3.7 s4.6 s3/5yesLast resort: 50 free requests a day.

Tried and left out: Groq's gpt-oss models (fast, but they cite as 【3】, which the widget doesn't recognize), Cloudflare's Mistral Small (never cited: 0/5), Cloudflare's GLM-5.3 ("not available on the Workers Free plan"), OpenRouter's Gemma 4 (429 on every call), Cerebras (now asks for a card before any call) and Cohere (free key is non-commercial only) and GitHub Models (shut down by GitHub on 30 July 2026; its endpoint now just answers "OK"). Llama 3.3 70B, the model every tutorial uses on Groq, is no longer listed there.

Then the real test: 6 questions in a row through the app. Groq answered the first ones; when it hit its per-minute limit the router logged "Falling back to … order 2" and Gemini answered, about 0.15 s later. Two seconds after that, Groq answered again. That surprised me: the cooldown was set to 60 s. LiteLLM reads the Retry-After header of a 429 and uses it when the provider gives one, and Groq refills its per-minute budget continuously, so it said "retry in ~2 s". That beats a fixed minute: the fastest model is used whenever it can be.

The fake model

EchoLLM implements the same interface without any network: it "answers" by listing the titles of the sources it was given. Tests use it, and you can run the whole app offline with LLM_MODELS=echo. Writing a fake for every external dependency is one of the most useful habits in engineering.

A visitor asks "What about his churn model?" right after a question about Drivago. Why does the model know what "his" refers to?

Each API call is stateless. The illusion of memory is the history you send. (The system prompt does help with "his" here, but for "what about that project?" only the history can resolve it.)

The model answering returns HTTP 429 after the visitor has already received half an answer. What does RouterLLM do?

The started flag: failover only applies before the first token. A second model can't continue another model's half-written sentence.

Groq answered 429 for one visitor. Ten seconds later another visitor asks a question. What happens?

That's what the cooldown is for: a provider known to be failing isn't tried again until LLM_COOLDOWN_SECONDS have passed, so nobody waits for an error we could predict.

Go further