EN ▾
Get API key

python-docx LLM: Generate Word Files From Model Output

A python-docx llm workflow has two halves. The model writes the content as structured data, and python-docx turns that data into a real Word file with headings, lists and tables. Below is the working code for both halves.

Updated

Data blocks flowing from a terminal into a stack of document pages

Key points

  • Ask the model for JSON, not for finished prose, and let python-docx do the layout.
  • Any OpenAI SDK works once you change the base URL and the key.
  • Fill existing templates by replacing placeholders at paragraph level, because Word splits text into runs.
  • A five-page report costs a fraction of a cent at $0.15 and $0.50 per 1M tokens.

The pattern in one minute

python-docx does not write anything. It builds files: paragraphs, headings, tables, styles. A language model does the opposite, it produces words but knows nothing about your page layout. Put them together by splitting the job along that line. The model returns a small JSON document that describes the content, and your Python code walks through that JSON and calls add_heading, add_paragraph and add_table.

That split gives you three practical benefits. The output always looks the same, because the layout lives in your code and your template. Bad model output is easy to catch, because you can validate JSON before you write a single byte to disk. And you can swap the prompt, the model settings or even the template without touching the other two parts.

The steps are:

  1. Install python-docx and the openai package.
  2. Point the OpenAI client at the API base URL and use the model ID uncensored.
  3. Ask for a JSON object with a fixed shape and switch on JSON mode.
  4. Validate the result, then build the document.
  5. Optionally fill a company template instead of starting from a blank file.

Install and connect

You need Python 3.9 or newer, two packages and an API key. If you do not have a key yet, the API key page explains sign-up and the one-click trial credit.

pip install python-docx openai

The package is called python-docx on PyPI, but you import it as docx. The service is OpenAI-compatible, so the official OpenAI SDK is the client. You change the base URL and the key, nothing else.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.whisperapi.cc/v1",
    api_key=os.environ["WHISPER_API_KEY"],
    max_retries=5,
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(resp.choices[0].message.content)

The same call as plain HTTP, which is handy when a script fails and you want to rule out the SDK:

curl https://api.whisperapi.cc/v1/chat/completions \
  -H "Authorization: Bearer $WHISPER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "uncensored", "messages": [{"role": "user", "content": "Say hello in five words."}]}'

The quickstart lists every supported parameter. The two you will use most here are response_format and temperature.

Ask for structure, not prose

The most common mistake is asking the model for a whole document as one blob of text and then trying to split it on blank lines. That breaks the first time the model adds a stray heading marker or a closing remark. Ask for data instead.

Define the shape in the system prompt, give one tiny example, and turn on JSON mode with response_format={"type": "json_object"}. JSON mode asks the model to produce a valid JSON object, but it does not know your schema, so you still check the keys yourself.

import json
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.whisperapi.cc/v1",
    api_key=os.environ["WHISPER_API_KEY"],
    max_retries=5,
)

SYSTEM = """You write business documents. Reply with one JSON object only.
Shape:
{"title": str,
 "sections": [{"heading": str,
               "paragraphs": [str],
               "bullets": [str],
               "table": {"columns": [str], "rows": [[str]]} or null}]}
Use 3 to 6 sections. Plain text only, no markdown symbols."""

def draft(topic: str, notes: str) -> dict:
    resp = client.chat.completions.create(
        model="uncensored",
        temperature=0.4,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"Topic: {topic}\n\nNotes:\n{notes}"},
        ],
    )
    choice = resp.choices[0]
    if choice.finish_reason == "length":
        raise RuntimeError("Output was cut off; raise max_tokens or ask for fewer sections")
    data = json.loads(choice.message.content)
    if "title" not in data or not isinstance(data.get("sections"), list):
        raise ValueError("Model returned the wrong shape")
    return data

Two details matter. A low temperature such as 0.3 to 0.5 keeps the structure stable between runs. And the finish_reason check catches truncated JSON before json.loads fails with a confusing error. The context window is 100,000 tokens for prompt and completion together, so truncation is rare for ordinary reports, but it can happen if you set a small max_tokens.

Turn the JSON into a Word document

Now the part python-docx is good at. The function below creates a document, writes the title, then loops over the sections. Bullets use the built-in List Bullet style, and tables use the Table Grid style so the borders are visible.

from docx import Document

def build_docx(data: dict, path: str) -> None:
    doc = Document()
    doc.core_properties.title = data["title"]
    doc.add_heading(data["title"], level=0)

    for sec in data["sections"]:
        doc.add_heading(sec["heading"], level=1)
        for text in sec.get("paragraphs", []):
            doc.add_paragraph(text)
        for item in sec.get("bullets", []):
            doc.add_paragraph(item, style="List Bullet")

        table = sec.get("table")
        if table and table.get("columns"):
            rows = [table["columns"]] + table.get("rows", [])
            grid = doc.add_table(rows=len(rows), cols=len(table["columns"]))
            grid.style = "Table Grid"
            for r, row in enumerate(rows):
                for c, value in enumerate(row[: len(table["columns"])]):
                    cell = grid.cell(r, c)
                    cell.text = str(value)
                    if r == 0:
                        for run in cell.paragraphs[0].runs:
                            run.bold = True
            doc.add_paragraph()

    doc.save(path)

report = draft("Q3 support review", "Ticket volume up 12 percent. Two outages. New FAQ launched.")
build_docx(report, "q3-support-review.docx")

Notice the slice row[: len(table["columns"])]. Models sometimes return a row with one cell too many, and python-docx raises an IndexError when you address a column that does not exist. Cutting the row to the header width turns a crash into a minor blemish you can catch in review.

Keep formatting out of the model's hands

