open knowledge drop — free forever

learn. build. ship.

raw notes. real code. actual experience.
by akriceus — data scientist @ gedu.
no fluff. no paywalls. just the signal.

scroll
agent_state.py

        
4levels
16concepts
75+resources
13projects
0paywalls
00 — start here

learning roadmap

click a level to expand. follow this order. don't skip.

beginner foundations — what is GenAI? +
how LLMs worktokens & context windows temperature & samplingtransformers & attention prompt engineering basicszero-shot vs few-shot chain-of-thoughthallucinations & why they happen OpenAI / Anthropic API 101system prompts & roles

start here: Karpathy "Intro to LLMs" (YouTube, 1hr) → DeepLearning.AI "ChatGPT Prompt Engineering for Devs" → Anthropic Prompt Engineering docs

intermediate building — RAG, embeddings & APIs +
vector embeddingscosine similarity vector databases (chromadb, pgvector, qdrant)RAG pipeline architecture chunking strategiesdocling & unstructured LangChain basicsFastAPI + LLM backend streaming SSEstructured output / Pydantic RAGAS eval basicsAzure OpenAI vs OpenAI API

key project: RAG chatbot over your own docs. FastAPI + ChromaDB + Dash. build this before touching agents.

advanced agentic AI — agents, graphs & orchestration +
ReAct patterntool calling LangGraph state machinesmulti-agent orchestration CrewAI roles & tasksmemory (short/long-term, episodic) corrective & adaptive RAGhuman-in-the-loop (HITL) prompt injection defenseLangSmith observability DeepEval / LLM-as-judgeAmazon Bedrock / Nova MCP (Model Context Protocol)context engineering agent skillsSystem One models (Jev) for routing & gating

key project: multi-agent due diligence pipeline. supervisor routes to researcher, analyst, writer sub-agents. state in LangGraph.

expert production — fine-tuning, evals & deployment +
fine-tuning vs RAGLoRA / QLoRA RLHF & DPOquantization (GGUF, GPTQ) vLLM inferenceeval pipelines in CI/CD cost optimizationhybrid search (BM25 + semantic) graph RAGmultimodal data leakage & jailbreaksenterprise deployment agent observability (Phoenix, Langfuse)open-weight MoE serving

mindset shift: bottleneck is now evals and iteration speed, not model capability. instrument everything. treat LLM calls like db queries.

01 — foundations

core concepts

12 core concepts. click any card to go deeper. no shortcuts.

click any card to go deeper ↗

[ 001 ] LLMs
Large Language Models
transformers trained on massive text to predict next tokens. probability distribution over vocabulary is everything. GPT, Claude, Gemini, Qwen — same core architecture, different scale, data and post-training.
transformersattentiontokensRLHF
[ 002 ] RAG
Retrieval-Augmented Generation
ground your LLM in real data at inference time. prevents hallucinations about domain knowledge. chunk → embed → store → retrieve → generate. that's the loop.
embeddingsvector dbsemantic searchchromadb
[ 003 ] Agents
Agentic AI & Tool Use
LLMs that call tools, take actions, loop until goal met. the model decides what to call. langgraph makes this stateful. crewai adds roles and collaboration.
ReActtool callingplanningLangGraph
[ 004 ] Embeddings
Vector Embeddings
semantic compression of text into high-dimensional vectors. similar meaning = similar direction. text-embedding-3-small or bge-large are your go-to. dimensions matter.
cosine simada-002bgeFAISS
[ 005 ] Prompting
Prompt Engineering
system prompts, few-shot, CoT, XML tags for Claude, JSON mode, output constraints. controlling model behavior without touching weights. massively underrated. master this first.
CoTfew-shotXML tagsstructured output
[ 006 ] Fine-Tuning
Fine-Tuning & PEFT
adapting a base model to your domain. LoRA injects low-rank matrices into attention layers. QLoRA at 4-bit. use when RAG + prompting isn't enough.
LoRAQLoRAPEFTunsloth
[ 007 ] Orchestration
Multi-Agent Orchestration
routing tasks across specialized agents, managing state, handling failures. supervisor delegates to workers. LangGraph's graph state is the cleanest abstraction. harder than it looks.
LangGraphstate machinessupervisorrouting
[ 008 ] Evals
LLM Evaluation
shipping without evals is shipping blind. RAGAS for RAG pipelines. DeepEval for LLM-as-judge. LangSmith for tracing. treat evals like unit tests — run them in CI.
DeepEvalRAGASLangSmithfaithfulness
[ 009 ] MCP
Model Context Protocol
Anthropic's open standard for giving AI models access to external tools and data. the USB-C of AI integrations. build once, works across Claude, Cursor, and custom apps.
Anthropictoolsserversopen standard
[ 010 ] Chunking
Document Processing
how you split documents determines RAG quality more than model choice. recursive, semantic, parent-doc retriever. docling for structure-aware parsing of tables and headings.
doclingrecursive splitsemantic chunkingoverlap
[ 011 ] Memory
Memory & State
agents need memory. in-context (short-term), external db (long-term), episodic (past conversations). LangGraph manages state across nodes. mem0 and Zep for persistence.
in-contextmem0episodicLangGraph state
[ 012 ] Guardrails
Safety & Guardrails
constitutional AI, RLHF, output filtering, prompt injection defense. production GenAI without guardrails is a liability. NeMo Guardrails, Llama Guard. think about it day one.
RLHFNeMoprompt injectionalignment
01.5 — bigger picture

things worth knowing

beyond the technical. the strategic, the philosophical, the stuff no course teaches you.

[ 013 ] Deployment ↗
Shipping to Production

a working agent on your laptop is worthless until it's live. this is the part most tutorials skip entirely.

01Dockerize your FastAPI app. pin your base image. use python:3.11-slim. multi-stage builds to keep image small.
02streaming needs ASGI. run uvicorn app:app --workers 4. don't use --reload in prod.
03env vars: .env locally, platform secrets in prod. never hardcode keys. use python-dotenv.
04Railway = fastest zero-config. connect github repo, add env vars, done. Cloud Run for enterprise / GCP shops.
RailwayDockerCloud Runuvicornenv vars
[ 014 ] Use Case Design
How to approach any GenAI problem
define the task what's the input? what's the output? what does "correct" mean? if you can't answer these, don't write a line of code yet.
pick the pattern static data + Q&A → RAG. multi-step autonomous task → agent. domain tone/style → fine-tune. most things are RAG. don't overengineer.
eval first write 20 test cases before you write any code. if you can't measure it, you can't ship it. this is the hardest discipline to build.
start minimal one agent, one tool. add complexity only when evals break. the system that ships beats the system that's perfect.
pattern picker
answers live in your docsRAG
answers live in a databasetext-to-SQL + tools
fixed steps, known orderworkflow / chain
steps depend on what it findsagent
same decision, thousands of timesclassifier / Jev
needs a voice or format RAG can't fixfine-tune
[ 015 ] LLM Comparison · updated Nov 2026
Current model landscape
Claude Fable 5.2 / Opus 5.5 / Sonnet 5.5 / Haiku 5.5 (Anthropic) best for enterprise

