共计 1983 个字符,预计需要花费 5 分钟才能阅读完成。
痛点分析
在构建生产级 AI Agent 时,开发者常遇到以下典型问题:

- 提示词版本混乱:不同环境(开发 / 测试 / 生产)使用不同版本的提示词,难以追踪变更影响
- 多轮对话状态维护困难:对话历史长度超出模型上下文窗口时,关键信息丢失
- 效果不稳定:相同提示词在不同时段返回质量波动大,缺乏量化评估手段
- 安全风险:用户输入可能包含敏感词或注入攻击
技术方案
分层提示词架构
-
系统提示(System Prompt):定义 AI 角色和基础行为准则,通常固定不变
SYSTEM_PROMPT = """ 你是一名专业客服助手,回答时需遵循:1. 使用中文简体回复 2. 保持友好但专业的态度 3. 不清楚的问题明确告知用户 """ -
用户提示(User Prompt):包含具体任务指令和输入变量
-
动态上下文(Context):自动注入的对话历史、知识库检索结果等
提示词模板引擎
使用 Jinja2 实现带类型检查的模板引擎:
from jinja2 import Template, StrictUndefined
from pydantic import BaseModel
class PromptTemplate:
def __init__(self, template_str: str):
self.template = Template(
template_str,
undefined=StrictUndefined # 强制变量声明
)
def render(self, **kwargs) -> str:
try:
return self.template.render(**kwargs)
except Exception as e:
raise ValueError(f"模板渲染失败: {str(e)}")
# 示例用法
question_template = PromptTemplate("""
根据用户 {{user_type}} 的问题进行解答:问题:{{question|trim}}
需引用 {{documents|length}} 份参考资料
""")
效果评估体系
实现可量化的评估指标:
def evaluate_response(
response: str,
ideal_length: int = 200
) -> dict:
"""返回包含各项指标的字典"""
return {"toxic_score": detect_toxicity(response),
"relevance": calculate_semantic_similarity(response, query),
"length_score": 1 - min(1, abs(len(response) - ideal_length)/ideal_length)
}
避坑指南
敏感词过滤实现
from ahocorasick import Automaton
class KeywordFilter:
def __init__(self):
self.automaton = Automaton()
def load_keywords(self, keywords: List[str]):
for idx, word in enumerate(keywords):
self.automaton.add_word(word, (idx, word))
self.automaton.make_automaton()
def detect(self, text: str) -> bool:
for _, (_, word) in self.automaton.iter(text):
return True
return False
对话历史压缩算法
采用重要性评分 +TF-IDF 的混合策略:
- 计算每轮对话的语义密度得分
- 保留得分最高的前 N 轮对话
- 对剩余内容提取关键词摘要
性能监控设计
在关键节点添加埋点:
# 使用 OpenTelemetry 实现
from opentelemetry import metrics
meter = metrics.get_meter(__name__)
prompt_counter = meter.create_counter(
"prompt.usage",
unit="1",
description="统计提示词调用次数"
)
# 调用示例
prompt_counter.add(1, {"template_name": "customer_service"})
架构流程图
flowchart TD
A[系统提示] --> B[模板引擎]
C[用户输入] --> B
D[知识库] --> B
B --> E[LLM 调用]
E --> F[响应评估]
F --> G[输出过滤]
G --> H[最终响应]
进阶思考
- 如何设计提示词的 A / B 测试框架,量化不同版本的效果差异?
- 当需要支持多语言时,提示词工程架构需要做哪些调整?
- 怎样实现提示词的动态热更新,避免服务重启?
在实际项目中落地时,建议从小的功能模块开始验证,逐步构建完整的提示词工程体系。通过代码化的方式管理提示词,可以显著提升 AI Agent 的稳定性和可维护性。
正文完
