快捷问题问答部分修改

main
zc 3 months ago
parent 43fbda1a50
commit b02900d50e
  1. 2
      app/api/chat/ai/chat_router.py
  2. 4
      app/api/chat/ai/chat_service.py
  3. 4
      app/api/v1/upload/upload.py
  4. 29
      app/core/init_app.py
  5. 5
      app/models/quick_question.py
  6. 2
      web/src/api/index.js
  7. 16
      web/src/views/system/question/index.vue

@ -137,5 +137,5 @@ class QuestionResponse(BaseModel):
@router.get("/getQuestion", summary="获取开启的前4个问题")
async def get_question():
# 查询状态为正常(0)的问题,按order_num正序排序,取前4条
questions = await QuickQuestion.filter(status="0").order_by("order_num").limit(4).values("id", "title")
questions = await QuickQuestion.filter(status="0").order_by("order_num").limit(4).values("title","subtitle","logo","label")
return questions

@ -324,9 +324,9 @@ async def query_flow(request: Request, spot: str) -> str:
async def handle_quick_question(inp: ChatIn, question_content: str) -> AsyncGenerator[str, None]:
chat_prompt = f"""
你是一个专门格式化内容的AI助手
你是一个专门格式化内容的AI助手不能修改内容仅修改格式
负责将接收到的包含html标签内容进行格式化要求是将能够转换成markdown语法的内容中的html标签转换成markdown语法
不能转换的保留html标签不能修改内容仅格式化标签
不能转换的保留html标签
"""
# 只包含系统提示和问题内容,不包含历史记录
messages = [

@ -13,7 +13,7 @@ UPLOAD_DIR = os.path.join(settings.BASE_DIR, 'web', 'public', 'resource')
@router.post('/image', summary='上传图片')
async def upload_image(file: UploadFile = File(...)):
print(file.filename)
print(f"收到上传请求,文件名: {file.filename}")
try:
# 确保目录存在
os.makedirs(os.path.join(UPLOAD_DIR, 'images'), exist_ok=True)
@ -25,6 +25,7 @@ async def upload_image(file: UploadFile = File(...)):
# 保存文件
with open(file_path, 'wb') as f:
f.write(await file.read())
print(f"文件保存成功: {file_path}")
# 构建访问URL
file_url = f'/resource/images/{filename}'
@ -36,6 +37,7 @@ async def upload_image(file: UploadFile = File(...)):
'href': ''
}, msg='上传成功')
except Exception as e:
print(f"上传失败: {str(e)}")
return Fail(code=500, msg=f'上传失败: {str(e)}')

@ -25,6 +25,7 @@ from app.log import logger
from app.models.admin import Api, Menu, Role
from app.schemas.menus import MenuType
from app.settings.config import settings
from tortoise.transactions import in_transaction
from .middlewares import BackGroundTaskMiddleware, HttpAuditLogMiddleware
@ -187,20 +188,34 @@ async def init_apis():
async def init_db():
command = Command(tortoise_config=settings.TORTOISE_ORM)
try:
await command.init_db(safe=True)
except FileExistsError:
pass
await command.init()
try:
await command.migrate()
except AttributeError:
logger.warning("unable to retrieve model history from database, model history will be created from scratch")
shutil.rmtree("migrations")
await command.init_db(safe=True)
await command.upgrade(run_in_transaction=True)
# ✅ 检查是否已经有迁移记录(只迁移一次)
async with in_transaction() as conn:
try:
result = await conn.execute_query("SELECT COUNT(*) FROM aerich")
count = result[1][0][0] # [ (123,) ] -> count = 123
except Exception as e:
count = 0 # 表不存在,视为未迁移
if count == 0:
logger.info("📦 First-time migration, running migrate + upgrade...")
try:
await command.migrate()
except AttributeError:
logger.warning("unable to retrieve model history from database, model history will be created from scratch")
shutil.rmtree("migrations")
await command.init_db(safe=True)
await command.upgrade(run_in_transaction=True)
else:
logger.info("✅ Migration already applied, skipping migrate + upgrade.")
async def init_roles():

@ -4,10 +4,15 @@ from .base import BaseModel
class QuickQuestion(BaseModel):
title = fields.CharField(max_length=255, null=True, description="标题")
subtitle = fields.CharField(max_length=255, null=True, description="副标题")
logo = fields.CharField(max_length=255, null=True, description="logo")
label = fields.CharField(max_length=255, null=True, description="标签")
order_num = fields.IntField(null=True, description="显示顺序")
status = fields.CharField(max_length=1, default='0', description="状态(0正常 1停用)")
content = fields.TextField(null=True, description="内容")
create_time = fields.DatetimeField(auto_now_add=True, description="创建时间")
update_time = fields.DatetimeField(auto_now=True, description="更新时间")
class Meta:
table = "quick_question"

@ -46,5 +46,5 @@ export default {
updateQuestion: (data = {}) => request.post('/question/update', data),
deleteQuestion: (params = {}) => request.delete('/question/delete', { params }),
// 上传图片
uploadImages: (data = {}) => request.post('/upload/image', data)
uploadImages: (data = {}, config = {}) => request.post('/upload/image', data, config)
}

@ -123,9 +123,22 @@ const editorConfig = ref({
const formData = new FormData();
formData.append('file', file);
// localStoragetokenlStorage.get
const token = localStorage.getItem('ACCESS_TOKEN') || '';
console.log('FormData内容:', formData.get('file'));
console.log('获取到的token:', token); // token便
console.log('准备发送请求...');
const res = await api.uploadImages(formData);
// 使api.uploadImagestoken
const res = await api.uploadImages(formData, {
headers: {
'token': token,
'Content-Type': 'multipart/form-data'
},
noNeedToken: false // token
});
console.log('请求响应:', res);
if (res.code === 200 && res.data && res.data.url) {
@ -142,7 +155,6 @@ const editorConfig = ref({
if (res.code === 200 && res.data && res.data.url) {
insertFn(res.data.url);
} else {
// NMessage
window.$message.error(`上传失败: ${res.msg || '未知错误'}`);
}
}

Loading…
Cancel
Save