505 lines
15 KiB
Markdown
505 lines
15 KiB
Markdown
# 🎯 生成专业提示词代码逻辑分析
|
||
|
||
## 📋 系统概述
|
||
|
||
生成专业提示词系统是一个基于Flask的Web应用,采用前后端分离架构,集成了DeepSeek LLM API,实现了智能化的提示词生成功能。
|
||
|
||
## 🏗️ 系统架构
|
||
|
||
### 1. 技术栈
|
||
- **后端**: Flask + SQLAlchemy + PyMySQL
|
||
- **前端**: HTML5 + CSS3 + JavaScript + Bootstrap
|
||
- **数据库**: MySQL (本地 + 腾讯云)
|
||
- **LLM API**: DeepSeek Chat API
|
||
- **部署**: Gunicorn + Nginx
|
||
|
||
### 2. 核心组件
|
||
- **路由层**: Flask Blueprint路由管理
|
||
- **模型层**: SQLAlchemy ORM模型
|
||
- **服务层**: LLM API集成服务
|
||
- **视图层**: Jinja2模板渲染
|
||
- **静态资源**: CSS/JS资源管理
|
||
|
||
## 🔄 完整生成流程
|
||
|
||
### 第一阶段:用户交互层
|
||
|
||
#### 1.1 前端界面 (`generate.html`)
|
||
```html
|
||
<!-- 模板选择区域 -->
|
||
<div class="template-grid">
|
||
{% for template in templates %}
|
||
<div class="template-card" data-template-id="{{ template.id }}">
|
||
<input type="radio" name="template_id" value="{{ template.id }}">
|
||
<label>{{ template.name }}</label>
|
||
</div>
|
||
{% endfor %}
|
||
</div>
|
||
|
||
<!-- 需求输入区域 -->
|
||
<div class="input-section">
|
||
<textarea name="input_text" placeholder="请详细描述您的需求..."></textarea>
|
||
</div>
|
||
|
||
<!-- 生成按钮 -->
|
||
<button type="submit" class="btn-generate">生成专业提示词</button>
|
||
```
|
||
|
||
#### 1.2 JavaScript交互逻辑
|
||
```javascript
|
||
// 模板选择处理
|
||
function handleTemplateSelection(radio) {
|
||
const card = radio.closest('.template-card');
|
||
const templateId = card.dataset.templateId;
|
||
|
||
// 添加选择动画
|
||
card.classList.add('selecting');
|
||
|
||
// 更新选择状态
|
||
updateSelectionStatus();
|
||
|
||
// 添加到选择历史
|
||
addToSelectionHistory(templateId, templateName);
|
||
}
|
||
|
||
// 表单提交处理
|
||
document.getElementById('promptForm').addEventListener('submit', function(e) {
|
||
e.preventDefault();
|
||
|
||
const formData = new FormData(this);
|
||
const templateId = formData.get('template_id');
|
||
const inputText = formData.get('input_text');
|
||
|
||
// 发送AJAX请求
|
||
fetch('/', {
|
||
method: 'POST',
|
||
body: formData
|
||
})
|
||
.then(response => response.text())
|
||
.then(html => {
|
||
// 更新页面内容
|
||
document.body.innerHTML = html;
|
||
});
|
||
});
|
||
```
|
||
|
||
### 第二阶段:后端处理层
|
||
|
||
#### 2.1 路由处理 (`routes.py`)
|
||
```python
|
||
@main_bp.route('/', methods=['GET', 'POST'])
|
||
def index():
|
||
form = PromptForm()
|
||
templates = PromptTemplate.query.all()
|
||
|
||
if form.validate_on_submit():
|
||
# 获取用户输入和模板ID
|
||
template_id = request.form.get('template_id')
|
||
input_text = form.input_text.data
|
||
|
||
# 调用LLM生成提示词
|
||
generated_text = generate_with_llm(input_text, template_id)
|
||
|
||
# 保存到数据库
|
||
prompt = Prompt(
|
||
input_text=input_text,
|
||
generated_text=generated_text,
|
||
user_id=get_user_id()
|
||
)
|
||
db.session.add(prompt)
|
||
db.session.commit()
|
||
|
||
# 返回结果页面
|
||
return render_template('generate.html',
|
||
form=form,
|
||
prompt=prompt,
|
||
templates=templates)
|
||
|
||
return render_template('generate.html',
|
||
form=form,
|
||
templates=templates)
|
||
```
|
||
|
||
#### 2.2 模板系统逻辑
|
||
```python
|
||
def get_system_prompt(template_id=None):
|
||
"""获取系统提示词模板"""
|
||
if template_id:
|
||
# 根据模板ID获取特定模板
|
||
template = PromptTemplate.query.get(template_id)
|
||
if template:
|
||
return template.system_prompt
|
||
|
||
# 获取默认模板
|
||
default_template = PromptTemplate.query.filter_by(is_default=True).first()
|
||
if default_template:
|
||
return default_template.system_prompt
|
||
|
||
# 硬编码默认模板
|
||
return """你是一个专业的提示词工程师,擅长将普通的描述转换为结构化、专业的 Prompt。
|
||
|
||
你需要:
|
||
1. 分析用户的需求和意图
|
||
2. 将其转换为清晰、详细的提示词
|
||
3. 添加必要的上下文和约束条件
|
||
4. 使用专业的术语和格式
|
||
5. 确保生成的提示词能够获得最佳的 AI 响应
|
||
|
||
请直接返回优化后的提示词,不要添加任何解释或其他内容。"""
|
||
```
|
||
|
||
### 第三阶段:LLM集成层
|
||
|
||
#### 3.1 API配置
|
||
```python
|
||
# OpenAI兼容客户端配置
|
||
client = OpenAI(
|
||
api_key='sk-fdf7cc1c73504e628ec0119b7e11b8cc',
|
||
base_url='https://api.deepseek.com/v1'
|
||
)
|
||
```
|
||
|
||
#### 3.2 LLM调用逻辑
|
||
```python
|
||
def generate_with_llm(input_text, template_id=None, max_retries=3):
|
||
"""调用大模型API生成提示词,带重试机制"""
|
||
system_prompt = get_system_prompt(template_id)
|
||
|
||
for attempt in range(max_retries):
|
||
try:
|
||
response = client.chat.completions.create(
|
||
model="deepseek-chat",
|
||
messages=[
|
||
{"role": "system", "content": system_prompt},
|
||
{"role": "user", "content": input_text}
|
||
],
|
||
temperature=0.7,
|
||
max_tokens=500,
|
||
timeout=60
|
||
)
|
||
|
||
generated_text = response.choices[0].message.content.strip()
|
||
return generated_text
|
||
|
||
except Exception as e:
|
||
if attempt == max_retries - 1:
|
||
current_app.logger.error(f'LLM API调用失败: {str(e)}')
|
||
return "提示词生成失败,请稍后重试"
|
||
time.sleep(2 ** attempt) # 指数退避
|
||
```
|
||
|
||
### 第四阶段:专家模式生成
|
||
|
||
#### 4.1 两阶段专家系统
|
||
```python
|
||
@main_bp.route('/api/wx/generate/expert', methods=['POST'])
|
||
def wx_generate_expert_prompt():
|
||
"""两阶段专家提示词生成系统"""
|
||
|
||
# 第一阶段:意图识别专家
|
||
intent_analyst_prompt = """你是一位资深的意图分析专家,请分析用户输入的意图和需求。
|
||
|
||
你必须严格按照以下JSON格式返回:
|
||
{
|
||
"core_intent": "技术", // 技术、创意、分析、咨询
|
||
"domain": "web开发", // 具体的专业领域
|
||
"key_requirements": [ // 2-4个关键需求
|
||
"需求1", "需求2"
|
||
],
|
||
"expected_output": "期望输出的具体形式",
|
||
"constraints": [ // 1-3个主要约束
|
||
"约束1", "约束2"
|
||
],
|
||
"keywords": [ // 2-4个关键词
|
||
"关键词1", "关键词2"
|
||
]
|
||
}"""
|
||
|
||
# 获取意图分析结果
|
||
intent_response = client.chat.completions.create(
|
||
model="deepseek-chat",
|
||
messages=[
|
||
{"role": "system", "content": intent_analyst_prompt},
|
||
{"role": "user", "content": user_input}
|
||
],
|
||
temperature=0.1
|
||
)
|
||
|
||
intent_analysis = json.loads(intent_response.choices[0].message.content.strip())
|
||
|
||
# 第二阶段:领域专家提示生成
|
||
domain_expert_templates = {
|
||
"技术": """你是一位专业的技术领域提示工程师。基于以下意图分析,生成一个专业的技术任务提示词:
|
||
|
||
意图分析:{analysis}
|
||
|
||
请生成的提示词包含:
|
||
1. 明确的技术背景和上下文
|
||
2. 具体的技术要求和规范
|
||
3. 性能和质量标准
|
||
4. 技术约束条件
|
||
5. 预期交付成果
|
||
6. 评估标准
|
||
|
||
使用专业技术术语,确保提示词的可执行性和可验证性。""",
|
||
|
||
"创意": """你是一位专业的创意领域提示工程师。基于以下意图分析,生成一个创意设计提示词:
|
||
|
||
意图分析:{analysis}
|
||
|
||
请生成的提示词包含:
|
||
1. 创意方向和灵感来源
|
||
2. 风格和氛围要求
|
||
3. 目标受众定义
|
||
4. 设计元素规范
|
||
5. 创意表现形式
|
||
6. 评估标准
|
||
|
||
使用专业创意术语,确保提示词的创新性和可执行性。"""
|
||
}
|
||
|
||
# 选择领域专家模板
|
||
expert_prompt = domain_expert_templates.get(
|
||
intent_analysis['core_intent'],
|
||
default_template
|
||
)
|
||
|
||
# 生成最终提示词
|
||
final_response = client.chat.completions.create(
|
||
model="deepseek-chat",
|
||
messages=[
|
||
{"role": "system", "content": expert_prompt.format(
|
||
analysis=json.dumps(intent_analysis, ensure_ascii=False, indent=2)
|
||
)},
|
||
{"role": "user", "content": user_input}
|
||
],
|
||
temperature=0.7
|
||
)
|
||
|
||
generated_prompt = final_response.choices[0].message.content.strip()
|
||
|
||
return jsonify({
|
||
'code': 200,
|
||
'data': {
|
||
'intent_analysis': intent_analysis,
|
||
'generated_prompt': generated_prompt
|
||
}
|
||
})
|
||
```
|
||
|
||
## 🗄️ 数据库设计
|
||
|
||
### 1. 核心表结构
|
||
|
||
#### Prompt表 (主要数据表)
|
||
```sql
|
||
CREATE TABLE prompt (
|
||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||
input_text TEXT NOT NULL,
|
||
generated_text TEXT NOT NULL,
|
||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||
user_id INT,
|
||
wx_user_id INT,
|
||
FOREIGN KEY (user_id) REFERENCES user(uid),
|
||
FOREIGN KEY (wx_user_id) REFERENCES wx_user(id)
|
||
);
|
||
```
|
||
|
||
#### PromptTemplate表 (模板管理)
|
||
```sql
|
||
CREATE TABLE prompt_template (
|
||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||
name VARCHAR(100) NOT NULL,
|
||
description TEXT,
|
||
category VARCHAR(50),
|
||
industry VARCHAR(50),
|
||
profession VARCHAR(50),
|
||
sub_category VARCHAR(50),
|
||
system_prompt TEXT NOT NULL,
|
||
is_default BOOLEAN DEFAULT FALSE,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
);
|
||
```
|
||
|
||
### 2. 数据流转
|
||
```
|
||
用户输入 → 模板选择 → LLM处理 → 结果生成 → 数据库存储 → 页面展示
|
||
```
|
||
|
||
## 🎨 前端交互逻辑
|
||
|
||
### 1. 模板选择系统
|
||
```javascript
|
||
// 模板筛选逻辑
|
||
function performSearchAndFilter() {
|
||
const searchTerm = document.getElementById('templateSearch').value.toLowerCase();
|
||
const selectedCategory = document.querySelector('.filter-tab.active')?.dataset.category;
|
||
|
||
document.querySelectorAll('.template-card').forEach(card => {
|
||
const templateName = card.querySelector('h3').textContent.toLowerCase();
|
||
const templateCategory = card.dataset.category;
|
||
|
||
const matchesSearch = templateName.includes(searchTerm);
|
||
const matchesCategory = !selectedCategory || templateCategory === selectedCategory;
|
||
|
||
card.style.display = (matchesSearch && matchesCategory) ? 'block' : 'none';
|
||
});
|
||
}
|
||
|
||
// 选择状态管理
|
||
function updateSelectionStatus() {
|
||
const selectedTemplates = document.querySelectorAll('input[name="template_id"]:checked');
|
||
const selectedCount = selectedTemplates.length;
|
||
|
||
document.getElementById('selectedCount').textContent = selectedCount;
|
||
document.getElementById('selectionStatus').style.display = selectedCount > 0 ? 'block' : 'none';
|
||
}
|
||
```
|
||
|
||
### 2. 用户体验优化
|
||
```javascript
|
||
// 现代交互功能
|
||
function initializeModernInteractions() {
|
||
// 平滑滚动
|
||
initializeSmoothScroll();
|
||
|
||
// 焦点管理
|
||
initializeFocusManagement();
|
||
|
||
// 悬停效果
|
||
initializeHoverEffects();
|
||
|
||
// 键盘导航
|
||
initializeKeyboardNavigation();
|
||
|
||
// 性能优化
|
||
initializePerformanceOptimizations();
|
||
}
|
||
|
||
// 防抖搜索
|
||
let searchTimeout;
|
||
document.getElementById('templateSearch').addEventListener('input', function() {
|
||
clearTimeout(searchTimeout);
|
||
searchTimeout = setTimeout(() => {
|
||
performSearchAndFilter();
|
||
}, 300);
|
||
});
|
||
```
|
||
|
||
## ⚙️ 配置管理
|
||
|
||
### 1. 环境配置
|
||
```python
|
||
class Config:
|
||
# 数据库配置
|
||
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/pro_db?charset=utf8mb4'
|
||
TENCENT_SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:!Rjb12191@gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com:24936/pro_db?charset=utf8mb4'
|
||
|
||
# LLM API配置
|
||
LLM_API_URL = 'https://api.deepseek.com/v1'
|
||
LLM_API_KEY = 'sk-fdf7cc1c73504e628ec0119b7e11b8cc'
|
||
|
||
# 微信小程序配置
|
||
WX_APPID = 'wx2c65877d37fc29bf'
|
||
WX_SECRET = '89aa97dda3c1347c6ae3d6ab4627f1f4'
|
||
```
|
||
|
||
### 2. 部署配置
|
||
```python
|
||
# Gunicorn配置 (gunicorn.conf.py)
|
||
bind = "0.0.0.0:5002"
|
||
workers = multiprocessing.cpu_count() * 2 + 1
|
||
worker_class = "sync"
|
||
timeout = 120
|
||
accesslog = "logs/gunicorn_access.log"
|
||
errorlog = "logs/gunicorn_error.log"
|
||
```
|
||
|
||
## 🔧 核心功能实现
|
||
|
||
### 1. 模板管理系统
|
||
- **模板分类**: 按行业、职业、领域分类
|
||
- **模板选择**: 单选模式,支持默认模板
|
||
- **模板搜索**: 实时搜索和筛选
|
||
- **模板历史**: 记录用户选择历史
|
||
|
||
### 2. 生成引擎
|
||
- **普通模式**: 单次LLM调用
|
||
- **专家模式**: 两阶段专家系统
|
||
- **重试机制**: 指数退避重试
|
||
- **错误处理**: 完善的异常处理
|
||
|
||
### 3. 数据管理
|
||
- **用户数据**: 支持普通用户和微信用户
|
||
- **历史记录**: 完整的生成历史管理
|
||
- **数据导出**: 支持JSON格式导出
|
||
- **统计分析**: 使用统计和分析
|
||
|
||
## 🚀 性能优化
|
||
|
||
### 1. 前端优化
|
||
- **懒加载**: 图片和资源懒加载
|
||
- **防抖搜索**: 减少API调用频率
|
||
- **缓存策略**: 模板数据缓存
|
||
- **响应式设计**: 移动端适配
|
||
|
||
### 2. 后端优化
|
||
- **连接池**: 数据库连接池管理
|
||
- **重试机制**: LLM API调用重试
|
||
- **日志记录**: 详细的日志追踪
|
||
- **错误处理**: 优雅的错误处理
|
||
|
||
### 3. 数据库优化
|
||
- **索引优化**: 关键字段索引
|
||
- **查询优化**: 减少N+1查询
|
||
- **分页查询**: 大数据量分页
|
||
- **连接管理**: 连接池和超时设置
|
||
|
||
## 📊 监控和日志
|
||
|
||
### 1. 日志系统
|
||
```python
|
||
# 配置日志
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# API调用日志
|
||
logger.info("=== API 调用参数 ===")
|
||
logger.info(f"模板ID: {template_id}")
|
||
logger.info(f"输入文本: {input_text}")
|
||
logger.info(f"系统提示: {system_prompt}")
|
||
|
||
# 错误日志
|
||
current_app.logger.error(f'LLM API调用失败: {str(e)}')
|
||
```
|
||
|
||
### 2. 性能监控
|
||
- **响应时间**: API调用响应时间
|
||
- **成功率**: 生成成功率统计
|
||
- **错误率**: 错误类型和频率
|
||
- **用户行为**: 用户使用模式分析
|
||
|
||
## 🎯 总结
|
||
|
||
生成专业提示词系统采用了现代化的架构设计,具有以下特点:
|
||
|
||
### 优势
|
||
1. **架构清晰**: 前后端分离,职责明确
|
||
2. **功能完整**: 支持多种生成模式
|
||
3. **用户体验**: 现代化的交互设计
|
||
4. **扩展性强**: 支持模板和功能扩展
|
||
5. **性能优化**: 多层次的性能优化
|
||
|
||
### 技术亮点
|
||
1. **两阶段专家系统**: 意图识别 + 领域专家
|
||
2. **智能模板选择**: 基于用户行为的推荐
|
||
3. **多数据库支持**: 本地 + 腾讯云
|
||
4. **完善的错误处理**: 重试机制和降级策略
|
||
5. **现代化前端**: 响应式设计和交互优化
|
||
|
||
这个系统为用户提供了专业、高效的提示词生成服务,通过智能化的模板选择和专家级的生成逻辑,帮助用户快速生成高质量的AI提示词。
|
||
|
||
---
|
||
*分析完成时间:2025年1月*
|
||
*系统版本:v1.0*
|
||
*维护人员:系统管理员*
|