5 Useful Python Scripts to Automate Your Local LLM Workflows with Ollama A KDnuggets tutorial published five dependency-free Python scripts that automate local LLM chores against an Ollama server at http://127.0.0.1:11434, covering note packing, resumable prompt batches, validation of extracted records, note search and smoke-testing model changes. The scripts were run against qwen3.5:4b with nomic-embed-text on Ollama 0.40.13 and Python 3.13, with no hosted service involved, and each script leaves an inspectable file behind. The shared helper sets stream=False and a finite timeout so a stalled server surfaces as a failed request rather than a hung script. 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 https://docs.ollama.com/api/generate 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 https://www.kdnuggets.com/5-docker-containers-you-need-for-a-home-ai-lab 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. python 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 https://docs.ollama.com/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. python 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: bash $ 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 https://docs.python.org/3.12/library/pathlib.html 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 https://apryse.com/blog/ocr-in-python 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. python 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: bash $ 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 https://docs.ollama.com/capabilities/structured-outputs let you pass a JSON schema in the format field, which constrains the shape of the reply. The Ollama output-format distinction https://www.kdnuggets.com/ollama-for-managing-local-language-models-a-kdnuggets-cheat-sheet 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. python 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 https://docs.ollama.com/api/embed 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. python 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: bash $ 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 https://www.kdnuggets.com/the-local-ai-stack-for-productive-slms 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. python 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 bash $ 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 https://docs.python.org/3.12/library/time.html 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\ http://nahlawrites.com/ http://nahlawrites.com/ 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.