Fable 5.2 (Nov 9) is the new #1 on the Artificial Analysis index, now $8/$40, but it rejects temperature / top_p. Opus 5.5 is still the recommended heavy default, Sonnet 5.5 the daily driver. Haiku 5.5 finally replaced 4.5: $0.10/$0.50 and good enough to run agents. what I build with at work.

GPT-6 Astra / 6.1 Sol / 6.1 Terra / 6 Luna (OpenAI) best ecosystem

Astra is the flagship. 6.1 Sol (DevDay) is the agent workhorse. 6.1 Terra (Oct 26) is the value pick: $1/$5 and 3x faster at computer use. gated specialists on the side: Rosalind for science, GPT-6 Cyber. Codex + Responses API is the agent story.

Gemini 4 Argon / Carbon · 3.8 Flash (Google) best context + output

Gemini 4 finally landed. Argon went to cyber defenders first, then general, with 1M output tokens. Carbon is #2 on the index but still Vertex-only. 3.8 Flash stays the speed pick, but its price doubles on Jan 1. also shipped: Harness², see new updates.

Kimi K3.1 Pro / Qwen 4 / Muse Spark Open / Mistral Large 4 (open weights) open weights

Kimi K3.1 Pro (Apache 2.0) is the best open model right now. Qwen 4 is API-only until weights drop (promised Dec 20). Meta is back with Muse Spark Open (816B, own license). Mistral Large 4 is GA. DeepSeek V4.1 Flash is the cheap multimodal pick. Qwen 3.8 27B is still my laptop model.

Jev (TypeSafe), not an LLM decisions, not text

System One model: typed Choice / Score / yes-no answers with calibrated probabilities in ~100ms. stop burning frontier tokens on routing and classification. full breakdown in the jev section below.

[ 016 ] The AI Bubble ↗
Hype vs Reality

an honest take from someone building in it

what's overvalued

GPT-4 wrappers with no moat. $100M valuations on 3-person teams with no proprietary data. "AI-powered" SaaS that's literally just a prompt + API call with a landing page.

what's actually real

companies with proprietary data + tight AI integration. the infra layer (Anthropic, OpenAI, Google). tooling. domain-specific apps with high switching costs and network effects.

where value actually sits

data flywheel + fine-tuned models + workflow integration. models are being commoditized fast. your moat is your data and your eval pipeline. build those.

01.7 — new model class

Jev: the model that doesn't talk

TypeSafe's "System One" model, launched Sep 2026. it doesn't generate text. it answers typed questions with calibrated probabilities. think of it as a smart if statement for your agent graph.

// the one-line pitch

most of the LLM calls in an agent pipeline aren't generation. they're decisions: which branch, is this safe, how urgent, is the answer grounded. Jev does only that, and does it fast and cheap.

System 1 vs System 2 (Kahneman): fast intuitive judgement vs slow deliberate reasoning. Jev is the fast one. your frontier LLM stays the slow one.

~100mstypical latency
(70–500ms range)
$0.042per 1M input tokens
output is free
0off-schema answers
it can't hallucinate a type
64ktoken budget across
state + questions
Choice
pick one of N

labeled options with descriptions, up to 255. returns the pick, the full probability distribution and a confidence score.

→ which agent handles this? which department? which tool?
Score
place on a scale

ordered levels (2–10). returns a probability-weighted score plus confidence. combine several into composite rankings.

→ how frustrated is the user? how risky is this diff? how relevant is this chunk?
Noul
yes / no as a probability

a single 0–1 probability. no confidence field, you set the threshold. that's the point: your code owns the cut-off.

→ is a refund requested? is this command destructive? is the answer grounded?
jev_router.pypython · pip install typesafe-sdk
from typesafe_sdk import TypeSafeClient, Choice, Noul

client = TypeSafeClient()  # reads TYPESAFE_API_KEY

res = client.system_one(
    state=user_message,
    questions={
        "route": Choice(
            instructions="Which specialist should handle this?",
            criteria={
                "rag":    "Question answerable from our docs",
                "sql":    "Needs numbers from the database",
                "human":  "Complaint, legal, or account change",
            },
        ),
        "urgent": Noul(instructions="Does this need a reply today?"),
    },
)

route = res.answers["route"]
if route.confidence < 0.5:
    next_node = "human"        # unsure → escalate, don't guess
else:
    next_node = route.choice
urgent = res.answers["urgent"].noul > 0.7
ask every question you might need in one call. latency comes from the shared state, not the number of questions.
where it slots into a LangGraph pipeline
user msg→ Jev: route + urgency→ RAG / SQL / human→ Claude generates→ Jev: grounded?→ reply
routingconditional edges without a frontier call. cheapest win.
tool gatingclassify a tool call as read-only / reversible / destructive before it runs. LangChain ships an AutoModeMiddleware for this.
guardrailsemergency / self-harm / PII / prompt-injection flags on every turn, at a cost you can actually afford per message.
eval checks"is this claim supported by the context?" as a Noul. a fast pre-filter before LLM-as-judge.
bulk labelingclassify 100k tickets, reviews or papers for cents. TypeSafe's own demo labeled ~1k papers for $0.08.
re-rankingScore retrieved chunks for relevance before they hit the context window.
use it when

the answer is one of a known set of options. you make the same decision thousands of times. latency matters (voice, chat, agent loops). you want a probability you can threshold instead of a string you have to parse.

don't use it for

writing prose or code. math, counting, or extracting dates and numbers (do that in code). images, audio or video (text in only, for now). anything needing more than ~32k tokens of state. open-ended reasoning: that's still your LLM's job.

honest caveats

brand new (Sep 2026), closed weights, architecture not published. the "40–400x cheaper" numbers are TypeSafe's own benchmarks on their own workflows. run it against your golden set before ripping out a working classifier.

01.8 · new updates

new updates

new models, tools and techniques as they ship, and what they change about how you build. dates are public release dates, prices are per 1M input / output tokens. latest batch: sep to nov 2026.

