"""Assemble prompts, validate fixed replies, and test a proposed refactor locally."""
import json
from lab_tools import run_exercise
def assemble(task, *, audience="", material=None, shape="", examples=(), constraints=()):
if not task.strip():
raise ValueError("task is required")
fields = {"任务": task}
if audience:
fields["视角与读者"] = audience
if material is not None:
fields["材料"] = material
if examples:
fields["示例"] = [{"输入": before, "期望输出": after} for before, after in examples]
if shape:
fields["输出形式"] = shape
if constraints:
fields["约束"] = list(constraints)
return json.dumps(fields, ensure_ascii=False, indent=2)
def validate_email(raw, limit):
try:
reply = json.loads(raw)
except json.JSONDecodeError:
return "invalid_json"
if not isinstance(reply, dict) or set(reply) != {"主题", "正文"}:
return "invalid_fields"
if any(not isinstance(value, str) or not value.strip() for value in reply.values()):
return "invalid_text"
return "accepted" if len(reply["正文"]) <= limit else "too_long"
def original_unique(items):
result = []
for item in items:
if item not in result:
result.append(item)
return result
def revised_unique(items):
return list(dict.fromkeys(items))
def exercise(checks, workspace):
expect = checks.expect
email = assemble("拟一封维修窗口通知", audience="客服编辑,为租户写作",
material={"停机": "周三 18:00–18:20", "渠道": "值班台"},
shape="仅包含主题和正文的 JSON",
examples=[("停机周四 9:00", {"主题": "例行检修", "正文": "周四 9:00 检修。"})],
constraints=["正文最多 45 个字符", "保留时间和联系渠道", "语气平实"])
payload = json.loads(email)
expect("prompt_email_payload", "维修通知+时间+渠道+示例",
"Assemble and decode the prompt to check all six structured fields",
["任务", "视角与读者", "材料", "示例", "输出形式", "约束"], list(payload))
expect("prompt_examples_and_material", "周三真实材料、周四示例",
"Compare the separate material and example fields",
["周三 18:00–18:20", "周四 9:00 检修。"], [payload["材料"]["停机"], payload["示例"][0]["期望输出"]["正文"]])
valid = '{"主题":"例行检修","正文":"周三 18:00–18:20 暂停服务。如需帮助,请联系值班台。"}'
replies = [valid, "{" , '{"主题":"例行检修"}', '{"主题":"例行检修","正文":false}']
expect("prompt_email_validation", replies,
"Parse four fixtures and check syntax, required fields, and text values",
["accepted", "invalid_json", "invalid_fields", "invalid_text"],
[validate_email(reply, 45) for reply in replies])
expect("prompt_email_length", 12, "Apply a stricter length limit to the same valid JSON",
"too_long", validate_email(valid, 12))
feedback = assemble("把通知正文缩到 28 个字符", audience="客服编辑,为租户写作",
material={"上一版": json.loads(valid), "原始材料": payload["材料"]},
shape=payload["输出形式"], constraints=["保留原时间", "保留值班台"])
turns = [{"role": "user", "content": email}, {"role": "assistant", "content": valid},
{"role": "user", "content": feedback}]
expect("prompt_followup", "反馈:缩短,保留时间和渠道",
"Pass previous draft and append explicit feedback without losing source data",
[["user", "assistant", "user"], "周三 18:00–18:20", ["保留原时间", "保留值班台"]],
[[turn["role"] for turn in turns], json.loads(turns[-1]["content"])["材料"]["原始材料"]["停机"],
json.loads(turns[-1]["content"])["约束"]])
code = assemble("改写字符串清单的去重函数", audience="维护 Python 3.12 的开发者",
material="当前代码逐项检查是否已经出现在结果清单。输入元素是字符串。",
shape="提交函数、复杂度假设和等价测试",
constraints=["保留首次出现顺序", "允许空输入", "保留原输入"])
contract = json.loads(code)
inputs = [["B", "A", "B", "C", "A"], [], ["A", "A"]]
before = [items.copy() for items in inputs]
expect("prompt_code_contract", inputs, "Execute both owned implementations and compare edge cases and unchanged inputs",
[[["B", "A", "C"], [], ["A"]], True, True, ["保留首次出现顺序", "允许空输入", "保留原输入"]],
[[revised_unique(items) for items in inputs],
all(original_unique(items) == revised_unique(items) for items in inputs), inputs == before, contract["约束"]])
try:
assemble(" ")
except ValueError as error:
failure = str(error)
else:
failure = None
expect("prompt_task_required", "三个空格", "Reject a missing task before using the prompt",
"task is required", failure)
expect("prompt_minimal_question", "周五是否开放?", "Omit optional fields for a single clear question",
{"任务": "周五是否开放?"}, json.loads(assemble("周五是否开放?")))
if __name__ == "__main__":
run_exercise(exercise)
本例需在 Python 3.12.14 标准库,本机样本和固定回包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.12.14 标准库,本机样本和固定回包。
入口文件:projects/ai-prompt/prompt_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
prompt_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.12.14 标准库,本机样本和固定回包。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a22.zip