Ollama Local LLM Real-time
Ollama LLM Local Llama3 Mistral Gemma GGUF Quantized GPU REST API Streaming Real-time Processing ข้อมูลไม่ออกจากเครื่อง ปลอดภัย
| Model | Parameters | VRAM | Speed (tok/s) | เหมาะกับ |
|---|---|---|---|---|
| Llama 3 8B | 8B | 6GB | 40-80 | General Purpose |
| Mistral 7B | 7B | 6GB | 45-90 | General + Code |
| Gemma 2 9B | 9B | 7GB | 35-70 | Google Quality |
| Phi-3 Mini | 3.8B | 3GB | 60-120 | Small & Fast |
| CodeLlama 7B | 7B | 6GB | 40-80 | Code Generation |
| Llama 3 70B | 70B | 40GB | 10-20 | Best Quality |
Ollama Setup และ API
# === Ollama Installation & Usage ===
# Install
# curl -fsSL https://ollama.com/install.sh | sh
# หรือ Windows: Download from ollama.com
# หรือ Docker:
# docker run -d -v ollama:/root/.ollama -p 11434:11434 ollama/ollama
# Basic Commands
# ollama pull llama3 # ดาวน์โหลด Model
# ollama run llama3 # รัน Interactive Chat
# ollama list # แสดง Models ที่มี
# ollama show llama3 # ข้อมูล Model
# ollama rm llama3 # ลบ Model
# ollama cp llama3 my-llama3 # Copy Model
# REST API
# curl http://localhost:11434/api/generate -d '{
# "model": "llama3",
# "prompt": "อธิบาย Python decorator",
# "stream": true,
# "options": {
# "temperature": 0.7,
# "top_p": 0.9,
# "num_predict": 512,
# "num_ctx": 4096
# }
# }'
# Chat API (Conversation)
# curl http://localhost:11434/api/chat -d '{
# "model": "llama3",
# "messages": [
# {"role": "system", "content": "คุณเป็น Python Expert"},
# {"role": "user", "content": "อธิบาย async/await"}
# ],
# "stream": true
# }'
# Python Client
# pip install ollama
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional
@dataclass
class OllamaConfig:
model: str
temperature: float = 0.7
top_p: float = 0.9
num_predict: int = 512
num_ctx: int = 4096
repeat_penalty: float = 1.1
stream: bool = True
@dataclass
class ChatMessage:
role: str # system, user, assistant
content: str
@dataclass
class OllamaClient:
base_url: str = "http://localhost:11434"
config: OllamaConfig = field(default_factory=lambda: OllamaConfig("llama3"))
history: List[ChatMessage] = field(default_factory=list)
def chat(self, message: str) -> str:
self.history.append(ChatMessage("user", message))
# In real code: requests.post(f"{self.base_url}/api/chat", ...)
response = f"[Response from {self.config.model}]"
self.history.append(ChatMessage("assistant", response))
return response
def generate(self, prompt: str) -> str:
# In real code: requests.post(f"{self.base_url}/api/generate", ...)
return f"[Generated from {self.config.model}]"
def list_models(self) -> List[str]:
return ["llama3:8b", "mistral:7b", "codellama:7b", "gemma2:9b"]
# Demo
client = OllamaClient(config=OllamaConfig("llama3", temperature=0.7))
print("=== Ollama Client ===")
print(f" Model: {client.config.model}")
print(f" Temperature: {client.config.temperature}")
print(f" Context: {client.config.num_ctx} tokens")
print(f" Stream: {client.config.stream}")
print(f" Models: {', '.join(client.list_models())}")
Real-time Streaming
# === Real-time Streaming Architecture ===
# FastAPI + SSE (Server-Sent Events)
# from fastapi import FastAPI
# from fastapi.responses import StreamingResponse
# import ollama
# import json
#
# app = FastAPI()
#
# async def stream_response(model: str, messages: list):
# stream = ollama.chat(
# model=model,
# messages=messages,
# stream=True,
# )
# for chunk in stream:
# content = chunk['message']['content']
# yield f"data: {json.dumps({'content': content})}\n\n"
# yield "data: [DONE]\n\n"
#
# @app.post("/api/chat/stream")
# async def chat_stream(request: ChatRequest):
# return StreamingResponse(
# stream_response(request.model, request.messages),
# media_type="text/event-stream",
# )
# WebSocket Alternative
# from fastapi import WebSocket
#
# @app.websocket("/ws/chat")
# async def websocket_chat(ws: WebSocket):
# await ws.accept()
# while True:
# data = await ws.receive_json()
# stream = ollama.chat(
# model=data['model'],
# messages=data['messages'],
# stream=True,
# )
# for chunk in stream:
# await ws.send_json({
# "content": chunk['message']['content'],
# "done": chunk.get('done', False),
# })
# Performance Optimization
optimizations = {
"KV Cache": {
"desc": "Cache Key-Value pairs สำหรับ Conversation",
"benefit": "ลด TTFT สำหรับ Multi-turn Chat",
"config": "num_ctx ให้พอดีกับ Conversation Length",
},
"Batching": {
"desc": "รวม Requests หลายตัวประมวลผลพร้อมกัน",
"benefit": "เพิ่ม Throughput สำหรับ Multiple Users",
"config": "ใช้ vLLM หรือ TGI สำหรับ Production",
},
"Quantization": {
"desc": "ลดขนาด Model Q4_K_M, Q5_K_M, Q8_0",
"benefit": "ลด VRAM ใช้ เร็วขึ้น Quality ลดน้อย",
"config": "Q4_K_M สมดุลที่สุด Q8_0 คุณภาพสูง",
},
"GPU Offload": {
"desc": "โยน Layers ไป GPU ให้มากที่สุด",
"benefit": "เร็วกว่า CPU 10-50x",
"config": "num_gpu ตั้งให้สูงที่สุดที่ VRAM รองรับ",
},
}
print("Performance Optimizations:")
for opt, info in optimizations.items():
print(f"\n [{opt}]")
for k, v in info.items():
print(f" {k}: {v}")
Production Architecture
# === Production Architecture ===
# Docker Compose — Ollama + API + Frontend
# version: '3.8'
# services:
# ollama:
# image: ollama/ollama
# ports:
# - "11434:11434"
# volumes:
# - ollama_data:/root/.ollama
# deploy:
# resources:
# reservations:
# devices:
# - driver: nvidia
# count: 1
# capabilities: [gpu]
#
# api:
# build: ./api
# ports:
# - "8000:8000"
# environment:
# - OLLAMA_HOST=http://ollama:11434
# depends_on:
# - ollama
#
# frontend:
# build: ./frontend
# ports:
# - "3000:3000"
# depends_on:
# - api
#
# volumes:
# ollama_data:
# Modelfile — Custom Model
# FROM llama3
# PARAMETER temperature 0.7
# PARAMETER top_p 0.9
# PARAMETER num_ctx 4096
# SYSTEM """
# คุณเป็น AI Assistant ภาษาไทย
# ตอบคำถามเกี่ยวกับ Programming และ Technology
# ใช้ภาษาที่เข้าใจง่าย มีตัวอย่างโค้ด
# """
#
# ollama create thai-coder -f Modelfile
use_cases = {
"Code Assistant": {
"model": "codellama:7b หรือ deepseek-coder:6.7b",
"config": "temperature=0.2 num_ctx=8192",
"desc": "ช่วยเขียนโค้ด Debug Review",
},
"Chat Bot": {
"model": "llama3:8b หรือ mistral:7b",
"config": "temperature=0.7 num_ctx=4096",
"desc": "ตอบคำถามทั่วไป Customer Support",
},
"Document QA": {
"model": "llama3:8b + RAG (ChromaDB)",
"config": "temperature=0.3 num_ctx=8192",
"desc": "ตอบคำถามจากเอกสาร Knowledge Base",
},
"Translation": {
"model": "llama3:8b",
"config": "temperature=0.1 num_ctx=4096",
"desc": "แปลภาษา Thai-English",
},
}
print("Ollama Use Cases:")
for case, info in use_cases.items():
print(f"\n [{case}]")
for k, v in info.items():
print(f" {k}: {v}")
# Hardware Recommendations
hardware = {
"Budget (20K)": "RTX 3060 12GB — 7B Models Q4",
"Mid (40K)": "RTX 4070 Ti 16GB — 13B Models Q4",
"High (80K)": "RTX 4090 24GB — 30B Models Q4",
"Enterprise": "2x RTX 4090 or A100 — 70B Models",
"Apple": "Mac M2 Pro 32GB — 13B Models Good",
}
print(f"\n\nHardware Recommendations:")
for tier, spec in hardware.items():
print(f" [{tier}]: {spec}")
เคล็ดลับ
- Q4_K_M: Quantization ที่สมดุลที่สุด Quality ดี VRAM น้อย
- Streaming: ใช้ SSE หรือ WebSocket ส่ง Token ทีละตัว
- Context: ตั้ง num_ctx ให้พอดี ไม่ใหญ่เกินจำเป็น
- GPU: ใช้ GPU เสมอ เร็วกว่า CPU 10-50 เท่า
- Modelfile: สร้าง Custom Model ด้วย System Prompt ที่เหมาะสม
Ollama คืออะไร
เครื่องมือรัน LLM Local Llama3 Mistral Gemma GGUF Quantized GPU REST API ข้อมูลไม่ออกจากเครื่อง ติดตั้งง่าย
Real-time Processing กับ LLM ทำอย่างไร
Streaming API Token ทีละตัว SSE WebSocket TTFT KV Cache Context Window ผู้ใช้เห็นผลลัพธ์ทันที
เลือก Model ขนาดไหนดี
VRAM 8GB ใช้ 7-8B VRAM 16GB ใช้ 13-14B VRAM 24GB+ ใช้ 30-70B Q4_K_M สมดุล Code ใช้ CodeLlama DeepSeek
Ollama กับ llama.cpp ต่างกันอย่างไร
llama.cpp C++ Runtime Compile Config เอง Ollama Wrapper REST API Model Management ง่าย ติดตั้งคำสั่งเดียว ดาวน์โหลดอัตโนมัติ
สรุป
Ollama Local LLM Llama3 Mistral GGUF Quantization REST API Streaming SSE WebSocket Real-time TTFT KV Cache GPU Docker Modelfile Custom Model Production Architecture
