Python for AI Engineers · Part A · Lesson 10 of 26
Python files, JSON, .env config and secrets
Read and write files with pathlib and UTF-8, turn JSON into dicts and back, store datasets and logs as JSON Lines, read settings from environment variables and .env, and keep API keys out of Git and logs. You finish by totalling token usage per user from a JSONL log of LLM calls.
⏱ 40 min3 exercises that check your codeRuns in your browser
By the end you can
- Build paths with pathlib and read and write text files with
encoding="utf-8"and the right open mode - Convert between JSON and Python with
json.loads,json.dumps(indent=2),json.loadandjson.dump - Write and stream JSON Lines files, the format of eval datasets and LLM call logs
- Load settings from environment variables and a
.envfile into one settings object, without ever committing or logging a secret - Parse a JSONL log of LLM calls and total the tokens each user spent
1Paths with pathlib
In Python you work with file paths through pathlib.Path, the same idea as java.nio.file.Path or Node's path module. A Path is an object, not a string: you join parts with the / operator, and it uses the right separator on Windows, macOS and Linux.
A Path can also do the file work itself. write_text creates or replaces a file with a string, read_text returns the whole file as one string, mkdir(parents=True, exist_ok=True) works like mkdir -p, and glob("*.txt") finds files by pattern.
So the examples on this page leave nothing behind, each one works inside tempfile.TemporaryDirectory(): a fresh, empty folder that Python deletes when the with block ends. In your own code you would use a real folder such as Path("data").
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp: # an empty folder, deleted after the block
root = Path(tmp)
data = root / "data" # join with /, never with string +
data.mkdir(parents=True, exist_ok=True) # like mkdir -p
prompt = data / "system_prompt.txt"
prompt.write_text("You are a helpful assistant.\n", encoding="utf-8")
(data / "notes.md").write_text("# Notes\n", encoding="utf-8")
print(prompt.name, prompt.stem, prompt.suffix)
print(prompt.parent.name)
print(prompt.exists(), (data / "missing.txt").exists())
print(repr(prompt.read_text(encoding="utf-8")))
print(sorted(p.name for p in data.glob("*.txt")))
print(sorted(p.name for p in data.iterdir()))
Expected output
system_prompt.txt system_prompt .txt data True False 'You are a helpful assistant.\n' ['system_prompt.txt'] ['notes.md', 'system_prompt.txt']
Path data = Path.of(tmp).resolve("data");
Files.createDirectories(data);
Path prompt = data.resolve("system_prompt.txt");
Files.writeString(prompt, "You are a helpful assistant.\n", StandardCharsets.UTF_8);
String text = Files.readString(prompt, StandardCharsets.UTF_8); const data = path.join(tmp, "data");
fs.mkdirSync(data, { recursive: true });
const prompt = path.join(data, "system_prompt.txt");
fs.writeFileSync(prompt, "You are a helpful assistant.\n", "utf8");
const text = fs.readFileSync(prompt, "utf8"); name is the file name, stem the name without its extension, suffix the extension with its dot, and parent the folder that contains it. iterdir() lists a folder in no guaranteed order, which is why the example sorts it. In the browser editor Python runs on an in-memory file system, so these files are real for the run and gone when you reload the page.
Tip To load a file that ships next to your code (a prompt template, a test fixture), use Path(__file__).parent / "prompt.txt". A bare Path("prompt.txt") is relative to the folder you started the program from, which changes when you run it from somewhere else.
2open(), modes and encoding="utf-8"
read_text and write_text handle a whole file at once. When you want to write in several steps, append to a file, or read a big file line by line, use open() inside a with block. The with closes the file at the end of the block, even if an exception is raised, like try-with-resources in Java.
The second argument is the mode: "r" read (the default), "w" write (creates the file, or empties it if it exists), "a" append to the end, "x" create but fail if the file already exists. Add "b" for binary ("rb", "wb") and you get bytes instead of str, for images, audio and PDFs.
Looping over an open text file gives you one line at a time, with its "\n" at the end, and only one line sits in memory. rstrip("\n") removes the newline.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
log = Path(tmp) / "chat.log"
with open(log, "w", encoding="utf-8") as f: # "w": create, or empty an existing file
f.write("user: Hi\n") # write() does not add a newline
f.write("assistant: Hello! 👋\n")
with open(log, "a", encoding="utf-8") as f: # "a": add to the end
print("user: What is DNS?", file=f) # print() can write to a file too
with open(log, encoding="utf-8") as f: # "r" is the default mode
for line in f: # one line at a time
print(line.rstrip("\n"))
try:
open(log, "x", encoding="utf-8") # "x": only create a new file
except FileExistsError:
print("x refused to overwrite chat.log")
text = log.read_text(encoding="utf-8")
raw = log.read_bytes() # the bytes on disk, not decoded
print(len(text), "characters,", len(raw), "bytes")
Expected output
user: Hi assistant: Hello! 👋 user: What is DNS? x refused to overwrite chat.log 48 characters, 51 bytes
The emoji is one character but four bytes in UTF-8, which is why the two counts differ. Text is str, bytes on disk are bytes, and the encoding is the rule that converts one into the other.
Watch out Without encoding=, open() uses the operating system's default encoding. On Linux and macOS that is usually UTF-8, but on many Windows machines it is cp1252, so the same code that works on your Mac crashes with UnicodeDecodeError (or silently garbles text) on a Windows laptop or server. Model output is full of non-ASCII text, so always pass encoding="utf-8" when you open text files.
3JSON: loads, dumps, load and dump
The built-in json module converts JSON text to Python objects and back. JSON objects become dict, arrays become list, true/false become True/False and null becomes None. There is no class mapping step as in Jackson: you get plain dicts and lists, exactly like JSON.parse in JavaScript.
The names are easy to mix up. The ones ending in s work with a string: json.loads(text) and json.dumps(obj). The ones without it work with an open file: json.load(f) and json.dump(obj, f).
dumps has three options you will use all the time: indent=2 for human-readable output, ensure_ascii=False to keep characters like é as they are instead of \u00e9 escapes, and sort_keys=True for a stable key order (handy in tests and diffs).
import json
import tempfile
from pathlib import Path
text = '{"model": "llama3.2:3b", "stream": false, "stop": null, "tags": ["demo"]}'
req = json.loads(text) # JSON text -> dict
print(type(req).__name__, req["stream"], req["stop"], req["tags"])
reply = {"answer": "Café opens at 9", "tokens": (12, 30), 1: "int key"}
print(json.dumps(reply)) # tuple -> list, 1 -> "1", é escaped
print(json.dumps(reply, ensure_ascii=False))
print(json.dumps({"b": 1, "a": [1, 2]}, indent=2, sort_keys=True))
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "report.json"
with path.open("w", encoding="utf-8") as f:
json.dump({"passed": 41, "failed": 2}, f, indent=2) # dict -> file
with path.open(encoding="utf-8") as f:
print(json.load(f)) # file -> dict
try:
json.loads("{'answer': 'single quotes'}") # not valid JSON
except json.JSONDecodeError as e:
print("bad JSON:", e.msg, "| line", e.lineno, "column", e.colno)
Expected output
dict False None ['demo']
{"answer": "Caf\u00e9 opens at 9", "tokens": [12, 30], "1": "int key"}
{"answer": "Café opens at 9", "tokens": [12, 30], "1": "int key"}
{
"a": [
1,
2
],
"b": 1
}
{'passed': 41, 'failed': 2}
bad JSON: Expecting property name enclosed in double quotes | line 1 column 2ObjectMapper mapper = new ObjectMapper();
Map<String, Object> req = mapper.readValue(text, new TypeReference<>() {});
String out = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(req); const req = JSON.parse(text);
const out = JSON.stringify(req, null, 2); // like json.dumps(req, indent=2) Look at the second line of output: JSON has no tuples, so (12, 30) became a list, and JSON keys are always strings, so the key 1 came back as "1". Values JSON cannot represent, such as a set or a datetime, raise TypeError: Object of type set is not JSON serializable. Convert them first, or pass default=str to turn anything unknown into a string.
Tip A model asked to "answer in JSON" often wraps it in a Markdown code fence or adds a sentence before it. Always parse its output inside try / except json.JSONDecodeError, and validate the shape with Pydantic (lesson 6) before you trust it.
4JSON Lines: one record per line
JSON Lines (.jsonl) is a text file with one complete JSON object per line. It is the standard format for eval datasets, fine-tuning data and logs of LLM calls, because it has two properties a single big JSON array does not have.
You can append a record without reading or rewriting the file: open with "a" and write one line. And you can stream it: read one line, parse it, handle it, move on, so a 10 GB log uses the same memory as a tiny one.
To write a line, use json.dumps(record) + "\n". dumps never puts a raw newline inside its output (a newline inside a string is written as the two characters \n), so every record stays on its own line. Do not pass indent here: that spreads one record over many lines.
import json
import tempfile
from pathlib import Path
examples = [
{"question": "What is DNS?", "expected": "It maps names to IP addresses."},
{"question": "What is TLS?", "expected": "It encrypts traffic.\nAnd checks identity."},
]
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "evals.jsonl"
with path.open("w", encoding="utf-8") as f:
for ex in examples:
f.write(json.dumps(ex, ensure_ascii=False) + "\n") # one object per line
with path.open("a", encoding="utf-8") as f: # adding a record = one append
f.write(json.dumps({"question": "What is a CDN?", "expected": "A cache near users."}) + "\n")
print(path.read_text(encoding="utf-8"), end="")
rows = []
with path.open(encoding="utf-8") as f:
for line in f:
if line.strip(): # skip blank lines, often left at the end
rows.append(json.loads(line))
print(len(rows), "rows; last:", rows[-1]["question"])
print(rows[1]["expected"].splitlines())
Expected output
{"question": "What is DNS?", "expected": "It maps names to IP addresses."}
{"question": "What is TLS?", "expected": "It encrypts traffic.\nAnd checks identity."}
{"question": "What is a CDN?", "expected": "A cache near users."}
3 rows; last: What is a CDN?
['It encrypts traffic.', 'And checks identity.']The second record contains a real newline in its text, yet it is written on one line as \n and comes back as a real newline after json.loads. That is what makes JSON Lines safe for any text a model produces.
Watch out json.load(f) on a .jsonl file fails with JSONDecodeError: Extra data, because it expects exactly one JSON value in the whole file. Read JSON Lines line by line and call json.loads on each line.
5CSV, briefly
CSV is still what spreadsheets and many business users want, for example an eval report someone opens in Excel. The csv module handles quoting for you: a value with a comma or a quote inside is wrapped in quotes automatically, which naive ",".join(...) code gets wrong.
csv.DictWriter writes dicts as rows under a header line, and csv.DictReader reads each row back as a dict keyed by the header. Open CSV files with newline="", as the csv docs require: the module writes its own line endings, and without it you get blank lines between rows on Windows.
import csv
import tempfile
from pathlib import Path
results = [
{"question": "What is DNS?", "score": 0.9, "passed": True},
{"question": "What is TLS, really?", "score": 0.4, "passed": False},
]
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "results.csv"
with path.open("w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["question", "score", "passed"])
writer.writeheader()
writer.writerows(results)
print(path.read_text(encoding="utf-8").splitlines())
with path.open(encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
print(row)
Expected output
['question,score,passed', 'What is DNS?,0.9,True', '"What is TLS, really?",0.4,False']
{'question': 'What is DNS?', 'score': '0.9', 'passed': 'True'}
{'question': 'What is TLS, really?', 'score': '0.4', 'passed': 'False'}Two things to notice. The question with a comma was quoted for you. And everything comes back as a string: CSV has no types, so score is "0.9" and passed is "False" (a non-empty string, which is truthy). Convert with float(row["score"]) and row["passed"] == "True". For anything bigger than a quick export, pandas (later in this course) reads and writes CSV in one line.
6Environment variables with os.environ
Settings that change between your laptop, CI and production (the model name, the API URL, the API key) belong in environment variables, not in the code. Your shell, Docker, Kubernetes or the hosting platform sets them, and the same code runs everywhere.
In Python they live in os.environ, which behaves like a dict of strings. os.environ["NAME"] raises KeyError when the variable is missing, so use it for settings that are required. os.environ.get("NAME", "default") returns a default instead, and os.getenv("NAME") is a shortcut for os.environ.get("NAME").
Every value is a string, always. Convert numbers with int() and parse booleans yourself. The snippet sets variables itself so you can run it; normally they come from outside the program.
import os
os.environ["APP_MODEL"] = "llama3.2:3b" # normally set by the shell, Docker or the host
os.environ["APP_MAX_TOKENS"] = "512"
os.environ["APP_STREAM"] = "false"
print(os.environ["APP_MODEL"])
print(os.environ.get("APP_TIMEOUT", "30")) # missing: use the default
print(os.getenv("APP_TIMEOUT")) # missing: None
max_tokens = int(os.environ["APP_MAX_TOKENS"]) # a str, so convert it
print(max_tokens + 1)
print(bool(os.environ["APP_STREAM"])) # the trap: any non-empty string is True
stream = os.environ["APP_STREAM"].strip().lower() in ("1", "true", "yes", "on")
print(stream)
try:
os.environ["APP_RETRIES"] = 3 # values must be strings
except TypeError as e:
print("TypeError:", e)
try:
os.environ["APP_API_KEY"]
except KeyError as e:
print("missing:", e)
Expected output
llama3.2:3b 30 None 513 True False TypeError: str expected, not int missing: 'APP_API_KEY'
String model = System.getenv("APP_MODEL"); // null if missing
String timeout = System.getenv().getOrDefault("APP_TIMEOUT", "30");
int maxTokens = Integer.parseInt(System.getenv("APP_MAX_TOKENS")); const model = process.env.APP_MODEL; // undefined if missing
const timeout = process.env.APP_TIMEOUT ?? "30";
const maxTokens = Number(process.env.APP_MAX_TOKENS); On your machine you set a variable for one run by putting it before the command: APP_MODEL=qwen2.5:3b uv run python main.py on macOS and Linux (bash or zsh). In Windows PowerShell run $env:APP_MODEL = "qwen2.5:3b" first, then the command. Changing os.environ inside Python affects only this process and the programs it starts, never your shell.
7.env files with python-dotenv
Typing every variable before every command gets old fast. In development you keep them in a file called .env in the project folder, one NAME=value per line, and the python-dotenv library copies them into os.environ when your program starts. It is the same idea as dotenv in Node or Spring's application.properties with environment overrides.
The rule that makes this safe: .env holds real values, including your API key, so it is listed in .gitignore and never committed. Next to it you commit a .env.example with the same names and fake values, so a teammate knows what to fill in.
This code needs a real file on disk, so run it on your machine. Install the library in your project first (the Build labs use it too):
uv add python-dotenv import os
from dotenv import load_dotenv
load_dotenv() # find .env and copy its values into os.environ
model = os.environ.get("LLM_MODEL", "llama3.2:3b")
base_url = os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1")
api_key = os.environ["LLM_API_KEY"] # required: fail at startup if missing
print("model:", model)
print("url:", base_url)
print("key loaded:", bool(api_key)) - The package is called
python-dotenv, but you import it asdotenv.line 3 load_dotenv()looks for.envin the folder of the script that calls it, then in each parent folder, and loads the first one it finds. If there is none it does nothing and returnsFalse, no error.line 5- A variable that is **already set** in the environment is not changed. So a real environment variable from your shell or the server always beats
.env, which is what you want in production.load_dotenv(override=True)reverses that.line 5 - Square brackets for a required setting: a missing key stops the program right here with
KeyError: 'LLM_API_KEY', instead of failing later with a confusing 401 from the API.line 9 - Print **whether** the key is set, never the key itself.line 13
# real values for your machine
LLM_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama3.2:3b
LLM_API_KEY=ollama # copy to .env and fill in
LLM_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama3.2:3b
LLM_API_KEY=replace-me .venv/
__pycache__/
.env Create the three files next to main.py and run uv run python main.py. You should see model: llama3.2:3b, url: http://localhost:11434/v1 and key loaded: True. Now run LLM_MODEL=qwen2.5:3b uv run python main.py (macOS or Linux): the first line becomes model: qwen2.5:3b, because the shell variable wins over .env. Ollama ignores the key, but hosted APIs need a real one, and that is the value .env protects.
Tip In .env, write NAME=value with no spaces around = and no export. Put quotes around values that contain spaces or a #, for example SYSTEM_PROMPT="Be brief. #1 rule: cite sources", because an unquoted # after a space starts a comment.
8One settings object, and keeping secrets secret
Reading os.environ all over the code makes settings hard to find and hard to test. Read them once, at startup, into one settings object, check that the required ones are there, and pass that object around. Lab 1's config.py does exactly this.
A frozen dataclass (lesson 5) is enough. field(repr=False) keeps the API key out of the text you get from print(settings), and from_env takes the environment as a parameter, so a test can pass a plain dict instead of touching the real environment.
The rules for secrets: never commit them (use .gitignore and .env.example); never log them (no print(os.environ), no logging of request headers, mask a key if you must show it); never put them in a prompt (the model can repeat it to the user); and if one leaks, revoke it and create a new one right away. Deleting the commit is not enough: Git history, forks and clones keep the old key.
import os
from dataclasses import dataclass, field
REQUIRED = ("LLM_API_KEY",)
@dataclass(frozen=True)
class Settings:
model: str
base_url: str
max_tokens: int
api_key: str = field(repr=False) # hidden from print() and logs
@classmethod
def from_env(cls, env=None):
env = os.environ if env is None else env
missing = [name for name in REQUIRED if not env.get(name)]
if missing:
raise RuntimeError(f"missing settings: {', '.join(missing)} (copy .env.example to .env)")
return cls(
model=env.get("LLM_MODEL", "llama3.2:3b"),
base_url=env.get("LLM_BASE_URL", "http://localhost:11434/v1"),
max_tokens=int(env.get("LLM_MAX_TOKENS", "512")),
api_key=env["LLM_API_KEY"],
)
def mask(secret):
"""Enough to tell keys apart in a log, not enough to use one."""
return secret[:3] + "..." + secret[-4:] if len(secret) > 12 else "***"
s = Settings.from_env({"LLM_API_KEY": "sk-test-51Hx9fakefake7d2a", "LLM_MAX_TOKENS": "256"})
print(s)
print("using key", mask(s.api_key))
print(s.max_tokens * 2)
try:
Settings.from_env({})
except RuntimeError as e:
print("startup failed:", e)
Expected output
Settings(model='llama3.2:3b', base_url='http://localhost:11434/v1', max_tokens=256) using key sk-...7d2a 512 startup failed: missing settings: LLM_API_KEY (copy .env.example to .env)
env=None and then os.environ if env is None else env is the safe-default pattern from lesson 4. In the real program you call Settings.from_env() with no argument, right after load_dotenv(), and the app either starts with valid settings or stops with a clear message.
Tip In bigger apps, the pydantic-settings package does all of this in one class: it reads environment variables and .env, converts types, reports every missing value, and has a SecretStr type that prints as **********.
Watch out repr=False only changes print() and repr(). dataclasses.asdict(s), vars(s) and json.dumps(vars(s)) still contain the key. Never dump a settings object into a log, an error report or an API response.
9Total token usage per user from a JSONL log
Now put it together. Most LLM apps write one JSON line per model call: who asked, which model, and the usage block the API returns (prompt_tokens and completion_tokens). Cost reports, rate limits and "who is burning our budget" questions all start from that file.
Real logs are messy. This one has a blank line, a failed call with no usage, and a last line cut off because the process crashed while writing it. The code skips what it cannot use, says what it skipped, and keeps going: one bad line must not lose a whole day of numbers.
collections.Counter is a dict that starts every key at 0, so tokens[user] += n works for a user it has not seen yet. most_common() returns (key, count) pairs, largest first. In the f-string, {user:<6} pads the name to 6 characters on the left and {total:>7} right-aligns the number in 7, which lines the report up in columns.
import json
import tempfile
from collections import Counter
from pathlib import Path
LOG = """\
{"ts": "2026-11-29T10:00:01", "user": "asha", "model": "llama3.2:3b", "usage": {"prompt_tokens": 120, "completion_tokens": 48}}
{"ts": "2026-11-29T10:00:07", "user": "ben", "model": "llama3.2:3b", "usage": {"prompt_tokens": 300, "completion_tokens": 95}}
{"ts": "2026-11-29T10:01:12", "user": "asha", "model": "qwen2.5:7b", "usage": {"prompt_tokens": 410, "completion_tokens": 160}}
{"ts": "2026-11-29T10:02:30", "user": "chen", "model": "llama3.2:3b", "error": "timeout"}
{"ts": "2026-11-29T10:03:05", "user": "ben", "model": "llama3.2:3b", "usage": {"prompt_tok
"""
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "llm_calls.jsonl"
path.write_text(LOG, encoding="utf-8") # pretend the app wrote this
tokens = Counter() # user -> total tokens
calls = Counter() # user -> successful calls
skipped = 0
with path.open(encoding="utf-8") as f:
for n, line in enumerate(f, start=1): # n = line number, for messages
if not line.strip():
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
print(f"line {n}: not valid JSON, skipped")
skipped += 1
continue
usage = rec.get("usage")
if usage is None: # a failed call has no usage
continue
tokens[rec["user"]] += usage["prompt_tokens"] + usage["completion_tokens"]
calls[rec["user"]] += 1
for user, total in tokens.most_common():
print(f"{user:<6}{calls[user]:>2} calls{total:>7} tokens")
summary = {"tokens_by_user": dict(tokens), "skipped_lines": skipped}
(Path(tmp) / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(json.dumps(summary))
Expected output
line 6: not valid JSON, skipped
asha 2 calls 738 tokens
ben 1 calls 395 tokens
{"tokens_by_user": {"asha": 738, "ben": 395}, "skipped_lines": 1}Asha made two calls: 120 + 48 and 410 + 160, so 738 tokens. Chen's only call timed out, so Chen is not in the report. The file is read one line at a time, so the same code works on a log of millions of calls. Multiply by a price per million tokens and you have a cost report; the tracing and cost lab builds this into a real app.
Tip When your app writes such a log, open it with "a", write one complete line with json.dumps(record) + "\n", and log token counts and IDs, not the user's whole prompt or any key. Prompts can hold personal data.
Common mistakes
- Calling
open()orread_text()withoutencoding="utf-8": it works on your Mac and breaks on Windows withUnicodeDecodeError. - Opening with
"w"when you meant"a":"w"empties the file first, so yesterday's log is gone. - Treating environment variables as typed:
bool("false")isTrueand"512" + 1is aTypeError. Every value is a string; convert it. - Committing
.env, or printing settings,os.environor request headers into logs. A leaked key must be revoked and replaced, not just deleted from Git. - Reading a
.jsonlfile withjson.load()(it fails with "Extra data"), or writing it withindent=2(one record spread over many lines). Onejson.dumpsper line, onejson.loadsper line. - Building paths with string concatenation (
folder + "/" + name) instead ofPath(folder) / name.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Load a JSON Lines file
Write load_jsonl(path) that reads a JSON Lines file (UTF-8) and returns a list of dicts, one per line, skipping blank lines. path may be a str or a Path.
import json
from pathlib import Path
def load_jsonl(path):
# your code here
return []
Hint
Open with `Path(path).open(encoding="utf-8")`, loop over the lines, skip a line when `line.strip()` is empty, and `json.loads` the rest.
2A boolean setting that means what it says
Write env_bool(name, default=False, env=None). It reads name from env (or os.environ when env is None). Ignoring case and surrounding spaces, 1, true, yes, on mean True and 0, false, no, off mean False. A missing or empty value returns default. Anything else raises ValueError, so a typo in a setting is caught at startup.
import os
def env_bool(name, default=False, env=None):
env = os.environ if env is None else env
value = env.get(name)
if value is None:
return default
return bool(value)
Hint
Strip and lower the value first. Check it against two tuples of words, return the default when it is empty, and `raise ValueError(...)` at the end.
3Tokens per model
Write tokens_by_model(lines). lines is a list of strings, each one line of a JSONL log of LLM calls like the one above. Return a dict mapping each model to its total prompt_tokens + completion_tokens. Skip blank lines, lines that are not valid JSON, and records without a usage key.
import json
def tokens_by_model(lines):
totals = {}
for line in lines:
rec = json.loads(line)
u = rec["usage"]
totals[rec["model"]] = u["prompt_tokens"] + u["completion_tokens"]
return totals
Hint
Use `totals.get(model, 0) + n` (or a `Counter`) so calls add up instead of overwriting. Wrap `json.loads` in `try / except json.JSONDecodeError` and `continue`.
Interview questions
Q1Why should you always pass encoding="utf-8" to open() in Python?
Without it, Python uses the platform's default encoding, which is UTF-8 on most Linux and macOS systems but often cp1252 on Windows. The same code then reads or writes different bytes on different machines and can crash with UnicodeDecodeError. Passing encoding="utf-8" makes it the same everywhere.
Q2What is the difference between json.load, json.loads, json.dump and json.dumps?
The s versions work with strings: loads parses a JSON string, dumps returns one. The others work with open files: load(f) reads and parses a file, dump(obj, f) writes to one. All map objects to dicts, arrays to lists, and null, true and false to None, True and False.
Q3Why use JSON Lines instead of a JSON array for datasets and logs?
Each line is a complete record, so you can append a record without rewriting the file, stream a huge file one line at a time with constant memory, process it in parallel by splitting on lines, and a corrupt line only loses that one record. A JSON array must be read and parsed whole.
Q4How do you manage configuration and secrets in a Python service?
Read settings from environment variables, with a .env file (via python-dotenv or pydantic-settings) for local development only. Load them once at startup into a typed settings object and fail fast if a required one is missing. Keep .env in .gitignore, commit a .env.example, use a secrets manager in production, never log or print secrets, and rotate a key immediately if it leaks.
Q5If a variable is set in both the shell and .env, which one does load_dotenv() use?
The shell (real environment) value. load_dotenv() does not overwrite variables that are already set unless you pass override=True. That lets production set real values while .env provides local defaults.
Q6How would you total token usage per user from a 20 GB JSONL log?
Stream it: open with UTF-8, loop over lines, json.loads each one inside try/except to skip corrupt lines, and add the usage to a Counter keyed by user. Memory stays constant because only one line and the running totals are held. For many files, process them in parallel and merge the counters.