The quickest way to use a local model from your own code is the official ollama Python library. You install one package and write three lines, and your script is talking to Gemma, Qwen or Llama running on your own GPU.
This guide covers everything you need in practice: chat and generate, streaming, model management, embeddings, async code, remote hosts, cloud models, error handling, and the newer features such as thinking, tools, structured outputs and web search.
All examples were checked against the library’s current README and source (version 0.6.3 on PyPI).
- Install:
pip install -U ollama(Python 3.8+). Ollama itself must be installed and running. - Chat:
chat(model="gemma4", messages=[...]), then readresponse.message.content. - Stream: add
stream=Trueand loop over the chunks. - Remote or custom:
Client(host="http://192.168.1.50:11434"), or setOLLAMA_HOST. UseAsyncClientfor asyncio. - Errors: catch
ollama.ResponseError; a 404 status means the model is not pulled yet.
New to Ollama? My Ollama guide covers install, models, commands and fixes in one place.
Install and First Script
You need two things:
- Ollama running on your machine (the app, or
ollama serve). - A model pulled, for example
ollama pull gemma4.
Then install the library, ideally in a virtual environment:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
pip install -U ollama
Your first script:
from ollama import chat
response = chat(
model="gemma4",
messages=[{"role": "user", "content": "Why is the sky blue? Answer in two lines."}],
)
print(response.message.content)
The response works both as an object and as a dict, so response["message"]["content"] gives the same text. Any model works; swap gemma4 for whatever ollama list shows. For picks, see best Ollama models or my Gemma 4 local guide.
Chat vs Generate
chat() |
generate() |
|
|---|---|---|
| Input | A list of messages with roles | A single prompt string |
| Output field | response.message.content |
response.response |
| Best for | Chatbots, history, tools, images | One-shot jobs: summarise, rewrite, complete |
import ollama
r = ollama.generate(model="gemma4", prompt="Write a haiku about GPUs.")
print(r.response)
Both map directly to the REST endpoints /api/chat and /api/generate, explained in my Ollama API guide.
Multi-Turn Conversations
The model has no memory between calls. You keep the history and send it each time:
from ollama import chat
messages = [{"role": "system", "content": "You are a friendly Python tutor. Keep answers short."}]
while True:
user = input("You: ")
if user.lower() in {"quit", "exit"}:
break
messages.append({"role": "user", "content": user})
reply = chat(model="gemma4", messages=messages)
messages.append(reply.message) # keep the assistant turn
print("AI:", reply.message.content)
Long chats eventually overflow the context window. Either raise num_ctx (below) or drop the oldest turns.
Streaming Responses
The SDK does not stream by default. Add stream=True to print tokens as they arrive:
from ollama import chat
stream = chat(
model="gemma4",
messages=[{"role": "user", "content": "Explain VRAM in one paragraph."}],
stream=True,
)
for chunk in stream:
print(chunk.message.content, end="", flush=True)
If you need the full text afterwards, add the chunks to a string inside the loop. generate(..., stream=True) works the same way, using chunk.response.
Options: Temperature, Context, Keep Alive
Model settings go in options. How long the model stays in memory goes in keep_alive:
r = chat(
model="gemma4",
messages=[{"role": "user", "content": "Give me 3 blog title ideas about local AI."}],
options={
"temperature": 0.7, # creativity (0 = repeatable)
"num_ctx": 16384, # context window in tokens
"num_predict": 300, # max tokens to generate
"seed": 42, # repeatable sampling
},
keep_alive="30m", # keep loaded 30 minutes; 0 unloads now, -1 keeps forever
)
Context size matters more than most people think, because Ollama’s default is small. See my context length guide and keep_alive guide.
Manage Models from Python
Everything the CLI does has a matching function:
import ollama
ollama.pull("gemma4") # download
print(ollama.list()) # installed models
print(ollama.show("gemma4")) # details, template, capabilities
print(ollama.ps()) # models loaded in memory
ollama.copy("gemma4", "my-gemma") # copy / rename
ollama.delete("my-gemma") # remove
ollama.create(model="tutor", from_="gemma4",
system="You are a patient maths tutor.") # custom model
Pulls can take a while, so show progress with stream=True:
for p in ollama.pull("qwen3", stream=True):
if p.total and p.completed:
print(f"{p.status}: {p.completed / p.total:.0%}", end="\r")
else:
print(p.status)
create() uses from_ (with an underscore) because from is a Python keyword. More ways to build custom models are in my Modelfile guide.
Embeddings
embed() turns text into vectors for search and RAG. Pass one string or a list:
import ollama
r = ollama.embed(
model="embeddinggemma",
input=["Ollama runs models locally.", "ComfyUI makes images."],
)
print(len(r.embeddings), "vectors of", len(r.embeddings[0]), "numbers")
Use a real embedding model for this, not a chat model. Model choices and a full search example are in my Ollama embeddings guide, and a ready-made RAG stack is in LangChain with Ollama.
Custom Client and Remote Hosts
The top-level functions use a default client that talks to http://localhost:11434. It also reads the OLLAMA_HOST environment variable if you set it. For anything else, create a Client:
from ollama import Client
client = Client(
host="http://192.168.1.50:11434", # Ollama on another PC
headers={"x-some-header": "some-value"},
timeout=120, # seconds; default is no timeout
)
r = client.chat(model="gemma4", messages=[{"role": "user", "content": "Hello!"}])
Extra keyword arguments go to the underlying httpx.Client, so proxies and similar settings work too. The remote machine must listen on the network (OLLAMA_HOST=0.0.0.0); see Ollama environment variables.
Async Client
For web apps and bots built on asyncio, use AsyncClient. It takes the same settings as Client:
import asyncio
from ollama import AsyncClient
async def main():
client = AsyncClient()
async for part in await client.chat(
model="gemma4",
messages=[{"role": "user", "content": "Name three uses for a local LLM."}],
stream=True,
):
print(part.message.content, end="", flush=True)
asyncio.run(main())
Note the await before client.chat(...). With stream=True it returns an async generator, which you then loop over with async for.
Cloud Models
The same library can run bigger models on Ollama’s cloud. There are two ways:
Through your local Ollama: run ollama signin once, then ollama pull gpt-oss:120b-cloud, and use that model name as normal.
Directly against ollama.com:
import os
from ollama import Client
client = Client(
host="https://ollama.com",
headers={"Authorization": "Bearer " + os.environ["OLLAMA_API_KEY"]},
)
for part in client.chat("gpt-oss:120b",
messages=[{"role": "user", "content": "Why is the sky blue?"}],
stream=True):
print(part.message.content, end="", flush=True)
If OLLAMA_API_KEY is set, the client adds the Bearer header for you. Remember that cloud prompts leave your PC, unlike local models.
Thinking, Tools, JSON and Web Search
chat() also handles Ollama’s advanced features. Each one has its own deep-dive guide:
| Feature | Parameter | Guide |
|---|---|---|
| Thinking / reasoning | think=True, False or "low"/"medium"/"high" |
Ollama thinking |
| Tool calling | tools=[my_function] |
Ollama tool calling |
| Structured JSON | format=MyModel.model_json_schema() |
Ollama structured outputs |
| Images | "images": ["photo.jpg"] in a message |
Ollama vision models |
| Web search | web_search(), web_fetch() |
Ollama web search |
| Decision models | ollama.systemone(...) |
Ollama decision models |
A quick taste of tools. Plain Python functions with type hints and a Google-style docstring become tools on their own:
from ollama import chat
def add(a: int, b: int) -> int:
"""Add two numbers.
Args:
a: First number
b: Second number
"""
return a + b
r = chat(model="qwen3", messages=[{"role": "user", "content": "What is 1234 + 4321?"}], tools=[add])
for call in r.message.tool_calls or []:
print(call.function.name, call.function.arguments, "=", add(**call.function.arguments))
Error Handling
The library raises ollama.ResponseError when the server returns an error, including errors that happen mid-stream:
import ollama
model = "qwen3"
try:
ollama.chat(model=model, messages=[{"role": "user", "content": "hi"}])
except ollama.ResponseError as e:
print("Error:", e.error)
if e.status_code == 404: # model not pulled yet
ollama.pull(model)
If Ollama is not running at all, you get a connection error instead. In current versions it is a ConnectionError with a message asking you to check that Ollama is installed and running.
Troubleshooting
ConnectionError / “Failed to connect to Ollama”
Ollama is not running, or it is on a different host or port. Start the app or run ollama serve, then open http://localhost:11434 in a browser. It should say “Ollama is running”. Check any OLLAMA_HOST value you have set.
ResponseError: model not found (404)
Pull it first (ollama pull gemma4) and use the exact name and tag from ollama list.
ImportError or “cannot import name chat”
Two common causes. Your own file may be named ollama.py, so Python imports it instead of the library; rename it. Or you have an old version installed; run pip install -U ollama.
The first call is very slow
The model is loading into memory. Later calls are fast while it stays loaded. Use keep_alive to keep it in memory longer, and check ollama ps to make sure it runs on the GPU. If not, see Ollama not using GPU.
Answers ignore earlier messages
You are not sending the history, or it no longer fits in the context. Append every turn to messages and raise num_ctx.
Requests hang forever
The default client has no timeout. Set Client(timeout=120) so a stuck request fails instead of waiting forever.
FAQ
Is the Ollama Python library free?
Yes. It is open source (MIT) and talks to your own Ollama server. Only Ollama’s cloud models and the web search API need an account.
Can I use the OpenAI Python SDK instead?
Yes. Point it at http://localhost:11434/v1 with any API key string. The native library gives you Ollama-only extras such as keep_alive, think levels and model management.
Does it work in Jupyter notebooks?
Yes. The normal client works as is. For AsyncClient, use await directly in a cell instead of asyncio.run().
Is there a JavaScript version?
Yes: npm i ollama. It has the same functions with camelCase names, such as webSearch.
How do I use it with LM Studio?
You don’t. LM Studio has its own SDK and an OpenAI-compatible server; see my LM Studio API guide and LM Studio vs Ollama.
Sources
- ollama-python on GitHub (README: install, chat, streaming, cloud, custom and async clients, API list, errors)
- ollama-python _client.py (OLLAMA_HOST and OLLAMA_API_KEY handling, default timeout, chat/pull/embed parameters)
- ollama on PyPI (version 0.6.3, Python 3.8+)
- Ollama docs: Streaming (SDK streaming is off by default)