anthropic
nov 09Claude Fable 5.2new #1 on the Artificial Analysis index (65). 1M ctx, 128k out. $8/$40, first price cut on the Fable line. breaking: temperature / top_p / top_k now error, forced tool choice is gone. Mythos 5.2 stays restricted.
oct 07Claude Haiku 5.5the router got good. $0.10/$0.50 under 100k tokens (5x above), effort levels low → max, first Haiku that works as an actual agent.
sep 28Claude Sonnet 5.5replaces Sonnet 5 at the same price. daily driver for docs + tool loops.
sep 22Claude Opus 5.5beats Fable 5.1 on most coding evals at a fraction of the price. still the recommended heavy default.
openai
nov 05GPT-6 Cyberrestricted, approval only. same story as Rosalind (oct 30) for science orgs. gated specialist models are now a pattern, not a one-off.
nov 04GPT Image 2.6Sunburst + Flare image models.
oct 26GPT-6.1 Terrathe sleeper. $1/$5, built for computer use + screenshots, 3x+ faster than Astra / 6.1 Sol on those tasks. gpt-6.1-terra.
sep 29GPT-6.1 SolDevDay. mid-tier agent workhorse that fixes Astra's cost problem. lineup is now Astra → Sol → Terra → Luna.
google
nov 10–12Gemini 4 Carbon / Hydrogenon Vertex. Carbon sits #2 on the AA index (60). no clean public purchase path yet, watch this space.
sep 30 → oct 13Gemini 4 Argonthe long-delayed flagship (replaced the 3.5 Pro plan). cyber defenders first, then general. 1M output tokens, up from 64k. intro $2/$10 doubles to $4/$20 on dec 1.
oct 09Harness²open-source agent self-improvement framework. full breakdown below.
heads up3.8 Flash pricedoubles to $1.50/$7.50 on jan 1, 2027. re-run your cost model.
open weights + others
nov 11Qwen 4 (Alibaba)1.2T sparse MoE, API at $1/$4. Apache 2.0 weights promised by dec 20, not out yet.
nov 05Mistral Large 4GA with open weights per the model card, after an oct 6 preview.
nov 04Kimi K3.1 ProApache 2.0, 2.8T total / 104B active. best open model on the index right now.
oct 15Muse Spark Open (Meta)816B / 42B active, 1M ctx. Meta is back in open weights, but under its own Muse license, not Apache. runs on two M5 Ultra Mac Studios.
sep–octDeepSeek V4.1 Flash · GLM 5.3 · Grok 4.7V4.1 Flash went native multimodal (refreshed oct 17, same price). DeepSeek also started billing search/fetch APIs.
what I'd change this week

swap Haiku 4.5 → 5.5 for routing and extraction, it's cheaper and smarter. try GPT-6.1 Terra for anything that reads screenshots or drives a UI. keep Opus 5.5 / Sonnet 5.5 as the default stack.

what will bite you

Fable 5.2 rejects sampling params, so any wrapper that hardcodes temperature=0 breaks. Gemini price doubles in dec / jan. model IDs churn fast: DeepSeek V4 Flash lived six weeks. pin IDs, wrap them in config.

the actual trend

the frontier is splitting into public models and gated specialists (Mythos, Rosalind, Cyber, Argon-for-defenders). and the gains people are chasing are moving out of the weights and into the harness. more on that below.

[ 017 ] google research · apache 2.0 · oct 2026

Harness²: agents that rewrite their own harness

the harness is everything around the model: system prompt, tools, memory, skills, guardrails. Harness² keeps the weights frozen and lets the agent edit that layer, but only keeps an edit if a side-by-side run proves it changed behaviour. no ground-truth labels needed. it's a research framework, not a supported Google product.

01 · propose
two candidate edits

after a reference run of the current harness, the editor proposes one general fix (better tool use, say) and one task-specific fix (a checking step for spreadsheets, say).

→ diffs to markdown / python / ts files, not to weights
02 · probe
run both, same conditions

each candidate runs on the same task with the same model and environment. behaviour gets compared against the reference run.

→ evidence over vibes: a plausible explanation isn't enough
03 · compose
keep what's proven

only edits with observed behavioural differences make it into the composed harness. then a reflector writes lessons to EXPERIENCE.md in a per-domain library for future tasks.

→ level 2 recursion: learning across tasks, not just within one
the 8 editable componentswhat Harness² is allowed to touch
harness/
├── systemprompt.md          # overarching instructions
├── guardrails.md            # written constraints (NOT a security boundary)
├── LongTermMEMORY.md        # persistent context
├── tool_guidance.md         # how to pick + use tools
├── sub_agents/<name>/AGENT.md  # delegated roles
├── skills/<name>/SKILL.md      # reusable procedures
├── scripts/<name>.py          # executable helpers
└── plugin/<name>.ts           # middleware around execution

# try the credential-free demo (shows the mechanics, not benchmark gains)
git clone https://github.com/google-research/harness2.git
cd harness2 && uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install -e '.[render]'
harness2-demo --output runs/demo --k 2
look familiar? it's the same shape as a Claude Code / Agent SDK project: CLAUDE.md, skills, subagents, hooks. Harness² is basically automated harness engineering for that layout.
numbers + the bill
WorkBuddy64.2 → 75.7 (+11.5) with GLM-5 under OpenCode. +5.1 with Gemini 3.5 Flash.
JobBench31.5 → 36.0 (+4.5) with Gemini 3.5 Flash.
LAB59.6% → 71.4% partial pass with GLM-5. all author-reported, one improvement step.
cost4k executor rollouts per task: k reference + k general + k domain + k composed. 4 runs at k=1, 20 at k=5. plus editor, reflector and selector calls on top.
metrictrack cost per accepted outcome, not cost per token. a 10% better agent at 4x the runs can easily lose.
safetyexecutor network isn't restricted and the Codex sandbox is off by default. one validation run fetched a grading rubric on its own. sandbox it, cap spend externally (--max-tasks caps tasks, not dollars).
[ 018 ] tool · pip install pydot · MIT

pydot: draw your agent graph as code

pure-python interface to Graphviz's DOT language. build, parse and render graphs from code. the useful bit for us: turn a compiled LangGraph into a real diagram for docs, PRs and design reviews, with clusters, colours and conditional edges styled the way you want. Mermaid is fine for a README. DOT is what you reach for when the graph gets big.

draw_graph.pypython · needs graphviz binary (apt / brew install graphviz)
import pydot

def langgraph_to_dot(app, name="agent") -> pydot.Dot:
    g = app.get_graph()  # compiled StateGraph → drawable graph
    dot = pydot.Dot(name, graph_type="digraph", rankdir="LR",
                    bgcolor="transparent", fontname="monospace")
    for node_id in g.nodes:
        terminal = node_id in ("__start__", "__end__")
        dot.add_node(pydot.Node(
            f'"{node_id}"',  # quote ids: DOT chokes on some names
            shape="circle" if terminal else "box",
            style="rounded,filled", fillcolor="#1e1b4b", fontcolor="white"))
    for e in g.edges:
        dot.add_edge(pydot.Edge(
            f'"{e.source}"', f'"{e.target}"',
            style="dashed" if e.conditional else "solid",
            color="#a78bfa" if e.conditional else "#22d3ee"))
    return dot

