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.
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.
| Chore | Script | Saved artifact | First boundary |
|---|---|---|---|
| Repeatedly gathering documents | pack_notes.py |
Source-labeled text pack and manifest | Text exports only; scans are processed first |
| Repeating a stopped batch | batch_prompts.py |
Per-item JSONL journal | Resume keys include inputs and configuration |
| Cleaning model-generated records | extract_actions.py |
Accepted CSV plus rejected JSONL | Shape and evidence checks precede export |
| Finding the relevant note | search_notes.py |
Same-identity local embedding index | Similarity is not correctness |
| Discovering a bad model or prompt change late | smoke_models.py |
Outcome and timing CSV | A small fixture set is not a benchmark |
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
Comments
No comments yet. Start the discussion.