5 个 Python 脚本:自动化本地 Ollama LLM 工作流

五个小巧、无依赖的 Python 脚本,用于本地 Ollama 环境,分别负责打包笔记、续跑提示词批次、校验抽取出的记录、搜索笔记,以及对模型变更做冒烟测试,每个脚本都会留下一个你可以检查的文件。
作者:Nahla Davies,KDnuggets,2026 年 12 月 4 日,发布于 Python
本地模型不到一秒就给出回答,然后杂活开始了。你打开三个笔记,把它们一条条粘贴进提示词,随后就忘了那个好答案到底出自哪个文件。你循环跑二十条提示词;终端在第十四条时关掉了;你只好把这二十条再跑一遍。模型返回了一个整齐的 JSON 对象,但键是错的。你手动把它修好。一周后,没人找得到那条提到磁盘问题的笔记,于是所有笔记又一次被塞进提示词。这些杂活都不是模型的问题。它们是围绕模型的工作,而且每次都是同样的工作。
这里的自动化指的是:用一个脚本完成那些重复的文件与模型操作,并留下一个你可以检查的文件,仅此而已。下面这五个脚本分别负责打包输入、续跑批次、校验抽取出的记录、搜索笔记,以及对模型变更做冒烟测试。它们共用一个小的辅助工具,以及你自己机器上运行的同一个 Ollama 服务;本文引用的每一份输出,都来自在 Ollama 0.40.13、Python 3.13 上对 qwen3.5:4b 配合 nomic-embed-text 的运行,全程不涉及任何托管服务。
在五个脚本之前:一个本地运行时和一个小辅助工具
先前搭建的家庭 AI 实验室环境涵盖了运行时和接口;这些脚本使用该运行时,而没有额外增加一个编排层。它们通过 http://127.0.0.1:11434 与 Ollama 的原生 API 通信,其中有两个关键设置。stream=False 意味着每次调用返回一个 JSON 对象,而不是一连串部分行的流。有限的超时意味着服务器卡住时会表现为请求失败,而不是脚本永远不结束。
# 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({})) # 回环地址绝不经过代理 class LocalLLMError(RuntimeError): """当脚本不得将任何响应当作答案时抛出。""" 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 记录模型的摘要,即运行时对模型内容生成的指纹,这样像 qwen3.5:4b 这样被重复使用的名称,就不会在重新拉取后悄无声息地代表不同的权重。对于会先执行一轮推理的模型,会发送 think: false;如果没有它,脚本 5 中留给简短回答的预算就会被思考 Token 花掉。而且仅凭 localhost URL 并不能证明是在本地计算,因为 Ollama 可以通过同一个本地服务器路由云端托管的模型。按 Ollama FAQ 所述,在守护进程的环境中设置 OLLAMA_NO_CLOUD=1 并重启该守护进程;在 Python 进程中设置它,对已经运行的服务器没有任何作用。接下来是每个脚本中真正起作用的部分;每个脚本外层的命令行封装都是普通的 argparse,下面的演示命令就是产生上述引用输出的命令。
图 1。五项任务以及每项任务留下的文件。这是提议的工作流,而非已部署系统的追踪记录;每个箭头都停留在本地机器上。原图由 Nahla Davies 绘制。
反复收集文档
带来源标签的文本包和清单
仅导出文本;扫描件会先被处理
重复执行已停止的批处理
恢复键包括输入和配置
清洗模型生成的记录
接受的 CSV 加上被拒绝的 JSONL
在导出之前进行形状和证据检查
找到相关笔记
同一身份的本地嵌入索引
相似并不等于正确
过晚发现糟糕的模型或提示词变更
小型测试夹具集不是基准测试
表 1。按任务选择脚本。
1. 构建带来源标签的输入包
第一项琐碎工作是收集。与其把笔记逐条粘贴到提示词中,不如让脚本指向一个文件夹,然后得到一个文本文件,其中每个块都标明了它来自哪个文件以及其内容的哈希。
# 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") # 非 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
在一个包含四篇简短笔记的文件夹上运行它,输出会列出输入了什么:
$ python pack_notes.py demo/inputs demo/outputs/pack packed 4 files, 552 bytes -> demo/outputs/pack/pack.txt ideas.md 155 bytes sha256:e2d8ca426543 reminder.txt 90 bytes sha256:7efa15e039a7 retro-october.txt 178 bytes sha256:78c27d8e792b standup-2026-11-03.md 129 bytes sha256:7b41af11368b
筛选规则刻意收得很窄,大部分工作由 pathlib 完成。只读取 .txt 和 .md 文件,并经过排序,确保两次运行产生完全相同的顺序。隐藏文件会被跳过(demo 文件夹里的 .hidden-note.md 始终没能被纳入),符号链接、以及解析后路径逃出根目录的文件同样被跳过。超大或非 UTF-8 编码的文件会让本次运行以一个具名错误中止,而不是被静默截断成一段文字。字节上限是为了让这个你之后要检查的提示词便于阅读而设的界限,并不是 tokenizer;一个控制在 60 KB 以内的 pack,仍可能放不进模型的上下文窗口。
这个 pack 不读取什么,和它读取什么同样重要。该 pack 从不会打开 PDF。对于纯图片 PDF,把扫描页转成可搜索文本是更早的一步;先检查提取出的文本,导出为 UTF-8 文件,再放入这个输入文件夹。可搜索 PDF 仍然不是纯文本文件,所以导出这一步必须显式保留。
2. 运行可续跑的提示词批处理
第二件杂活是处理只做了一半的批处理。解决办法是一份日志:每次调用后追加一行 JSON 记录(JSONL),这样重跑时就能看到哪些已经成功。
原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(5 Useful Python Scripts to Automate Your Local LLM Workflows with Ollama)
Five small, dependency-free Python scripts for a local Ollama setup that pack notes, resume prompt batches, validate extracted records, search notes, and smoke-test model changes, each leaving a file you can inspect.
By Nahla Davies, KDnuggets on December 4, 2026 in Python

