Call a local LLM from Python with Ollama: a stateless request, then a chatbot with memory

Step-by-step Python code that calls Ollama's /api/chat. First we prove the model remembers nothing between requests. Then we build a terminal chatbot that remembers, and see why the assistant's answers and the context window matter.

Three requests. Request 1 sends the user message This is Prasad, 5 tokens, and the model replies Nice to meet you, Prasad. Request 2 sends only What is my name?, 6 tokens, and the model replies Sorry, I don't know your name. Request 3 sends the earlier user message and assistant reply, highlighted as history, plus What is my name?, 20 tokens, and the model replies Your name is Prasad. A footer says the window starts empty every request, and the model doesn't remember, your app does.
Fig. 1 — The model starts every request with an empty window. To remember, your app sends the history again.

You have Ollama running and a model downloaded. Now let’s talk to it from Python.

We’ll build this up in small steps, each one a complete program you can copy and run:

  1. A first call: send one message to /api/chat and print the answer.
  2. A stateless test: tell the model your name, then ask for it in a second request. It won’t know. We’ll see exactly why.
  3. A chatbot with memory: keep a history list, send it every time, and the model “remembers”.
  4. The context window: why the history can’t grow forever, and how to trim it.
  5. Bonus: streaming the answer word by word, and the official ollama Python library.

This is part seven of a series, but it stands on its own. (Prefer Java? The same journey is in Call a local LLM from Java.)

Before you start

You need three things:

ollama pull qwen3.5:4b
  • Python 3.9 or newer, and the popular requests library for HTTP:
pip install requests

Every program below talks to the same address: http://localhost:11434/api/chat. That is Ollama’s chat endpoint; the REST API guide explains every field we send.

Step 1: your first call to Ollama from Python

Here is the whole idea in one small function. It takes a list of messages, sends them to Ollama, and returns the reply text.

import requests

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3.5:4b"


def chat(messages):
    """Send a list of messages to Ollama and return the assistant's reply text."""
    body = {
        "model": MODEL,
        "messages": messages,
        "think": False,   # skip the model's reasoning step
        "stream": False,  # one complete JSON instead of many pieces
    }
    response = requests.post(OLLAMA_URL, json=body, timeout=300)
    response.raise_for_status()
    return response.json()["message"]["content"]


print(chat([{"role": "user", "content": "Explain RAG in two sentences."}]))

What each part does:

  • body is exactly the JSON you would type into Postman or curl. In Python it is just a dictionary.
  • "messages" is a list. Each message is a dictionary with a role ("user" here) and content (the text).
  • "think": False tells Qwen 3.5 to answer directly instead of reasoning first, which is much faster on a laptop.
  • "stream": False asks for one complete JSON response, so we can read it in one go.
  • requests.post(..., json=body) turns the dictionary into JSON and sends it. timeout=300 gives a slow laptop up to five minutes.
  • raise_for_status() turns an HTTP error (like “model not found”) into a clear Python exception instead of a confusing crash later.
  • response.json()["message"]["content"] digs the answer out of the response. The reply lives inside message, and its text is in content.

Save it as first_call.py and run python first_call.py. You should see a short explanation of RAG, generated entirely on your own machine.

Step 2: the model is stateless (it remembers nothing)

Now an experiment. We send two separate requests:

  1. “This is Prasad”
  2. “What is my name?”
import requests

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3.5:4b"


def chat(messages):
    """Send a list of messages to Ollama and return the assistant's reply text."""
    body = {
        "model": MODEL,
        "messages": messages,
        "think": False,   # skip the model's reasoning step
        "stream": False,  # one complete JSON instead of many pieces
    }
    response = requests.post(OLLAMA_URL, json=body, timeout=300)
    response.raise_for_status()
    return response.json()["message"]["content"]


# Request 1: introduce yourself
print("Request 1:", chat([{"role": "user", "content": "This is Prasad"}]))

# Request 2: a brand-new request with only the new question
print("Request 2:", chat([{"role": "user", "content": "What is my name?"}]))

Example output (the exact words will vary):

Request 1: Nice to meet you, Prasad! How can I help you today?
Request 2: I'm sorry, but I don't know your name. Could you tell me?

The model greeted Prasad by name, and a second later it has no idea who you are. It didn’t forget. It never saw it. The second request contained only “What is my name?”, and that is all the model received.

