# Prompt template: define the output shape first, then discuss wording

Date: 2026-11-15
Category: Technology
Tags: Prompt, Structured Output, Engineering Trade-offs
Summary: The value of a template lies not in elegant wording but in fixing the output shape: Markdown for humans to read, JSON for programs to consume, wrapped in a parsing retry layer with error messages

A colleague built an "AI auto-generates weekly reports" prototype. The demo went smoothly: input three progress items, and the model produced a fairly decent summary. The problem came on the day we integrated it into the system—the frontend parsed those three sections itself, and six out of ten couldn't be split out. Sometimes the model wrote "下周计划" as "Plan," sometimes it inserted an extra "总结" section at the front, sometimes it started with "一、".

We spent a whole evening discussing how to make the regex more lenient. The next day I flipped the direction: the program shouldn't accommodate the model's wording; the prompt should fix the shape of the output.

Later I left a comment in that code: the template isn't to make the output look good, it's to make the output catchable. Humans catching it, tables catching it, programs catching it—these are three different things.

## Output drift usually happens in these three places

- The instruction itself is ambiguous: list 3 points this time, 7 next time; ask for suggestions this time, conclusions next time.
- The output has no shape: the same thing, once as a table, once as prose.
- The acceptance criteria exist only in someone's head: you think it's "not deep enough" but can't say where.

The first two are solved by changing structure; the third has to be written back into the prompt. I once wrote "please provide an in-depth analysis," and the model gave me three paragraphs of correct nonsense: the market is changing, user needs are diverse, recommend continuous optimization. Later I changed it to "each finding must include a specific number or a counterexample." Same data, and the output changed immediately. It finally knew what "in-depth" means to me.

## Among the five parts, the weights differ enormously

The circulating skeleton has five sections: role, task, input, output, acceptance. Using them one by one, you'll find they're not on the same order of magnitude at all.

Role is the most overrated; it mainly affects tone, not structure. Writing "you are a senior data analyst" versus "you are doing e-commerce customer data analysis, and the readers are non-technical operations colleagues"—the difference isn't the level of skill, it's that the latter sets a specific reader and granularity for the output.

Task is the easiest to write vaguely. "Analyze this data" says nothing; change it to "find the customer segments worth additional investment and explain why this category," and the output has direction.

Input is the most worth spending time on: field meanings, time range, units, what missing values represent—all must be written. The model won't ask; it will guess, and guess confidently. I usually add "fill null for uncertain fields and state what's missing," which is better than letting it make things up.

Output determines whether downstream can use it: shape, length, hierarchy.

Acceptance tells it what to delete before submitting. Writing "don't force in things that don't meet the criteria" is often more effective than ten positive requirements. This section is often omitted from templates, but it essentially moves the review step forward to the model.

A minimal version looks roughly like this:

```text
角色：你在做电商客户数据分析，读者是不懂技术的运营同学。
任务：从下面的订单数据里找出值得追加投入的客户群，并说明理由。
输入：字段含义见数据字典；时间范围 2025-01 至 2025-06；金额单位是元；缺失值用 null。
输出：先用一句话给结论，再用 3 条发现支撑，每条必须带一个具体数字。
验收：如果某条发现没有数字支撑，删掉它，不要用“整体表现良好”凑数。
```

The input section takes up a third, and I think that's the most justified investment. If the data dictionary is vague, no matter how pretty the format is, it's garbage in, garbage out.

## Choosing a format depends on who catches it

Markdown is what the model knows best and almost never gets wrong—suitable for reports and documents; the downside is that structure relies on heading-level conventions, and if the heading wording changes, downstream parsing breaks. Tables are good for human scanning, comparison at a glance, but only for two-dimensional data with the same fields per row; once there are too many columns the model starts dropping them, and within five columns is fairly stable. JSON is the only format programs can reliably consume, at the cost of tokens, the model's love of adding explanations, and dropped fields once the schema gets complex.

When the same task needs to be both human-readable and program-usable, my approach is to have the model output only structured data, then render Markdown or a table from that data. Asking it to write both versions at once usually makes both subpar.

Conversely, if the output is only for humans and thrown away after reading, templating is a waste. My criterion for whether to use a schema is very crude: will this output be read by a second program? If not, Markdown is enough. The more rigidly you fix the shape, the less room the model has to work—so don't do this for explanatory or creative tasks.

