Call an LLM API from Python: Your First Request
You have a model answering curl in your terminal, but an app has to ask it questions from code. This lesson shows you how to call an LLM API from Python: send a first request to Ollama, read the answer and its token counts, stream it, and handle the errors you will meet.
The order slip: an LLM call is one HTTP request
An API, an application programming interface, is a fixed way for one program to ask another for something (What Is an API?). Ollama's API runs over HTTP: your program sends a POST, the HTTP method for sending data, to an endpoint, a URL path that does one job. The data is JSON, plain text of named fields and lists (REST APIs and JSON), and so is the answer.
In the previous lesson you started Ollama on port 11434 and sent one prompt to /api/generate. Here you use /api/chat, which takes a list of messages: the shape later lessons build on. Because it is only HTTP and JSON, any language can make the call. Notice in the flowchart that nothing is special to AI: it is an ordinary POST.
Send your first request from Python
A virtual environment is a folder with its own installed packages on top of your normal Python (Python's venv docs), so this lab cannot break other projects. Into it you install requests, a popular HTTP library. With the labs cloned as in lesson 1, run:
cd course-labs/building-llm-apps/02-python-first-request
python3 -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
python3 -m venv .venv creates the environment in .venv; . .venv/bin/activate switches this terminal to it, and your prompt starts with (.venv). pip should end with a line starting Successfully installed that lists requests-2.34.2. On Debian or Ubuntu, ensurepip is not available means you need the python3-venv package; externally-managed-environment from pip means the environment is not active. The heart of first_request.py, without error handling:
import requests
payload = {
"model": "llama3.2:3b",
"messages": [{"role": "user", "content": "Explain in two sentences what an API is."}],
"stream": False,
}
response = requests.post("http://localhost:11434/api/chat", json=payload, timeout=(5, 120))
data = response.json()
print(data["message"]["content"])
payload is the order slip. model must match a name in ollama list. messages is the conversation so far: a list of dictionaries with a role and content, where user means you wrote it; lesson 3 adds the other roles. json=payload sends the dictionary as JSON, so Python's False arrives as false, and response.json() turns the reply back into a dictionary.
Run python3 first_request.py. You should see two sentences about APIs, worded differently each run, then a line such as prompt_eval_count=36 (tokens in), eval_count=58 (tokens out), done=True, 4.2 s in total (illustrative numbers). The first run after a start is slower while the model loads.
Read the reply
The diagram sets the reply beside the request. The aha: the text you want sits two levels deep, in message.content, and the fields around it say what the call used.
message has the role assistant, meaning the model wrote it. done is true when the reply is complete, and done_reason says why it ended, usually stop. prompt_eval_count counts the tokens, the word pieces a model reads, in your input; eval_count counts the tokens it wrote. Durations are in nanoseconds.
Tokens in exceeds your word count because Ollama wraps your messages in the model's chat template: marker tokens that show where each message starts and ends. Watch both counts. Hosted APIs bill per token, and every model has a limit on how much it reads at once; lesson 12 measures them.
Streaming: read the reply as it is written
Leave out "stream": False and /api/chat streams, its default: the server sends the reply in pieces while the model writes it. The format is newline-delimited JSON, one small, complete JSON object, a chunk, per line.
Each chunk carries a few characters in message.content and "done": false; the last has "done": true, empty content, and the counts. The aha: a person can start reading long before the reply is finished. The core of stream_request.py, where OLLAMA_URL is "http://localhost:11434":
payload = {"model": "llama3.2:3b",
"messages": [{"role": "user", "content": "Write a four-line poem about a kettle."}]}
with requests.post(f"{OLLAMA_URL}/api/chat", json=payload, stream=True, timeout=(5, 60)) as response:
for line in response.iter_lines():
if line:
chunk = json.loads(line)
print(chunk["message"]["content"], end="", flush=True)
if chunk["done"]:
print("\ntokens out:", chunk["eval_count"])
Two streams are at work. The JSON field tells Ollama what to send; stream=True tells requests not to wait for the whole body, and iter_lines() yields each line as it arrives. Run python3 stream_request.py and the poem appears a few words at a time; --raw prints every JSON line. Stream when a person is waiting, and use "stream": false when your code needs the whole answer first.
Handle failure properly
Three failures are common: a slow model, a stopped server and a wrong model name. requests waits forever by default, so always pass a timeout. timeout=(5, 120) allows 5 seconds to connect and a read timeout of 120, which the requests docs define as the wait between bytes, not a limit on the whole download. With "stream": false nothing arrives until the reply is complete, so it must cover loading the model plus writing every token.
The error handling in first_request.py, shortened (the lab adds a hint to each message):
try:
response = requests.post(f"{OLLAMA_URL}/api/chat", json=payload, timeout=(5, 120))
except requests.exceptions.Timeout:
print("Error: no reply from Ollama within 120 seconds.")
except requests.exceptions.ConnectionError:
print(f"Error: cannot connect to Ollama at {OLLAMA_URL}.")
else:
if not response.ok:
reason = response.json().get("error")
print(f"Error: Ollama answered HTTP {response.status_code}: {reason}")
Timeout is caught first because a connect timeout counts as both kinds. With the container stopped, nothing listens on port 11434, the connection is refused at once, and you get the hint instead of a traceback. python3 first_request.py --timeout 0.5 shows the timeout message.
A wrong model name raises nothing, because the server did answer: HTTP status code 404, not found, with the body {"error":"model 'llama3.2' not found"}. response.ok is false for codes of 400 or above, so check it. python3 first_request.py --model llama3.2 should print Error: Ollama answered HTTP 404: model 'llama3.2' not found. Mid-stream errors arrive as a line with an error field.
Optional: the OpenAI-compatible endpoint
Many hosted LLM APIs and client libraries use the shape OpenAI made common: POST /v1/chat/completions with model and messages, and the text in choices[0].message.content. Ollama serves it too, as its OpenAI compatibility docs describe. Code written for a hosted API can usually run locally if you change its base URL, the part of the address all endpoints share, to http://localhost:11434/v1/, and the model name.
The official openai Python package also wants an api_key: pass any value, such as "ollama", which Ollama ignores. python3 openai_compat.py makes this call with requests. Later lessons stay on /api/chat for Ollama's own counts and timings.
Check yourself
Your script uses timeout=(5, 10) with "stream": false. The first run after starting Ollama times out; the second works. Why?
No byte arrives until the whole reply is written, so the 10-second read timeout must cover loading the model plus writing the answer. The second run finds the model already in memory. Raise the read timeout, or stream.
Stopping the container makes requests raise ConnectionError, but a mistyped model name raises nothing. Why the difference?
With the container stopped, no server answers, a network failure, so requests raises. A wrong name gets a real HTTP answer, a 404 with an error field, so your code must check response.ok itself.
You ask a nine-word question and prompt_eval_count says 36. Is the counter broken?
No. Tokens are word pieces, not words, and the chat template adds marker tokens around your message that the model also reads.