Python basics for the AI labs¶
Run it, don't just read it
Every lab runs on your laptop with Ollama. Set up once (INSTALL), then:
git clone https://github.com/JSWOne/ai-learning.git && cd ai-learning
cd python-basics && python 01_data_shapes.py
Lab files and data: python-basics/ on GitHub. In VS Code, open the repo folder and use Terminal > Run Task > Run this lab.
Just enough Python to read, run and change the code in the other topics. Not a Python course. New to Python? Read learn-python-basics.md first: what you need and why, with diagrams. If you already write Python daily, skip to prompting. Before you start: any programming language; only lab 09 calls a model, so it needs the setup (Start here). After it, you can: read and change the Python in every lab: messages, JSON, Pydantic, async, and the state behind LangGraph.
Every example uses the same fake B2B data as the labs (SKUs, price tiers, customers with credit), in shop.py.
Setup¶
Install steps for all topics are in ../INSTALL.md. Short version, from the ai-learning folder:
uv venv && source .venv/bin/activate # the one venv at ai-learning/ (see ../INSTALL.md section 4)
uv pip install -r requirements.lock # all topics, the tested versions
cd python-basics && python 01_data_shapes.py
Scripts 01–08 need no model. Only 09_putting_it_together.py needs a model: Ollama with qwen3:8b, through the repo's door package.
Files¶
Track: Prereq. Do these first if you're new to Python; they are not part of the Core path count.
| File | Track | What you learn | Where the labs use it | Time |
|---|---|---|---|---|
shop.py |
Shared fake data and helpers | Same idea as catalog.py, rag.py |
||
01_data_shapes.py |
Prereq | Dicts, lists, list of dicts, .get, comprehensions, sorted, enumerate, zip, f-strings |
Chat messages, tool results, search hits: everywhere | seconds |
02_functions.py |
Prereq | Defaults, keyword args, type hints, docstrings, Literal, **kwargs, functions as values, a decorator that registers (@tool), :=, keyword-only *, Callable, * unpacking |
Tool definitions; fn(**args) in the agent loop; @mcp.tool() and FastAPI routes; injecting a fake chat in agents |
seconds |
03_json.py |
Prereq | json.dumps/loads, pulling JSON out of messy model text, Path files |
Tool results, structured output, golden sets | seconds |
04_errors_and_retries.py |
Prereq | try/except/else/finally, custom exceptions, a retry decorator with @wraps |
llm-api/04_error_handling.py, agent.py |
seconds |
05_classes_and_pydantic.py |
Prereq | A plain class, @dataclass, Pydantic BaseModel, Field, ValidationError, JSON schema |
Argument validation, prompting/triage.py, rag.py |
seconds |
06_async_and_parallel.py |
Prereq | async/await, asyncio.gather, async with, wait_for timeouts, async for, ThreadPoolExecutor |
mcp-server (all), agents/agent/, llm-api/02_parallel_calls.py |
seconds |
07_scripts_files_streams.py |
Prereq | Imports, __name__ guard, argparse flags, Path(__file__), re for codes in text, sqlite3 with ? parameters, generators with yield |
Every script's wiring and flags (--quick); the guards' regexes; rag 12-13 and rnr's database; 08_streaming.py |
seconds |
08_state_and_graphs.py |
Prereq | TypedDict, Annotated reducers, partial updates, closures, {**d}; a graph runner by hand, then the same nodes in LangGraph |
agents/lg_agent.py, 07_langgraph.py |
seconds |
09_putting_it_together.py |
Prereq | An email becomes a validated, priced order: 01–05 plus one model call | Bridge into prompting |
~10 s |
test_basics.py |
pytest: assert, parametrize, raises, testing model code without a model |
Every topic's tests |
Questions and answers are in FAQ.md. The learning guide is learn-python-basics.md (diagrams in diagrams/).
Rules of thumb¶
- Read optional fields with
.get(). Anything a model returns is optional until validated. - Turn errors into data (
{"error": ...}) at the boundary, and catch specific exceptions everywhere else. - Validate model output with Pydantic, then trust the typed object inside your code.
- Never let the model do arithmetic or business rules. It drafts; your code computes and decides.
asyncfor waiting on the network,gatherfor independent calls only, and a timeout on every external call.- A graph node is a plain function: state in, partial update out. Never change the state in place.
- Run scripts from their own folder, and never name a file after a library (
json.py,ollama.py).
Tests¶
pytest -q runs model-free tests for shop.py, the JSON parser and the order pricing, using a hand-built Order instead of the model.