Skip to content
IntermediateLocal AIAI DevelopmentPython

Call a Local Language Model from Python

Send prompts to a model running on your own machine through Ollama’s local HTTP API.

20 min2 stepsPublished

Ollama llama logo
Photo: Ollama (MIT licence)

Prerequisites

  • Ollama installed and running
  • A model pulled, e.g. ollama pull llama3.2
  • Python 3.10+
  1. 1

    Check that the local server is running

    terminal
    ollama list

    You should see the models you downloaded. Ollama listens on http://localhost:11434.

  2. 2

    Send a prompt

    ask_local.py Tested
    import json
    import urllib.request
    
    payload = {
        "model": "llama3.2",
        "prompt": "Give me three tips for writing clear emails.",
        "stream": False,
    }
    
    request = urllib.request.Request(
        "http://localhost:11434/api/generate",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=120) as response:
        answer = json.load(response)
    
    print(answer["response"])

Troubleshooting

Connection refused

Start Ollama (open the app, or run `ollama serve`).

model not found

Download it first with `ollama pull llama3.2`.

Check your understanding

Why set "stream": False in the request?