Python for AI: The Five Tools You Actually Need
The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.
What you will learn
- Read a JSON file into dicts and lists, and build a chat message as a dict
- Write a small typed function with a dataclass and filter with a list comprehension
- Read an API key from the environment without ever printing it
- Survive a model reply that is not JSON with try and except
Before you start
- Python installed (3.10 or newer)
- Running a .py file from a terminal
Python is huge, and you don't need all of it to build with LLMs. An electrician owns a whole workshop full of tools, hundreds of them. But on a normal day they wear a belt with maybe five: the ones they reach for again and again. That belt is what makes them fast.
AI code is the same. A handful of Python features show up in almost every script. Know those well and you can read and write most AI code. This article covers that belt, using three small scripts that need only the standard library.
Almost every AI script has five steps
What does AI code actually do? Almost every script follows the same five steps, and each step needs one small piece of Python:
- Read data: a file, and an API key from the environment.
- Build a request: requests to an LLM are JSON, and in Python that means dicts and lists.
- Call the model, usually inside a small function with type hints.
- Check the reply: replies go wrong, so we need
tryandexcept. - Keep what matters: filter and reshape with comprehensions.
The data: four support tickets
All three scripts read the same small file, tickets.json:
[
{"id": 1001, "subject": "Refund not received", "priority": "high", "body": "I returned my order two weeks ago and still have no refund."},
{"id": 1002, "subject": "Change delivery address", "priority": "low", "body": "Can you send order 1002 to my office instead?"},
{"id": 1003, "subject": "Card charged twice", "priority": "high", "body": "My card shows two payments for one order."},
{"id": 1004, "subject": "Invoice copy", "priority": "low", "body": "Please email me a copy of my last invoice."}
]
JSON is dicts and lists
"""LLM APIs speak JSON. In Python, JSON is dicts and lists."""
import json
from pathlib import Path
text = Path("tickets.json").read_text(encoding="utf-8")
tickets = json.loads(text) # a list of dicts
print("tickets:", len(tickets))
first = tickets[0]
print("first:", first["id"], "-", first["subject"])
print("keys:", list(first))
# the shape every chat API expects for one message
message = {"role": "user", "content": first["body"]}
print(json.dumps(message))
tickets: 4
first: 1001 - Refund not received
keys: ['id', 'subject', 'priority', 'body']
{"role": "user", "content": "I returned my order two weeks ago and still have no refund."}
Path.read_textreads the file as text.json.loadsturns that text into Python: a list of dicts. Four tickets.tickets[0]picks the first ticket by position.first["subject"]picks a value by key.list(first)shows its keys.- Now the important part: a chat message for an LLM is just a dict with a
roleand acontent.json.dumpsturns it back into JSON text, ready to send.
loads, work with plain dicts and lists, send with dumps.If you can read and build dicts like this, you can read any LLM API. Requests and replies are nested dicts and lists, nothing more.
Small, typed functions and comprehensions
"""Functions with type hints, a dataclass, comprehensions."""
import json
from dataclasses import dataclass
from pathlib import Path
@dataclass
class Ticket:
id: int
subject: str
priority: str
def load(path: str) -> list[Ticket]:
rows = json.loads(Path(path).read_text(encoding="utf-8"))
return [Ticket(r["id"], r["subject"], r["priority"]) for r in rows]
tickets = load("tickets.json")
urgent = [t for t in tickets if t.priority == "high"]
for t in urgent:
print(f"#{t.id} {t.subject!r} needs a reply today")
print("urgent:", len(urgent), "of", len(tickets))
#1001 'Refund not received' needs a reply today
#1003 'Card charged twice' needs a reply today
urgent: 2 of 4
@dataclassgives us a ticket record with three typed fields:id,subjectandpriority.loadtakes a path and says it returnslist[Ticket]. Those type hints help your editor, and later, libraries like Pydantic use the same idea to check LLM output (see Structured LLM Output with Pydantic).- Inside, a list comprehension builds one
Ticketfor every row, in one line. - Another comprehension keeps only the
"high"priority tickets. - An f-string drops the values into a sentence.
!rshows the subject with its quotes.
Two urgent tickets out of four: 1001 and 1003.
Keys from the environment, and bad replies
"""Keys come from the environment; bad replies must not crash you."""
import json
import os
api_key = os.environ.get("OPENAI_API_KEY", "")
print("key set:", bool(api_key)) # never print the key itself
# two replies written for this lesson: one JSON, one chatty
replies = ['{"category": "refund"}', "Sure! The category is refund."]
for raw in replies:
try:
data = json.loads(raw)
print("parsed:", data["category"])
except json.JSONDecodeError as err:
print("not JSON:", err.msg)
key set: False
parsed: refund
not JSON: Expecting value
os.environ.getreads the API key from the environment, with an empty default. The key never goes into the code.- We print only whether it's set, never the key itself. Here it says
False, because no key is set. - Next, two replies written for this lesson. One is clean JSON. The other is a chatty sentence, which is exactly what models sometimes send back.
json.loadsparses the first one fine:refund. The second one fails, andexceptcatches theJSONDecodeError:not JSON: Expecting value. The script keeps running instead of crashing.
Catch the specific error. except json.JSONDecodeError handles a reply that isn't JSON. A bare except: would also hide real bugs, like a typo in a key name.
To keep keys in a .env file and out of git, see Set Up a Python AI Project with uv, VS Code and an API Key.
What you need now, and what can wait
Let's be honest about what you can skip for now:
| Need now | Can wait | Why it can wait |
|---|---|---|
| dicts, lists, JSON | metaclasses, descriptors | Frameworks use them; you rarely write them |
| functions, type hints, dataclasses | writing your own decorators | You'll use decorators long before you write one |
| comprehensions, f-strings | threads and processes | The SDKs handle concurrency for you at first |
pathlib, os.environ, try / except | GUI toolkits, packaging for PyPI | The AI apps here are scripts and web services |
Learn the left column well. Pick up the right one when a real problem asks for it.
Common mistakes
- Treating a reply as JSON without a
try. Models sometimes answer with a friendly sentence, and one unguardedjson.loadscrashes the whole script. - Putting the key in the code, or printing it to check it. Read it from the environment and print only
bool(api_key).
Quick recap
| Tool | Code | In the scripts |
|---|---|---|
| JSON is dicts and lists | json.loads, json.dumps | tickets: 4, a chat message dict |
| Typed functions | @dataclass, list[Ticket] | load() returns one Ticket per row |
| Comprehensions, f-strings | [t for t in tickets if ...] | urgent: 2 of 4 |
| Keys from the environment | os.environ.get("OPENAI_API_KEY", "") | key set: False |
| Bad replies | except json.JSONDecodeError | not JSON: Expecting value |
Try it yourself
Add a fifth ticket with priority "high" to tickets.json and rerun 02_functions.py. Then write a comprehension for tickets with an id above 1002. Finally, set OPENAI_API_KEY in your shell to any value and rerun 03_env_and_errors.py. What changes?
The three scripts and tickets.json are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)