DEV Community

Cover image for Running Local LLMs with Ollama: CLI, curl, and Python
Hollson
Hollson

Posted on Originally published at hollson.github.io

Running Local LLMs with Ollama: CLI, curl, and Python

Ollama gives local LLMs a lightweight service layer: offline, single machine, no cloud account.

The binary is 10–20 MB, needs no extra GPU driver, and the CPU build runs on most laptops.

1. What Ollama Is

Install it, pull a model, and you have an HTTP service on localhost:11434 speaking both Ollama's own API and an OpenAI-compatible one. That means existing SDK code works by changing the base URL.

2. Basic Operations

Install

Platform Method Command
macOS (Apple Silicon and Intel) Homebrew brew install ollama
Linux (Ubuntu/Debian) Install script `curl -fsSL https://ollama.com/install.sh \
Windows Installer Download from ollama.com and run it

After installing, check with {% raw %}ollama --version.

Change the model directory

# inspect the environment
echo "$OLLAMA_HOME"     # ~/.ollama
echo "$OLLAMA_MODELS"   # ~/.ollama/models

# option 1: config file
# ~/.ollama/config.yaml
models_dir: /opt/ollama_models

# option 2: environment variable
export OLLAMA_MODELS_DIR="~/.ollama/models"
ollama serve

# option 3: per-command path (newer builds only)
ollama pull model_name --path ~/.ollama/models
Enter fullscreen mode Exit fullscreen mode

A fuller config file for reference (all fields optional):

log_dir: # default $OLLAMA_HOME/logs/

servers:
  - listen: "127.0.0.1"  # 0.0.0.0 exposes it publicly
    port: 11434
    allow_remote: true   # only on a network you trust
    max_conn: 128
    timeout: 30

models_dir: /opt/ollama_models

gpu_device: 0,1   # GPU indices
gpu_quant: false  # 4-bit / 8-bit quantization

openai_compatibility: true
license_key: ""
Enter fullscreen mode Exit fullscreen mode

Pull models

# general
ollama pull qwen3:0.6b

# OCR
ollama run deepseek-ocr
ollama run glm-ocr:latest
ollama run MedAIBase/PaddleOCR-VL:0.9b

# Llama
ollama pull llama3.2:1b

# audio
ollama pull qwen3:0.6b-whisper
Enter fullscreen mode Exit fullscreen mode
$ ollama list
NAME                        ID              SIZE      MODIFIED
llama3:latest               365c0bd3c000    4.7 GB    35 seconds ago
qwen3:0.6b                  7df6b6e09427    522 MB    2 days ago
glm-ocr:latest              6effedd0dc8a    2.2 GB    3 days ago
gpt-oss:20b-cloud           875e8e3a629a    -         2 months ago
qwen3-coder:480b-cloud      e30e45586389    -         3 months ago
qwen2.5:1.5b                65ec06548149    986 MB    3 months ago

# remove a model
ollama rm llama3.2:1b
Enter fullscreen mode Exit fullscreen mode

Start the service

# listens on 127.0.0.1:11434 by default; not reachable from the network
ollama serve
Enter fullscreen mode Exit fullscreen mode

To expose it, pass --listen:

ollama serve --listen=0.0.0.0
Enter fullscreen mode Exit fullscreen mode

The CPU build needs a warm-up; the first request can take a few seconds.

3. Using Ollama

Command line

$ ollama run llama3 "Explain machine learning in two sentences"
$ ollama run qwen3:0.6b "Explain RAG in two sentences"

$ ollama run llama3
>>> hello
Hi! How can I help?
>>> tell me a joke
Sure, here goes...
>>> /bye
Enter fullscreen mode Exit fullscreen mode

ollama run <model> connects to the local service and opens a REPL in the terminal.

curl

# disable streaming
curl -X POST http://localhost:11434/api/chat \
     -H "Content-Type: application/json" \
     -d '{"model":"qwen3:0.6b","stream":false,"messages":[{"role":"user","content":"tell me a joke"}]}' \
     -w "\n"
Enter fullscreen mode Exit fullscreen mode

Python, non-streaming

import httpx

response = httpx.post(
    "http://localhost:11434/api/chat",
    json={
        "model": "qwen3:0.6b",
        "messages": [{"role": "user", "content": "Explain entropy briefly"}],
        "stream": False,
    },
    timeout=None,
)
print(response.json()["message"]["content"])  # note: message.content, not response
Enter fullscreen mode Exit fullscreen mode

Python, streaming

import httpx
import json

with httpx.stream(
    "POST",
    "http://localhost:11434/api/chat",
    json={
        "model": "qwen3:0.6b",
        "stream": True,
        "messages": [{"role": "user", "content": "Explain entropy briefly"}],
    },
    timeout=None,
) as response:
    full_response = full_thinking = ""

    for chunk in response.iter_bytes():
        if not chunk:
            continue
        line = chunk.decode().strip()
        if not line:
            continue

        try:
            data = json.loads(line)
            if "message" in data:
                msg = data["message"]
                if thinking := msg.get("thinking", ""):
                    full_thinking += thinking
                    print(f"\033[90m{thinking}\033[0m", end="", flush=True)
                if content := msg.get("content", ""):
                    full_response += content
                    print(content, end="", flush=True)
        except json.JSONDecodeError:
            pass

    print(f"\n\n{'=' * 72}\nthinking:\n{full_thinking}\n{'=' * 50}\nanswer:\n{full_response}")
Enter fullscreen mode Exit fullscreen mode

OpenAI SDK

from openai import OpenAI

client = OpenAI(
    api_key="ollama",  # Ollama does not check the key; any placeholder works
    base_url="http://localhost:11434/v1",
)
resp = client.chat.completions.create(
    model="qwen3:0.6b",
    temperature=0.5,
    messages=[{"role": "user", "content": "Name one four-word English idiom about horses."}],
)
print(resp.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

4. Advanced Usage

Command-line flags for ollama run

Flag Meaning Example
--format string Response format, e.g. json ollama run llama3 --format json
--verbose Print timing statistics ollama run llama3 --verbose
--keepalive string How long to keep the model loaded ollama run llama3 --keepalive 5m
--think string Thinking mode: true/false/high/medium/low ollama run llama3 --think true
--hidethinking Hide thinking output ollama run llama3 --hidethinking
--nowordwrap Disable word wrapping ollama run llama3 --nowordwrap

API options

Option Meaning Example
temperature Creativity, 0–1, higher is more random "temperature": 0.7
top_p Sampling probability threshold "top_p": 0.9
max_tokens Maximum generated length "max_tokens": 2000
num_ctx Context window size "num_ctx": 4096
num_predict Maximum predicted tokens "num_predict": 512
repeat_penalty Repetition penalty "repeat_penalty": 1.1

Practical settings

# pass options through the API
curl -X POST http://localhost:11434/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "model": "llama3",
    "messages": [{"role": "user", "content": "Write a short poem"}],
    "stream": false,
    "options": {"temperature": 0.7, "top_p": 0.9, "max_tokens": 500}
  }'

# environment configuration
export OLLAMA_HOST=0.0.0.0:11434  # allow external access
export OLLAMA_NUM_GPU=1           # GPU count
export OLLAMA_LOAD_TIMEOUT=5m     # model load timeout

ollama ps        # models currently loaded
ollama stop llama3
Enter fullscreen mode Exit fullscreen mode

Performance tips

# small machines: pick a small model
ollama run qwen3:0.6b

# shrink the context window to save memory
curl -X POST http://localhost:11434/api/chat -H "Content-Type: application/json" \
  -d '{"model":"llama3","messages":[{"role":"user","content":"hi"}],"options":{"num_ctx":2048}}'

# keep the model resident to avoid reloads
ollama run llama3 --keepalive 10m
Enter fullscreen mode Exit fullscreen mode

VS Code integration

Add a task in .vscode/tasks.json to review the current file:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "AI Code Review",
      "type": "shell",
      "command": "curl",
      "args": [
        "-X", "POST", "http://localhost:11434/api/chat",
        "-H", "Content-Type: application/json",
        "-d", "{\"model\":\"llama3\",\"messages\":[{\"role\":\"user\",\"content\":\"Review this code:\\n${file}\"}],\"stream\":false}"
      ],
      "problemMatcher": []
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Help

ollama --help lists the subcommands: serve, create, show, run, stop, pull, push, signin, signout, list, ps, cp, rm, launch, help.

ollama run --help covers the flags above plus a few extras: --dimensions (truncate embeddings), --experimental and --experimental-websearch (agent loop and web search), --experimental-yolo (skip tool approval prompts), --insecure (untrusted registry), --truncate (embedding input truncation), and experimental image-generation flags (--width, --height, --steps, --seed, --negative). The relevant environment variables are OLLAMA_HOST (default 127.0.0.1:11434) and OLLAMA_NOHISTORY.

5. A Small CLI Project

#!/usr/bin/env python3
import argparse
import json
import sys

import requests

# usage:
#   python llm_cli.py "what is RAG"
#   python llm_cli.py -m qwen3:0.6b "explain entropy"
#   python llm_cli.py -v "hello"


def main():
    parser = argparse.ArgumentParser(description="Chat with an Ollama model")
    parser.add_argument("prompt", nargs="?", default="hello", help="prompt text")
    parser.add_argument("-m", "--model", default="qwen3:0.6b", help="model name")
    parser.add_argument("-v", "--verbose", action="store_true", help="dump full JSON")
    args = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(0)

    print(f"calling {args.model}...")
    response = requests.post(
        "http://localhost:11434/api/chat",
        json={
            "model": args.model,
            "messages": [{"role": "user", "content": args.prompt}],
            "stream": False,
        },
    )
    result = response.json()

    if args.verbose:
        print(json.dumps(result, ensure_ascii=False, indent=2))
    else:
        print(result["message"]["content"])


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Drop it in ~/bin and call llm_cli.py directly.

Resources

Top comments (0)