dot = langgraph_to_dot(app)
dot.write_svg("agent.svg")       # or write_png / write_pdf
print(dot.to_string())         # raw DOT: diff it in PRs
conditional edges dashed, normal edges solid. commit the .dot next to the code and your architecture diagram can't drift from reality.
pydot cheatsheet
buildpydot.Dot(graph_type="digraph"), then add_node / add_edge. any Graphviz attribute is a kwarg.
parsepydot.graph_from_dot_data(s) returns a list of graphs. take [0].
grouppydot.Cluster("rag", label="retrieval") draws a box around a subgraph. great for supervisor / worker layouts.
renderwrite_svg, write_png, create_png() for bytes (e.g. streamed from FastAPI).
networkxnx.drawing.nx_pydot.to_pydot(G) and back. handy for knowledge graphs in GraphRAG.
gotchas"dot not found" means the Graphviz binary is missing, not pydot. names with : or spaces need quoting. DEBUG logging can dump graph contents, so watch it with sensitive data.
vs othersgraphviz pkg = thinner wrapper, no parser. pygraphviz = C bindings, painful installs. pydot = pure python, easiest to ship.
01.9 · inside the model

activation steering

prompting changes the input. fine-tuning changes the weights. steering changes the model's internal activations at inference time: find the direction for a concept, add it to the residual stream, and the behaviour shifts. no training run, no prompt.

// the core idea in one line

concepts look roughly linear inside a transformer. so take the mean activation on prompts that show a behaviour, subtract the mean on prompts that don't, and you get a vector. add α · v at layer L and the model leans toward that behaviour. subtract it and it leans away.

h′ = h + α·v, where v = mean(h | positive) − mean(h | negative). that's contrastive activation addition (CAA). Golden Gate Claude was the famous demo of the same family, using a sparse-autoencoder feature instead of a contrastive mean.

0gradient steps
no training
~100contrast pairs is
often enough
1 vecper behaviour
a few KB on disk
αone dial for strength
too high = gibberish
1 · collect
contrast pairs

same prompt, two completions: one with the behaviour, one without. "answer honestly" vs "answer sycophantically". keep everything else identical so the difference is just the concept.

→ quality of the pairs = quality of the vector
2 · extract
difference of means

run both sides through the model, grab residual-stream activations at a middle layer (roughly 30–60% depth works best), average the differences. PCA on the diffs is the common alternative.

→ sweep layers. the right one varies by model and concept
3 · apply
hook + scale

register a forward hook that adds α·v to that layer's output on every token. tune α on a small eval: watch the target metric and a fluency metric at the same time.

→ negative α ablates. same vector, both directions
steer.pypython · torch + transformers · open-weights models only
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

name = "Qwen/Qwen2.5-7B-Instruct"   # any llama-style decoder
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.bfloat16, device_map="auto")
LAYER = 14

@torch.no_grad()
def last_token_act(text):
    ids = tok(text, return_tensors="pt").to(model.device)
    hs = model(**ids, output_hidden_states=True).hidden_states
    return hs[LAYER + 1][0, -1]  # [0] is embeddings, so +1

# pairs: list of (positive_text, negative_text)
diffs = [last_token_act(p) - last_token_act(n) for p, n in pairs]
v = torch.stack(diffs).mean(0)
v = v / v.norm()

def make_hook(alpha):
    def hook(module, inp, out):
        h = out[0] if isinstance(out, tuple) else out
        h = h + alpha * v.to(h.dtype)
        return (h,) + out[1:] if isinstance(out, tuple) else h
    return hook

handle = model.model.layers[LAYER].register_forward_hook(make_hook(8.0))
try:
    out = model.generate(**tok(prompt, return_tensors="pt").to(model.device), max_new_tokens=200)
finally:
    handle.remove()   # always unhook, or every later call stays steered
α depends on the residual norm at that layer. start around 4–12 for a unit vector on a 7B model and sweep. if you don't want to hand-roll it: repeng wraps this whole loop in about ten lines.
steering vs prompting vs fine-tuning
promptingcheapest, works on closed APIs, but costs context every call and can be overridden by a clever user.
steeringno tokens, no training, adjustable live via α, reversible. needs open weights and access to activations.
fine-tuningmost robust for format and style, but it's a training run, a new artifact to host, and it's sticky.
where it's actually useful
monitoringdot-product live activations with a vector to detect a trait (sycophancy, refusal, "evil") before it shows in the text. Anthropic's persona vectors work does exactly this.
behaviour dialsformality, verbosity, refusal rate, honesty, as a slider instead of a prompt rewrite.
data vettingscore fine-tuning data by how hard it pushes along a bad direction, and drop the worst before training.
researchif adding v changes behaviour, the concept is causally used there, not just correlated. that's the interpretability payoff.
use it when

you self-host open weights (vLLM, TGI, local) and want a cheap, tunable behaviour knob. you want to monitor traits, not just filter outputs. you're doing interpretability or safety research.

don't bother when

you're on Claude / GPT / Gemini APIs: no activation access, full stop. you need precise facts or formats: steering shifts tendencies, it doesn't add knowledge. a two-line system prompt already does the job.

honest caveats

vectors are model- and layer-specific, they don't transfer. high α degrades fluency and general capability, so eval both. concepts aren't perfectly linear: you'll steer side effects too. it's a dial, not a guardrail.

01.10 · retrieval playbook

chunking, indexing, retrieval, reranking

most bad RAG answers are retrieval bugs, not model bugs. if the right chunk never reaches the context window, no model can save you. four stages, each with real trade-offs.

parse→ chunk→ embed→ index→ rewrite query→ retrieve top-50→ rerank → top-5→ generate
01chunking strategieshow you cut decides what can be found
fixed-size

split every N tokens with overlap. dumb, fast, predictable. cuts sentences and tables in half.

baseline / logscost: none
recursive character

try paragraph breaks, then lines, then sentences, then words, until it fits. respects natural boundaries. the sane default: 400–800 tokens, 10–15% overlap.

default for prosecost: none
structure-aware

split on the document's own structure: headings, sections, tables, code blocks, slides. Docling / Unstructured / markdown header splitters. keep the heading path as metadata.

PDFs, policies, docscost: parsing
semantic

embed each sentence, start a new chunk where similarity between neighbours drops. topic-coherent chunks, but uneven sizes and an embedding pass at ingest.

long unstructured textcost: embeddings
parent-child (small-to-big)

embed small chunks for precise matching, but return their larger parent section to the LLM. precision on search, context on generation. my default for real docs.

most production RAGcost: 2 stores
contextual chunks

prepend an LLM-written line to each chunk saying where it sits ("from the 2026 fees policy, refunds section") before embedding and BM25. Anthropic reported big cuts in failed retrievals, bigger with a reranker.

chunks that lose meaning alonecost: 1 LLM call / chunk (cache it)
late chunking

run the whole document through a long-context embedding model first, then pool token embeddings per chunk. every chunk vector "saw" the full doc, so pronouns and references survive.

