Run Open-Source LLMs Locally with Ollama

While cloud-hosted APIs like OpenAI, Anthropic, and Google Gemini offer immense power and scale, many enterprise use cases demand strict data privacy, offline execution, zero cloud dependency, and elimination of per-token API costs. Running state-of-the-art open-source Large Language Models (such as Llama 3, Mistral, Gemma, and Phi-3) directly on your local workstation or edge hardware has never been easier thanks to Ollama.

This comprehensive tutorial walks through setting up Ollama, managing model weights, integrating local models into Python applications, and creating customized model instances.

1. What is Ollama and Why Use It?

Ollama is a lightweight, open-source framework built on top of llama.cpp that allows developers to run, create, and share large language models locally on macOS, Linux, and Windows.

  • Data Privacy & Security: Sensitive codebases, financial records, and proprietary documents never leave your local machine.
  • Offline Capability: Develop and test AI-driven workflows without an active internet connection.
  • Zero API Costs: Experiment freely, run infinite inference loops, and fine-tune prompts without incurring cloud API charges.

2. Installation and Basic CLI Commands

Download and install Ollama from the official website, then use the command-line interface to pull and run models.

C
# Pull and run Llama 3 locally
ollama run llama3

# List downloaded local models
ollama list

# Pull specific model variants
ollama pull mistral
ollama pull codellama

3. Integrating Ollama with Python

Ollama exposes an OpenAI-compatible REST API as well as an official Python client library, making local model inference drop-in compatible with standard Python scripts.

C
# Terminal installation command
pip install ollama
C
# Python script executing local inference
import ollama

response = ollama.chat(model='llama3', messages=[
  {
    'role': 'user',
    'content': 'Explain the difference between process threads and async loops in Python.',
  },
])

print(response['message']['content'])

4. Creating Custom Models with a Modelfile

You can customize base open-source models with specific system prompts, temperature parameters, and persona constraints by creating a Modelfile.

C
# Example Modelfile configuration
FROM llama3

# Set custom system prompt
SYSTEM "You are an expert C# and .NET Core architect. Answer questions concisely with production-grade code snippets."

# Set temperature parameters
PARAMETER temperature 0.3
PARAMETER num_ctx 4096
C
# Build and run your custom local model via terminal
ollama create csharp-expert -f ./Modelfile
ollama run csharp-expert

Conclusion

Running open-source LLMs locally with Ollama empowers developers to build secure, offline-capable, and cost-free AI applications. By combining local model management with Python integrations and custom Modelfiles, you can prototype and deploy specialized language models on your own hardware.