174 lines
5.5 KiB
Python
174 lines
5.5 KiB
Python
"""
|
|||
|
|
提示词优化服务
|
||
|
|
==============
|
||
|
|
|
||
|
|
【功能说明】
|
||
|
|
基于 prompt-polisher Skill 定义,把用户的粗糙/口语化/不完整想法
|
||
|
|
润色成结构清晰、无歧义、可直接发给 AI 执行的高质量提示词。
|
||
|
|
|
||
|
|
【技术选型理由】
|
||
|
|
1. 直接读取 SKILL.md 作为 System Prompt,规则统一维护、可迭代;
|
||
|
|
2. 调用强模型执行润色,结果结构化返回(润色后 + 改动说明 + 待定问题)。
|
||
|
|
|
||
|
|
【实现思路】
|
||
|
|
- load_skill_prompt():读取 SKILL.md 内容;
|
||
|
|
- polish():组装 Prompt → 调模型 → 解析输出结构;
|
||
|
|
- 结果分为 polish_result / changes / questions 三部分。
|
||
|
|
|
||
|
|
【潜在风险与应对】
|
||
|
|
风险1:模型输出格式不符合预期。
|
||
|
|
应对:宽松解析(提取【润色后】【改了什么】【还需要你定】三个区块)。
|
||
|
|
风险2:SKILL.md 文件丢失或编码异常。
|
||
|
|
应对:启动时缓存,文件不存在时用内置简化规则兜底。
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
import re
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
logger = logging.getLogger("agent.prompt_polisher")
|
||
|
|
|
||
|
|
# Skill 文件路径
|
||
|
|
SKILL_PATH = Path(r"D:\Agent\SKILLS\prompt-polisher\SKILL.md")
|
||
|
|
|
||
|
|
# 内置兜底规则(SKILL.md 缺失时使用)
|
||
|
|
FALLBACK_RULES = """你是一个提示词润色专家。把用户的粗糙想法润色成高质量提示词。
|
||
|
|
|
||
|
|
铁律:只润色提示词本身,不执行任务。不分析项目、不写代码、不查文件。
|
||
|
|
|
||
|
|
输出格式:
|
||
|
|
【润色后】
|
||
|
|
(可直接复制的提示词)
|
||
|
|
|
||
|
|
【改了什么】
|
||
|
|
- 补了什么
|
||
|
|
- 去掉了什么歧义
|
||
|
|
|
||
|
|
【还需要你定】(如有)
|
||
|
|
- 问题 1:选项 A / 选项 B"""
|
||
|
|
|
||
|
|
|
||
|
|
def _load_skill_prompt() -> str:
|
||
|
|
"""读取 SKILL.md 作为系统提示词(缓存结果)。"""
|
||
|
|
try:
|
||
|
|
if SKILL_PATH.exists():
|
||
|
|
return SKILL_PATH.read_text(encoding="utf-8")
|
||
|
|
except Exception as exc: # noqa: BLE001
|
||
|
|
logger.warning("读取 SKILL.md 失败:%s,使用内置规则", exc)
|
||
|
|
return FALLBACK_RULES
|
||
|
|
|
||
|
|
|
||
|
|
# 缓存(模块加载时读一次)
|
||
|
|
_SKILL_PROMPT: str | None = None
|
||
|
|
|
||
|
|
|
||
|
|
def _get_skill_prompt() -> str:
|
||
|
|
global _SKILL_PROMPT
|
||
|
|
if _SKILL_PROMPT is None:
|
||
|
|
_SKILL_PROMPT = _load_skill_prompt()
|
||
|
|
return _SKILL_PROMPT
|
||
|
|
|
||
|
|
|
||
|
|
def polish(text: str, model_preference: str = "auto") -> dict:
|
||
|
|
"""
|
||
|
|
优化用户输入的提示词。
|
||
|
|
|
||
|
|
【参数】
|
||
|
|
text:用户原始输入(粗糙/口语化的想法)
|
||
|
|
model_preference:模型偏好(auto=智能选)
|
||
|
|
【返回】{polish_result, changes, questions, model}
|
||
|
|
"""
|
||
|
|
from app.models.model_router import get_model_for_task
|
||
|
|
|
||
|
|
if not text or not text.strip():
|
||
|
|
return {"success": False, "message": "请输入要优化的内容"}
|
||
|
|
|
||
|
|
system_prompt = _get_skill_prompt()
|
||
|
|
|
||
|
|
user_prompt = f"""请润色下面这段提示词:
|
||
|
|
|
||
|
|
{text}"""
|
||
|
|
|
||
|
|
try:
|
||
|
|
model = get_model_for_task(model_preference, "strong")
|
||
|
|
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||
|
|
|
||
|
|
# 组装消息:System = Skill 规则,User = 用户原始输入
|
||
|
|
from langchain_core.messages import HumanMessage, SystemMessage
|
||
|
|
|
||
|
|
resp = model.invoke(
|
||
|
|
[
|
||
|
|
SystemMessage(content=system_prompt),
|
||
|
|
HumanMessage(content=user_prompt),
|
||
|
|
]
|
||
|
|
)
|
||
|
|
output = resp.content if hasattr(resp, "content") else str(resp)
|
||
|
|
|
||
|
|
# 宽松解析输出结构
|
||
|
|
polished, changes, questions = _parse_output(output)
|
||
|
|
|
||
|
|
return {
|
||
|
|
"success": True,
|
||
|
|
"polish_result": polished or output,
|
||
|
|
"changes": changes,
|
||
|
|
"questions": questions,
|
||
|
|
"model": model_name,
|
||
|
|
}
|
||
|
|
except Exception as exc: # noqa: BLE001
|
||
|
|
logger.exception("提示词优化失败")
|
||
|
|
return {"success": False, "message": f"优化失败:{exc}"}
|
||
|
|
|
||
|
|
|
||
|
|
def _parse_output(output: str) -> tuple[str, list[str], list[str]]:
|
||
|
|
"""
|
||
|
|
宽松解析润色输出:提取【润色后】【改了什么】【还需要你定】三个区块。
|
||
|
|
|
||
|
|
【容错】区块标题可能有轻微变体,用正则宽松匹配。
|
||
|
|
"""
|
||
|
|
polished = ""
|
||
|
|
changes: list[str] = []
|
||
|
|
questions: list[str] = []
|
||
|
|
|
||
|
|
# 提取【润色后】区块
|
||
|
|
m_polish = re.search(
|
||
|
|
r"【润色后】\s*\n(.*?)(?=【改了什么】|【还需要你定】|$)",
|
||
|
|
output,
|
||
|
|
re.DOTALL,
|
||
|
|
)
|
||
|
|
if m_polish:
|
||
|
|
polished = m_polish.group(1).strip()
|
||
|
|
# 去掉代码块包裹标记
|
||
|
|
polished = re.sub(r"^```[a-z]*\n?|```$", "", polished.strip(), flags=re.MULTILINE).strip()
|
||
|
|
|
||
|
|
# 提取【改了什么】
|
||
|
|
m_changes = re.search(
|
||
|
|
r"【改了什么】\s*\n(.*?)(?=【还需要你定】|【润色后】|$)",
|
||
|
|
output,
|
||
|
|
re.DOTALL,
|
||
|
|
)
|
||
|
|
if m_changes:
|
||
|
|
raw = m_changes.group(1).strip()
|
||
|
|
changes = [
|
||
|
|
re.sub(r"^[-•*]\s*", "", line.strip())
|
||
|
|
for line in raw.splitlines()
|
||
|
|
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||
|
|
]
|
||
|
|
|
||
|
|
# 提取【还需要你定】
|
||
|
|
m_questions = re.search(
|
||
|
|
r"【还需要你定】\s*\n(.*?)(?=【润色后】|【改了什么】|$)",
|
||
|
|
output,
|
||
|
|
re.DOTALL,
|
||
|
|
)
|
||
|
|
if m_questions:
|
||
|
|
raw = m_questions.group(1).strip()
|
||
|
|
questions = [
|
||
|
|
re.sub(r"^[-•*]\s*", "", line.strip())
|
||
|
|
for line in raw.splitlines()
|
||
|
|
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||
|
|
]
|
||
|
|
|
||
|
|
return polished, changes, questions
|