This is what stateless means: every request starts with an empty context window. The model reads only what is inside the current request, writes an answer, and keeps nothing.

Why are LLMs built this way?

It feels odd at first, but there are three good reasons:

  • The weights are frozen. Chatting doesn’t change the model; only training does. There is nowhere inside the model to “save” your name. (See what a large language model is.)
  • One model, many users. The same model can answer many people and many conversations. If each request stands on its own, none of them get mixed up.
  • It reads everything to predict. Every next token is chosen by looking at all the tokens in the window. So “what the model knows right now” is simply “what is in this request”.
“The model doesn’t remember. Your app does.”

Step 3: a chatbot with memory

So how do ChatGPT-style apps remember? The app keeps the conversation in a list and sends the whole list on every request. The model still forgets everything; it just gets reminded every single time.

Here is a complete terminal chatbot:

import requests

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3.5:4b"


def chat(messages):
    body = {"model": MODEL, "messages": messages, "think": False, "stream": False}
    response = requests.post(OLLAMA_URL, json=body, timeout=300)
    response.raise_for_status()
    return response.json()["message"]["content"]


def main():
    # The memory of the conversation lives here, in your program.
    history = [
        {"role": "system", "content": "You are a friendly tutor. Keep answers short and simple."}
    ]

    print("Chat with", MODEL, "(type /bye to quit)")
    while True:
        user_text = input("You: ").strip()
        if user_text == "/bye":
            break
        if not user_text:
            continue

        history.append({"role": "user", "content": user_text})       # 1. add the question
        reply = chat(history)                                          # 2. send EVERYTHING
        history.append({"role": "assistant", "content": reply})       # 3. remember the answer

        print("AI:", reply)
        print()


if __name__ == "__main__":
    main()

Save it as simple_chatbot.py and run it:

Chat with qwen3.5:4b (type /bye to quit)
You: This is Prasad
AI: Nice to meet you, Prasad! What would you like to learn today?

You: What is my name?
AI: Your name is Prasad.

You: /bye

It remembers. Nothing about the model changed. Only our code did.

What actually gets sent

The loop does three things every turn: add the question, send everything, remember the answer. Here is the history list at the moment we ask “What is my name?”:

[
  { "role": "system",    "content": "You are a friendly tutor. Keep answers short and simple." },
  { "role": "user",      "content": "This is Prasad" },
  { "role": "assistant", "content": "Nice to meet you, Prasad!" },
  { "role": "user",      "content": "What is my name?" }
]

Now “Prasad” is inside the request, so the model can answer. Look at each role:

  • system (first, once): the rules. The person chatting never types it. (More on roles.)
  • user: everything the person typed, in order.
  • assistant: everything the model answered, in order.

Why we must add the assistant’s answer

It is tempting to send only the user’s messages. Don’t. Without the assistant messages, the model would see:

user: This is Prasad
user: What is my name?
user: Can you give me an example of that?

A list of questions with no answers. The model can’t tell what it already said, so follow-ups like “an example of that” or “say it more simply” have nothing to refer to, and it may repeat itself or contradict its earlier answers. Adding each reply with the role assistant gives the model the real conversation, both sides of it.

Step 4: the context window (why history can’t grow forever)

There is a catch. Because we resend everything, every request is bigger than the last.

Six turns of a chat. Turn 1 sends 1 message, about 12 tokens. Turn 2 sends 3 messages, about 41 tokens. Turn 3 sends 5 messages, about 70 tokens, and so on up to turn 6 with 11 messages and about 171 tokens. User, assistant and new-question messages are coloured differently. Below, a context window bar fills up with system plus history plus new question, towards a dashed limit. A note says old turns eventually won't fit, so keep the system message and drop or summarise the oldest turns.
Each turn resends the whole conversation. Token counts are illustrative.

The context window is the maximum number of tokens the model can read in one request: the system message, the whole history, and the new question, all together. Qwen 3.5 can handle about 256K tokens, which sounds like a lot. But:

  • Ollama may use a smaller window by default to save memory. You can raise it per request with "options": {"num_ctx": 32768}, or in the Ollama app’s settings. A bigger window uses more memory.
  • Bigger requests are slower. The model reads every token of the history on every turn.
  • Real apps put a lot in the window. Picture a shop’s support bot. A system message (120 tokens), the whole refund policy (about 6,000 tokens), the customer’s order (180 tokens) and the question (25 tokens): about 6,325 tokens for a single message. Six messages later, the app has sent about 40,000 tokens, and 36,000 of those were the same policy, over and over. Locally that is only time; on a cloud API you pay for every one of those tokens.

