Call Ollama's Local Generate API From Python
Send one bounded request to an Ollama server on loopback, extract the result and diagnose the common failure paths.
Difficulty Intermediate
What you will build
A short Python client will call Ollama's generate endpoint and print only its generated text. The example keeps the host fixed to loopback and asks for one JSON response, avoiding the need for a streaming parser.
Prerequisites
Use Python 3 and an installed, running Ollama service. Install a small local model from the Ollama library and check its licence before use. Run ollama list and copy the exact name and tag from that output. RAM or VRAM use depends on the model and its context settings, so start with a small tag. Internet access is normally needed for the initial model download.
Create the client
Save as local_generate.py. Enter your installed local model tag as the only argument.
import json
import sys
from urllib.error import HTTPError, URLError
from urllib.request import (
HTTPRedirectHandler,
ProxyHandler,
Request,
build_opener,
)
class RejectRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
if len(sys.argv) != 2:
raise SystemExit("Usage: python3 local_generate.py MODEL_TAG")
payload = {
"model": sys.argv[1],
"prompt": "In one sentence, explain why bicycles have gears.",
"stream": False,
"options": {"num_predict": 80},
}
request = Request(
"http://127.0.0.1:11434/api/generate",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
client = build_opener(ProxyHandler({}), RejectRedirects())
try:
with client.open(request, timeout=120) as response:
result = json.load(response)
print(result["response"])
except HTTPError as error:
raise SystemExit(f"Ollama returned HTTP {error.code}.")
except (URLError, TimeoutError) as error:
raise SystemExit(f"Could not complete the local request: {error}")
The stream flag requests a single response object. The num_predict option limits generation length. The request has a socket timeout, which is especially relevant during a cold model load. Explicitly disabling configured proxies and following no redirects keeps this example's request on the chosen loopback address.
Troubleshooting and practice
A connection refusal usually warrants checking whether the daemon is running and whether it is listening on 127.0.0.1:11434. For HTTP 404, verify the installed tag and the request path. A timeout during the first request may indicate a slow load or limited memory. Check resource use and try a smaller model before increasing the timeout. Keep the service bound to loopback for this exercise. Run the exercise twice with different installed tags, then compare factual accuracy and the time to first completed answer using a stopwatch.