Sub topic 9
Calling the REST API with generate and chat
Ollama runs a local HTTP server, and the ollama command is only one client of it. Any program that can send JSON over HTTP can use the same server. This chapter covers the two main endpoints, /api/generate and /api/chat, and the request and response fields you need to use them.
This chapter assumes you have these prerequisites:
- Ollama is installed and the server is running on the default address,
http://localhost:11434. - You have pulled
llama3.2or another model. - You are comfortable reading JSON and running
curl. - You know basic Python.
How a request flows
Your client sends an HTTP POST with a JSON body. The server loads the model into memory if it is not already loaded, runs inference, and returns JSON. The first call to a model is slower because of that load step. Later calls reuse the loaded model until it is unloaded after the keep-alive period.
Choosing between generate and chat
The two endpoints differ in what they accept as input.
| Endpoint | Input | Best for |
|---|---|---|
| `/api/generate` | A single `prompt` string, plus an optional `system` string | One-shot tasks such as summarizing, classifying, or extracting |
| `/api/chat` | A `messages` array of role and content objects | Conversations, and anything that needs system, user, and assistant roles |
Both are stateless. The server does not remember earlier requests. For a multi-turn conversation, your client must resend the whole history each time.
The generate endpoint
The smallest useful request sets model, prompt, and "stream": false.
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "Explain what a context window is in one sentence.",
"stream": false
}'With streaming off, you get one JSON object back. The fields you will use most are:
response: the full generated text.done:truewhen generation has finished.done_reason: why it stopped, for examplestop(the model finished) orlength(it hit a token limit).total_duration,load_duration,eval_duration: timings in nanoseconds.prompt_eval_countandeval_count: the number of prompt tokens and generated tokens.
The count fields tell you how close you are to the context limit and how fast generation ran. Divide eval_count by eval_duration (converted from nanoseconds to seconds) to get tokens per second.
The chat endpoint
/api/chat takes a list of messages. Each message has a role of system, user, or assistant, and a content string.
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2",
"messages": [
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What is quantization?"}
]
}'This request omits "stream": false, so the server streams its reply. You receive many small JSON objects, one per line. Each carries a piece of text in message.content. The last object has "done": true and includes the timing fields. The next chapter covers how to consume that stream. For now, add "stream": false when you want one complete object.
A non-streaming chat response has a message object where generate has a response string:
{
"model": "llama3.2",
"message": {"role": "assistant", "content": "Quantization stores model weights with fewer bits."},
"done": true,
"done_reason": "stop"
}Other fields, such as timings, are omitted here for brevity.
Calling the API from Python
The same request works from any language. This script sends one chat message and prints the reply. raise_for_status() makes an HTTP error stop the script instead of failing later with a confusing KeyError.
import requests
resp = requests.post(
"http://localhost:11434/api/chat",
json={
"model": "llama3.2",
"messages": [{"role": "user", "content": "Why is the sky blue?"}],
"stream": False,
},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["message"]["content"])The generous timeout is deliberate. The first request may wait for a model to load from disk, which can take many seconds on a large model.
Keeping conversation history
Because the server is stateless, a multi-turn chat means appending each reply to your own list and sending the whole list again.
import requests
URL = "http://localhost:11434/api/chat"
messages = [{"role": "system", "content": "You are a concise assistant."}]
for question in ["What is a token?", "How many tokens is a typical word?"]:
messages.append({"role": "user", "content": question})
resp = requests.post(
URL,
json={"model": "llama3.2", "messages": messages, "stream": False},
timeout=120,
)
resp.raise_for_status()
reply = resp.json()["message"]
messages.append(reply)
print(f"Q: {question}\nA: {reply['content']}\n")The second question says "typical word" without naming tokens. The model can answer only because the first exchange is in messages. Every turn grows the prompt, so a long conversation eventually exceeds the context window. At that point the server truncates the oldest content without raising an error. Trim or summarize old messages yourself.
Setting options
Generation settings go in an options object, not at the top level of the request.
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "List three uses for a local LLM.",
"stream": false,
"options": {
"temperature": 0.2,
"num_ctx": 4096,
"num_predict": 120,
"seed": 42
}
}'temperaturecontrols randomness. Lower values give more repeatable output.num_ctxsets the context window size in tokens for this request.num_predictcaps the number of generated tokens.seedmakes sampling reproducible when the other settings are the same.
Options in a request override defaults from the model's Modelfile. Changing num_ctx between requests can force the server to reload the model with a new context size, which adds latency.
Other useful top-level fields are:
system: replaces the system prompt for a generate request.format: set to"json"to constrain output to valid JSON. You should still tell the model in the prompt to produce JSON.keep_alive: how long the model stays loaded after the request, for example"10m", or0to unload immediately.
Common errors
- Connection refused. The server is not running or is on another host or port. Check with
curl http://localhost:11434/and expect the text "Ollama is running". - 404 with
model "..." not found. The model has not been pulled, or the name or tag is misspelled. Runollama listto see exact names. - Options ignored.
temperatureplaced at the top level instead of insideoptionsis silently ignored. KeyError: 'response'or'message'. You used the wrong field for the endpoint, or the body was an error object. Generate returnsresponse, and chat returnsmessage.content.- Truncated output. Check
done_reason. A value oflengthmeansnum_predictor the context limit stopped generation. - Parse errors on a streamed reply. Without
"stream": false, the body is many JSON lines, soresp.json()fails.
Exercise
You send a request to /api/chat with "options" set correctly and "stream" omitted, then call resp.json() in Python and get a JSON decode error. What is the cause, and what are two ways to fix it?
Show answer
Streaming is on by default, so the body is many newline-delimited JSON objects, not one object. Either add "stream": false to the request, or read the response line by line (for example with stream=True and iter_lines) and parse each line as its own JSON object.
Exercise
A two-turn Python chat script gets an answer to turn one but the model seems unaware of it on turn two. What is missing from the second request?
Show answer
The earlier messages. The server is stateless, so the second request must include the system message, the first user message, and the assistant's first reply (in the messages array) before the new user message.