Below you’ll find two parts:
PART A – A reasonably robust, ready-to-run Python script that
• walks over all .txt files in a folder
• appends a configurable extra sentence to each file’s text (but only if the whole thing will still fit in the model’s context)
• sends the resulting prompt to an Ollama-hosted model (e.g. llama3:8b)
• stores the model’s answer in a sibling “-out.txt” file
PART B – A brief guide to which prompting approach usually works best for “structure very long documents” jobs (zero-shot vs few-shot vs CoT, etc.).
PART A – Python script
#!/usr/bin/env python3
"""
batch_llama_structurer.py
Requires:
pip install ollama tqdm tiktoken # tiktoken is only for token-length estimates
Usage:
python batch_llama_structurer.py --source_folder ./docs \
--model llama3:8b \
--extra_sentence "=== End of extract ===" \
--output_suffix "-out.txt"
"""
import argparse
import json
import os
from pathlib import Path
import ollama # python-ollama (pip install ollama)
import tiktoken # for rough token counting
from tqdm import tqdm
# -------------------------------------------------------------
# 1. Some helpers
# -------------------------------------------------------------
def num_tokens(text: str, enc_name: str = "cl100k_base") -> int:
"""
Llama 3 isn't trained with the OpenAI tokenizer,
but cl100k_base gives a *reasonable* upper-bound estimate.
"""
enc = tiktoken.get_encoding(enc_name)
return len(enc.encode(text))
def chat_ollama(model: str, system_prompt: str, user_prompt: str, temperature: float = 0.1) -> str:
"""
Minimal wrapper around ollama.chat().
"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
response = ollama.chat(model=model,
messages=messages,
temperature=temperature,
stream=False) # we want the full text back
return response["message"]["content"]
# -------------------------------------------------------------
# 2. The main batch processor
# -------------------------------------------------------------
def process_all_txt(
folder: Path,
model: str,
extra_sentence: str,
context_limit_tokens: int = 8192,
output_suffix: str = "-out.txt") -> None:
txt_files = sorted(folder.glob("*.txt"))
if not txt_files:
print("No .txt files found in", folder.resolve())
return
system_prompt = (
"You are a professional document analyst. "
"When given a raw document, restructure it into a concise, hierarchical outline "
"with bullet points, headings, and a short executive summary up top. "
"Use Markdown formatting."
)
for fpath in tqdm(txt_files, desc="Processing files"):
raw = fpath.read_text(encoding="utf-8")
# -----------------------------------------
# 2a. Make sure we stay within context size
# -----------------------------------------
candidate_prompt = raw + "\n\n" + extra_sentence
n_tokens = num_tokens(system_prompt + candidate_prompt)
if n_tokens > context_limit_tokens:
# naïve fallback: truncate from the end to fit
over_by = n_tokens - context_limit_tokens
approx_chars_to_chop = int(over_by * 4) # 4 chars ≈ 1 token heuristic
candidate_prompt = candidate_prompt[:-approx_chars_to_chop]
candidate_prompt += "\n\n[Content truncated due to context length]\n"
# -----------------------------------------
# 2b. Send to Ollama
# -----------------------------------------
answer = chat_ollama(model=model,
system_prompt=system_prompt,
user_prompt=candidate_prompt)
# -----------------------------------------
# 2c. Save next to original file
# -----------------------------------------
out_path = fpath.with_name(fpath.stem + output_suffix)
out_path.write_text(answer, encoding="utf-8")
# -------------------------------------------------------------
# 3. CLI entry-point
# -------------------------------------------------------------
def cli():
p = argparse.ArgumentParser()
p.add_argument("--source_folder", required=True, type=Path,
help="Folder containing .txt files")
p.add_argument("--model", default="llama3:8b",
help="Any model visible to `ollama list`")
p.add_argument("--extra_sentence", default="Please restructure the document above following the agreed template.",
help="Sentence that will be appended to each file's content.")
p.add_argument("--context_limit", type=int, default=8192,
help="Hard context limit of the chosen model (tokens).")
p.add_argument("--output_suffix", default="-out.txt",
help="Suffix appended to create output file names.")
args = p.parse_args()
process_all_txt(folder=args.source_folder,
model=args.model,
extra_sentence=args.extra_sentence,
context_limit_tokens=args.context_limit,
output_suffix=args.output_suffix)
if __name__ == "__main__":
cli()
How it works (quick tour):
- Reads every
.txt in --source_folder.
- Concats
extra_sentence to the end.
- Estimates token count (
tiktoken) and trims if needed so the whole system + user prompt ≤ context.
- Calls
ollama.chat()—sends a single user message (the full doc) plus a system message specifying the restructuring template.
- Saves the answer beside the original as
originalFileName-out.txt.
Feel free to tweak:
• Swap truncation logic for a smarter chunk-and-summarise (map-reduce) approach.
• Use stream=True for progressive output.
• Change temperature, top_p, num_predict, etc.—all forwarded to Ollama.
PART B – Which prompting style works best for “structure very long docs”?
Below is a concise cheat-sheet:
| Scenario | Recommended technique | Why |
|---|
| Document easily fits in context | 0-shot with a very explicit template OR 1-shot (single example) | Simple, fastest. Give the exact headings / JSON schema you want. Llama 3 is already strong at following well-specified instructions. |
| You have 2-5 good examples of the exact kind of structured output you want | Few-shot | Greatly increases consistency; costs only a few hundred tokens. |
| Document does not fit context, but you can split it into independent sections (chapters, slides, log lines, …) | Map-Reduce (aka Hierarchical) prompting with CoT allowed inside each chunk | Process chunks in parallel (“map”); then feed the partial summaries into a second prompt (“reduce”) to get a global summary/outline. |
| Highly reasoning-heavy tasks (e.g. trace causality, detect argument fallacies) | Chain-of-Thought (CoT) or “Plan-and-Solve” | Forces model to externalise reasoning before producing the final answer; improves faithfulness. |
| Complex multi-step decision trees | “Tree-of-Thought” or Self-Consistency | Explore multiple reasoning branches, pick the best; expensive but state-of-art for puzzles. |
For the narrow goal “take a very long document and reorganise it into a predefined structure”, empirical evidence says:
- Hierarchical summarisation (map-reduce) + clear template in each prompt covers 90 % of needs.
- You rarely need full tree-of-thought unless the doc is ambiguous or you require deep reasoning.
- Adding one or two exemplars (few-shot) inside each chunk prompt tends to stabilise section naming, bullet syntax, etc.
Therefore a practical recipe:
• STEP 1 (MAP): Break doc into ≤4 k-token chunks. Prompt each chunk:
“Here is part X/ N of a larger doc. Transform it into the following Markdown outline … (few-shot examples) …”
• STEP 2 (REDUCE): Feed all partial outlines to a second prompt:
“Merge and deduplicate the following outlines into a single coherent outline (same spec).”
Optionally add a CoT instruction: “Think step-by-step; first draft the merged heading list, then produce the final outline.”
That gives you both scalability and consistent formatting, while staying simple enough to manage in code.
Happy coding 🚀