Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

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.

Chaand Sheikh

·27 November 2026Basics

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:

Five steps, five Python tools 1 Read data, key 2 Build the request 3 Call the model 4 Check the reply 5 Keep what matters pathlib, os.environ dicts, lists, JSON typed function try / except comprehensions
Top row: what the script does. Bottom row: the Python piece each step needs.
  1. Read data: a file, and an API key from the environment.
  2. Build a request: requests to an LLM are JSON, and in Python that means dicts and lists.
  3. Call the model, usually inside a small function with type hints.
  4. Check the reply: replies go wrong, so we need try and except.
  5. 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_text reads the file as text.
  • json.loads turns 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 role and a content. json.dumps turns it back into JSON text, ready to send.
json.loads and json.dumps JSON text a file, or the wire Python objects list of dicts json.loads(text) json.dumps(message)
Read with 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
  • @dataclass gives us a ticket record with three typed fields: id, subject and priority.
  • load takes a path and says it returns list[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 Ticket for every row, in one line.
  • Another comprehension keeps only the "high" priority tickets.
  • An f-string drops the values into a sentence. !r shows 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.get reads 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.loads parses the first one fine: refund. The second one fails, and except catches the JSONDecodeError: 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 nowCan waitWhy it can wait
dicts, lists, JSONmetaclasses, descriptorsFrameworks use them; you rarely write them
functions, type hints, dataclasseswriting your own decoratorsYou'll use decorators long before you write one
comprehensions, f-stringsthreads and processesThe SDKs handle concurrency for you at first
pathlib, os.environ, try / exceptGUI toolkits, packaging for PyPIThe 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 unguarded json.loads crashes 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

ToolCodeIn the scripts
JSON is dicts and listsjson.loads, json.dumpstickets: 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 environmentos.environ.get("OPENAI_API_KEY", "")key set: False
Bad repliesexcept json.JSONDecodeErrornot 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 1 of 3

Next post
Python Class Methods, Static Methods and Properties: What Each One Receives

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)

On this page

  • Almost every AI script has five steps
  • The data: four support tickets
  • JSON is dicts and lists
  • Small, typed functions and comprehensions
  • Keys from the environment, and bad replies
  • What you need now, and what can wait
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.