Skip to main content
This guide shows how to set up a minimal Python project that communicates with a locally running Ollama server. You’ll create a virtual environment, install the official Ollama Python client, and run two example scripts:
  • A single-request text generation (one-shot prompt)
  • A context-aware chat loop that preserves conversation history
Environment note: this walkthrough was performed in Visual Studio Code on Windows using WSL. Your Ollama instance should be running locally and have at least one model available:
If you need general documentation, see the Ollama docs and Python venv docs:

1) Create and activate a virtual environment

From your project directory create a virtual environment with Python 3:
Activate the virtual environment:
  • WSL / macOS / Linux:
  • Windows (PowerShell):
Quick reference commands:

2) Install the Ollama Python client

With the venv active, install the client:
The Ollama Python package is a lightweight HTTP client that sends requests to your locally running Ollama background process. The package does not run models locally; it forwards requests to the Ollama server.

3) Simple generation example (single prompt)

Create a file named main.py and add:
Run it:
Why use this pattern? The generate call is ideal for one-shot prompts — you send a single prompt and receive a single response, useful for tasks like summarization, code generation, and short Q&A.

4) Context-aware chat loop

For multi-turn conversations you should accumulate the message history and use the chat API. Save this as chat_main.py (or merge into main.py).
Example usage:
  • Type a prompt when asked (for example: “Tell me a funny joke about Python”).
  • Continue the conversation; the messages list preserves the full exchange so the model can reference earlier turns.
  • Enter /exit or press Enter on an empty line to quit.
Why this structure?
  • The generate example demonstrates single-shot usage.
  • The chat loop shows how to preserve conversational context by appending {'role': 'user'|'assistant', 'content': ...} entries to a messages list and sending that full history each time.

File summary

Make sure your Ollama server is running locally before executing these scripts. The Python client communicates with the background Ollama process via HTTP and will fail if the server is not available. Also replace gemma3:latest with the model name you have installed.
Final reminders
  • Keep your virtual environment activated while installing and running the scripts.
  • Monitor available models with ollama list and update the model= parameter accordingly.
  • Use the chat pattern to maintain conversational state when building bots, assistants, or multi-turn tools.

Watch Video