Zum Inhalt springen

Lektion 9 · Running Llama Locally

Call a Local Llama Server from Python

Send chat requests to a local Llama server with Python, read replies and token counts, keep conversation history, stream output and handle errors.

A good way to build an application is to talk to the model over a local HTTP API. Then the model can run in Ollama, llama.cpp or a bigger server without changing most of your code. This lesson shows Ollama's chat API and the OpenAI-compatible style.

The request and the reply

Ollama's native chat endpoint is POST http://localhost:11434/api/chat. The main fields are model, messages, stream and options. This is real code, to run on your computer with Ollama active:

Python
import json
import urllib.request

payload = {
    "model": "llama3.2:3b",
    "messages": [{"role": "user", "content": "Give me one tip for naming variables."}],
    "stream": False,
    "options": {"temperature": 0.2, "num_ctx": 4096, "num_predict": 200},
}

request = urllib.request.Request(
    "http://localhost:11434/api/chat",
    data=json.dumps(payload).encode(),
    headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=120) as response:
    reply = json.load(response)

print(reply["message"]["content"])

According to Ollama's API reference (December 2026), stream defaults to true, so set it to false when you want one JSON object. The reply has a message, a done flag with a done_reason, and counts such as prompt_eval_count and eval_count. Duration fields are in nanoseconds.

The conversation is your job

The server does not remember previous chat calls. You send the whole history every time. That history grows, uses more context and costs more time.

Python Stand-in: keep history within a budget

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the system message is always kept. Dropping it silently can make a chatbot seem to change personality in long chats.

Reading the metrics

Python Stand-in: turn timing fields into speed

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The OpenAI-compatible style

Many tools speak the same shape as OpenAI's chat API. Ollama offers it under http://localhost:11434/v1/, and llama.cpp's server and vLLM offer similar endpoints. With the openai Python package, you point the client at your server:

Python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")  # ignored by local Ollama
response = client.chat.completions.create(
    model="llama3.2:3b",
    messages=[{"role": "user", "content": "Say hello in French."}],
)
print(response.choices[0].message.content)

"Compatible" does not mean "identical". Each server supports a subset of fields. Ollama's compatibility page, for example, lists some chat parameters it does not support. Test every feature you rely on.

Streaming and errors

Streaming sends the reply in pieces, so users see text sooner. With Ollama's native API, each line is a JSON object with a partial message, and the last one has done: true. Your code should:

  • use a timeout, since a first request may be slow while the model loads,
  • handle connection errors (is the server running?),
  • handle a missing model (did you pull it?),
  • check done_reason before treating a reply as complete,
  • retry only errors that can succeed later, with a limited number of tries.

Ollama keeps a model loaded for a while after a request (5 minutes by default, per its FAQ). The keep_alive field changes that.

Treat model output as untrusted text. Do not pass it directly to eval, a shell, SQL or an HTML page.

Wrap the API in one function

Do not spread HTTP calls through your program. Write a single function that takes messages and returns the reply text plus a few facts such as why generation stopped and how many tokens were used. The rest of your code then does not care which server you use. When you switch from Ollama to another server, you change one place. This also makes testing easy, because a test can replace that function with a fake.

Choose options deliberately

The options object in the example controls generation. A low temperature suits factual and structured work. num_ctx sets the context size for the request, and num_predict caps the number of output tokens. A fixed seed can help when you debug, although it does not guarantee identical output across different hardware or versions.

When a reply is short or cut off, look at done_reason and the counts before you change the prompt. If prompt_eval_count is close to your context size, the input may not fit, and the beginning of the conversation could be lost.

Structured replies from the same API

The chat endpoint also accepts a format field, which you can set to json or to a JSON schema. The reply text is then expected to follow that shape. Your code should still parse it with json.loads inside a try block and check the fields, as the prompting lesson shows.

Concurrency

A local server often processes only a few requests at the same time, and the rest wait. If your program sends many requests at once, add a small worker limit and a queue. Measure before you raise it, because more parallel work uses more memory. For a service with real users, see serving Llama.

Logging for debugging

While you develop, record the model name, the options, the number of messages, the token counts, the duration and the reason generation stopped. These facts explain most surprises. Be careful with message text: it may contain personal or confidential data. Log the text only when you need it, keep it for a short time and protect it like the original data.

Test without a server

Your automated tests should not depend on a running model, because results can vary and the machine that runs tests may have no model at all. Replace the call with a fake function that returns fixed text, an empty string, an error or a very long reply. Then check how your program reacts to each one. Keep a separate, smaller set of checks that use the real model, run them by hand or on a suitable machine, and judge them by properties such as format and key facts rather than exact wording.

One last check. Before you build on a server, send one request by hand and read the whole JSON reply.

Practice idea. Add a retry with a short delay for connection errors, and test it with a fake that fails once.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. How does a typical chat API remember earlier turns?

    In this style of API, you resend the messages.
  2. 2. In Ollama's reply, which unit do the duration fields use?

    Divide by 1,000,000,000 to get seconds.
  3. 3. What does 'OpenAI-compatible' promise in practice?

    Support varies, so test the fields you need.

Summary

  • Talk to local models through an HTTP chat API.
  • Send the history yourself and keep it inside the context budget.
  • Use timeouts, check why generation stopped and validate output.
  • OpenAI-compatible endpoints help portability, but support differs.

Next: Llama Chat Templates

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.