Concepts / Querying Ollama Models

Querying Ollama Models

query_model builds a dictionary payload with model, messages, and options keys, converts it to JSON bytes, and sends it as a POST request to the chat endpoint.

  • Programming

Predicting the Shape of a Request

Most of the time you will meet the Ollama REST API through a small function that wraps the request for you. This article starts from exactly that kind of function, called query_model, and works backward into the mechanics. Instead of memorizing the HTTP details first, you will follow one call from start to finish and watch what changes at each stage.

What do you think happens?

Before reading on: when query_model builds the dictionary that it will send to the server, which top-level keys do you expect it to contain?

  • Only the prompt

  • The model name, the messages, and the options

  • The URL, the prompt, and the reply

  • A single key holding the whole text

Reveal answer
Answer:

The model name, the messages, and the options

The payload is a dictionary with three keys: model, messages, and options. The prompt travels inside the messages part, and the URL is not part of the payload at all; it is a parameter the function uses to decide where to send the request.

Keep one question in mind as you read. When you call the function with a prompt and get text back, that text passed through several stages: a dictionary was built, converted to bytes, sent over HTTP, and then read back in pieces. If the result is wrong, your goal is to identify the stage where it went off track.

The query_model Function and Its Parameters

The function accepts three parameters: prompt, model, and url. The prompt is the text you want the model to respond to. The model is the name of the Ollama model that should generate the reply. The url tells the function where the Ollama service is listening. Its default endpoint is http://localhost:11434/api/chat, which means that if you leave the url argument out, the request goes to the chat endpoint on the local machine.

Defaults are written into the function's signature, so you can read them there to see what a call uses when you leave arguments out. This matters when you trace a result: a value you did not pass explicitly may still be shaping the request.

Building the Payload Dictionary

The first thing query_model does is assemble a dictionary. This dictionary is the payload: the data the function will send to the server. Its outer structure has three keys, which are the model name, the messages, and the options. Each key holds a different part of the request, and the prompt you passed in ends up inside the messages part.

python
Notes on the code
  • model: the model name the caller supplied
  • messages: a list that carries the prompt text
  • options: settings for the request, shown here as an empty dictionary
payloaddictionary built firstmodelname of the Ollama modelmessagescarries the promptoptionsrequest settingskeykeykey
How the model, messages, and options keys are nested inside the payload dictionary before it is converted to JSON bytes.

Sending the Payload as a POST Request

Once the payload dictionary exists, query_model converts it to JSON bytes and sends it as a POST request to the chat endpoint. The conversion step turns the Python dictionary into a serialized form that can travel over HTTP. The server then processes the request and sends its reply back to the function over the same connection.

query_modelPython functionOllama REST APIchat endpoint1. POST payload as JSON bytes2. reply arrives as lines3. read and gather content
The order in which the Python function and the Ollama REST API exchange messages during a single query_model call.

Reading the Reply One Line at a Time

The reply is not read as one block. The function reads it one line at a time, and each line carries a piece of the model's output in its message content. Reading line by line means the function handles each piece as it arrives instead of waiting for a single fixed-size result. The loop continues until there are no more lines to read.

read next lineone line of the replytake message contenttext from this lineappend to stringgrowing replymore lines?return replyfull stringnextnextnextyesno
How the function repeatedly reads one line, handles it, and checks whether the stream has ended before reading again.

Gathering Content Into a Single String

Each line's message content is appended to a growing string. The string starts out holding nothing useful and gets longer with every line. When the reading loop finishes, the accumulated string is the reply, and the function returns it. This is why the value you receive is one complete piece of text even though it arrived in many fragments.

fragment 1content from line 1fragment 2content from line 2fragment 3content from line 3accumulated stringgrows with each appendreturned replyfinal textappendappendappendreturn
How message fragments from successive response lines flow into one accumulating string that is returned as the final reply.

Running the Example Call

The source demonstrates query_model with a single example call. The call asks the llama3 model what llamas eat. The model name is stored in a variable first, and the prompt is passed directly as the first argument. Storing the model name in a variable makes it easy to change later without touching the rest of the call.

python
Output (expected)
The output is plain text. Its content depends on the model, and the example shown in the source is cut off partway through the reply.
Notes on the code
  • model holds the model name in a variable
  • the prompt is the first argument
  • print displays the returned string

Tracing Where a Wrong Result Starts

When a result from query_model looks wrong, do not guess. Walk the stages in order and check the value each one produced. The stages are building the payload, encoding it as JSON, sending the POST request, reading the lines, and gathering the content into the returned string. The Ollama service itself sits outside these stages and can also be the source of a surprising reply.

build payloadmodel, messages, optionsencode JSONdictionary to bytesPOST requestto the chat endpointread linesone line at a timegather contentappend to stringreturn replyfinal textpayloadbytesreplyeach linestring
The ordered stages a query_model call passes through, from building the payload to returning the reply. A wrong result can be introduced at any one of them.

A useful habit is to ask, for each suspicious result, which stage could have produced that specific value. A wrong model name points toward the payload. A failure to reach the server points toward the request. A reply that is incomplete points toward the reading loop or the gathering step. A reply that is correct in form but unexpected in content may point to the Ollama service and the model it ran.

Mistakes When Reading query_model Results

  • Common mistake

    Treating the url as part of the payload

    Why it fails

    The payload holds model, messages, and options. The url only decides where the request is sent.

    Do this instead

    Trace the url through the request stage and the payload through the payload stage.

  • Common mistake

    Expecting the reply to arrive as one block

    Why it fails

    The function reads the reply one line at a time, so the text comes in fragments.

    Do this instead

    Think of the reading loop and the string accumulation as separate steps that together produce one result.

  • Common mistake

    Assuming the output is a fixed or formatted answer

    Why it fails

    The function returns whatever the model generated, and the source example is cut off.

    Do this instead

    Judge the result against the stage that produced it, not against an expected wording.

Locating the Stage in a Real Trace

MEDIUM

A colleague calls query_model with a correct prompt and gets back a reply that stops halfway through a sentence. Using the stages from this article, name the stage you would check first and explain what you would look at in that stage.

Hints
  • Ask which stage handles the text after it has been received, not before it is sent.
  • Think about what the reading loop and the gathering step each contribute to the final string.

Key Takeaways

  • query_model builds a payload dictionary with model, messages, and options keys, converts it to JSON bytes, and sends it as a POST request to the chat endpoint.
  • The default endpoint is http://localhost:11434/api/chat, and url controls where the request goes, not what it contains.
  • The reply is read one line at a time, and each line's message content is appended to a growing string that the function returns.
  • When a result is wrong, check the stage that produced it: the payload, the request, the reading loop, or the Ollama service itself.

More concepts starting with Q