AI Basics cheat sheet
A scannable AI Basics reference: 11 short snippets across 9 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| AI, machine learning, deep learning | AI is the goal: machines doing things we would call intelligent. Machine learning is the dominant method: instead of | lesson |
| The model lifecycle | The most common failure is solving the wrong problem precisely. Before any modelling, write down the decision the | lesson |
| Prompt engineering fundamentals | Chain-of-thought helps on genuinely multi-step problems and hurts on simple extraction, where it invites the model to | lesson |
| Embeddings and semantic search | Include the document title and section heading in each chunk's text, not just in metadata. The heading is often the | lesson |
| Retrieval-augmented generation | Exact identifiers, error codes and rare product names are where pure vector search is weakest, because their meaning is | lesson |
| AI safety, privacy and data governance | Log the metadata that lets you investigate an incident and answer a customer question: which prompt version ran, which | lesson |
| Local versus hosted models | Add memory for the key-value cache, which grows with context length and concurrent requests, and expect throughput to | lesson |
| Multimodal AI in practice | For documents, a pipeline of OCR plus a text model is often more accurate and much cheaper than asking a vision model | lesson |
| Designing an AI feature end to end | The failure path is part of the design, not an afterthought. Decide before you build what the user sees when the model | lesson |
Quick snippets
AI, machine learning, deep learning
What a model really is
# the shape of every supervised learning problem
X, y = load_data() # features and known answers
model = Model()
for epoch in range(EPOCHS):
preds = model(X)
loss = criterion(preds, y) # how wrong are we?
loss.backward() # gradients
optimizer.step() # nudge the parameters
optimizer.zero_grad()Full lesson: AI, machine learning, deep learning →
The model lifecycle
Data and splits
all data
├── train (fit the parameters) ~70%
├── val (tune settings, early stop) ~15%
└── test (report the final number) ~15% touch it once
Evaluation, deployment, monitoring
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
print(confusion_matrix(y_test, preds))
print(classification_report(y_test, preds))
roc_auc_score(y_test, proba) # threshold-independent ranking qualityFull lesson: The model lifecycle →
Prompt engineering fundamentals
Structure of a prompt
resp = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
messages=[
{"role": "system", "content":
"You classify support tickets. Reply with exactly one label from: "
"billing, technical, account, other. No explanation."},
{"role": "user", "content":
"Ticket: I was charged twice for last month's subscription."},
],
)
label = resp.choices[0].message.content.strip()
Prompts are code
prompts/
classify_v3.txt # current, referenced by name and version
classify_v2.txt # kept for comparison
CHANGELOG.md # what changed, and why, with the eval deltaFull lesson: Prompt engineering fundamentals →
Embeddings and semantic search
Chunking
def chunk(text, size=800, overlap=120):
words = text.split()
step = size - overlap
return [" ".join(words[i:i + size]) for i in range(0, len(words), step)]
chunks = chunk(open("handbook.txt").read())
print(len(chunks), len(chunks[0].split()))Full lesson: Embeddings and semantic search →
Retrieval-augmented generation
What goes wrong
# hybrid retrieval: combine lexical and vector scores instead of choosing one
def hybrid(query, k=5, alpha=0.6):
vec = vector_scores(query) # normalised to 0..1
lex = bm25_scores(query) # normalised to 0..1
return (alpha * vec + (1 - alpha) * lex).argsort()[-k:][::-1]
# always filter before you rank when access is involved
def vector_scores(query, tenant):
scores = INDEX["vectors"] @ normalise(embed([query])[0])
scores[INDEX["tenant"] != tenant] = -np.inf
return scoresFull lesson: Retrieval-augmented generation →
AI safety, privacy and data governance
Prompt injection and output handling
import html
def safe_render(model_output: str) -> str:
# treat model output as untrusted for the same reason you treat user input as untrusted
return html.escape(model_output, quote=True)
def run_tool(name, args, allowed):
if name not in allowed:
raise PermissionError(f"tool {name} is not allowed")
if not validate_args(name, args): # never trust model-supplied arguments
raise ValueError("invalid arguments")
return TOOLS[name](**args)Full lesson: AI safety, privacy and data governance →
Local versus hosted models
Sizing local hardware
def vram_gb(params_b, bits_per_weight=4, overhead=1.2):
"""Rough weight memory for a quantised model, with room for the KV cache."""
return params_b * bits_per_weight / 8 * overhead
for p in (3, 8, 14, 32, 70):
print(f"{p}B at 4-bit: about {vram_gb(p):.1f} GB")Full lesson: Local versus hosted models →
Multimodal AI in practice
Speech
# speech to text
with open("call.mp3", "rb") as f:
tr = client.audio.transcriptions.create(model="whisper-1", file=f, language="en")
print(tr.text)
# text to speech
with client.audio.speech.with_streaming_response.create(
model="tts-1", voice="alloy", input="Your order has shipped.") as response:
response.stream_to_file("reply.mp3")Full lesson: Multimodal AI in practice →
Designing an AI feature end to end
Shipping and watching
METRICS = {
"requests": counter("ai.feature.requests"),
"fallbacks": counter("ai.feature.fallbacks", tags=["reason"]),
"invalid_rate": gauge("ai.feature.invalid_output_rate"),
"latency_ms": histogram("ai.feature.latency_ms"),
"cost_per_request": gauge("ai.feature.cost"),
}Full lesson: Designing an AI feature end to end →
FAQ
Is this AI Basics cheat sheet free to use?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
AI Agents Math for AI Machine Learning scikit-learn TensorFlow PyTorch
Last refreshed 2026-09-27.