5 Python Script ช่วยงาน Local LLM แบบอัตโนมัติด้วย Ollama

เมื่อโมเดลในเครื่องตอบคำถามได้รวดเร็วทันใจ งานจุกจิกที่ตามมามักจะเป็นการคัดลอกโน้ตลงใน prompt การรันงานซ้ำเมื่อโปรแกรมค้าง หรือการไล่แก้ JSON ที่ผิดโครงสร้าง งานเหล่านี้ไม่ใช่ความผิดของโมเดล แต่เป็นกระบวนการรอบตัวที่ซ้ำซากและน่าเบื่อ
การสร้างระบบอัตโนมัติในที่นี้หมายถึงการใช้สคริปต์จัดการไฟล์และโมเดล เพื่อสร้างผลลัพธ์ที่ตรวจสอบได้ สคริปต์ทั้ง 5 ตัวนี้จะช่วยรวม input, รัน batch ต่ออัตโนมัติ, ตรวจสอบ record, ค้นหาโน้ต และทำ smoke-test เมื่อเปลี่ยนโมเดล โดยทำงานผ่าน API ของ Ollama บนเครื่องของคุณเอง ผ่าน Python 3.13 และโมเดลอย่าง qwen3.5:4b โดยไม่ต้องพึ่งพาคลาวด์
ก่อนเริ่มสคริปต์ทั้งห้า: หนึ่ง Local Runtime และตัวช่วยขนาดเล็ก
สคริปต์เหล่านี้สื่อสารโดยตรงกับ Native API ของ Ollama ที่ http://127.0.0.1:11434 โดยตั้งค่า stream=False เพื่อให้ได้ JSON ที่สมบูรณ์ในครั้งเดียว และกำหนด timeout เพื่อป้องกันสคริปต์ค้างหากเซิร์ฟเวอร์มีปัญหา
# llm_local.py
import json, os, urllib.error, urllib.request
BASE_URL = os.environ.get("LOCAL_LLM_URL", "http://127.0.0.1:11434")
TIMEOUT_SECONDS = float(os.environ.get("LOCAL_LLM_TIMEOUT", "120"))
THINK_OFF = os.environ.get("LOCAL_LLM_THINK", "").lower() == "off"
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback never goes through a proxy
class LocalLLMError(RuntimeError):
"""Raised for any response the scripts must not treat as an answer."""
def post_json(path, payload, timeout=TIMEOUT_SECONDS):
request = urllib.request.Request(BASE_URL + path, data=json.dumps(payload).encode("utf-8"),
method="POST", headers={"Content-Type": "application/json"})
try:
with _OPENER.open(request, timeout=timeout) as response:
data = json.loads(response.read())
except urllib.error.HTTPError as err:
raise LocalLLMError(f"HTTP {err.code} from {path}: {err.read().decode('utf-8', 'replace')[:300]}") from err
except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as err:
raise LocalLLMError(f"no usable answer from {BASE_URL}{path}: {err}") from err
if isinstance(data, dict) and data.get("error"):
raise LocalLLMError(f"server error from {path}: {data['error']}")
return data
def list_models():
request = urllib.request.Request(BASE_URL + "/api/tags", method="GET")
with _OPENER.open(request, timeout=TIMEOUT_SECONDS) as response:
return {m["name"]: m.get("digest", "") for m in json.loads(response.read())["models"]}
def model_digest(model):
models = list_models()
for candidate in (model, f"{model}:latest"):
if candidate in models:
return models[candidate]
raise LocalLLMError(f"model {model!r} is not installed; run `ollama pull {model}`")
def generate(model, prompt, *, options=None, fmt=None):
payload = {"model": model, "prompt": prompt, "stream": False}
if THINK_OFF:
payload["think"] = False
if options:
payload["options"] = options
if fmt is not None:
payload["format"] = fmt
data = post_json("/api/generate", payload)
if not data.get("done") or "response" not in data:
raise LocalLLMError("incomplete response")
return data
def embed(model, inputs):
data = post_json("/api/embed", {"model": model, "input": inputs, "truncate": False})
vectors = data.get("embeddings")
if not isinstance(vectors, list) or len(vectors) != len(inputs):
raise LocalLLMError("embedding count does not match input count")
return vectorsจุดสำคัญคือ model_digest ที่ใช้บันทึก "ลายนิ้วมือ" ของโมเดลเพื่อป้องกันความสับสนเวลาอัปเดตโมเดลใหม่ และการตั้งค่า think: false เพื่อประหยัด token ในโมเดลกลุ่ม Reasoning ส่วนการบังคับให้ประมวลผลในเครื่องอย่างแท้จริงทำได้โดยตั้งค่า OLLAMA_NO_CLOUD=1 ในระดับระบบ

