On-Premises Model Deployment
"Data never leaves the machine"—this isn’t science fiction; it’s the reality of on-premises AI. When privacy regulations prohibit uploading data to the cloud, network instability affects service, or API call fees become prohibitively expensive, deploying AI models on-premises becomes a practical choice. This chapter will help you understand the differences between on-premises deployment and cloud APIs, install Ollama to run open-source LLMs, call local models using Python, and experience the benefits of privacy protection and offline AI.
1. What You'll Learn
- Pros and Cons of On-Premises Deployment vs. Cloud APIs
- Installing and Using Ollama
- Open-source model family (Llama / Mistral / Qwen / Gemma)
- Calling a local model using Python
- Quantitative Models and Hardware Requirements
2. Story: Charlie’s Privacy Dilemma
(1) Pain Point: Data Cannot Be Migrated to the Cloud
Charlie's medical AI project requires analyzing patient medical records to extract key symptoms and medication information. He had originally planned to use the OpenAI API for this, but the compliance team raised a red flag:
"Patient medical records are considered sensitive personal data and, in accordance with the GDPR and the Personal Information Protection Act, cannot be sent to third-party cloud APIs."
The API proposal was rejected outright. Charlie was in a bind—the AI was very powerful, but the data couldn’t be uploaded to the cloud.
(2) Bob's Approach: Running the Model Locally
After hearing about the situation, Bob made a suggestion: "Use Ollama to run Llama 3 locally—the data stays on the machine, which is both compliant and cost-effective."
One command:
ollama run llama3
The >>> prompt appears on the screen—a large language model running entirely locally is now ready. The medical records do not need to leave Charlie’s laptop.
(3) Benefits: Privacy, cost savings, and offline access—all in one
After testing, Charlie found that while the local model isn’t as powerful as GPT-4, it’s perfectly adequate for the medical record summarization task, saves $50 in API fees each month, and works even without an internet connection.
3. On-Premises Deployment vs. Cloud API
(1) Key Differences
On-premises deployment and cloud APIs represent two distinctly different AI usage paradigms—the former is “own and run,” while the latter is “rent and call.”
(2) Comparison Table: On-Premises vs. Cloud API
| Dimension | On-premises | Cloud API |
|---|---|---|
| Privacy | Data remains on the device and is fully under your control | Data is sent to third-party servers |
| Cost | One-time hardware investment; no ongoing API fees | Billed per token; high long-term costs |
| Latency | Consistent inference latency, no network fluctuations | Depends on the network; latency varies between 1 and 5 seconds |
| Model Size | Limited by local memory/GPU memory; typically 7B–70B | No restrictions; supports GPT-4-level large models |
| Offline | Fully available offline | Internet connection required |
| Operations and Maintenance | Requires managing hardware and updates yourself | Zero O&M; ready to use and configure |
| Model Quality | Open-source models, not on par with GPT-4 | Commercial models, highest quality |
| Customization | Finely tunable; all parameters can be controlled | Black box; adjustments made only through API parameters |
(3) How to Choose?
- On-premises: Sensitive data, high call volumes, offline scenarios, limited budget
- Choose the cloud: When you need the most powerful models, rapid prototyping, low usage frequency, and no hardware requirements
4. Installing and Using Ollama
(1) What is Ollama?
Ollama is an open-source framework for running local LLMs that wraps model downloads, quantization, loading, and API services into minimal command-line operations. It uses the llama.cpp inference engine under the hood and supports both GPU-accelerated and CPU-based inference.
(2) Install Ollama
macOS / Linux:
curl -fsSL https://ollama.com/install.sh | sh
Windows:
Download the installer from ollama.com and double-click it to install.
Manual Installation on Linux:
sudo systemctl start ollama
After installation, Ollama starts the REST API service on http://localhost:11434 by default.
(3) Ollama Workflow
graph TB
A["ollama pull llama3<br/>Download model"] --> B["Quantized GGUF<br/>Auto-quantized"]
B --> C["Load to Memory/VRAM<br/>Model loading"]
C --> D["API Server :11434<br/>REST API endpoint"]
D --> E["Python / CLI / App<br/>Client calls"]
E --> F["Inference<br/>Generate response"]
F --> D
▶ Example: Downloading a Model (Difficulty: ⭐)
# Download Llama 3 8B model (about 4.7 GB)
ollama pull llama3
# Download Qwen2 7B
ollama pull qwen2
# Download Mistral 7B
ollama pull mistral
The download progress bar displays the speed and remaining time. The models are stored in the ~/.ollama/models directory.
▶ Example: Command-Line Dialogue (Difficulty: ⭐)
# Start interactive chat with Llama 3
ollama run llama3
# >>> Hello! Can you explain what a neural network is in one paragraph?
# A neural network is a computational model inspired by the way biological
# neurons work in the human brain. It consists of layers of interconnected
# nodes (neurons) that process information...
# Type /bye to exit
# >>> /bye
▶ Example: View Installed Models (Difficulty ⭐)
# List all downloaded models
ollama list
# Output example:
# NAME ID SIZE MODIFIED
# llama3:latest 365c0bd3c000 4.7 GB 2 hours ago
# mistral:latest 2b3e8435e228 4.1 GB 5 days ago
# qwen2:latest e3d7e5e5e5e5 4.4 GB 1 day ago
5. Open-Source LLM Families
(1) Major Open-Source Models
The open-source LLM ecosystem experienced explosive growth in 2023–2024, giving rise to several model families:
(2) Comparison Table of Open-Source LLMs
| Model | Number of Parameters | Developer | Context Length | Features |
|---|---|---|---|---|
| Llama 3 | 8B / 70B | Meta | 8K | Strong general-purpose capabilities, richest ecosystem |
| Mistral | 7B / 8x7B | Mistral AI | 32K | High-efficiency inference, support for long context |
| Qwen2 | 7B / 72B | Alibaba Cloud | 32K–128K | Excellent Chinese language capabilities, strong multilingual capabilities |
| Gemma 2 | 9B / 27B | 8K | Good security, lightweight and efficient | |
| Phi-3 | 3.8B / 14B | Microsoft | 4K-128K | Compact yet high-performance, suitable for edge computing |
(3) How do you choose a model?
- Chinese Tasks: Prioritize Qwen2
- General English: Llama 3 or Mistral
- Resource-constrained: Phi-3 (runs with 3.8B parameters)
- Long-document processing: Mistral or Qwen2 (32K+ context)
- Security-sensitive scenarios: Gemma 2
6. Model Quantification and Hardware Requirements
(1) What is quantitative analysis?
Quantization is the process of compressing model weights from high precision (such as FP16, where each weight is 16 bits) to low precision (such as Q4, where each weight is 4 bits). It significantly reduces memory usage at the cost of a slight loss in quality.
Ollama uses quantization models in GGUF format (based on llama.cpp) by default. Common quantization levels:
(2) Comparison Table of Quantification Levels
| Quantization Level | Bits per Weight | 7B Model Size | Quality Loss | Applicable Scenarios |
|---|---|---|---|---|
| FP16 | 16-bit | ~14 GB | None | Quality-first, with ample VRAM |
| Q8 | 8-bit | ~7 GB | Very small | Balances quality and size |
| Q5 | 5 bits | ~5 GB | Minor | Balanced Choice |
| Q4 | 4-bit | ~4 GB | Acceptable | Preferred when memory is tight |
(3) Hardware Requirements Reference Table
| Number of Model Parameters | Q4 Quantization Size | Minimum Memory/VRAM | Recommended Configuration |
|---|---|---|---|
| 3B | ~2 GB | 4 GB | Laptops with integrated graphics |
| 7B-8B | ~4-5 GB | 8 GB | 8 GB VRAM GPU or 16 GB RAM |
| 13B-14B | ~8 GB | 16 GB | 16 GB VRAM GPU |
| 70B-72B | ~40 GB | 48 GB | 2×24 GB GPU or 64 GB RAM + CPU |
The quantized 7B model (Q4) requires only about 4 GB of memory and can run on most modern laptops. This is key to significantly lowering the barrier to entry for on-device AI.
7. Calling a Local Model Using Python
(1) Install the ollama library
pip install ollama
(2) Two Ways to Call It
Ollama supports two ways to call Python:
- ollama Python library: A pre-packaged Python SDK
- REST API: Direct HTTP requests
http://localhost:11434
▶ Example: Calling a Local Model in Python (Difficulty: ⭐)
import ollama
# Simple chat with local Llama 3
response = ollama.chat(
model="llama3",
messages=[
{"role": "user", "content": "Explain quantum computing in one sentence."},
],
)
print(response["message"]["content"])
▶ Example: Comparing Local and Cloud API Latency (Difficulty: ⭐⭐)
import time
import ollama
from openai import OpenAI
# Local model latency
start = time.time()
local_response = ollama.chat(
model="llama3",
messages=[{"role": "user", "content": "What is machine learning?"}],
)
local_time = time.time() - start
# Cloud API latency
client = OpenAI()
start = time.time()
cloud_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What is machine learning?"}],
)
cloud_time = time.time() - start
print(f"Local model: {local_time:.2f}s")
print(f"Cloud API: {cloud_time:.2f}s")
print(f"Local output: {local_response['message']['content'][:100]}")
print(f"Cloud output: {cloud_response.choices[0].message.content[:100]}")
▶ Example: Direct Call via REST API (Difficulty: ⭐⭐)
import requests
import json
# Call Ollama REST API directly
url = "http://localhost:11434/api/chat"
payload = {
"model": "llama3",
"messages": [{"role": "user", "content": "Write a haiku about programming."}],
"stream": False,
}
response = requests.post(url, json=payload)
result = response.json()
print(result["message"]["content"])
8. Comprehensive Example: Local AI Translator
▶ Example: Complete Translator—From Installation to Runtime (Difficulty: ⭐⭐)
This comprehensive example demonstrates: installing Ollama → downloading Llama 3 → implementing a "local AI translator" using the Python ollama library → comparing the differences in output quality with the OpenAI API.
import ollama
from openai import OpenAI
def local_translate(text: str, source: str = "English", target: str = "Chinese") -> str:
prompt = (
f"You are a professional {source}-{target} translator. "
f"Translate the following {source} text to {target}. "
f"Only output the translation, no explanation.\n\n{text}"
)
response = ollama.chat(
model="llama3",
messages=[{"role": "user", "content": prompt}],
)
return response["message"]["content"]
def cloud_translate(text: str, source: str = "English", target: str = "Chinese") -> str:
client = OpenAI()
prompt = (
f"You are a professional {source}-{target} translator. "
f"Translate the following {source} text to {target}. "
f"Only output the translation, no explanation.\n\n{text}"
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
test_sentences = [
"The patient presented with persistent cough and mild fever for three days.",
"Artificial intelligence is transforming healthcare diagnostics.",
"The stock market rallied after the central bank announced rate cuts.",
]
print("=" * 60)
print("Local AI Translator vs Cloud API Translator")
print("=" * 60)
for i, sentence in enumerate(test_sentences, 1):
local_result = local_translate(sentence)
cloud_result = cloud_translate(sentence)
print(f"\n[{i}] EN: {sentence}")
print(f" Local: {local_result}")
print(f" Cloud: {cloud_result}")
print(f" {'--- Match ---' if local_result.strip() == cloud_result.strip() else '--- Different ---'}")
Before running, make sure:
# Step 1: Install and start Ollama
ollama serve
# Step 2: Download model (in another terminal)
ollama pull llama3
# Step 3: Install Python dependencies
pip install ollama openai
# Step 4: Run the translator
python local_translator.py
Example of Expected Output:
============================================================
Local AI Translator vs Cloud API Translator
============================================================
[1] EN: The patient presented with persistent cough and mild fever for three days.
Local: Patient presents with persistent cough and mild fever for three days.
Cloud: Patient shows persistent cough and mild fever for three days.
--- Different ---
[2] EN: Artificial intelligence is transforming healthcare diagnostics.
Local: AI is transforming medical diagnosis.
Cloud: AI is revolutionizing the medical diagnosis field.
--- Different ---
Both translations are accurate, but the wording and style differ—the local model is fully capable of meeting everyday translation needs.
❓ FAQ
📖 Summary
- On-Premises vs. Cloud: On-premises wins in terms of privacy and cost; the cloud wins in terms of model quality and convenience
- Ollama: Run a local LLM with a single command; built-in REST API service
- Open-Source LLMs: Llama 3, Mistral, Qwen2, and Gemma 2 Each Have Their Own Strengths
- Quantification: Model size significantly reduced in Q4, with minimal loss of quality
- Hardware: 8 GB RAM for basic use, 16 GB for smooth performance, 48 GB+ for running large models
- Python Integration: The ollama library or REST API; the calling method is similar to that of the OpenAI SDK
📝 Exercises
Basics (⭐)
Install Ollama and download a model, then carry out a conversation in the command line:
# Step 1: Install Ollama from https://ollama.com
# Step 2: Download a model
ollama pull llama3
# Step 3: Start a chat
ollama run llama3
# >>> Tell me three interesting facts about the planet Mars.
# Step 4: List installed models
ollama list
Advanced (⭐⭐)
Use the Python ollama library to call a local model for translation and implement an interactive translator:
import ollama
def interactive_translator():
print("Local AI Translator (type 'quit' to exit)")
print("-" * 40)
while True:
text = input("EN> ")
if text.lower() == "quit":
break
response = ollama.chat(
model="llama3",
messages=[
{
"role": "user",
"content": f"Translate to Chinese, only output the translation:\n\n{text}",
},
],
)
print(f"CN> {response['message']['content']}\n")
interactive_translator()
Challenge (⭐⭐⭐)
Compare the differences in output between the local model and the cloud API for the same prompt, and write an analysis report:
import ollama
from openai import OpenAI
import time
PROMPT = """Analyze the following customer review and extract:
1. Sentiment (Positive/Negative/Neutral)
2. Key complaint or praise
3. Suggested action for the company
Review: "The headphones sound amazing but the Bluetooth keeps disconnecting every 10 minutes. I have to restart them constantly. Great audio quality but unusable for calls."
"""
def compare_outputs():
# Local model
start = time.time()
local = ollama.chat(
model="llama3",
messages=[{"role": "user", "content": PROMPT}],
)
local_time = time.time() - start
local_text = local["message"]["content"]
# Cloud API
client = OpenAI()
start = time.time()
cloud = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": PROMPT}],
)
cloud_time = time.time() - start
cloud_text = cloud.choices[0].message.content
print("PROMPT:", PROMPT[:80], "...")
print("=" * 60)
print(f"[Local - {local_time:.1f}s]\n{local_text}")
print("=" * 60)
print(f"[Cloud - {cloud_time:.1f}s]\n{cloud_text}")
print("=" * 60)
# TODO: Write a brief analysis comparing:
# - Accuracy of sentiment extraction
# - Completeness of key points
# - Actionability of suggestions
# - Response time difference
compare_outputs()