cross-references, contractscost: long-ctx embedder
propositions / agentic

an LLM rewrites text into atomic, self-contained facts, or decides the cut points itself. highest quality on dense material, slowest and most expensive ingest.

FAQs, knowledge basescost: LLM over full corpus
02indexing techniqueshow you store decides how fast and how well you search
flat (exact kNN)

compare the query to every vector. perfect recall, linear cost. totally fine up to ~100k vectors. don't over-engineer a small corpus.

<100k chunksrecall: 100%
HNSW

layered proximity graph, greedy search from the top layer down. the default ANN index in pgvector, Qdrant, Chroma, Weaviate. tune M, ef_construction, ef_search.

default ANNmemory heavy
IVF + PQ

cluster vectors (IVF), only search the nearest clusters (nprobe), compress them with product quantization. FAISS / Milvus territory once you're into tens of millions.

10M+ vectorstrades recall for RAM
quantization

store vectors as int8 or binary instead of float32. binary is ~32x smaller. search the cheap version first, rescore the top candidates with full precision.

cost / memory cutssmall recall hit
inverted index (BM25)

classic keyword search. catches what embeddings miss: product codes, names, error strings, acronyms. never ship a production RAG without it.

exact terms, IDscheap
learned sparse (SPLADE)

a model expands text into weighted vocabulary terms, then you search it like an inverted index. keyword precision with some synonym awareness.

hybrid without 2 systemsmodel at ingest
multi-vector (ColBERT)

one vector per token, scored with late interaction (MaxSim). much better at fine-grained matching, much bigger index. ColPali does the same on page images, skipping parsing entirely.

hard / visual docsstorage ×10–100
hierarchical / graph

RAPTOR builds a tree of cluster summaries for "what's this whole corpus about" questions. GraphRAG extracts entities + relations for multi-hop questions. also cheap and underrated: index LLM-generated questions per chunk.

global + multi-hop Qsheavy ingest
03retrievalget high recall first. precision comes in step 04
[ search modes ]
denseembedding similarity. great at meaning, bad at exact strings.
sparseBM25 / SPLADE. great at exact strings, bad at paraphrase.
hybridrun both, fuse with RRF. almost always beats either alone.
RRFscore = Σ 1/(k + rank), k≈60. rank-based, so no score normalising headaches.
filterspre-filter on metadata (tenant, date, doc type) before vector search. also your access control.
[ query transforms ]
rewriteturn chatty follow-ups into standalone queries using chat history. biggest win in chatbots.
multi-querygenerate 3–5 phrasings, retrieve for each, fuse with RRF.
HyDEhave the LLM write a fake answer, embed that instead of the question. answers look like answers.
decomposesplit multi-part questions into sub-queries. retrieve each separately.
self-queryLLM extracts metadata filters from the question ("2026 fees for MBA" → year, program).
[ agentic retrieval ]
retrieval as toollet the agent decide when and what to search. skip retrieval for small talk.
CRAGgrade retrieved chunks. if they're weak, rewrite and search again, or fall back to web.
iterativeretrieve → read → retrieve again for multi-hop. cap the loops.
MMRdiversify results so top-5 isn't five near-duplicates.
long context1M windows don't kill RAG. cost, latency and lost-in-the-middle still do.
04rerankingthe cheapest big quality jump in RAG
hybrid_rerank.pypython · retrieve wide, rerank narrow
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")

def rrf(rank_lists, k=60):
    scores = {}
    for ranks in rank_lists:
        for pos, doc_id in enumerate(ranks):
            scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + pos + 1)
    return sorted(scores, key=scores.get, reverse=True)

def retrieve(query, top_n=5):
    dense  = vector_store.search(query, k=50)   # ids by cosine
    sparse = bm25.search(query, k=50)           # ids by BM25
    candidates = rrf([dense, sparse])[:50]   # high recall

    pairs = [(query, docs[i].text) for i in candidates]
    scores = reranker.predict(pairs)          # joint query+doc scoring
    ranked = sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)

    # drop junk instead of always stuffing top_n
    return [docs[i] for i, s in ranked[:top_n] if s > 0.2]
bi-encoders embed query and doc separately (fast, fuzzy). cross-encoders read them together (slow, sharp). so: bi-encoder for 50, cross-encoder for 5. the 0.2 threshold is a placeholder, tune it on your golden set.
reranker options
cross-encoderbge-reranker-v2-m3, mxbai, ms-marco MiniLM. self-hosted, multilingual options, ~20–100ms for 50 docs on GPU.
hosted APICohere Rerank, Voyage, Jina. one call, no GPU. easiest upgrade to an existing pipeline.
late interactionColBERT as a reranker over first-stage results. good middle ground on speed vs quality.
LLM rerankerask a small model (Haiku 5.5, Terra) to rank or score chunks listwise. best on reasoning-heavy relevance, slowest and priciest.
Jev Scoretyped relevance score with calibrated confidence, fast enough to run per chunk. see the Jev section.
defaults I'd ship
chunkstructure-aware parse + recursive split, parent-child, contextual header on each chunk.
indexHNSW + BM25 in the same store (pgvector + tsvector, or Qdrant hybrid). metadata on everything.
retrieverewrite query → hybrid top-50 → RRF.
rerankcross-encoder → top-5 with a score floor.
measurerecall@50 for retrieval, nDCG@5 / MRR for rerank, RAGAS on the final answer. tune the stage that's actually failing.
01.6 — use case breakdown

PE Due Diligence Automation

a client comes to you with a problem. walk through how to deconstruct any GenAI use case — what to build, what to skip, and why.

// real use case — why this example
why this use case

PE due diligence is the ideal GenAI use case — structured inputs (PDFs), structured outputs (fixed report template), bounded reasoning, measurable quality. if you understand how this pipeline was built, you can build any enterprise document workflow.

what the diagram shows

this is the actual architecture of Verdikt — every node is a real agent or processing step. edges show real data flow. click any node to see the exact model, tools, inputs and outputs used in production.

apply it to your use case

swap "CIM Document" for any domain document. the supervisor → specialist → writer pattern works for legal contracts, medical records, financial filings, procurement docs — any structured document workflow.

click any node to inspect
start INPUT CIM Doc PDF · 184 pages PARSER Docling 342 chunks SUPERVISOR LangGraph Claude Sonnet 4.6 SPECIALIST Researcher Groq · Tavily · ChromaDB SPECIALIST Analyst Claude · Pydantic WRITER Writer Agent Claude Sonnet 4.6 OUTPUT DD Report ~90 seconds end [ parallel execution ] AgentState { messages, cim_chunks, researcher_output, analyst_output, report }
← swipe to see the full pipeline →
— click any node to inspect it —
the business problem