Trim the history

The simplest fix is to keep the system message and only the most recent turns:

MAX_TURNS = 10  # keep the last 10 user/assistant pairs


def trim(history, max_turns=MAX_TURNS):
    """Keep the system message (if any) plus the most recent turns."""
    system = [m for m in history[:1] if m["role"] == "system"]
    rest = history[len(system):]
    return system + rest[-max_turns * 2:]

Call it after you add the assistant’s reply:

history.append({"role": "assistant", "content": reply})
history = trim(history)

The model will now forget things older than ten turns, which is usually fine for a chat. Smarter approaches summarise old turns instead of dropping them, or, for big documents like that refund policy, search for just the paragraph that matters and send only that. That idea is called RAG, and it is where this series goes next.

Bonus: stream the answer word by word

With "stream": False the user waits for the whole answer. Set it to True and Ollama sends many small JSON lines as the answer is written. Here is a version that prints them as they arrive:

import json
import requests

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen3.5:4b"


def chat_stream(messages):
    """Print the reply as it is written, and return the full text at the end."""
    body = {"model": MODEL, "messages": messages, "think": False, "stream": True}
    full_reply = ""
    with requests.post(OLLAMA_URL, json=body, stream=True, timeout=300) as response:
        response.raise_for_status()
        for line in response.iter_lines():
            if not line:
                continue
            chunk = json.loads(line)                     # one small JSON per line
            piece = chunk["message"]["content"]
            print(piece, end="", flush=True)
            full_reply += piece
            if chunk.get("done"):
                break
    print()
    return full_reply


history = [{"role": "user", "content": "Explain RAG in two sentences."}]
reply = chat_stream(history)
history.append({"role": "assistant", "content": reply})

Note the last line: even when streaming, you still join the pieces and add the full reply to the history. Drop chat_stream into the chatbot in place of chat and the answers appear word by word.

Bonus: the official ollama Python library

Calling the REST API with requests shows you exactly what happens, which is why we did it first. For real projects, Ollama also has an official library that wraps the same API:

pip install ollama
from ollama import chat

response = chat(
    model="qwen3.5:4b",
    messages=[{"role": "user", "content": "Explain RAG in two sentences."}],
    think=False,
)
print(response.message.content)

Same JSON, same endpoint, same stateless model. Everything above about history and the context window still applies.

Troubleshooting

  • ConnectionError / connection refused: Ollama isn’t running. Open the app or run ollama serve.
  • HTTPError: 404: the model isn’t downloaded or the name is spelled differently. Run ollama pull qwen3.5:4b and check ollama list.
  • The first answer is slow: the model is loading into memory. It stays loaded for about 5 minutes, so the next answers are faster.
  • Answers are slow in general: keep "think": False, try a smaller model, or close other heavy apps.

Key takeaways

  • Calling Ollama from Python is one requests.post to http://localhost:11434/api/chat with a JSON body.
  • The model is stateless: every request starts with an empty window and it keeps nothing afterwards.
  • A chatbot “remembers” because your code keeps a history list and sends it every time: add the question, send everything, add the answer.
  • Always add the model’s reply with the role assistant, or follow-up questions lose their meaning.
  • History grows every turn. Respect the context window: trim old turns, and send only what’s needed.

The full series: Run LLMs locally with Ollama

Each part stands on its own, so jump to whichever you need:

  1. How to run an LLM on your own computer
  2. What is Ollama? The video player for AI models, and localhost:11434 explained
  3. Ollama CLI commands: the complete cheat sheet
  4. The Ollama desktop app: chat, pick models, and launch Claude Code or Copilot
  5. System, user and assistant roles explained
  6. Ollama REST API: /api/generate vs /api/chat
  7. Call a local LLM from Python: a stateless request, then a chatbot with memory (you are here)
  8. Call a local LLM from Java: HttpClient, a stateless request, then a chatbot with memory

See it in action

Prefer watching? This video walks through the same ideas with live, hands-on demos.

Video thumbnail: Call a local LLM from Python with Ollama: a stateless request, then a chatbot with memoryWatch on YouTube ↗

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.