Cheat sheets / Python for AI cheat sheet

Python for AI cheat sheet

The building blocks of AI work in Python: arrays with NumPy, quick charts, a scikit-learn model in five lines, calling an LLM, validating its JSON with Pydantic, and the retrieve-then-generate loop behind RAG.

NumPy

a = np.array([1, 2, 3]); a.shape, a.dtype
create and inspect
a * 2, a + b, np.sqrt(a)
vectorised maths, no loops
m.sum(axis=0), m.mean(axis=1)
per column / per row
a[a > 1], np.where(a > 1, 1, 0)
filter and choose
rng = np.random.default_rng(42)
reproducible random numbers
a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
cosine similarity

Charts

fig, ax = plt.subplots(figsize=(7, 4))
figure and axes
ax.plot(x, y); ax.bar(x, y); ax.scatter(x, y)
line, bar, scatter
ax.set_title("..."); ax.set_xlabel("..."); ax.set_ylabel("...")
always label
fig.savefig("chart.png", dpi=150, bbox_inches="tight")
save

scikit-learn

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
split
model = make_pipeline(StandardScaler(), LogisticRegression())
preprocessing + model
model.fit(X_train, y_train)
train
pred = model.predict(X_test)
predict
accuracy_score(y_test, pred), confusion_matrix(y_test, pred)
evaluate
cross_val_score(model, X, y, cv=5).mean()
more honest score

Calling an LLM

client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
key from environment, never in code
r = client.messages.create(model=MODEL, max_tokens=400, system="You are concise.", messages=[{"role": "user", "content": q}])
one request
r.content[0].text, r.usage.input_tokens
answer and token count
messages.append({"role": "assistant", "content": answer})
send history each time
with client.messages.stream(...) as s: for t in s.text_stream: ...
stream tokens

Structured output

class Review(BaseModel): sentiment: str score: int
describe the JSON you want
Review.model_json_schema()
schema to put in the prompt
Review.model_validate_json(reply)
parse and check, or raise ValidationError

RAG in four lines

chunks = split(documents, size=500, overlap=50)
1. chunk
vectors = embed(chunks) # normalise to length 1
2. embed and store
best = [chunks[i] for i in np.argsort(vectors @ embed(q))[::-1][:3]]
3. retrieve top 3
prompt = f"Answer only from these sources...\n{best}\nQuestion: {q}"
4. generate with sources

PythonMates · pythonmates.com/cheat-sheets/python-for-ai/ · Python 3.15 · updated 2026-11-19