密钥写死,处理报错
This commit is contained in:
@@ -3,39 +3,21 @@ from openai import OpenAI
|
||||
from src.flask_prompt_master import db
|
||||
from src.flask_prompt_master.models import User, Prompt, Feedback, PromptTemplate, WxUser
|
||||
from src.flask_prompt_master.forms import PromptForm, FeedbackForm
|
||||
from src.flask_prompt_master.config import Config
|
||||
import pymysql
|
||||
from datetime import datetime
|
||||
import requests
|
||||
import hashlib
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
|
||||
main_bp = Blueprint('main', __name__)
|
||||
|
||||
@main_bp.route('/health')
|
||||
def health_check():
|
||||
"""健康检查接口"""
|
||||
return jsonify({
|
||||
'status': 'healthy',
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'environment': os.environ.get('FLASK_ENV', 'unknown')
|
||||
})
|
||||
client = OpenAI(api_key='sk-fdf7cc1c73504e628ec0119b7e11b8cc', base_url='https://api.deepseek.com/v1')
|
||||
|
||||
# 使用current_app获取配置,而不是直接导入
|
||||
def get_openai_client():
|
||||
"""获取OpenAI客户端实例"""
|
||||
return OpenAI(
|
||||
api_key=current_app.config['LLM_API_KEY'],
|
||||
base_url=current_app.config['LLM_API_URL']
|
||||
)
|
||||
|
||||
def get_wx_config():
|
||||
"""获取微信小程序配置"""
|
||||
return {
|
||||
'appid': current_app.config['WX_APPID'],
|
||||
'secret': current_app.config['WX_SECRET']
|
||||
}
|
||||
# 从配置中获取微信小程序配置
|
||||
WX_APPID = Config.WX_APPID
|
||||
WX_SECRET = Config.WX_SECRET
|
||||
|
||||
def get_system_prompt(template_id=None):
|
||||
"""获取系统提示词模板"""
|
||||
@@ -66,9 +48,6 @@ def generate_with_llm(input_text, template_id=None):
|
||||
try:
|
||||
system_prompt = get_system_prompt(template_id)
|
||||
|
||||
# 获取OpenAI客户端
|
||||
client = get_openai_client()
|
||||
|
||||
# 打印参数
|
||||
print("\n=== API 调用参数 ===")
|
||||
print(f"模板ID: {template_id}")
|
||||
@@ -76,35 +55,6 @@ def generate_with_llm(input_text, template_id=None):
|
||||
print(f"系统提示: {system_prompt}")
|
||||
print("==================\n")
|
||||
|
||||
# 开发环境模拟API响应(当API密钥无效时)
|
||||
api_key = current_app.config.get('LLM_API_KEY', '')
|
||||
print(f"\n=== 当前API密钥: {api_key} ===")
|
||||
|
||||
if api_key in ['test-api-key', 'your-actual-api-key-here', 'sk-your-api-key-here'] or 'test' in api_key.lower() or 'your-api-key' in api_key.lower():
|
||||
# 模拟API响应
|
||||
mock_responses = {
|
||||
"写一篇关于python的文章": "请帮我写一篇关于Python编程语言的技术文章,要求:\n1. 介绍Python的基本特性和优势\n2. 包含实际代码示例\n3. 适合初学者阅读\n4. 字数在1000-1500字之间\n5. 结构清晰,逻辑性强",
|
||||
"python代码优化": "请帮我优化以下Python代码,要求:\n1. 提高代码执行效率\n2. 改善代码可读性\n3. 遵循Python编码规范\n4. 添加必要的注释\n5. 考虑内存使用优化",
|
||||
"python程序优化": "请帮我优化Python程序,要求:\n1. 分析程序性能瓶颈\n2. 提供优化建议\n3. 展示优化前后对比\n4. 考虑不同场景的优化策略\n5. 提供可执行的优化代码"
|
||||
}
|
||||
|
||||
# 根据输入文本返回相应的模拟响应
|
||||
for key, value in mock_responses.items():
|
||||
if key in input_text:
|
||||
generated_text = value
|
||||
print("\n=== 模拟API响应结果 ===")
|
||||
print(f"生成的提示词: {generated_text}")
|
||||
print("==================\n")
|
||||
return generated_text
|
||||
|
||||
# 默认模拟响应
|
||||
generated_text = f"请帮我{input_text},要求:\n1. 内容专业且实用\n2. 结构清晰,逻辑性强\n3. 包含具体示例\n4. 适合目标受众\n5. 符合行业标准"
|
||||
print("\n=== 模拟API响应结果 ===")
|
||||
print(f"生成的提示词: {generated_text}")
|
||||
print("==================\n")
|
||||
return generated_text
|
||||
|
||||
# 真实API调用
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[
|
||||
@@ -399,13 +349,10 @@ def wx_get_template_detail(template_id):
|
||||
def wx_login():
|
||||
"""微信小程序登录接口"""
|
||||
try:
|
||||
# 获取微信小程序配置
|
||||
wx_config = get_wx_config()
|
||||
|
||||
# 添加调试日志
|
||||
print("\n=== 微信登录配置 ===")
|
||||
print(f"APPID: {wx_config['appid']}")
|
||||
print(f"SECRET: {wx_config['secret']}")
|
||||
print(f"APPID: {WX_APPID}")
|
||||
print(f"SECRET: {WX_SECRET}")
|
||||
print("==================\n")
|
||||
|
||||
data = request.get_json()
|
||||
@@ -422,8 +369,8 @@ def wx_login():
|
||||
# 请求微信接口
|
||||
wx_url = 'https://api.weixin.qq.com/sns/jscode2session'
|
||||
params = {
|
||||
'appid': wx_config['appid'],
|
||||
'secret': wx_config['secret'],
|
||||
'appid': WX_APPID,
|
||||
'secret': WX_SECRET,
|
||||
'js_code': code,
|
||||
'grant_type': 'authorization_code'
|
||||
}
|
||||
@@ -903,54 +850,17 @@ def wx_get_template_by_intent():
|
||||
|
||||
只返回分类名称,不要其他任何内容。"""
|
||||
|
||||
# 开发环境模拟API响应(当API密钥无效时)
|
||||
api_key = current_app.config.get('LLM_API_KEY', '')
|
||||
print(f"\n=== 意图识别API密钥: {api_key} ===")
|
||||
# 调用意图识别
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[
|
||||
{"role": "system", "content": intent_system_prompt},
|
||||
{"role": "user", "content": user_input}
|
||||
],
|
||||
temperature=0.1
|
||||
)
|
||||
|
||||
if api_key in ['test-api-key', 'your-actual-api-key-here', 'sk-your-api-key-here'] or 'test' in api_key.lower() or 'your-api-key' in api_key.lower():
|
||||
# 模拟意图识别响应
|
||||
mock_intents = {
|
||||
"写代码": "代码开发",
|
||||
"开发": "代码开发",
|
||||
"编程": "代码开发",
|
||||
"网站": "网站开发",
|
||||
"网页": "网站开发",
|
||||
"设计": "产品设计",
|
||||
"UI": "产品设计",
|
||||
"界面": "产品设计",
|
||||
"图片": "生成图片",
|
||||
"图像": "生成图片",
|
||||
"新闻": "新闻获取",
|
||||
"资讯": "新闻获取",
|
||||
"文案": "文案创作",
|
||||
"营销": "市场营销",
|
||||
"推广": "市场营销",
|
||||
"数据": "数据分析",
|
||||
"分析": "数据分析"
|
||||
}
|
||||
|
||||
# 根据输入文本返回相应的模拟意图
|
||||
for key, value in mock_intents.items():
|
||||
if key in user_input:
|
||||
intent = value
|
||||
print(f"\n=== 模拟意图识别结果: {intent} ===")
|
||||
break
|
||||
else:
|
||||
intent = "其它"
|
||||
print(f"\n=== 模拟意图识别结果: {intent} ===")
|
||||
else:
|
||||
# 真实API调用
|
||||
client = get_openai_client()
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[
|
||||
{"role": "system", "content": intent_system_prompt},
|
||||
{"role": "user", "content": user_input}
|
||||
],
|
||||
temperature=0.1
|
||||
)
|
||||
|
||||
intent = response.choices[0].message.content.strip()
|
||||
intent = response.choices[0].message.content.strip()
|
||||
|
||||
# 根据意图获取对应的模板提示词
|
||||
intent_prompts = {
|
||||
@@ -1056,81 +966,17 @@ def wx_generate_expert_prompt():
|
||||
6. 不要添加任何额外的文本"""
|
||||
|
||||
try:
|
||||
# 开发环境模拟API响应(当API密钥无效时)
|
||||
api_key = current_app.config.get('LLM_API_KEY', '')
|
||||
print(f"\n=== 专家意图分析API密钥: {api_key} ===")
|
||||
# 获取意图分析结果
|
||||
intent_response = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[
|
||||
{"role": "system", "content": intent_analyst_prompt},
|
||||
{"role": "user", "content": user_input}
|
||||
],
|
||||
temperature=0.1 # 降低温度,使输出更确定
|
||||
)
|
||||
|
||||
if api_key in ['test-api-key', 'your-actual-api-key-here', 'sk-your-api-key-here'] or 'test' in api_key.lower() or 'your-api-key' in api_key.lower():
|
||||
# 模拟意图分析响应
|
||||
mock_intent_analysis = {
|
||||
"core_intent": "技术",
|
||||
"domain": "软件开发",
|
||||
"key_requirements": [
|
||||
"功能完整性",
|
||||
"性能优化",
|
||||
"代码质量"
|
||||
],
|
||||
"expected_output": "可执行的代码解决方案",
|
||||
"constraints": [
|
||||
"遵循最佳实践",
|
||||
"考虑可维护性"
|
||||
],
|
||||
"keywords": [
|
||||
"编程",
|
||||
"开发",
|
||||
"技术"
|
||||
]
|
||||
}
|
||||
|
||||
# 根据输入文本调整分析结果
|
||||
print(f"\n=== 输入文本分析: {user_input} ===")
|
||||
|
||||
if any(keyword in user_input for keyword in ["设计", "UI", "界面", "用户体验", "视觉", "交互", "原型", "界面设计", "UI设计"]):
|
||||
mock_intent_analysis["core_intent"] = "创意"
|
||||
mock_intent_analysis["domain"] = "产品设计"
|
||||
mock_intent_analysis["key_requirements"] = ["用户体验", "视觉设计", "交互设计"]
|
||||
mock_intent_analysis["expected_output"] = "设计方案和原型"
|
||||
mock_intent_analysis["keywords"] = ["设计", "UI", "用户体验"]
|
||||
print("=== 匹配到创意类型 ===")
|
||||
elif any(keyword in user_input for keyword in ["分析", "数据", "统计", "报告", "洞察", "趋势", "图表", "可视化", "挖掘"]):
|
||||
mock_intent_analysis["core_intent"] = "分析"
|
||||
mock_intent_analysis["domain"] = "数据分析"
|
||||
mock_intent_analysis["key_requirements"] = ["数据准确性", "分析深度", "洞察价值"]
|
||||
mock_intent_analysis["expected_output"] = "分析报告和建议"
|
||||
mock_intent_analysis["keywords"] = ["分析", "数据", "洞察"]
|
||||
print("=== 匹配到分析类型 ===")
|
||||
elif any(keyword in user_input for keyword in ["咨询", "建议", "方案", "策略", "规划", "优化", "改进", "评估", "诊断"]):
|
||||
mock_intent_analysis["core_intent"] = "咨询"
|
||||
mock_intent_analysis["domain"] = "业务咨询"
|
||||
mock_intent_analysis["key_requirements"] = ["专业建议", "可行性分析", "实施方案"]
|
||||
mock_intent_analysis["expected_output"] = "咨询报告和方案"
|
||||
mock_intent_analysis["keywords"] = ["咨询", "建议", "方案"]
|
||||
print("=== 匹配到咨询类型 ===")
|
||||
elif any(keyword in user_input for keyword in ["代码", "编程", "开发", "技术", "系统", "软件", "应用", "程序", "算法", "架构"]):
|
||||
mock_intent_analysis["core_intent"] = "技术"
|
||||
mock_intent_analysis["domain"] = "软件开发"
|
||||
mock_intent_analysis["key_requirements"] = ["功能完整性", "性能优化", "代码质量"]
|
||||
mock_intent_analysis["expected_output"] = "可执行的代码解决方案"
|
||||
mock_intent_analysis["keywords"] = ["编程", "开发", "技术"]
|
||||
print("=== 匹配到技术类型 ===")
|
||||
else:
|
||||
print("=== 未匹配到特定类型,使用默认技术类型 ===")
|
||||
|
||||
intent_analysis_text = json.dumps(mock_intent_analysis, ensure_ascii=False, indent=2)
|
||||
print(f"\n=== 模拟意图分析结果: {intent_analysis_text} ===")
|
||||
else:
|
||||
# 真实API调用
|
||||
client = get_openai_client()
|
||||
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_text = intent_response.choices[0].message.content.strip()
|
||||
intent_analysis_text = intent_response.choices[0].message.content.strip()
|
||||
|
||||
# 添加日志记录
|
||||
current_app.logger.info(f"AI返回的意图分析结果: {intent_analysis_text}")
|
||||
@@ -1265,176 +1111,19 @@ def wx_generate_expert_prompt():
|
||||
)
|
||||
|
||||
try:
|
||||
# 开发环境模拟API响应(当API密钥无效时)
|
||||
api_key = current_app.config.get('LLM_API_KEY', '')
|
||||
print(f"\n=== 专家提示词生成API密钥: {api_key} ===")
|
||||
# 生成最终提示词
|
||||
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
|
||||
)
|
||||
|
||||
if api_key in ['test-api-key', 'your-actual-api-key-here', 'sk-your-api-key-here'] or 'test' in api_key.lower() or 'your-api-key' in api_key.lower():
|
||||
# 模拟专家提示词生成响应
|
||||
core_intent = intent_analysis.get('core_intent', '技术')
|
||||
domain = intent_analysis.get('domain', '软件开发')
|
||||
|
||||
mock_expert_prompts = {
|
||||
"技术": f"""基于您的需求,我为您生成一个专业的技术任务提示词:
|
||||
|
||||
**技术背景和上下文:**
|
||||
您需要在{domain}领域完成一项技术任务,需要确保技术方案的可行性和实用性。
|
||||
|
||||
**技术要求和规范:**
|
||||
1. 遵循行业最佳实践和标准
|
||||
2. 确保代码质量和可维护性
|
||||
3. 考虑性能和安全性要求
|
||||
4. 提供完整的实现方案
|
||||
|
||||
**性能和质量标准:**
|
||||
- 代码执行效率优化
|
||||
- 错误处理和异常管理
|
||||
- 文档和注释完整性
|
||||
- 测试覆盖率要求
|
||||
|
||||
**技术约束条件:**
|
||||
- 技术栈兼容性
|
||||
- 资源使用限制
|
||||
- 时间进度要求
|
||||
- 团队协作规范
|
||||
|
||||
**预期交付成果:**
|
||||
- 完整的技术实现方案
|
||||
- 详细的代码示例
|
||||
- 部署和配置说明
|
||||
- 测试验证方案
|
||||
|
||||
**评估标准:**
|
||||
- 功能完整性验证
|
||||
- 性能指标达标
|
||||
- 代码质量审查
|
||||
- 用户体验评估""",
|
||||
|
||||
"创意": f"""基于您的创意需求,我为您生成一个专业的创意设计提示词:
|
||||
|
||||
**创意方向和灵感来源:**
|
||||
在{domain}领域探索创新的设计理念,结合用户需求和市场趋势,创造独特的视觉体验。
|
||||
|
||||
**风格和氛围要求:**
|
||||
1. 现代简约的设计风格
|
||||
2. 温暖友好的用户界面
|
||||
3. 专业可信的品牌形象
|
||||
4. 富有创意的视觉元素
|
||||
|
||||
**目标受众定义:**
|
||||
- 明确用户群体特征
|
||||
- 理解用户行为习惯
|
||||
- 分析用户需求痛点
|
||||
- 设计用户旅程地图
|
||||
|
||||
**设计元素规范:**
|
||||
- 色彩搭配和视觉层次
|
||||
- 字体选择和排版规范
|
||||
- 图标和插画风格
|
||||
- 布局和空间设计
|
||||
|
||||
**创意表现形式:**
|
||||
- 交互设计创新
|
||||
- 动效和过渡效果
|
||||
- 响应式设计适配
|
||||
- 无障碍设计考虑
|
||||
|
||||
**评估标准:**
|
||||
- 视觉吸引力评估
|
||||
- 用户体验测试
|
||||
- 品牌一致性检查
|
||||
- 创新性价值验证""",
|
||||
|
||||
"分析": f"""基于您的分析需求,我为您生成一个专业的数据分析提示词:
|
||||
|
||||
**分析目标和范围:**
|
||||
在{domain}领域进行深入的数据分析,挖掘有价值的信息洞察,为决策提供数据支撑。
|
||||
|
||||
**数据要求和规范:**
|
||||
1. 数据来源的可靠性和完整性
|
||||
2. 数据格式和结构标准化
|
||||
3. 数据清洗和预处理要求
|
||||
4. 数据安全和隐私保护
|
||||
|
||||
**分析方法和工具:**
|
||||
- 统计分析方法和模型选择
|
||||
- 数据可视化工具和技术
|
||||
- 机器学习算法应用
|
||||
- 业务指标和KPI定义
|
||||
|
||||
**输出格式要求:**
|
||||
- 分析报告的结构和内容
|
||||
- 图表和可视化展示
|
||||
- 关键发现和建议总结
|
||||
- 可操作的洞察建议
|
||||
|
||||
**关键指标定义:**
|
||||
- 核心业务指标监控
|
||||
- 趋势分析和预测模型
|
||||
- 异常检测和预警机制
|
||||
- 效果评估和ROI分析
|
||||
|
||||
**质量控制标准:**
|
||||
- 数据准确性验证
|
||||
- 分析逻辑合理性
|
||||
- 结果可解释性
|
||||
- 建议可操作性""",
|
||||
|
||||
"咨询": f"""基于您的咨询需求,我为您生成一个专业的咨询服务提示词:
|
||||
|
||||
**咨询问题界定:**
|
||||
在{domain}领域提供专业的咨询服务,帮助您解决业务挑战,制定有效的解决方案。
|
||||
|
||||
**背景信息要求:**
|
||||
1. 当前业务状况和挑战
|
||||
2. 目标和期望结果
|
||||
3. 资源和约束条件
|
||||
4. 时间进度要求
|
||||
|
||||
**分析框架设定:**
|
||||
- 问题分析和诊断方法
|
||||
- 市场调研和竞争分析
|
||||
- 风险评估和管理策略
|
||||
- 成本效益分析模型
|
||||
|
||||
**建议输出格式:**
|
||||
- 咨询报告的结构和内容
|
||||
- 解决方案的详细说明
|
||||
- 实施计划和里程碑
|
||||
- 预期效果和评估指标
|
||||
|
||||
**实施考虑因素:**
|
||||
- 组织变革管理
|
||||
- 团队培训和能力建设
|
||||
- 技术支持和维护
|
||||
- 持续改进机制
|
||||
|
||||
**效果评估标准:**
|
||||
- 目标达成度评估
|
||||
- 投资回报率分析
|
||||
- 客户满意度调查
|
||||
- 长期价值创造"""
|
||||
}
|
||||
|
||||
generated_prompt = mock_expert_prompts.get(core_intent, mock_expert_prompts["技术"])
|
||||
print(f"\n=== 模拟专家提示词生成结果 ===")
|
||||
print(f"生成的提示词: {generated_prompt[:200]}...")
|
||||
print("==================\n")
|
||||
else:
|
||||
# 真实API调用
|
||||
client = get_openai_client()
|
||||
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()
|
||||
generated_prompt = final_response.choices[0].message.content.strip()
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"生成提示词失败: {str(e)}")
|
||||
|
||||
Reference in New Issue
Block a user