รูปภาพที่ 1 แผนภาพเวิร์กโฟลว์ของทั้ง 5 งานที่ทำงานจบภายในเครื่องเดียว โดย Nahla Davies
| งานจุกจิก | สคริปต์ | สิ่งที่ถูกบันทึกไว้ | ขอบเขตแรก |
|---|---|---|---|
| การรวบรวมเอกสารซ้ำๆ | pack_notes.py | ชุดข้อความพร้อมป้ายกำกับแหล่งที่มา | ส่งออกข้อความเท่านั้น |
| การรัน batch ที่หยุดชะงักซ้ำ | batch_prompts.py | บันทึกแบบ JSONL | รันต่อจากจุดที่ค้างได้ |
| การทำความสะอาด Record | extract_actions.py | CSV ที่ผ่านเกณฑ์และ JSONL ที่ถูกปัดตก | ตรวจสอบรูปแบบก่อนส่งออก |
| การหาโน้ตที่เกี่ยวข้อง | search_notes.py | ดัชนี local embedding | เน้นความคล้ายคลึง |
| การเช็กคุณภาพโมเดล | smoke_models.py | CSV สรุปผลและเวลาที่ใช้ | ชุดทดสอบขนาดเล็ก |
1. สร้างชุดข้อมูล Input ที่ระบุป้ายกำกับแหล่งที่มา
แทนที่จะคัดลอกโน้ตทีละไฟล์ สคริปต์นี้จะรวมไฟล์จากโฟลเดอร์ให้เป็นไฟล์เดียว พร้อมติดป้ายกำกับชื่อไฟล์และค่า hash เพื่อให้รู้ว่าข้อมูลมาจากไหน
# pack_notes.py
import hashlib, json
from pathlib import Path
ALLOWED = {".txt", ".md"}
def select_files(root):
root = root.resolve()
chosen = []
for path in sorted(root.rglob("*")):
if path.is_symlink() or not path.is_file() or path.suffix.lower() not in ALLOWED:
continue
if any(part.startswith(".") for part in path.relative_to(root).parts):
continue
if root not in path.resolve().parents:
continue
chosen.append(path)
return chosen
def build_pack(root, out_dir, max_file_bytes=20_000, max_total_bytes=60_000):
root, blocks, entries, total = root.resolve(), [], [], 0
out_dir.mkdir(parents=True, exist_ok=True)
for path in select_files(root):
data = path.read_bytes()
if len(data) > max_file_bytes:
raise ValueError(f"{path.relative_to(root)} is {len(data)} bytes; limit {max_file_bytes}")
text = data.decode("utf-8")
total += len(data)
if total > max_total_bytes:
raise ValueError(f"pack would exceed {max_total_bytes} bytes at {path.relative_to(root)}")
digest = hashlib.sha256(data).hexdigest()
rel = path.relative_to(root).as_posix()
entries.append({"source": rel, "bytes": len(data), "sha256": digest})
blocks.append(f"### source: {rel} (sha256:{digest[:12]})\n{text.rstrip()}\n")
(out_dir / "pack.txt").write_text("\n".join(blocks), encoding="utf-8")
(out_dir / "manifest.json").write_text(json.dumps({"files": entries, "total_bytes": total}, indent=2), encoding="utf-8")
return entriesสคริปต์นี้ใช้ pathlib กรองเฉพาะไฟล์ .txt และ .md โดยอัตโนมัติ พร้อมข้ามไฟล์ซ่อนและ symlink เพื่อความปลอดภัย ข้อมูลที่รวมมาจะช่วยให้คุณตรวจสอบที่มาของคำตอบได้ง่ายขึ้น
2. รัน Prompt Batch ที่สามารถรันต่อจากเดิมได้
หากการรันงานจำนวนมากถูกขัดจังหวะ สคริปต์นี้จะช่วยให้คุณไม่ต้องเริ่มใหม่ทั้งหมด โดยการบันทึกสถานะลงไฟล์ JSONL ทุกครั้งที่สำเร็จ
# batch_prompts.py
import hashlib, json
from datetime import datetime, timezone
from llm_local import LocalLLMError, generate, model_digest
OPTIONS = {"temperature": 0, "num_predict": 200}
def job_key(item, digest, prompt_version):
material = json.dumps({"prompt": item["prompt"], "prompt_version": prompt_version,
"model_digest": digest, "options": OPTIONS, "schema": "none"}, sort_keys=True)
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:16]
def load_journal(path):
done, unreadable = {}, 0
if path.exists():
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
unreadable += 1
continue
if record.get("status") == "ok":
done[record["key"]] = record
return done, unreadable
def run(items, journal_path, model, prompt_version="v1", limit=None):
digest = model_digest(model)
done, unreadable = load_journal(journal_path)
counts, calls = {"skipped": 0, "ok": 0, "error": 0, "unreadable_lines": unreadable}, 0
with journal_path.open("a", encoding="utf-8") as journal:
for item in items:
key = job_key(item, digest, prompt_version)
if key in done:
counts["skipped"] += 1
continue
if limit is not None and calls >= limit:
break
calls += 1
record = {"key": key, "id": item["id"], "model": model, "model_digest": digest[:12],
"prompt_version": prompt_version, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")}
try:
record.update(status="ok", response=generate(model, item["prompt"], options=OPTIONS)["response"].strip())
counts["ok"] += 1
except LocalLLMError as err:
record.update(status="error", error=str(err))
counts["error"] += 1
journal.write(json.dumps(record, ensure_ascii=False) + "\n")
journal.flush()
return countsหัวใจคือ job_key ที่แฮชค่าทั้ง prompt, โมเดล และการตั้งค่า หากคุณเปลี่ยนค่าใดค่าหนึ่ง สคริปต์จะถือเป็นงานใหม่ทันที ช่วยให้การจัดการ batch โปร่งใสและตรวจสอบข้อผิดพลาดได้เป็นรายบรรทัด
3. ส่งออกเฉพาะ Action Record ที่ผ่านการตรวจสอบแล้ว
การใช้ structured outputs ช่วยคุมรูปแบบ JSON ได้ แต่ยังบอกไม่ได้ว่าข้อมูลนั้นถูกต้องหรือไม่ สคริปต์นี้จึงเพิ่มการตรวจสอบเนื้อหา (evidence) ก่อนบันทึกลง CSV
# extract_actions.py
import csv, json
from llm_local import LocalLLMError, generate
SCHEMA = {"type": "object",
"properties": {"owner": {"type": "string"}, "task": {"type": "string"}, "evidence": {"type": "string"}},
"required": ["owner", "task", "evidence"], "additionalProperties": False}
def check_record(record, source_text):
if not isinstance(record, dict): return "not a JSON object"
if set(record) != {"owner", "task", "evidence"}: return f"unexpected keys: {sorted(record)}"
if "evidence" in record and " ".join(record["evidence"].split()) not in " ".join(source_text.split()):
return "evidence quote not found in the note"
return Noneสคริปต์จะคัดแยกข้อมูลที่ผ่านเกณฑ์ลงไฟล์ accepted.csv และเก็บข้อมูลที่ผิดพลาดพร้อมเหตุผลไว้ใน rejected.jsonl เพื่อให้มนุษย์เข้ามาตรวจสอบในภายหลัง ป้องกันโมเดลมโนคำตอบ (hallucination) เอง
4. ค้นหาโฟลเดอร์โน้ตขนาดเล็กในเครื่อง
เมื่อโน้ตมีจำนวนมากขึ้น การใส่ทุกอย่างลงใน prompt จะเริ่มไม่ได้ผล ดัชนี embedding ช่วยให้คุณค้นหาย่อหน้าที่เกี่ยวข้องที่สุดมาตอบคำถามได้ โดยใช้ฟีเจอร์ embeddings endpoint ของ Ollama
# search_notes.py
import json, math
from llm_local import LocalLLMError, embed, model_digest
def cosine(a, b):
return sum(x * y for x, y in zip(a, b)) / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def query(index_path, question, top=3):
index = json.loads(index_path.read_text(encoding="utf-8"))
[qvec] = embed(index["model"], [question])
return sorted(((cosine(qvec, c["vector"]), c["source"], c["text"]) for c in index["chunks"]), reverse=True)[:top]ดัชนีจะเก็บทั้งข้อความและเวกเตอร์ไว้ในไฟล์ JSON เดียว ทำให้การค้นหาข้อมูลในเครื่องทำได้รวดเร็วและเป็นส่วนตัว โดยไม่ต้องใช้ฐานข้อมูลเวกเตอร์ที่ซับซ้อน
5. รัน Smoke Test ของงานก่อนสลับโมเดล
ก่อนเปลี่ยนโมเดลหรือแก้ prompt ครั้งใหญ่ การรัน Smoke Test จะช่วยยืนยันว่าโมเดลใหม่ยังคงทำงานพื้นฐานอย่าง การคำนวณ หรือการทำตาม JSON schema ได้ถูกต้องหรือไม่
# smoke_models.py
import csv, json, statistics, time
from llm_local import LocalLLMError, generate, model_digest
FIXTURES = [
{"name": "arithmetic", "prompt": "What is 17 + 26? Reply with the number only.", "check": lambda r: "43" in r},
{"name": "json_shape", "prompt": "Name the capital of France.", "format": {"type": "object", "required": ["answer"]}, "check": lambda r: "answer" in r},
]สคริปต์นี้จะวัดผลทั้งความถูกต้องและเวลาที่ใช้ (Latency) เพื่อให้คุณตัดสินใจได้ว่าโมเดลใหม่คุ้มค่ากับการสลับไปใช้งานหรือไม่
สรุปแล้ว การทำให้งานเหล่านี้เป็นอัตโนมัติจะช่วยให้เวิร์กโฟลว์ Local AI ของคุณเสถียรขึ้น เริ่มจากงานที่ซ้ำซากที่สุด แล้วค่อยๆ ขยายไปสู่ส่วนอื่นๆ เพื่อให้คุณโฟลเดอร์กับผลลัพธ์ที่มีคุณภาพมากกว่าการมานั่งคัดลอกวางข้อมูลด้วยตัวเอง
ความคิดเห็น (0)
เข้าสู่ระบบเพื่อร่วมแสดงความเห็น
สมัครสมาชิกมาเป็นคนแรกที่แสดงความเห็นกันเลยโบร