A local model answers in under a second, and then the chores start. You open three notes and paste them into a prompt one at a time, then lose track of which file the good answer came from. You run twenty prompts in a loop; the terminal closes at number fourteen; you run all twenty again. The model returns a tidy JSON object with the wrong keys. You fix it by hand. A week later nobody can find the note that mentioned the disk problem, so all of them go into the prompt once more. None of these chores is the model's fault. It is the work around the model, and it is the same work every time.
Automation here means a script that does one of those repeated file-and-model jobs and leaves a file you can inspect, nothing grander. The five below pack inputs, resume a batch, validate extracted records, search notes and smoke-test a model change. They share one small helper and one running Ollama server on your own machine, and every output quoted in this article comes from running them against qwen3.5:4b with nomic-embed-text on Ollama 0.40.13, Python 3.13, with no hosted service involved.
Before the Five Scripts: One Local Runtime and a Small Helper
The earlier home AI lab setup covers the runtime and interface; these scripts use that runtime without adding another orchestration layer. They talk to Ollama's native API at http://127.0.0.1:11434 with two settings that matter. stream=False means each call returns one JSON object rather than a stream of partial lines. A finite timeout means a stalled server shows up as a failed request instead of a script that never ends.
# 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
Three decisions in here matter later. model_digest records the model's digest, the runtime's fingerprint of the model contents, so that a reused name like qwen3.5:4b can't silently stand for different weights after a re-pull. think: false is sent for models that run a reasoning pass first; without it, the short answer budgets in script 5 get spent on thinking tokens. And a localhost URL alone doesn't prove local computation, because Ollama can route cloud-hosted models through the same local server. Set OLLAMA_NO_CLOUD=1 in the daemon's environment and restart it, as the Ollama FAQ describes; setting it in the Python process does nothing to a server that is already running. What follows is each script's working part; the command-line wrapper around each one is ordinary argparse, and the demo commands below are the ones that produced the quoted output.
Figure 1. The five jobs and the file each one leaves behind. Proposed workflow, not a trace of a deployed system; every arrow stays on the local machine. Original diagram by Nahla Davies.
Repeatedly gathering documents
Source-labeled text pack and manifest
Text exports only; scans are processed first
Repeating a stopped batch
Resume keys include inputs and configuration
Cleaning model-generated records
Accepted CSV plus rejected JSONL
Shape and evidence checks precede export
Finding the relevant note
Same-identity local embedding index
Similarity is not correctness
Discovering a bad model or prompt change late
A small fixture set is not a benchmark
Table 1. Pick the script by the chore.
1. Build a Source-Labeled Input Pack
The first chore is gathering. Instead of pasting notes into a prompt one by one, point a script at a folder and get back one text file where every block is labeled with the file it came from and a hash of its contents.
# 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") # a non-UTF-8 file raises here, by design
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
Run it on a folder of four short notes and the output names what went in:
$ python pack_notes.py demo/inputs demo/outputs/pack
packed 4 files, 552 bytes -> demo/outputs/pack/pack.txt
ideas.md 155 bytes sha256:e2d8ca426543
reminder.txt 90 bytes sha256:7efa15e039a7
retro-october.txt 178 bytes sha256:78c27d8e792b
standup-2026-11-03.md 129 bytes sha256:7b41af11368b
The selection rules are deliberately narrow, and pathlib does most of the work. Only .txt and .md files are read, sorted so two runs produce the same order. Hidden files are skipped (a .hidden-note.md in the demo folder never made it in), as are symlinks and anything whose resolved path escapes the root. An oversize or non-UTF-8 file stops the run with a named error rather than becoming a silently truncated paragraph. The byte caps are a readability bound for a prompt you'll inspect, not a tokenizer; a pack that fits in 60 KB may still not fit a model's context window.
What the pack doesn't read is as important as what it does. The pack never opens a PDF. For image-only PDFs, turning scanned pages into searchable text is an earlier step; inspect the extracted text and export a UTF-8 file before adding it to this input folder. A searchable PDF is still not a plain-text file, so the export step stays explicit.
2. Run a Prompt Batch That Can Resume
The second chore is the half-finished batch. The fix is a journal: one JSON record per line (JSONL), appended after every call, so a rerun can see what already succeeded.
# 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 # a partial final line from an interrupted write is counted, not hidden
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
The key is the whole decision. It hashes the prompt text, the prompt version, the model digest, the options and a schema version, so a record only counts as done for exactly the configuration that produced it. The --limit flag exists to simulate an interruption; here is a two-prompt batch stopped after one call, resumed, and then rerun under a new prompt version:
$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b --limit 1
skipped 0 (already done), ok 1, errors 0, unreadable journal lines 0
$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b
skipped 1 (already done), ok 1, errors 0, unreadable journal lines 0
$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b --prompt-version v2 --limit 0
skipped 0 (already done), ok 0, errors 0, unreadable journal lines 0
The second run skipped the item the first run completed and made only the one call that was missing. The third run, with v2 in the key, found nothing it could reuse, which is the behavior you want when the prompt changed. The journal itself is readable: each line carries the key, the item ID, the model digest, a timestamp and either the response or the error, so a failed item is a visible error record and never a clean empty batch.
One honest caveat: this is resume behavior, not exactly-once execution. If the process dies after the model has answered but before the line is written, that item runs again on the next pass. For a sequential batch of prompts that's the right trade; a journal is simpler to inspect than a queue, and nothing here is parallel or retried automatically.
3. Export Only Validated Action Records
The third chore is the JSON that parses and still can't be used. Ollama's structured outputs let you pass a JSON schema in the format field, which constrains the shape of the reply. The Ollama output-format distinction matters here: asking for JSON alone does not specify the fields this export needs. The schema does that. What the schema can't do is decide whether the record should reach your spreadsheet, so the script checks it locally before writing a row.
# 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}
PROMPT = ("Read the note. Return one JSON object with exactly these keys: owner (the person responsible), "
"task (what they must do), evidence (a short quote copied exactly from the note that supports both). "
"Use only words present in the note.\n\nNote:\n{note}\n")
def normalize(text):
return " ".join(text.split())
def check_record(record, source_text):
"""Return a rejection reason, or None if the record may be exported."""
if not isinstance(record, dict):
return "not a JSON object"
if set(record) != {"owner", "task", "evidence"}:
return f"unexpected keys: {sorted(record)}"
for key in ("owner", "task", "evidence"):
if not isinstance(record[key], str) or not record[key].strip():
return f"{key} is not a non-empty string"
if normalize(record["evidence"]) not in normalize(source_text):
return "evidence quote not found in the note"
return None
def extract(note_paths, out_dir, model):
out_dir.mkdir(parents=True, exist_ok=True)
with (out_dir / "accepted.csv").open("w", newline="", encoding="utf-8") as acc, \
(out_dir / "rejected.jsonl").open("w", encoding="utf-8") as rej:
writer = csv.DictWriter(acc, fieldnames=["source", "owner", "task", "evidence"])
writer.writeheader()
for path in note_paths:
note = path.read_text(encoding="utf-8")
try:
record = json.loads(generate(model, PROMPT.format(note=note), options={"temperature": 0}, fmt=SCHEMA)["response"])
reason = check_record(record, note)
except LocalLLMError as err:
record, reason = None, f"model call failed: {err}"
except json.JSONDecodeError:
record, reason = None, "response was not valid JSON"
if reason is None:
writer.writerow({"source": path.name, **record})
else:
rej.write(json.dumps({"source": path.name, "reason": reason, "record": record}) + "\n")
On the four demo notes, qwen3.5:4b produced four records that passed every check. Those four rows are the interesting result, because two of them should not be used:
source,owner,task,evidence
ideas.md,unknown,compare on the same three prompts first,Try a smaller model for the nightly summaries and compare on the same three prompts first.
reminder.txt,the floor,repairs,Nothing else to report.
retro-october.txt,Theo,Add the journal folder to the cleanup allowlist,The batch job restarted twice because the journal file was deleted by a cleanup script.
standup-2026-11-03.md,Maya,Archive the old config,Action: Archive the old config
The standup and retro rows are what you'd want. The ideas.md row has an owner of unknown, which is at least candid. The reminder.txt row has an owner of the floor and a task of repairs, extracted from a note that contains no action at all, with an evidence quote (Nothing else to report.) that really does appear in the note. Every check passed; the record is nonsense. The schema guaranteed the shape, the evidence check guaranteed traceability, and neither can judge whether the note contained an action in the first place. That's the review boundary this script keeps: the accepted file is a queue for a person to confirm, not a finished export, and the rejected.jsonl file holds the reasons for anything that failed a check so the failures stay visible too.
4. Search a Small Folder of Notes Locally
The fourth chore is finding the note that mentioned the disk problem. Is retrieval worth building for a folder this small? Pasting every note into every prompt stops scaling at about a dozen files. An embedding index lets you ask a question and get back the three most similar passages with their sources, so the answer depends on how often you go looking.
An embedding is a list of numbers that represents a piece of text so that similar texts sit near each other. The script compares two of those lists with cosine similarity, a single number between -1 and 1 for how aligned they are. Ollama's embeddings endpoint returns one vector per input string, and truncate=False makes it refuse an input that's too long for the model instead of embedding a silently shortened version of it.
# search_notes.py
import json, math
from llm_local import LocalLLMError, embed, model_digest
MAX_CHUNK_CHARS = 600
def chunks_from(notes_dir):
for path in sorted(p for p in notes_dir.iterdir() if p.suffix.lower() in {".txt", ".md"} and not p.name.startswith(".")):
for i, para in enumerate(p for p in path.read_text(encoding="utf-8").split("\n\n") if p.strip()):
text = " ".join(para.split())
if len(text) > MAX_CHUNK_CHARS:
raise ValueError(f"{path.name} paragraph {i} is {len(text)} chars; split it before indexing")
yield {"source": f"{path.name}#{i}", "text": text}
def check_vectors(vectors, dim=None):
for v in vectors:
dim = dim or len(v)
if len(v) != dim or not all(math.isfinite(x) for x in v) or not any(v):
raise ValueError("embedding has wrong length, non-finite values or is all zeros")
return dim
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 build(notes_dir, index_path, model):
chunks = list(chunks_from(notes_dir))
vectors = embed(model, [c["text"] for c in chunks])
dim = check_vectors(vectors)
for chunk, vector in zip(chunks, vectors):
chunk["vector"] = vector
index_path.write_text(json.dumps({"model": model, "model_digest": model_digest(model), "dim": dim, "chunks": chunks}), encoding="utf-8")
def query(index_path, question, top=3):
index = json.loads(index_path.read_text(encoding="utf-8"))
if model_digest(index["model"]) != index["model_digest"]:
raise LocalLLMError(f"index was built with a different {index['model']}; rebuild it")
[qvec] = embed(index["model"], [question])
check_vectors([qvec], index["dim"])
return sorted(((cosine(qvec, c["vector"]), c["source"], c["text"]) for c in index["chunks"]), reverse=True)[:top]
Build the index once, then query it:
$ python search_notes.py build demo/inputs demo/outputs/index.json --model nomic-embed-text
indexed 11 chunks, 768 dimensions, nomic-embed-text (digest 0a109f422b47) -> demo/outputs/index.json
$ python search_notes.py query demo/outputs/index.json "which server is low on disk" --top 3
0.702 standup-2026-11-03.md#2 The build server is named orion and its disk is at 81%.
0.545 standup-2026-11-03.md#1 Action: Archive the old config. Owner: Maya.
0.497 reminder.txt#1 The office is closed on Friday for the floor repairs. Nothing else to report.
The top hit is the right paragraph, and the score gap between it and the next two is the thing to read. The context-retrieval layer supplies relevant passages; the generator still has to use them correctly. A score of 0.70 says "most similar of these eleven" and nothing about whether the passage answers the question. The index file stores the model's name and digest alongside the vectors, and a query refuses to run if the installed model's digest has changed, because vectors from two different embedding models aren't comparable even when the dimensions match. For eleven paragraphs a JSON file is the whole database. It also contains your notes in plain text, so treat it with the same care as the notes.
5. Run a Task Smoke Test Before Switching Models
The fifth chore is the one you only notice late: you swap in a smaller model or rewrite a prompt, and the batch from script 2 quietly starts producing worse answers. A smoke test is three fixed prompts with explicit checks, run the same way every time.
# smoke_models.py
import csv, json, statistics, time
from llm_local import LocalLLMError, generate, model_digest
OPTIONS = {"temperature": 0, "num_predict": 60}
ANSWER_SCHEMA = {"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"], "additionalProperties": False}
FIXTURES = [
{"name": "arithmetic", "prompt": "What is 17 + 26? Reply with the number only.",
"check": lambda r: r.strip().rstrip(".") == "43", "format": None},
{"name": "json_shape", "prompt": "Name the capital of France. Put it in the answer field.",
"check": lambda r: set(json.loads(r)) == {"answer"}, "format": ANSWER_SCHEMA},
{"name": "context_fact", "prompt": "Context: The build server is named orion.\nQuestion: What is the build server named? Answer with one word.",
"check": lambda r: "orion" in r.lower(), "format": None},
]
def attempt(model, fixture):
started = time.perf_counter()
try:
text = generate(model, fixture["prompt"], options=OPTIONS, fmt=fixture["format"])["response"]
elapsed = time.perf_counter() - started
try:
ok = bool(fixture["check"](text))
except (json.JSONDecodeError, KeyError, TypeError):
ok = False
return {"outcome": "pass" if ok else "fail", "seconds": round(elapsed, 3), "response": text.strip()[:80]}
except LocalLLMError as err:
return {"outcome": "error", "seconds": round(time.perf_counter() - started, 3), "response": str(err)[:80]}
def smoke(models, out_path, prompt_version="v1"):
rows = []
for model in models:
digest = model_digest(model)[:12]
rows.append({"model": model, "digest": digest, "prompt_version": prompt_version, "fixture": "warmup", **attempt(model, FIXTURES[0])})
for fixture in FIXTURES:
rows.append({"model": model, "digest": digest, "prompt_version": prompt_version, "fixture": fixture["name"], **attempt(model, fixture)})
with out_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
return rows
$ python smoke_models.py demo/outputs/smoke.csv --model qwen3.5:4b
qwen3.5:4b: pass 3, fail 0, error 0, median answered 0.07s
arithmetic pass 0.07s 43
json_shape pass 0.17s { "answer": "Paris" }
context_fact pass 0.07s Orion
Each fixture checks one thing: that the model can do trivial arithmetic when told to answer with a number, that it respects a schema, and that it reads a fact out of supplied context rather than from memory. The first call per model is a labeled warmup and is never scored, because it carries the model load. Timings come from perf_counter around the whole request, so they are end-to-end client seconds on one machine with the model already loaded. The server reports its own load and generation durations in the response, and those are a different measure. A failed attempt stays in the CSV as a failure with its time, and a faster wrong answer never counts as a pass. Pass the script a second --model, or a second prompt version, and you get the same three rows for each side. Three fixtures can't rank models; they can tell you, before you change anything the other four scripts depend on, that the new configuration still clears the bar the old one did.
Automate the Chore You Already Repeat
Start with whichever of these chores you did by hand this week. If it was gathering files, the pack; if it was rerunning a loop, the journal; if you're about to change a model or a prompt, the smoke set first. The embedding index is the one to add last, and only when finding the right note has become the slow part rather than reading it.
Whichever you pick, the test is the same: run it, open the file it wrote, change one input or one setting, run it again, and check that the second result is easier to understand than the first was. Keep a person between accepted.csv and anything that matters, since the record that named the floor as an owner passed every automated check there is. A script earns a place in your workflow when its output file is something you'd trust more than your own copy-and-paste, and these five are small enough that you can read the whole thing before deciding.
Nahla Davies is a software developer and tech writer. Before devoting her work full time to technical writing, she managed—among other intriguing things—to serve as a lead programmer at an Inc. 5,000 experiential branding organization whose clients include Samsung, Time Warner, Netflix, and Sony.
原文为英文,正文由自动抓取并保留原文。
原文发布于 KDnuggets(5 Useful Python Scripts to Automate Your Local LLM Workflows with Ollama),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。