Sub topic 1
Running a Model Locally Behind an HTTP Server
A local inference server is a program that loads a language model into your machine's memory and answers requests over HTTP. This chapter explains how that setup works, which servers are common, and what to check before you write any client code. The rest of the tutorial assumes this layer is running.
Prerequisites
This chapter assumes the following:
- Basic Python, including installing packages with pip.
- Familiarity with HTTP requests and JSON.
- A general idea of what a large language model and a prompt are.
- A command line you can use to run programs and
curl.
You do not need a model server installed yet. By the end of the chapter you will have installed one, or know how to, and you will have confirmed that it is listening.
Why put a model behind a server
You can run a model inside your own Python process with a library that loads the weights directly. A separate server process has several advantages:
- Load once, reuse often. Loading a multi-gigabyte model takes seconds to minutes. A server keeps it in memory while many short-lived scripts connect and disconnect.
- Language independence. Anything that can send HTTP can use the model, including Python, JavaScript, shell scripts, and other tools.
- Separation of concerns. The server handles GPU or CPU memory, tokenization, and the generation loop. Your application sends text and receives text.
- Swappable backends. If the server follows a shared API shape, you can change which server or model you use by changing a URL and a model name.
The last point is why this tutorial exists. Chapter by chapter, you will use the standard OpenAI Python client against a server running on your own machine.
What the server does for each request
A request passes through several stages inside the server.
In more detail:
- Startup. The server reads the model file and copies the weights into RAM, or into GPU memory (VRAM) if you have a supported GPU. This is the slow step.
- Request. Your client sends JSON. The server converts the text into tokens, which are the integer pieces the model actually reads.
- Generation. The model predicts one token at a time. Each new token is appended to the input, and the loop repeats until the model emits a stop token or hits a length limit.
- Response. The server converts the tokens back into text and returns them, either all at once or piece by piece as they are produced.
The client never sees steps 2 and 3. It sees only HTTP in and HTTP out.
Common local servers
Four servers cover most local setups. All of them can expose OpenAI-style endpoints. The ports below are their defaults.
| Server | Typical start command | Default port | Notes |
|---|---|---|---|
| Ollama | `ollama serve` (often started automatically) | 11434 | Downloads and manages models for you. Simple to install on macOS, Linux, and Windows. |
| llama.cpp `llama-server` | `llama-server -m model.gguf` | 8080 | You supply a GGUF model file. Runs well on CPU, with optional GPU offload. |
| LM Studio | Start the local server from the app | 1234 | Desktop app with a graphical model browser. |
| vLLM | `vllm serve <model-name>` | 8000 | Built for high throughput on GPUs. Heavier to install. |
The examples in this tutorial use Ollama on port 11434 with the llama3.2 model. If you use a different server, replace the port and the model name. Everything else stays the same, apart from the differences covered in a later chapter.
Setting up Ollama as a worked example
Install Ollama from its website, then download a model. Downloading is called pulling:
ollama pull llama3.2The default llama3.2 model is about 2 GB. Pulling it once stores it on disk, and you do not repeat it for each run.
On macOS and Windows, the Ollama app starts the server in the background. On Linux, the installer normally sets up a service. If nothing is listening, start the server by hand:
ollama serveThat command keeps running in its terminal, so open a second terminal for the next step. If you see an error that the address is already in use, the server is probably already running, which is fine.
Confirming the server is listening
Before you write any Python, confirm that the server is reachable. A plain request to the root URL is enough for Ollama:
curl http://localhost:11434/Ollama replies with the text Ollama is running. Other servers answer on different paths, and a few return a 404 on the root URL even when they are healthy, so for those use a request to a real endpoint instead.
A real request to the chat endpoint looks like this. It assumes Ollama on its default port with llama3.2 already downloaded:
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "llama3.2", "messages": [{"role": "user", "content": "Say hello in one sentence."}]}'The first reply can take noticeably longer than later ones, because the server may have to load the model into memory. You should get back a JSON document with a choices list holding the model's answer. If you do, the server layer works, and every later chapter builds on it. The structure of that response is covered in the chat completions chapter, so do not worry about reading it closely yet.
How much memory a model needs
Model size drives most local problems, so estimate it before you pull anything. The weights take roughly the number of parameters multiplied by the bytes stored per parameter.
- A model with 8 billion parameters stored at 16-bit precision needs about 16 GB.
- The same model quantized to 4 bits per weight needs about 4 to 5 GB.
Quantization means storing weights with fewer bits, trading a small loss in quality for a large saving in memory. Most files you download for local use are already quantized, which is why a model named with something like Q4 is far smaller than its original.
Weights are not the only cost. The server also keeps a key-value cache (KV cache) for the text it is processing, and it grows with the length of the conversation. A model that loads fine can still run out of memory when you give it a very long prompt. If the model plus cache does not fit in VRAM, many servers spill some layers to system RAM and run much slower. Plan for a few gigabytes of headroom beyond the file size.
Lifecycle behavior to expect
Local servers manage memory differently from hosted services, and some behaviors surprise first-time users.
- Lazy loading. Ollama loads a model on the first request that names it, not at startup. That first call is slow.
- Idle unloading. Ollama unloads a model after a period without requests, five minutes by default, to free memory. The next request pays the loading cost again.
llama-serverand vLLM load the model at startup and keep it until you stop the process. - Limited concurrency. A home machine has one set of compute resources. Several simultaneous requests either queue or slow each other down. vLLM batches requests efficiently, but a laptop running Ollama will not match a hosted service under load.
- Variable speed. Generation speed depends on your hardware, the model size, and the quantization. A small model on a modern GPU is quick. A large model on CPU alone can produce only a few tokens per second.
Network exposure and security
A local server often has no authentication. By default, most servers bind to 127.0.0.1, which means only programs on your own machine can connect. That is the safe default.
Some servers let you bind to all network interfaces, for example with --host 0.0.0.0 in llama-server or the OLLAMA_HOST environment variable for Ollama. Doing so lets other devices on the network use your model. Anyone who can reach that address can then spend your compute and send the model any prompt. Do this only on a network you trust, and put an authenticating reverse proxy or firewall rule in front of it if you must share it.
The same goes for containers and remote development environments. If your Python code runs in a container while the server runs on the host, localhost inside the container does not point at the host. You will need the host's address and a server binding that accepts the connection.
Checking the server from Python
You do not need the OpenAI client for this chapter. If you want a quick Python check before moving on, the standard library is enough:
import urllib.request
with urllib.request.urlopen("http://localhost:11434/", timeout=5) as resp:
print(resp.status, resp.read().decode())A working Ollama server prints 200 Ollama is running. If the server is down, urlopen raises a URLError whose message says the connection was refused. That error means nothing is listening at that host and port. It does not mean your code is wrong.
What to take into the next chapters
Keep these facts handy:
- The server is a separate process. It must be running before any client call can work.
- The server decides which models exist. Your client can only ask for models the server has loaded or can load.
- The address has three parts you will configure: the host, the port, and a path prefix such as
/v1. Mistakes in any of them cause most early failures. - Hardware sets the limits on model size, speed, and concurrency.
The next chapter explains what it means for these different servers to share the OpenAI API shape, so that one client library can talk to all of them.
Exercise
You start llama-server on your laptop, and a script running inside a Docker container on the same laptop gets "connection refused" when it calls http://localhost:8080/. The same URL works from your laptop's terminal. Give the most likely cause and one fix.
Show answer
Inside the container, localhost refers to the container itself, not the laptop, and nothing is listening on port 8080 there. The server is running on the host. Fix it by pointing the script at an address that reaches the host, such as host.docker.internal on Docker Desktop, or the host's IP address. Also make sure the server binds to an interface the container can reach, for example by starting it with --host 0.0.0.0, and only do that on a trusted network.
Exercise
A model file is 8 billion parameters at 4 bits per weight. Estimate the memory the weights need, and name one reason a machine with exactly that much free VRAM could still fail or slow down.
Show answer
8 billion parameters at 4 bits is half a byte each, so about 4 GB (roughly 4 to 5 GB with overhead). The weights are not the whole cost. The KV cache grows with prompt and conversation length and also needs memory. If the total exceeds VRAM, the server fails to load the model or moves some layers to system RAM, which makes generation much slower.