PE analysts spend 40–60 hrs per deal manually reading CIM documents, pulling news, checking financials, and writing the same structured due diligence report. the output format never changes. the work is high-volume, repetitive, and rule-driven.

why GenAI fits here

the inputs are structured (PDFs, web data). the output is structured (a fixed report format). the reasoning is bounded — not open-ended creativity. there's domain knowledge that can be encoded. measurable quality. this is the sweet spot.

what we shipped

multi-agent system (Verdikt). supervisor routes to researcher, analyst, writer. full report in ~90 seconds. the same architecture applies to any consulting, legal, or financial document workflow.

decision 01 what pattern fits this use case? → multi-agent +
✗ fine-tune
fine-tuning gives you style, not capability. you can't fine-tune a model to browse the web or query a vector DB. it's the wrong tool for tasks that require live data access and multi-step reasoning.
~ RAG only
RAG handles "answer questions from documents" well. but this use case requires: search the web → pull the CIM → cross-reference financials → structure a report. RAG doesn't orchestrate across steps — it just retrieves. you need something that can plan.
✓ multi-agent with RAG inside
the task decomposes cleanly: research (web + docs) → analyse (financial reasoning, risk) → write (structured output). each step is a specialist with its own tools. RAG lives inside the researcher agent. the supervisor orchestrates the flow. LangGraph manages state across all of them.
rule: if a human would break the task into distinct phases with different skills — it's multi-agent. if it's one Q&A interaction over documents — RAG is enough.
decision 02 which model? cost vs quality tradeoff → depends on the context +
✗ one model for everything
using a frontier model for every step including simple routing and classification burns money and adds latency. a PE firm processing 50 deals/month can't afford $0.30 per report step multiplied across 200 LLM calls.
~ Claude for everything
Claude Sonnet is excellent for document analysis and structured output. but using it for classification routing and simple transformations is overkill. reserve heavyweight models for heavyweight tasks.
✓ tiered model selection
routing + classification → Jev (typed decisions, ~100ms, fractions of a cent) or Claude Haiku 4.5 / GPT-6 Luna. document analysis → Claude Sonnet 5.5. deep financial reasoning → Claude Opus 5.5 or GPT-6 Sol. dev/prototyping → DeepSeek V4 Flash / Qwen 3.8 locally. the right model for the right step.
rule: route cheap tasks to cheap models. only pay for reasoning power when the task actually needs reasoning.
decision 03 how do you handle the input documents? → docling + chromadb +
✗ pypdf + naive chunking
CIM documents have financial tables, section headers, and structured data. pypdf strips all of that and returns a flat blob of text. you lose 40% of the signal before the model even sees it. never use this for structured financial documents.
~ stuff everything in context
works with Gemini's 1M context window, but expensive and slow. also doesn't scale when each deal has 200 pages of attachments. retrieval is still better architecture than long-context stuffing for production workloads.
✓ Docling → chunk → ChromaDB
Docling preserves table structure, headings, and section hierarchy — critical for financials. semantic chunking at 512 tokens, 50 overlap. ChromaDB for local dev, pgvector or Qdrant for production scale. hybrid retrieval (BM25 + semantic) for best recall.
rule: if your documents have tables or structured sections, use structure-aware parsing. docling > everything else for financial and legal docs.
decision 04 how many agents and what architecture? → supervisor + 3 specialists +
✗ single agent, all tools
one agent with 8 tools, a massive prompt, and a multi-step task loses track of what it's doing. context gets bloated. the model starts confusing its own outputs. quality degrades hard past ~5k tokens in the agent loop.
✓ supervisor + 3 specialists
Researcher — Tavily web search + ChromaDB RAG. focused on finding information. 2 tools max.
Analyst — financial ratio calculation, risk scoring, competitive positioning. gets researcher's output as context.
Writer — takes analyst output, generates structured Pydantic report. no tools, pure generation.
The supervisor routes between them. each has a tight prompt and a clear job. output quality is dramatically better.
rule: specialisation beats generalisation in agents. a focused agent with 2 tools outperforms a god-agent with 10. decompose until each agent has one clear job.
decision 05 how do you measure if it's actually working? → structured output + RAGAS +
✗ vibe check / manual review
not scalable. when a PE analyst says "looks good", what exactly looks good? you have no baseline. you can't track regression. you don't know if a prompt change made things better or worse. subjective review is not an eval.
✓ pydantic schema + ragas metrics
Pydantic output model validates structure on every call — if the agent produces a malformed report, it fails immediately. RAGAS measures faithfulness (are claims grounded in source docs?), context precision (did retrieval get the right chunks?), and answer relevancy. 20 golden test cases with known-good answers. run in CI on every prompt change.
rule: Pydantic is your minimum eval. RAGAS is your baseline. LLM-as-judge is your ceiling. ship none of these and you're flying blind.
02 — curated resources

the reading list

everything i actually used to learn and build. all links verified.

