大多数大语言模型应用都是从几行硬编码的提示词开始的。项目慢慢变大,逻辑散落到各个文件里,提示词管理就变成了字符串拼接、环境变量判断和散落配置的大杂烩。
这正是DynaPrompt想要解决的问题。这是一个面向大模型应用的动态提示词管理与配置库,支持懒加载、Jinja2模板和Pydantic模式验证。
GitHub地址:mohamed-em2m/dynaprompt
为什么提示词管理会变乱
当提示词直接写在应用代码里,测试、版本控制和复用都会变得困难。DynaPrompt的思路完全相反:把模板和业务逻辑分离,把提示词当作配置而不是内联字符串来处理。
看看下面这种代码是怎么快速变脏的:
import os
import json
user_name = os.getenv("USER_NAME", "Guest")
SYSTEM_PROMPT = f"""
You are a helpful assistant.
Current User: {user_name}
Format your output according to this schema:
{json.dumps(MySchema.model_json_schema(), indent=2)}
if os.getenv("ENV") == "production":
model = "gpt-4"
temperature = 0.2
else:
model = "gpt-3.5-turbo"
temperature = 0.7
DynaPrompt改变了什么
这个库让你从文件加载提示词,在运行时渲染,并把环境相关的配置放在应用逻辑之外。
干净版本长这样:
from dynaprompt import DynaPrompt
prompts = DynaPrompt(settings_files=["prompts/"])
rendered = prompts.system.render(user_name="Emam")
response = llm_client.generate(
prompt=rendered.text,
model=rendered.config["model"],
temperature=rendered.config["temperature"],
response_format=rendered.response_schema,
Markdown提示词配YAML前置元数据
DynaPrompt最舒服的设计之一,是提示词可以放在Markdown文件里,顶部用YAML前置元数据来设置模型参数和模式元数据,和提示词文本放在一起。
model: gpt-4o
temperature: 0.2
max_tokens: 1000
response_schema: AnalysisSchema
You are an expert code analyzer.
Please review the following code snippet from {{ developer_name }}:
{{ code_snippet }}
Analyze it and return the result strictly matching the schema.
然后这样渲染:
from dynaprompt import DynaPrompt
prompts = DynaPrompt(settings_files=["prompts/"])
result = prompts.code_analyzer.render(
developer_name="Alice",
code_snippet="def hello(): pass"