Chạy AI Local Với Ollama — Hướng Dẫn Từ A Đến Z
Ollama cho phép chạy LLM trên máy bạn hoàn toàn miễn phí, không internet, không API key. Hướng dẫn cài đặt, API, và tích hợp code.
Chạy AI trên cloud tiện — nhưng có ba vấn đề: tốn phí theo request, rate limit, và dữ liệu nhạy cảm phải gửi lên server người khác. Ollama giải quyết tất cả: một tool mã nguồn mở cho phép bạn chạy LLM hoàn toàn trên máy mình, không internet, không API key, không giới hạn.
Ollama Là Gì?#
Ollama là runtime mã nguồn mở (95k+ sao GitHub) để tải, quản lý và chạy LLM local. Think of it như Docker cho AI models — một lệnh pull, một lệnh run, và bạn đang chat với Llama 3, Mistral, Qwen, Gemma ngay trên terminal.
ollama pull llama3.2
ollama run llama3.2
>>> viết một bài thơ về RusttxtSau lần tải đầu tiên, không cần internet. Model chạy hoàn toàn trên CPU hoặc GPU của bạn.
Tại Sao Nên Chạy AI Local?#
| Vấn đề | Cloud API | Ollama (local) |
|---|---|---|
| Chi phí | Theo token, có thể $100-1000/tháng | 0đ — chỉ tốn điện |
| Privacy | Gửi dữ liệu lên server bên thứ ba | 100% local |
| Rate limit | Có (requests/phút) | Không |
| Offline | Không | Có |
| Latency | ~500ms-2s (network) | ~50ms-200ms (GPU) |
Cài Đặt#
macOS#
brew install ollamabashLinux#
curl -fsSL https://ollama.com/install.sh | shbashWindows#
Tải installer từ ollama.com/download ↗. Hỗ trợ native Windows (không cần WSL2).
Docker#
docker run -d -p 11434:11434 --name ollama ollama/ollamabashSau cài đặt, Ollama chạy ngầm và expose REST API tại http://localhost:11434.
Tải Và Chạy Model#
Các Lệnh Cơ Bản#
# Liệt kê model có sẵn
ollama list
# Tải model
ollama pull llama3.2 # 3B params, ~2GB
ollama pull mistral # 7B params, ~4GB
ollama pull qwen2.5:7b # 7B params, ~4.5GB
ollama pull gemma3:12b # 12B params, ~8GB
# Chạy interactive chat
ollama run llama3.2
# Chạy một câu hỏi
ollama run mistral "giải thích blockchain trong 2 câu"
# Xoá model
ollama rm llama3.2bashChọn Model Nào?#
| Model | Tham số | RAM | Chất lượng | Dùng cho |
|---|---|---|---|---|
| Llama 3.2 | 3B | ~2GB | Tốt | General, coding cơ bản |
| Mistral | 7B | ~4GB | Khá | General, hỗ trợ tool calling |
| Qwen 2.5 | 7B-32B | ~4-20GB | Rất tốt | Coding mạnh, đa ngôn ngữ |
| Gemma 3 | 12B-27B | ~8-18GB | Xuất sắc | General, reasoning |
| DeepSeek R1 | 7B-70B | ~4-43GB | Tốt nhất | Reasoning, toán, code |
| Phi-4 | 14B | ~9GB | Tốt | Code, nhẹ hơn cùng size |
Rule of thumb: máy 8GB RAM chạy 7B model, 16GB chạy 14B-32B, 32GB+ chạy 70B.
REST API#
Ollama expose API tại localhost:11434. Hai interface:
Native API#
# Chat
curl http://localhost:11434/api/chat \
-d '{"model":"mistral","messages":[{"role":"user","content":"Xin chào"}]}'bashOpenAI-Compatible API#
Ollama hỗ trợ endpoint /v1/chat/completions tương thích hoàn toàn với OpenAI SDK. Chỉ cần đổi base_url:
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama" # SDK yêu cầu, Ollama bỏ qua
)
response = client.chat.completions.create(
model="mistral",
messages=[{"role": "user", "content": "Giải thích async/await trong JavaScript"}]
)
print(response.choices[0].message.content)pythonLợi ích: mọi code đang dùng OpenAI API có thể chạy local chỉ bằng đổi base_url. LangChain, LlamaIndex, AutoGen đều hoạt động.
Tích Hợp Python#
Dùng thư viện chính thức#
pip install ollamabashimport ollama
response = ollama.chat(model='mistral', messages=[
{'role': 'user', 'content': 'Viết một function Python tính Fibonacci'}
])
print(response['message']['content'])pythonStreaming#
stream = ollama.chat(model='mistral', messages=[
{'role': 'user', 'content': 'Kể chuyện dài 100 từ'}
], stream=True)
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)pythonStructured Output (JSON)#
response = ollama.chat(model='qwen2.5', messages=[
{'role': 'user', 'content': 'Liệt kê 3 ngôn ngữ lập trình phổ biến'}
], format='json')pythonXây Dựng Local RAG#
Ollama + ChromaDB = RAG pipeline hoàn toàn local:
import ollama
import chromadb
# Tạo embedding local
embedding = ollama.embeddings(model='nomic-embed-text', prompt='Nội dung cần index')
# Lưu vào ChromaDB
chroma_client = chromadb.Client()
collection = chroma_client.create_collection("docs")
collection.add(
embeddings=[embedding['embedding']],
documents=["Nội dung tài liệu"],
ids=["doc_1"]
)
# Query
results = collection.query(
query_embeddings=[ollama.embeddings(
model='nomic-embed-text', prompt='Câu hỏi'
)['embedding']],
n_results=3
)
# Generate với context
context = "\n".join(results['documents'][0])
response = ollama.chat(model='mistral', messages=[
{'role': 'system', 'content': f'Trả lời dựa trên context:\n{context}'},
{'role': 'user', 'content': 'Câu hỏi'}
])pythonCấu Hình Quan Trọng#
# Bind ra tất cả interface (để dùng từ máy khác)
OLLAMA_HOST=0.0.0.0:11434 ollama serve
# Giữ model resident, không unload
OLLAMA_KEEP_ALIVE=-1 ollama serve
# Parallel requests
OLLAMA_NUM_PARALLEL=4 ollama serve
# Flash attention (giảm RAM, tăng tốc)
OLLAMA_FLASH_ATTENTION=1 ollama serve
# Context window lớn hơn
OLLAMA_CONTEXT_LENGTH=16384 ollama servebashOllama Với AI Coding Agent#
Ollama hoạt động như backend cho hầu hết AI coding tools nhờ OpenAI-compatible API:
# OpenCode
opencode --model ollama:mistral
# Continue.dev (VS Code)
# config.json: { "models": [{ "provider": "ollama", "model": "mistral" }] }
# Claude Code (qua proxy)
# Chỉ OLLAMA_HOST, dùng công cụ như 'ollama-serve' để convert APIbashGiới Hạn#
- Model nhỏ hơn cloud — Llama 3 70B chạy local cần 43GB RAM. GPT-4 không có bản local.
- Tốc độ — GPU tầm trung (RTX 3060) đạt ~20-30 token/s cho 7B model. Cloud nhanh hơn.
- Không fine-tuning — Ollama chạy pre-trained model, không train.
- Tool calling — Chỉ một số model hỗ trợ (Llama 3.1+, Qwen 2.5, Mistral).
Kết Luận#
Ollama là công cụ không thể thiếu cho bất kỳ ai làm việc với AI coding agent. Miễn phí, private, không rate limit — chạy trên Docker một lệnh, API tương thích OpenAI, tích hợp với mọi framework.
Cài ngay hôm nay, pull Mistral, và thử thay thế hoàn toàn cloud API cho workflow hàng ngày. Bạn sẽ ngạc nhiên vì chất lượng 7B model trên máy local.