papertopicwhy read it
foundational
the transformer paper. read this once and everything makes sense.
free
RAG
the original RAG paper. foundational for understanding why retrieval matters.
free
agents
the foundational agentic pattern. backbone of most agent frameworks today.
free
RAG
adds a retrieval evaluator that fixes bad retrievals before generation. major quality boost.
free
fine-tuning
the PEFT paper that changed fine-tuning. inject trainable matrices, freeze everything else.
free
agents + RAG
comprehensive 2025 survey. multi-agent retrieval, adaptive RAG, all current approaches.
free
LLMs
how OpenAI evaluated and aligned GPT-4. useful for understanding RLHF in practice.
free
architecture
mixture of experts architecture. explains how models scale efficiently, and why every big open model is MoE now.
free
reasoning
RL-trained reasoning without a mountain of human labels. explains why every model now "thinks" before answering.
free
long context
models ignore stuff buried mid-context. still the best argument for retrieval + ordering over context stuffing.
free
RAG
model decides when to retrieve and critiques its own output. the idea behind most adaptive RAG graphs.
free
steering
contrastive activation addition. the cleanest intro to steering vectors.
free
chunking
embed the whole doc first, chunk after. chunks keep their context.
free
graph RAG
Microsoft's community-summary approach. read it before bolting a knowledge graph onto your RAG.
free
coursetypewhat you learn
course
Andrew Ng + OpenAI. best practices, iterative development, summarization, chatbots. start here.
free
course
state machines, tool use, HITL. the most practical agent course available.
free
course
chains, memory, agents. foundation before jumping to LangGraph.
free
course
graph RAG with Neo4j. structured + unstructured retrieval. growing area.
free
course
transformers library from the people who built it. tokenizers, models, fine-tuning.
free
course
Azure OpenAI, responsible AI. good for enterprise / Azure-focused work.
free
course
evals, debugging, experiment tracking. most engineers skip this too long.
free
course
router, tool, multi-document agents. LlamaIndex approach. good complement to LangGraph course.
free
course
reflection, tool use, planning, multi-agent. framework-agnostic, so the patterns stick after the libraries change.
free
course
packaging instructions + scripts as reusable skills. the cleanest way to give agents procedural knowledge.
free
course
agents from first principles with smolagents, LangGraph and LlamaIndex. certificate if you care.
free
course
build and consume MCP servers end to end. do this before writing your own integrations.
free
blog / docstypewhy
blog
definitive survey on agentic systems. read before building any agent.
free
blog
patterns, antipatterns, when NOT to use agents. essential reading.
free
docs
XML tags, CoT, structured outputs. canonical reference for Claude prompting.
free
docs
official tutorials. actually great docs. read them top-to-bottom once.
free
docs
context precision, faithfulness, answer relevancy. learn the eval metrics deeply.
free
docs
LoRA, QLoRA, adapters. canonical fine-tuning reference. consumer hardware friendly.
free
docs
structure-aware document parsing. tables, headings, figures. use this not pypdf.
free
blog
production GenAI on Bedrock. real case studies. good for enterprise patterns.
free
blog
prompt engineering grew up. what goes in the window, what gets compacted, what lives in memory.
free
blog
real orchestrator-worker lessons from production: token budgets, delegation prompts, evals.
free
blog
error analysis first, metrics second. the most practical eval writing out there.
free
blog
the whole year in one read: Fable, GPT-6, open-weight surge, coding agents. best catch-up post.
free
docs
how Jev thinks: Choice, Score, Noul primitives, confidence, when to escalate to a human.
free
repotypewhat's inside
repo
comprehensive agent tutorials from basic to advanced. LangGraph, tools, multi-agent. gold mine.
free
repo
interview prep, research updates, RAG papers table, notebooks. consistently maintained.
free
repo
modular agentic RAG with LangGraph, conversation memory, HITL. cleanest beginner repo.
free
repo
the source. read examples/. agentic RAG, CRAG, adaptive RAG notebooks are essential.
free
repo
pytest for LLMs. LLM-as-judge, hallucination detection, RAG metrics. integrates with CI/CD.
free
repo
minimal GPT-2 in ~300 lines of pytorch. best way to understand LLM internals.
free
repo
every major RAG paper 2023–2025. EMNLP 2025. go here for deep RAG research.
free
repo
alternative to LangChain for data-heavy RAG. better for complex ingestion pipelines.
free
repo
official recipes: tool use, RAG, sub-agents, prompt caching, skills. copy-paste ready.
free
repo
reference MCP servers. read two of these and you can write your own in an afternoon.
free
repo
the default for serving open-weight models. paged attention, batching, OpenAI-compatible API.
free
repo
fastest LoRA / QLoRA fine-tuning on a single GPU. notebooks for basically every open model.
free
video / channeltypewhat you get
video
builds GPT-2 from zero. no better way to understand transformers. watch before any framework.
free
video
non-technical intro to LLM capabilities and limitations. best beginner video.
free
video
3.5 hours: pretraining, SFT, RL, tool use, why models hallucinate. the modern successor to Intro to LLMs.
free
channel
former OpenAI, former Tesla AI. every video is essential.
free
channel
practical LangChain and LangGraph tutorials. best applied agent engineering channel.
free
channel
visual explanations of backprop, attention, transformers. understand the actual math.
free
lecture
Stanford's academic LLM course. architecture, capabilities, harms, social impact.
free
tooltypeuse it for
framework
stateful multi-agent orchestration as graphs. best abstraction for complex workflows.
free
framework
role-based multi-agent. agents have roles, goals, backstories. crew-style collaboration.
free
vector db
easiest vector db locally. persistent, Python-native. great for dev and hackathons.
free
framework
async Python APIs. standard for LLM backends. pairs perfectly with LangGraph.
free
eval
pytest for LLMs. LLM-as-judge, RAG metrics, hallucination detection. runs in CI/CD.
free
inference
fast LLaMA inference via LPU chips. free tier is generous. good for hackathons.
free tier
parsing
structure-aware doc parsing. tables, headings, figures. use instead of pypdf.
free
deploy
easiest deploy for FastAPI + LangGraph. github integration, auto-redeploy. what I use.
free tier
decisions
typed routing, gating and labeling at ~100ms. $0.042 per million input tokens, output free.
usage-based
observability
open-source tracing + evals for agents. OpenTelemetry native. what Flightcheck runs on.
free
observability
self-hostable LangSmith alternative. traces, prompt versions, datasets, cost tracking.
free
local LLMs
one command to run Qwen, DeepSeek, Mistral locally. perfect for offline dev and cost-free prototyping.
free
agents
Google Research's self-improving agent harness. edits prompts, skills, tools; keeps only proven changes.
free
viz
pure-python Graphviz DOT. render your LangGraph to SVG for docs and PRs.
free
steering
control vectors for open-weights models in a few lines. easiest way into activation steering.
free
reranker
open multilingual cross-encoder. the default self-hosted reranker.
free
benchmarks
independent quality / speed / price comparisons. check here before trusting a launch blog.
free
akriceus@dev:~$ ls ./projects --filter=hackathon
novaDD/ — m&a due diligence | bedrock nova · 🏆 winner
flightcheck/ — agent that monitors agents | arize phoenix
tribal-knowledge/— slack history → cited answers
blast-radius/ — MR impact review | gitlab knowledge graph
vaultdesk/ — auth0 token vault + langgraph | live
...8 more — scroll down
akriceus@dev:~$ ▋
03 — shipped

projects

not tutorials. real code, real architecture decisions, real tradeoffs. 13 builds, 21 hackathons, 1 win so far.

🏆 winner
NovaDD
amazon nova AI hackathon winner. four agents work a whole data room: financials, contracts, compliance. outputs a weighted deal score with a proceed / pass call. 4-engineer team.
Amazon BedrockNova Extended ThinkingChromaDBLangGraph
hackathon
Flightcheck
an autonomous agent that watches your other agents. reads live traces from Arize Phoenix, catches quality degradation and files alerts with no human in the loop.
Arize PhoenixOpenTelemetryLLM-as-judgeagents
hackathon
Tribal Knowledge Agent
turns scattered Slack history into direct answers with citations. detects conflicting answers across threads and says so when there is no answer at all.
Slack APIRAGcitationsconflict detection
hackathon
Blast Radius Reviewer
know what breaks before you merge. uses GitLab Orbit's knowledge graph to map merge-request impact, visualise dependency risk and post AI review comments.
GitLab Orbitknowledge graphcode reviewagents
live
VaultDesk
auth0 "authorized to act" hackathon. M&A deal agent that searches Gmail and drafts replies, but only sends after you approve via Auth0 Guardian push. Token Vault keeps credentials off the agent.
LangGraphAmazon Nova LiteAuth0 CIBAToken VaultRailway
hackathon
Verdikt
HackHazards '26. multi-agent PE due diligence. five agents on financials, risk, market and ops, ending in a GO / NO-GO investment report. the pipeline deconstructed above.
GroqCrewAITavilyChromaDB
hackathon
Gemini VDR
Gemini Live API hackathon. ask questions about deal documents by voice in real time. Live API + WebSocket pipeline + Cloud Run.
Gemini Live APIWebSocketsPyAudioCloud Run
// more builds
// hackathons

