{"slug": "5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama", "title": "5 Useful Python Scripts to Automate Your Local LLM Workflows with Ollama", "summary": "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.", "body_md": "# 5 Useful Python Scripts to Automate Your Local LLM Workflows with Ollama\n\nFive 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.\n\nA 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.\n\nAutomation 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.\n\n## Before the Five Scripts: One Local Runtime and a Small Helper\n\nThe 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.\n\n``` python\n# llm_local.py\nimport json, os, urllib.error, urllib.request\n\nBASE_URL = os.environ.get(\"LOCAL_LLM_URL\", \"http://127.0.0.1:11434\")\nTIMEOUT_SECONDS = float(os.environ.get(\"LOCAL_LLM_TIMEOUT\", \"120\"))\nTHINK_OFF = os.environ.get(\"LOCAL_LLM_THINK\", \"\").lower() == \"off\"\n_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))  # loopback never goes through a proxy\n\nclass LocalLLMError(RuntimeError):\n    \"\"\"Raised for any response the scripts must not treat as an answer.\"\"\"\n\ndef post_json(path, payload, timeout=TIMEOUT_SECONDS):\n    request = urllib.request.Request(BASE_URL + path, data=json.dumps(payload).encode(\"utf-8\"),\n                                     method=\"POST\", headers={\"Content-Type\": \"application/json\"})\n    try:\n        with _OPENER.open(request, timeout=timeout) as response:\n            data = json.loads(response.read())\n    except urllib.error.HTTPError as err:\n        raise LocalLLMError(f\"HTTP {err.code} from {path}: {err.read().decode('utf-8', 'replace')[:300]}\") from err\n    except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as err:\n        raise LocalLLMError(f\"no usable answer from {BASE_URL}{path}: {err}\") from err\n    if isinstance(data, dict) and data.get(\"error\"):\n        raise LocalLLMError(f\"server error from {path}: {data['error']}\")\n    return data\n\ndef list_models():\n    request = urllib.request.Request(BASE_URL + \"/api/tags\", method=\"GET\")\n    with _OPENER.open(request, timeout=TIMEOUT_SECONDS) as response:\n        return {m[\"name\"]: m.get(\"digest\", \"\") for m in json.loads(response.read())[\"models\"]}\n\ndef model_digest(model):\n    models = list_models()\n    for candidate in (model, f\"{model}:latest\"):\n        if candidate in models:\n            return models[candidate]\n    raise LocalLLMError(f\"model {model!r} is not installed; run `ollama pull {model}`\")\n\ndef generate(model, prompt, *, options=None, fmt=None):\n    payload = {\"model\": model, \"prompt\": prompt, \"stream\": False}\n    if THINK_OFF:\n        payload[\"think\"] = False\n    if options:\n        payload[\"options\"] = options\n    if fmt is not None:\n        payload[\"format\"] = fmt\n    data = post_json(\"/api/generate\", payload)\n    if not data.get(\"done\") or \"response\" not in data:\n        raise LocalLLMError(\"incomplete response\")\n    return data\n\ndef embed(model, inputs):\n    data = post_json(\"/api/embed\", {\"model\": model, \"input\": inputs, \"truncate\": False})\n    vectors = data.get(\"embeddings\")\n    if not isinstance(vectors, list) or len(vectors) != len(inputs):\n        raise LocalLLMError(\"embedding count does not match input count\")\n    return vectors\n```\n\nThree 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.\n\n| Chore | Script | Saved artifact | First boundary | \n|---|---|---|---|\n| Repeatedly gathering documents | `pack_notes.py` | Source-labeled text pack and manifest | Text exports only; scans are processed first | \n| Repeating a stopped batch | `batch_prompts.py` | Per-item JSONL journal | Resume keys include inputs and configuration | \n| Cleaning model-generated records | `extract_actions.py` | Accepted CSV plus rejected JSONL | Shape and evidence checks precede export | \n| Finding the relevant note | `search_notes.py` | Same-identity local embedding index | Similarity is not correctness | \n| Discovering a bad model or prompt change late | `smoke_models.py` | Outcome and timing CSV | A small fixture set is not a benchmark | \n\n## 1. Build a Source-Labeled Input Pack\n\nThe 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.\n\n``` python\n# pack_notes.py\nimport hashlib, json\nfrom pathlib import Path\n\nALLOWED = {\".txt\", \".md\"}\n\ndef select_files(root):\n    root = root.resolve()\n    chosen = []\n    for path in sorted(root.rglob(\"*\")):\n        if path.is_symlink() or not path.is_file() or path.suffix.lower() not in ALLOWED:\n            continue\n        if any(part.startswith(\".\") for part in path.relative_to(root).parts):\n            continue\n        if root not in path.resolve().parents:\n            continue\n        chosen.append(path)\n    return chosen\n\ndef build_pack(root, out_dir, max_file_bytes=20_000, max_total_bytes=60_000):\n    root, blocks, entries, total = root.resolve(), [], [], 0\n    out_dir.mkdir(parents=True, exist_ok=True)\n    for path in select_files(root):\n        data = path.read_bytes()\n        if len(data) > max_file_bytes:\n            raise ValueError(f\"{path.relative_to(root)} is {len(data)} bytes; limit {max_file_bytes}\")\n        text = data.decode(\"utf-8\")  # a non-UTF-8 file raises here, by design\n        total += len(data)\n        if total > max_total_bytes:\n            raise ValueError(f\"pack would exceed {max_total_bytes} bytes at {path.relative_to(root)}\")\n        digest = hashlib.sha256(data).hexdigest()\n        rel = path.relative_to(root).as_posix()\n        entries.append({\"source\": rel, \"bytes\": len(data), \"sha256\": digest})\n        blocks.append(f\"### source: {rel} (sha256:{digest[:12]})\\n{text.rstrip()}\\n\")\n    (out_dir / \"pack.txt\").write_text(\"\\n\".join(blocks), encoding=\"utf-8\")\n    (out_dir / \"manifest.json\").write_text(json.dumps({\"files\": entries, \"total_bytes\": total}, indent=2), encoding=\"utf-8\")\n    return entries\n```\n\nRun it on a folder of four short notes and the output names what went in:\n\n``` bash\n$ python pack_notes.py demo/inputs demo/outputs/pack\npacked 4 files, 552 bytes -> demo/outputs/pack/pack.txt\n  ideas.md                        155 bytes  sha256:e2d8ca426543\n  reminder.txt                     90 bytes  sha256:7efa15e039a7\n  retro-october.txt               178 bytes  sha256:78c27d8e792b\n  standup-2026-11-03.md           129 bytes  sha256:7b41af11368b\n```\n\nThe 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.\n\nWhat 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.\n\n## 2. Run a Prompt Batch That Can Resume\n\nThe 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.\n\n``` python\n# batch_prompts.py\nimport hashlib, json\nfrom datetime import datetime, timezone\nfrom llm_local import LocalLLMError, generate, model_digest\n\nOPTIONS = {\"temperature\": 0, \"num_predict\": 200}\n\ndef job_key(item, digest, prompt_version):\n    material = json.dumps({\"prompt\": item[\"prompt\"], \"prompt_version\": prompt_version,\n                           \"model_digest\": digest, \"options\": OPTIONS, \"schema\": \"none\"}, sort_keys=True)\n    return hashlib.sha256(material.encode(\"utf-8\")).hexdigest()[:16]\n\ndef load_journal(path):\n    done, unreadable = {}, 0\n    if path.exists():\n        for line in path.read_text(encoding=\"utf-8\").splitlines():\n            if not line.strip():\n                continue\n            try:\n                record = json.loads(line)\n            except json.JSONDecodeError:\n                unreadable += 1  # a partial final line from an interrupted write is counted, not hidden\n                continue\n            if record.get(\"status\") == \"ok\":\n                done[record[\"key\"]] = record\n    return done, unreadable\n\ndef run(items, journal_path, model, prompt_version=\"v1\", limit=None):\n    digest = model_digest(model)\n    done, unreadable = load_journal(journal_path)\n    counts, calls = {\"skipped\": 0, \"ok\": 0, \"error\": 0, \"unreadable_lines\": unreadable}, 0\n    with journal_path.open(\"a\", encoding=\"utf-8\") as journal:\n        for item in items:\n            key = job_key(item, digest, prompt_version)\n            if key in done:\n                counts[\"skipped\"] += 1\n                continue\n            if limit is not None and calls >= limit:\n                break\n            calls += 1\n            record = {\"key\": key, \"id\": item[\"id\"], \"model\": model, \"model_digest\": digest[:12],\n                      \"prompt_version\": prompt_version, \"at\": datetime.now(timezone.utc).isoformat(timespec=\"seconds\")}\n            try:\n                record.update(status=\"ok\", response=generate(model, item[\"prompt\"], options=OPTIONS)[\"response\"].strip())\n                counts[\"ok\"] += 1\n            except LocalLLMError as err:\n                record.update(status=\"error\", error=str(err))\n                counts[\"error\"] += 1\n            journal.write(json.dumps(record, ensure_ascii=False) + \"\\n\")\n            journal.flush()\n    return counts\n```\n\nThe 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:\n\n``` bash\n$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b --limit 1\nskipped 0 (already done), ok 1, errors 0, unreadable journal lines 0\n$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b\nskipped 1 (already done), ok 1, errors 0, unreadable journal lines 0\n$ python batch_prompts.py demo/prompts.jsonl demo/outputs/journal.jsonl --model qwen3.5:4b --prompt-version v2 --limit 0\nskipped 0 (already done), ok 0, errors 0, unreadable journal lines 0\n```\n\nThe 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.\n\nOne 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.\n\n## 3. Export Only Validated Action Records\n\nThe 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.\n\n``` python\n# extract_actions.py\nimport csv, json\nfrom llm_local import LocalLLMError, generate\n\nSCHEMA = {\"type\": \"object\",\n          \"properties\": {\"owner\": {\"type\": \"string\"}, \"task\": {\"type\": \"string\"}, \"evidence\": {\"type\": \"string\"}},\n          \"required\": [\"owner\", \"task\", \"evidence\"], \"additionalProperties\": False}\nPROMPT = (\"Read the note. Return one JSON object with exactly these keys: owner (the person responsible), \"\n          \"task (what they must do), evidence (a short quote copied exactly from the note that supports both). \"\n          \"Use only words present in the note.\\n\\nNote:\\n{note}\\n\")\n\ndef normalize(text):\n    return \" \".join(text.split())\n\ndef check_record(record, source_text):\n    \"\"\"Return a rejection reason, or None if the record may be exported.\"\"\"\n    if not isinstance(record, dict):\n        return \"not a JSON object\"\n    if set(record) != {\"owner\", \"task\", \"evidence\"}:\n        return f\"unexpected keys: {sorted(record)}\"\n    for key in (\"owner\", \"task\", \"evidence\"):\n        if not isinstance(record[key], str) or not record[key].strip():\n            return f\"{key} is not a non-empty string\"\n    if normalize(record[\"evidence\"]) not in normalize(source_text):\n        return \"evidence quote not found in the note\"\n    return None\n\ndef extract(note_paths, out_dir, model):\n    out_dir.mkdir(parents=True, exist_ok=True)\n    with (out_dir / \"accepted.csv\").open(\"w\", newline=\"\", encoding=\"utf-8\") as acc, \\\n         (out_dir / \"rejected.jsonl\").open(\"w\", encoding=\"utf-8\") as rej:\n        writer = csv.DictWriter(acc, fieldnames=[\"source\", \"owner\", \"task\", \"evidence\"])\n        writer.writeheader()\n        for path in note_paths:\n            note = path.read_text(encoding=\"utf-8\")\n            try:\n                record = json.loads(generate(model, PROMPT.format(note=note), options={\"temperature\": 0}, fmt=SCHEMA)[\"response\"])\n                reason = check_record(record, note)\n            except LocalLLMError as err:\n                record, reason = None, f\"model call failed: {err}\"\n            except json.JSONDecodeError:\n                record, reason = None, \"response was not valid JSON\"\n            if reason is None:\n                writer.writerow({\"source\": path.name, **record})\n            else:\n                rej.write(json.dumps({\"source\": path.name, \"reason\": reason, \"record\": record}) + \"\\n\")\n```\n\nOn 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:\n\n```\nsource,owner,task,evidence\nideas.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.\nreminder.txt,the floor,repairs,Nothing else to report.\nretro-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.\nstandup-2026-11-03.md,Maya,Archive the old config,Action: Archive the old config\n```\n\nThe 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.\n\n## 4. Search a Small Folder of Notes Locally\n\nThe 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.\n\nAn 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.\n\n``` python\n# search_notes.py\nimport json, math\nfrom llm_local import LocalLLMError, embed, model_digest\n\nMAX_CHUNK_CHARS = 600\n\ndef chunks_from(notes_dir):\n    for path in sorted(p for p in notes_dir.iterdir() if p.suffix.lower() in {\".txt\", \".md\"} and not p.name.startswith(\".\")):\n        for i, para in enumerate(p for p in path.read_text(encoding=\"utf-8\").split(\"\\n\\n\") if p.strip()):\n            text = \" \".join(para.split())\n            if len(text) > MAX_CHUNK_CHARS:\n                raise ValueError(f\"{path.name} paragraph {i} is {len(text)} chars; split it before indexing\")\n            yield {\"source\": f\"{path.name}#{i}\", \"text\": text}\n\ndef check_vectors(vectors, dim=None):\n    for v in vectors:\n        dim = dim or len(v)\n        if len(v) != dim or not all(math.isfinite(x) for x in v) or not any(v):\n            raise ValueError(\"embedding has wrong length, non-finite values or is all zeros\")\n    return dim\n\ndef cosine(a, b):\n    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)))\n\ndef build(notes_dir, index_path, model):\n    chunks = list(chunks_from(notes_dir))\n    vectors = embed(model, [c[\"text\"] for c in chunks])\n    dim = check_vectors(vectors)\n    for chunk, vector in zip(chunks, vectors):\n        chunk[\"vector\"] = vector\n    index_path.write_text(json.dumps({\"model\": model, \"model_digest\": model_digest(model), \"dim\": dim, \"chunks\": chunks}), encoding=\"utf-8\")\n\ndef query(index_path, question, top=3):\n    index = json.loads(index_path.read_text(encoding=\"utf-8\"))\n    if model_digest(index[\"model\"]) != index[\"model_digest\"]:\n        raise LocalLLMError(f\"index was built with a different {index['model']}; rebuild it\")\n    [qvec] = embed(index[\"model\"], [question])\n    check_vectors([qvec], index[\"dim\"])\n    return sorted(((cosine(qvec, c[\"vector\"]), c[\"source\"], c[\"text\"]) for c in index[\"chunks\"]), reverse=True)[:top]\n```\n\nBuild the index once, then query it:\n\n``` bash\n$ python search_notes.py build demo/inputs demo/outputs/index.json --model nomic-embed-text\nindexed 11 chunks, 768 dimensions, nomic-embed-text (digest 0a109f422b47) -> demo/outputs/index.json\n$ python search_notes.py query demo/outputs/index.json \"which server is low on disk\" --top 3\n0.702  standup-2026-11-03.md#2 The build server is named orion and its disk is at 81%.\n0.545  standup-2026-11-03.md#1 Action: Archive the old config. Owner: Maya.\n0.497  reminder.txt#1         The office is closed on Friday for the floor repairs. Nothing else to report.\n```\n\nThe 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.\n\n## 5. Run a Task Smoke Test Before Switching Models\n\nThe 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.\n\n``` python\n# smoke_models.py\nimport csv, json, statistics, time\nfrom llm_local import LocalLLMError, generate, model_digest\n\nOPTIONS = {\"temperature\": 0, \"num_predict\": 60}\nANSWER_SCHEMA = {\"type\": \"object\", \"properties\": {\"answer\": {\"type\": \"string\"}}, \"required\": [\"answer\"], \"additionalProperties\": False}\nFIXTURES = [\n    {\"name\": \"arithmetic\", \"prompt\": \"What is 17 + 26? Reply with the number only.\",\n     \"check\": lambda r: r.strip().rstrip(\".\") == \"43\", \"format\": None},\n    {\"name\": \"json_shape\", \"prompt\": \"Name the capital of France. Put it in the answer field.\",\n     \"check\": lambda r: set(json.loads(r)) == {\"answer\"}, \"format\": ANSWER_SCHEMA},\n    {\"name\": \"context_fact\", \"prompt\": \"Context: The build server is named orion.\\nQuestion: What is the build server named? Answer with one word.\",\n     \"check\": lambda r: \"orion\" in r.lower(), \"format\": None},\n]\n\ndef attempt(model, fixture):\n    started = time.perf_counter()\n    try:\n        text = generate(model, fixture[\"prompt\"], options=OPTIONS, fmt=fixture[\"format\"])[\"response\"]\n        elapsed = time.perf_counter() - started\n        try:\n            ok = bool(fixture[\"check\"](text))\n        except (json.JSONDecodeError, KeyError, TypeError):\n            ok = False\n        return {\"outcome\": \"pass\" if ok else \"fail\", \"seconds\": round(elapsed, 3), \"response\": text.strip()[:80]}\n    except LocalLLMError as err:\n        return {\"outcome\": \"error\", \"seconds\": round(time.perf_counter() - started, 3), \"response\": str(err)[:80]}\n\ndef smoke(models, out_path, prompt_version=\"v1\"):\n    rows = []\n    for model in models:\n        digest = model_digest(model)[:12]\n        rows.append({\"model\": model, \"digest\": digest, \"prompt_version\": prompt_version, \"fixture\": \"warmup\", **attempt(model, FIXTURES[0])})\n        for fixture in FIXTURES:\n            rows.append({\"model\": model, \"digest\": digest, \"prompt_version\": prompt_version, \"fixture\": fixture[\"name\"], **attempt(model, fixture)})\n    with out_path.open(\"w\", newline=\"\", encoding=\"utf-8\") as f:\n        writer = csv.DictWriter(f, fieldnames=list(rows[0]))\n        writer.writeheader()\n        writer.writerows(rows)\n    return rows\nbash\n$ python smoke_models.py demo/outputs/smoke.csv --model qwen3.5:4b\nqwen3.5:4b: pass 3, fail 0, error 0, median answered 0.07s\n  arithmetic    pass    0.07s  43\n  json_shape    pass    0.17s  { \"answer\": \"Paris\" }\n  context_fact  pass    0.07s  Orion\n```\n\nEach 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.\n\n## Automate the Chore You Already Repeat\n\nStart 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.\n\nWhichever 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.\n\n \n\n \n\n[**\\[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.", "url": "https://wpnews.pro/news/5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama", "canonical_source": "https://www.kdnuggets.com/5-useful-python-scripts-to-automate-your-local-llm-workflows", "published_at": "2026-12-04 13:00:00+00:00", "updated_at": "2026-12-04 13:15:56.652419+00:00", "lang": "en", "topics": ["ai-tools", "large-language-models", "developer-tools", "ai-agents"], "entities": ["Ollama", "KDnuggets", "qwen3.5:4b", "nomic-embed-text", "Python 3.13"], "also_reported_by": [], "takeaway": "Calling Ollama's native API with stream=False and a finite timeout (120 seconds by default) turns a stalled local server into a catchable LocalLLMError instead of a script that never ends.", "recommendation": {"advice": "Set stream=False and a finite request timeout on every local Ollama call so a stalled server raises a catchable error rather than hanging the script indefinitely.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama", "markdown": "https://wpnews.pro/news/5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama.md", "text": "https://wpnews.pro/news/5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama.txt", "jsonld": "https://wpnews.pro/news/5-useful-python-scripts-to-automate-your-local-llm-workflows-with-ollama.jsonld"}}