I've stepped on a few pitfalls with the JSON route, and now I always write it like this:

1. Paste the schema directly into the prompt, wrapped in a code block—don't describe fields in prose.
2. Hard-code enums and nulls: "status can only be active / churn / unknown; if unavailable, fill null, don't make it up."
3. Explicitly forbid prefixes and suffixes: "output only the JSON object, no explanation, no code blocks."
4. Keep fields within 8 and nesting within two levels; if exceeded, split into two calls.
5. Put long text in arrays, don't concatenate into a several-hundred-word string—once concatenated, you can't validate item by item.

```text
输出必须是下面这个结构的 JSON，不要加任何说明文字：

{
  "summary": {"total": <int>, "age_range": {"min": <int>, "max": <int>}},
  "segments": [{"name": <string>, "count": <int>, "evidence": <string>}],
  "actions": [{"target": <string>, "action": <string>, "expected": <string>}]
}

规则：
- segments 至少 2 项，每项 evidence 里必须出现一个数字。
- 某个字段拿不到数据时填 null，不要猜。
- 只输出 JSON，不要代码块。
```

I tried four versions on a ten-customer sample: without a template I got three hundred words of generalities, conclusions without evidence; after adding a role and three specific questions, the number of paragraphs varied with the model's mood; after adding a numbered output format and table requirements, four paragraphs stabilized, though table column names occasionally still changed; finally switching to JSON with a schema, the frontend could render directly. From the third version to the fourth, what changed wasn't the wording but those twenty-odd lines of schema. Token cost went up; what was saved was manual proofreading.

What's most worth remembering in this comparison is actually the second to third version: role and phrases like "please analyze from three angles" are the most like prompt tricks, yet yield the least.

## What really catches failures is the outer loop

No matter how detailed the schema, you'll always encounter the model adding "Sure, here is the analysis result." So the parsing layer can't be skipped, and retries must carry the error message—not just ask again verbatim.

```python
import json

def parse(raw: str) -> dict:
    text = raw.strip()
    if text.startswith("```"):
        text = text.split("\n", 1)[1].rsplit("```", 1)[0]
    return json.loads(text)

def ask_json(prompt: str, data: str, tries: int = 2) -> dict:
    messages = [{"role": "user", "content": prompt + "\n\n数据：\n" + data}]
    for _ in range(tries + 1):
        raw = call_model(messages)                     # 你的模型调用
        try:
            return parse(raw)
        except json.JSONDecodeError as e:
            messages += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"上面这段不是合法 JSON（{e.msg}，第 {e.pos} 个字符）。"
                                            f"只输出 JSON 对象，不要解释，不要代码块。"},
            ]
    raise ValueError("重试后仍然无法解析")
```

Retry at most twice; more is a waste. The error message must include the position—the model can fix it itself based on that. If both fail, take the fallback path: hand it to a human, or fall back to the lenient text parsing in the template. Don't leave users staring at a spinner.

## Templates rot; keep accounts for them

The same template starts having problems after three months: the model upgraded, business fields changed, or a patch sentence added to fix some issue now becomes a constraint.

I now keep three things for a template. The version number goes into the repo with the code—don't let it scatter across someone's chat history; a set of hard samples covering normal input, boundary input, input that should be refused, and input most likely to break the format; and two numbers: parse success rate and manual rewrite rate. The former dropping means a format problem; the latter rising means a content quality problem.

When troubleshooting, check parameters before wording: if output is too long, first check max_tokens and whether a length limit is written; if JSON parsing fails, first check JSON mode and stop sequences; if quality fluctuates, first check temperature and whether the examples were touched. A lot of "the prompt doesn't work" is actually parameters left unset—changing the wording ten times won't help.

## What happened to that weekly report

In the end we didn't write a lenient regex. We changed the output to three fixed JSON sections, wrapped in this parsing-retry layer. It still occasionally fails, and failures fall into the manual queue, but at least no more midnight alerts.

If you have a template in hand right now, do one thing tonight: run the same input five times, put the five outputs side by side, and see at which line the first difference appears. That line is usually where you weren't clear.