build on Devpost

Devpost is where hackathons live. free to join, thousands of prizes, and genuinely the fastest way to go from idea → shipped product → portfolio piece in 48–72 hours. almost every project above started as a hackathon submission. the quality bar is lower than you think. just ship.

21hackathons
12submissions
1win
01pick a hackathon with a sponsor whose API you want to learn (Auth0, AWS, Google) — the constraint forces you to actually ship
02build the demo video first. judges watch 90 seconds max. demo > code quality
03modular architecture from day 1. you will refactor at 3am. make it survivable
04build something you would actually use. the ones that win solve a real annoyance with a sharp demo, not the biggest architecture diagram
browse hackathons on devpost ↗ my devpost ↗
04 — stay current

newsletters worth reading

the ones that actually keep you ahead. all free to subscribe.

daily
Alpha Signal
curated AI research papers, repos, and tools. signal-to-noise ratio is actually high. best for staying on top of what's shipping.
alphasignal.ai ↗
daily
TLDR AI
3-minute daily brief on AI/ML. papers, product launches, funding. great for busy mornings when you can't read everything.
tldr.tech/ai ↗
weekly
The Batch — DeepLearning.AI
Andrew Ng's weekly. covers research, applications, and the business of AI. consistent quality. good for the broader picture.
deeplearning.ai/the-batch ↗
weekly
Import AI — Jack Clark
Jack Clark (Anthropic co-founder). deep analysis of AI research and policy. technical but accessible. some of the best takes in the field.
importai.substack.com ↗
weekly
Interconnects
Nathan Lambert (Ai2). deep dives on alignment, RLHF, and open-source models. technical depth without the hype. best writing on model training.
interconnects.ai ↗
daily
Ben's Bites
Ben Tossell's daily AI news digest. covers tools, products, and use cases. more product-focused than research-focused. good for the applied side.
bensbites.com ↗
weekly
Last Week in AI
comprehensive weekly roundup of AI news. covers research, industry, policy. great for catching up if you missed the week.
lastweekin.ai ↗
weekly
The Rundown AI
500k+ readers. covers the biggest AI developments of the week in plain english. good onboarding read for people new to the space.
therundown.ai ↗
weekly
Latent Space
swyx + Alessio. the AI engineer's podcast and newsletter. deep interviews with people shipping agents, evals and infra.
latent.space ↗
daily
Simon Willison's Weblog
hands-on notes on every model launch, usually within hours. skeptical, practical, and he actually runs the stuff.
simonwillison.net ↗
05 — quick reference

engineer's cheatsheet

the things you forget and google at 2am.

[ RAG pipeline ]
1. loadparse with Docling (not pypdf). preserve structure.
2. chunkrecursive, 512 tokens, 50 overlap. semantic > fixed for complex docs.
3. embedtext-embedding-3-small (fast) or bge-large (quality).
4. storeChromaDB (local), pgvector (prod), Qdrant (scale).
5. retrievehybrid top-50 → RRF → cross-encoder → top-5. see retrieval playbook.
6. generateinject context, instruct no hallucination. stream it.
7. evalRAGAS: faithfulness + ctx_precision + answer_relevancy.
[ LangGraph patterns ]
StateGraphdefine state schema with TypedDict or Pydantic.
add_nodeeach node is a function: state → updated state.
add_edgedeterministic. add_conditional_edges for dynamic routing.
HITLinterrupt_before=["node"] + checkpointer.
memoryMemorySaver in-memory, SqliteSaver persistent.
streaminggraph.astream_events() for token-level SSE in FastAPI.
[ prompt engineering ]
systemrole + context + constraints + output format. be explicit.
CoT"think step by step" or <thinking> for complex reasoning.
XML (Claude)wrap context in <context>, docs in <document>.
few-shot3–5 examples beats zero-shot for structured output.
structuredPydantic + .with_structured_output() = reliable JSON.
temperature0 for extraction/SQL/code where supported. Fable 5.2 rejects it: use effort + prompts.
[ model selection · nov 2026 ]
reasoningClaude Fable 5.2 / Opus 5.5 / GPT-6 Astra / Gemini 4 Argon.
daily driverClaude Sonnet 5.5 / GPT-6.1 Sol. docs, agents, tool use.
fast + cheapClaude Haiku 5.5 / GPT-6.1 Terra / GPT-6 Luna / Gemini 3.8 Flash.
computer useGPT-6.1 Terra for speed, Opus 5.5 for hard flows.
decisionsJev for routing, gating, labeling. typed + calibrated.
open weightsKimi K3.1 Pro, Muse Spark Open, DeepSeek V4.1 Flash, Qwen 3.8 (local).
voiceGemini 3.8 Live / OpenAI Realtime.
[ evals checklist ]
faithfulnessanswer grounded in retrieved context? (RAGAS)
ctx_precisionretrieved chunks actually relevant? (RAGAS)
answer_relanswer addresses the question? (RAGAS)
hallucinationLLM-as-judge: claim unsupported by context?
latencyp50/p95/p99. budget: <2s simple, <8s agentic.
costtrack tokens per request. cache aggressively.
[ deployment ]
Railwaypush to github → auto-deploy. free tier. what I use.
Dockerpin base image. slim variants. multi-stage builds.
env varsnever hardcode keys. .env local, secrets in prod.
cachingsemantic cache with Redis. huge cost saver.
rate limitsexponential backoff + jitter. tenacity in Python.
monitoringLangSmith traces. Sentry errors. log everything.
06 — battle-tested

the stack

earned through production systems, hackathons, and 2am debugging sessions.

Azure OpenAI
LangGraph
LangChain
CrewAI
Amazon Bedrock
FastAPI
Plotly Dash
ChromaDB
DuckDB
Docling
python-pptx
Pydantic
Auth0
Railway
Groq
Tavily
DeepEval
RAGAS
LangSmith
Bright Data
Gemini
HuggingFace
Qdrant
Unsloth
Claude API
Arize Phoenix
Jev
React + Vite
Vercel
MCP
07 — get in touch

book a call

freelance GenAI consulting — RAG, agents, LLM pipelines, architecture reviews.

what I can help with

building production GenAI systems from scratch, reviewing existing architectures, designing eval pipelines, picking the right stack for your use case, or just a call to talk through what you're building.

RAG pipelines multi-agent systems LLM evals architecture review Azure OpenAI Amazon Bedrock LangGraph doc processing