现有提示词模板多采用 “定义 - 渲染” 的一次性流程,模板结构(如角色、指令、约束)一旦定义,便形成固定框架。在需要动态调整提示逻辑的场景中(例如多轮对话中根据模型反馈逐步强化指令、或在复杂任务中分阶段解锁新要求),开发者往往需要重新定义整个模板或手动拼接字符串,难以实现 “模块化增量修改”. 例如,在一个知识问答任务中,若首轮提示未获取足够信息,需要追加 “请补充 XX 领域细节” 的指令,现有模板无法仅对 “INSTRUCTION” 部分进行增量更新,而需重新渲染包含新增指令的完整提示,既冗余又易出错. 而 Prompt4Py 是一个专为 Python 设计的程序化提示模板工具,旨在简化与大语言模型(LLM)交互时的提示工程流程。该项目通过提供结构化的模板定义方式,允许开发者以编程方式配置提示的角色、目标、指令、约束、上下文等核心要素,并支持动态变量替换与格式化输出,从而高效生成规范、一致的提示文本.
Repo: Prompt4py - Github
基础用法
Prompt4Py 的核心是通过 GeneralTemplate 类实现提示词的结构化定义与动态渲染,基础使用流程围绕 “模板定义 - 变量填充 - 生成提示” 三个步骤展开,适合快速构建标准化提示词.
-
安装与导入:
通过 pip 安装后,直接导入核心类即可开始使用:
pip install -U prompt4py导入核心 API
from prompt4py import GeneralTemplate -
定义提示模板
from prompt4py import GeneralTemplate # Create your prompt template prompt_template = GeneralTemplate() prompt_template.role = 'An NER machine' prompt_template.objective = 'Extract all \ from CONTEXT.' prompt_template.instruction = { 1: 'Think deeply on every entities in CONTEXT', 2: 'Extract all \', 3: 'Output the entities you have extracted' } prompt_template.constraint = 'Do not include any markdown grams' prompt_template.capability = 'Extract entities' prompt_template.context = '\, \, \' prompt_template.output_dtype = 'str' prompt_template.output_format = 'jsonl' prompt_template.output_example = str([ { 'entity_type': '\', 'entity_text': '\' } ]) -
渲染提示模板得到提示词
在运行的过程中, 我们可以反复渲染提示词, 以实现提示词的动态改动, 可以实现: 记忆增强, 检索增强, Reprompt, 提示词压缩等等高级提示词工程技术.
# Render the template prompt = prompt_template.render(entity_type='PERSON', ent_1='John Lennon', ent_2='Joe Biden', ent_3='Charlemagne', example_entity_type_1='PERSON', example_entity_text_1='Elizabeth') print(prompt)我们会得到以下提示词:
## _TIMESTAMP [82159.8475038] ## ROLE An NER machine ## OBJECTIVE Extract all PERSON from CONTEXT. ## INSTRUCTION - **1**: Think deeply on every entities in CONTEXT - **2**: Extract all PERSON - **3**: Output the entities you have extracted ## CONSTRAINT Do not include any markdown grams ## CAPABILITY Extract entities ## CONTEXT John Lennon, Joe Biden, Charlemagne ## OUTPUT_DATATYPE str ## OUTPUT_FORMAT jsonl ## OUTPUT_EXAMPLE [{'entity_type': 'PERSON', 'entity_text': 'Elizabeth'}] -
使用以上提示词调用大模型, 我们会得到
{"entity_type": "PERSON", "entity_text": "John Lennon"} {"entity_type": "PERSON", "entity_text": "Joe Biden"} {"entity_type": "PERSON", "entity_text": "Charlemagne"}