AI EngineeringZero to ProductionHome·About·Contact
Quick Reference

The Cheat Sheet

Keep this open in a tab while you work through the labs. Every core idea in the course, compressed to what you need at a glance.

★ Skim anytime🧠 Core concepts🪤 Gotchas

Core concepts

🔤 Tokens

The unit the model reads and writes. Roughly ¾ of a word in English (≈4 characters). "hamburger" ≈ 3 tokens.

You pay per token — input (what you send) + output (what it generates), at different rates.

cost = in_tokens×in_rate + out_tokens×out_rate

Context window = max tokens (input + output) the model can hold at once. Overflow it and you must trim, summarize, or chunk.

💬 The request

Everything is messages.create(). Key fields:

modelwhich model
max_tokensoutput cap
systemthe rules/role
messagesthe conversation
efforthow hard it works

Stateless: the API remembers nothing. You resend the whole history every call — that is "memory".

🎚️ Effort & thinking

thinking:{type:"adaptive"} — model decides how much to reason.

effort: lowmax. Higher = smarter + slower + pricier.

lowclassify, route
mediummost work
high/maxagents, hard reasoning

📦 Structured output

Force schema-valid JSON instead of parsing free text.

client.messages.parse(..., output_format=MyModel)

Define shape with Pydantic; use Literal[...] for fixed value sets → the model literally can't return anything off-list.

Rule: if code consumes the output, constrain it. Never regex model text.

🧲 Embeddings

Text → a vector of numbers where similar meaning = close together.

Retrieval = embed the question, find the nearest chunk vectors (cosine similarity).

Golden rule: embed queries and documents with the same model, or similarity is garbage.

🏷️ Model tiers

Opusreasoning, agents, RAG gen
Sonnetbalanced, high-volume
Haikuclassify, rerank — cheap+fast

Match tier to task difficulty. Using Opus for sentiment is like renting a truck to carry a letter.

Stop reasons — always check before reading content

stop_reasonMeansDo
end_turnFinished normallyUse the content ✅
max_tokensTruncated at output capRaise max_tokens / stream
tool_useWants to call a toolRun it, send result back
refusalDeclined for safetyDon't read content[0] blindly — handle it
pause_turnLong tool run pausedRe-send to resume
The habit that prevents crashesWrite if resp.stop_reason == "refusal" and == "max_tokens" branches from day one. Code that assumes text is always there will break on a refusal.

RAG in a nutshell

One sentenceFetch the most relevant snippets of your data at query time, put them in the prompt, and make the model answer only from them.
PhaseSteps
Offline (once)documents → chunkembed → store vectors
Online (per question)embed question → retrieve (vector + keyword) → re-rank → build context → generate + cite

Two rules that stop hallucination:

  1. "Answer only from the numbered context."
  2. "If it's not there, say you don't know." ← test this works!
"Hallucination" in RAG is usually a RETRIEVAL failure — the right chunk was never fetched. Test retrieval alone, first.

The agent loop

An agent is a while loop around the API call. The model can't run tools — it asks you to via a tool_use block; you run it and hand back the result.

call model → end_turn? done : run tool(s) → append results → loop (with a hard step cap)

Three things people get wrong:

Append the assistant turn (resp.content) verbatim before results
Every tool_result needs the matching tool_use_id
All parallel results go back in one user message
Agent safety, non-negotiableHard step cap · validate tool inputs (untrusted!) · gate irreversible actions behind human approval · sandbox any code/shell execution.

Cost & caching

💾 Prompt caching

Reuse a big stable prefix at ~10% price. Prefix match: any byte change invalidates everything after it.

Order: stable first (system, tools) → volatile last (the question).

verify: usage.cache_read_input_tokens > 0

🪫 Cache killers

Silent zero-hit causes:

datetime.now() in prefix
UUID / request-id up front
unsorted json.dumps()
per-user tool set

✂️ Spend less

route easy → small model
semantic cache repeats
right-size max_tokens
batch non-urgent jobs

Top 10 gotchas (bookmark this)

#GotchaFix
1content is a list, not a stringLoop, check block.type=="text"
2Assuming text exists on a refusalCheck stop_reason first
3Truncated output looks completeHandle max_tokens; raise it / stream
4Regex-parsing model outputUse output_format schema
5Query & docs embedded differentlyOne embed() everywhere
6"It hallucinates" (RAG)It's retrieval — test top-k recall
7Agent loop never endsHard MAX_STEPS cap
8Missing / wrong tool_use_idCopy block.id into result
9Cache never hitsNo volatile bytes in the prefix
10Frontier model for trivial workRoute to Haiku
When stuckPrint three things: resp.stop_reason, resp.usage, and (for RAG) the retrieved chunk IDs. 90% of bugs reveal themselves in those three values.
© 2026 studybydoing.in · AI Engineering: Zero to Production · All rights reserved. · About · Privacy Policy · Terms · Contact
Educational content, provided as-is and without warranty. Code samples are examples — review, test, and adapt them before using in production. See the Terms of Use & Disclaimer. Use at your own risk.
© studybydoing.in