New Tool Radar

Local AI

How to Call a Local Ollama Model from Python with LlamaIndex

Call a local Ollama model from Python with LlamaIndex's Ollama class, so the same script can later grow into retrieval over your own documents.

Schematic diagram with three steps: install llama-index-llms-ollama and pull llama2, create an Ollama model in Python, then complete a prompt and print the reply.

The Ollama Python library calls a local model directly, which is enough for a one-off script. LlamaIndex adds a layer on top: its Ollama class presents the same local model through LlamaIndex’s standard LLM interface, so the code you write for one question can later grow into indexes, retrieval, and agents without changing how you talk to the model. The integration lives in the llama-index-llms-ollama package, and LlamaIndex’s own reference page shows the setup: install the package, start the server with ollama serve, and pull the model first.

Install the package and pull a model

Install the package and pull the model the script will call. The reference page’s own example uses llama2, so the script below keeps that name:

pip install llama-index-llms-ollama

ollama pull llama2

Write the script

Save this as llamaindex_ollama_chat.py. The import, the model call, and the prompt follow LlamaIndex’s reference example exactly:

from llama_index.llms.ollama import Ollama

llm = Ollama(model="llama2", request_timeout=60.0)

response = llm.complete("What is the capital of France?")

print(response)

Ollama talks to the local server, whose base URL defaults to http://localhost:11434 in the reference, and complete returns the model’s reply as text. The local API needs no API key, because the request stays on your own computer.

Try it: three checks from install to reply

Check What you should see What it means
Package installed pip install llama-index-llms-ollama finishes without error The Ollama class is available to import
Model ready ollama pull llama2 reports the model is already there or downloads it The model name in the script matches a model Ollama has
Reply python llamaindex_ollama_chat.py prints a reply naming Paris LlamaIndex reached your local model through Ollama

Expected result. We checked LlamaIndex’s Ollama reference page, which gives the install command, the import, the Ollama call with model and timeout, and the complete example with the same prompt. We did not install llama-index-llms-ollama, pull a model, or run the script on this machine.

Limits

LlamaIndex only wraps the call; the model still runs in Ollama, so a model that is not pulled cannot be used. The request_timeout value in the script is the reference example’s own setting of 60 seconds, and a slow first load can exceed it. This guide covers one completion only: chat messages, streaming, JSON mode, and structured outputs are shown on the same reference page, but they are separate tasks. We did not test any of this ourselves.

Sources

See all