Tell the model to avoid markdown. If it writes **bold** into a paragraph, Word shows the asterisks literally. If you do want inline emphasis, ask for a tiny convention such as [b]word[/b], and split on it in your code to create runs with run.bold = True. Most reports do not need it, and plain paragraphs are easier to review.

Fill an existing template

Many teams already have a Word template with a logo, a header and fixed styles. Open that file with Document("template.docx") and replace placeholders such as {{summary}} with model output. The trap is that Word stores text in runs, and a placeholder you typed in one go can be saved as three runs, {{, summary and }}. A naive replace on each run never finds it.

The safer approach joins the runs of a paragraph, replaces the placeholder in the joined string, and writes the result back to the first run.

from docx import Document

def fill_paragraph(paragraph, values: dict) -> None:
    joined = "".join(run.text for run in paragraph.runs)
    if "{{" not in joined:
        return
    for key, value in values.items():
        joined = joined.replace("{{" + key + "}}", value)
    for i, run in enumerate(paragraph.runs):
        run.text = joined if i == 0 else ""

def fill_template(src: str, dst: str, values: dict) -> None:
    doc = Document(src)
    for paragraph in doc.paragraphs:
        fill_paragraph(paragraph, values)
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    fill_paragraph(paragraph, values)
    for section in doc.sections:
        for paragraph in section.header.paragraphs + section.footer.paragraphs:
            fill_paragraph(paragraph, values)
    doc.save(dst)

The trade-off is that mixed formatting inside one paragraph collapses to the style of the first run. For placeholders that sit alone in their own paragraph, which is the usual template design, nothing is lost. To generate the values, ask the model for a flat JSON object whose keys match your placeholders, and refuse to continue if a key is missing.

Longer documents, streaming and rate limits

For a document longer than a few pages, generate it section by section instead of in one call. Send the outline plus the sections written so far, then ask for the next one. This keeps every request focused, and with a 100,000-token window you have room to include a lot of source material, such as meeting notes or a product spec, in each prompt.

If a person is waiting, stream the response. Set stream=True and print tokens as they arrive. You cannot parse partial JSON, so streaming fits the plain-text case, for example showing a draft summary on screen while you build the file from a second, non-streamed call.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.whisperapi.cc/v1",
    api_key=os.environ["WHISPER_API_KEY"],
)

stream = client.chat.completions.create(
    model="uncensored",
    stream=True,
    messages=[{"role": "user", "content": "Write a 120-word summary of a quarterly support review."}],
)
for part in stream:
    if part.choices and part.choices[0].delta.content:
        print(part.choices[0].delta.content, end="", flush=True)

When you generate many documents at once, mind the limits. A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. Over the limit you get HTTP 429 with the error code rate_limited or concurrency. A streamed request holds its concurrency slot until the stream ends, so a slow reader can starve your other workers. The SDK retries 429 responses on its own, which is why the examples set max_retries. Keep a thread pool at 8 workers or fewer and the retries will rarely fire.

What it costs and what to check

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. A typical five-page report prompt is about 1,500 tokens of notes and instructions, and the JSON that comes back is about 3,000 tokens. That is 1,500 x $0.15 / 1,000,000 = $0.000225 for input plus 3,000 x $0.50 / 1,000,000 = $0.0015 for output, so $0.001725 per report. Generating 1,000 of them costs about $1.73. The pricing page has the top-up tiers, and failed or refused requests are not charged.

Before you ship, run through this short list:

  • Validate every JSON reply and retry once with a stricter prompt if it fails.
  • Open a generated file in Word and in LibreOffice. Styles such as List Bullet exist in the default template but may be missing from a custom one.
  • Log the X-Request-Id response header with each document so you can trace a bad output later.
  • Do not send secrets in prompts that you would not want in a log of your own.

The service is text only, so images inside the document come from your own files, added with doc.add_picture. For a broader look at what the endpoint does, see the overview of OpenAI-compatible text generation.

Common failures and how to fix them

Most problems with this setup show up in the same four places, and each has a short fix.

  • The reply is not valid JSON. This usually means the output was cut off or the prompt asked for something the format cannot hold. Check finish_reason, lower the number of sections, and retry once before giving up.
  • Keys are missing or renamed. The model sometimes writes paragraph where you asked for paragraphs. Repeat the exact schema in the prompt and read fields with .get() and sensible defaults.
  • A style is not found. python-docx raises a KeyError when a style name does not exist in the template. Print [s.name for s in doc.styles] to see what your file really has.
  • Text looks cramped or oversized. That is a template issue, not a model issue. Change the style in Word once, save the template, and every future document inherits it.

Treat the first run on a new template as a test. Generate three documents on different topics, open them, and look at lists, tables and long paragraphs. Ten minutes of checking here saves you from fixing a hundred files later.

Questions and answers

Can python-docx call an LLM by itself?

No. python-docx only reads and writes .docx files. You call the model with a client such as the OpenAI SDK, then pass the returned text or JSON to python-docx functions.

Which model ID and base URL do I use?

Use the model ID "uncensored" and the base URL https://api.whisperapi.cc/v1 with any OpenAI-compatible client. The key goes in the Authorization header as a Bearer token.

How do I stop the model from adding markdown to my document?

Say so in the system prompt and ask for plain text inside JSON fields. If symbols still slip through, strip them in code before calling add_paragraph.

Can I generate a .docx without a template?

Yes. Document() with no argument starts from python-docx's built-in default template, which already includes heading, list and table styles.

Does the API read an existing Word file for me?

No. Extract the text with python-docx first, then put it in the prompt. The model only receives text and the limit is 100,000 tokens per request, prompt and completion together.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Start with trial credit

Email and password, key on screen right away.