Most AI features are a Python service calling a language model over HTTP, either a hosted provider or a model you serve yourself. The call itself is easy; making it dependable is a checklist: keys from the environment, a system prompt and messages, limits on output length, streaming for responsiveness, structured output that you validate, a tool-calling loop with a step limit, retries with backoff, and a record of tokens and cost per request. This lesson builds a ticket triage service on an LLM API, and shows the two failures that reach the bill or the pager: no limits, and trusting the model's text to be valid JSON.
Difficulty: Intermediate · Know this first: Lesson 40, Lesson 246
This bar adds up seconds per ticket, including what failures cost. It is a worked example, not a measurement. The tools and validation hops decide whether the service is safe to run unattended.
Each tool step resends the whole conversation. Set the starting prompt size, the tokens each step adds, and the number of steps allowed.
Runaway: cost grows with the square of the number of steps
Three questions. No score is saved anywhere — this is just you against the material.
Calling LLMs from Python grows in four levels: a first call, dependable calls, tools and streaming, and LLM features in production.
At the basic level you can send messages and read a reply.
max_tokens, temperature; the key from the environment.Where it breaks: a key committed to Git, which must then be rotated.
Try it: Basic
Where should the API key live?
Now do it: Search your repositories for strings that look like API keys.
At the intermediate level every call is bounded and checked.
Try it: Intermediate
Validation fails on a reply. What is a good recovery?
Now do it: Add a one-retry-then-fallback wrapper to one LLM call.
At the advanced level the model can act, safely.
Try it: Advanced
A tool asks the model for a file path to delete. What must happen before running it?
Now do it: List the tools in one agent and mark which change anything.
At the master level LLM features are measured like any service.
Trade-off: larger models answer harder cases and cost more per token and per second; routing easy requests to a small model saves money and needs an evaluation to prove quality holds.
Try it: Master
What should gate a change to a prompt in production?
Now do it: Collect 100 real inputs with expected outputs for one LLM feature.
A triage call with a schema, validation, one retry, a fallback, and token logging. It targets an OpenAI-compatible endpoint; the default is a local Ollama server (ollama pull qwen2.5:0.5b), so it runs without an account.
import json, os, re, urllib.request
URL = os.environ.get("LLM_URL", "http://localhost:11434/v1/chat/completions")
MODEL = os.environ.get("LLM_MODEL", "qwen2.5:0.5b")
CATEGORIES = {"billing", "login", "bug", "other"}
SYSTEM = ('You triage support tickets. Reply with JSON only: '
'{"category": one of billing, login, bug, other; "urgency": 1-4; "summary": short string}.')
def call(messages, max_tokens=300):
body = {"model": MODEL, "messages": messages, "max_tokens": max_tokens, "temperature": 0}
req = urllib.request.Request(URL, data=json.dumps(body).encode(), headers={
"Content-Type": "application/json", "Authorization": f"Bearer {os.environ.get('LLM_API_KEY', 'none')}"})
with urllib.request.urlopen(req, timeout=60) as r:
data = json.load(r)
usage = data.get("usage", {})
print("tokens in/out:", usage.get("prompt_tokens"), usage.get("completion_tokens"))
return data["choices"][0]["message"]["content"]
def validate(text):
m = re.search(r"\{.*\}", text, re.S) # tolerate a preamble or a code fence
if not m:
raise ValueError("no JSON object in reply")
d = json.loads(m.group(0))
if d.get("category") not in CATEGORIES or d.get("urgency") not in (1, 2, 3, 4) or not isinstance(d.get("summary"), str):
raise ValueError(f"bad fields: {d}")
return d
def triage(ticket):
messages = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"<ticket>{ticket}</ticket>"}]
for attempt in (1, 2):
reply = call(messages)
try:
return validate(reply)
except (ValueError, json.JSONDecodeError) as e:
messages += [{"role": "assistant", "content": reply},
{"role": "user", "content": f"That was invalid ({e}). Reply with the JSON object only."}]
return {"category": "other", "urgency": 2, "summary": "needs human triage"} # safe fallback
print(triage("I was charged twice for my March invoice and need a refund today."))
This is a composite of a failure pattern that keeps repeating; the details are illustrative. One confusing ticket cost as much as a normal day.
Tool loops are capped at 4 steps and 20,000 tokens per request, tickets over the cap go to a person, and steps and cost per request are graphed with alerts at the 99th percentile.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: For the commands, a local model with Ollama: curl -fsSL https://ollama.com/install.sh | sh && ollama pull qwen2.5:0.5b.
Type each one, read what it prints, and compare it with the note above it.
An OpenAI-compatible chat call to a local model, with max_tokens.
curl -s localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "max_tokens": 40, "temperature": 0, "messages": [{"role": "system", "content": "Reply in one short sentence."}, {"role": "user", "content": "What is a load balancer?"}]}' | python3 -c "import sys, json; d = json.load(sys.stdin); print(d['choices'][0]['message']['content']); print('usage:', d['usage'])"Ask for JSON and validate it: never trust it blindly.
curl -s localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "max_tokens": 60, "temperature": 0, "response_format": {"type": "json_object"}, "messages": [{"role": "user", "content": "Return JSON with keys category (billing|login|bug|other) and urgency (1-4) for: I was charged twice."}]}' | python3 -c "import sys, json; r = json.loads(json.load(sys.stdin)['choices'][0]['message']['content']); print(r, 'VALID' if r.get('category') in {'billing', 'login', 'bug', 'other'} else 'INVALID')"Streaming: the first words arrive long before the end.
curl -sN localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "stream": true, "max_tokens": 30, "messages": [{"role": "user", "content": "Count to ten."}]}' | head -3tool_loop_budget.pyThis program runs a tool-calling loop against a scripted fake model that keeps asking for more searches, once without limits and once with a step cap and a token budget, and prints the tokens each would bill. Save it as tool_loop_budget.py, then run it.
# tool_loop_budget.py
def fake_model(conversation_tokens, step):
return {"tool": "search_kb", "adds": 700} if step < 46 else {"answer": "done"} # a confused model
def run(max_steps=None, max_tokens=None, start=1100):
tokens_billed, conv, step = 0, start, 0
while True:
tokens_billed += conv # each call resends the whole conversation
reply = fake_model(conv, step)
if "answer" in reply:
return step, tokens_billed, "answered"
step += 1
conv += reply["adds"]
if max_steps and step >= max_steps:
return step, tokens_billed, "step cap reached: handed to a person"
if max_tokens and tokens_billed >= max_tokens:
return step, tokens_billed, "token budget reached: handed to a person"
for label, kwargs in [("no limits", {}), ("cap 4 steps, 20k tokens", {"max_steps": 4, "max_tokens": 20_000})]:
steps, billed, how = run(**kwargs)
print(f"{label:<24} steps {steps:>2}, input tokens billed {billed:>9,} -> {how}")
Run it, and you should see this output:
$ python3 tool_loop_budget.py no limits steps 46, input tokens billed 808,400 -> answered cap 4 steps, 20k tokens steps 4, input tokens billed 8,600 -> step cap reached: handed to a person
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/calling-llm-apis-from-python && cd ~/labs/calling-llm-apis-from-python) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Calling LLM APIs from Python", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'An OpenAI-compatible chat call to a local model, with max_tokens.'
'Ask for JSON and validate it: never trust it blindly.'
'Streaming: the first words arrive long before the end.'
)
step_1() {
curl -s localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "max_tokens": 40, "temperature": 0, "messages": [{"role": "system", "content": "Reply in one short sentence."}, {"role": "user", "content": "What is a load balancer?"}]}' | python3 -c "import sys, json; d = json.load(sys.stdin); print(d['choices'][0]['message']['content']); print('usage:', d['usage'])"
}
step_2() {
curl -s localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "max_tokens": 60, "temperature": 0, "response_format": {"type": "json_object"}, "messages": [{"role": "user", "content": "Return JSON with keys category (billing|login|bug|other) and urgency (1-4) for: I was charged twice."}]}' | python3 -c "import sys, json; r = json.loads(json.load(sys.stdin)['choices'][0]['message']['content']); print(r, 'VALID' if r.get('category') in {'billing', 'login', 'bug', 'other'} else 'INVALID')"
}
step_3() {
curl -sN localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen2.5:0.5b", "stream": true, "max_tokens": 30, "messages": [{"role": "user", "content": "Count to ten."}]}' | head -3
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
head, curl, Pipes.Build a service that extracts structured fields (vendor, date, total, currency, line items) from 20,000 invoice PDFs a day using an LLM API.
What is the output schema, and how is it validated? What happens when validation fails twice? How are rate limits and retries handled at this volume? How do you know cost per invoice and catch runaway requests?
Say 3,000 input tokens per invoice, 400 output tokens, a rate limit of 500 requests per minute, and a target of under 2 cents per invoice.
Text extracted from PDFs first; a JSON schema via structured output; Pydantic validation plus arithmetic checks (line items sum to the total); one retry with the error, then a human queue; a work queue with 6 concurrent workers and backoff on 429; max_tokens 600; tokens, cost, and validation failures logged per invoice with daily dashboards and alerts.
A larger model fails validation less often and costs more per invoice; a smaller model with one retry may be cheaper overall. Strict checks send more invoices to people, and keep wrong totals out of the accounts.