cm-wisdom-cube/backend/app/routers/chat.py

89 lines
3.7 KiB
Python
Raw Normal View History

2025-03-14 16:57:26 +08:00
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel
from openai import OpenAI
from app.core.database import get_db
from app.models.requirement import Requirement
from app.utils.common_util import SuccessData
from app.core.security import get_current_user
client = OpenAI(
api_key="sk-P7bm1Ioe7eovIWkbabAbY8yEON2VFu4RcHqumAFCfoxDVDdi",
base_url="https://api.lkeap.cloud.tencent.com/v1"
)
messages = [
# {'role': 'system', 'content': '您现在是一个代码质量审核专家,您的任务是结合业务需求代码进行审核,判断代码是否符合需求'},
]
class WorkScore(BaseModel):
prompt: str
requirement_id: int
router = APIRouter(prefix="/chat", tags=["chat"])
@router.post("/work-score", description="工作内容审核")
async def work_chat(work_score: WorkScore,
db: Session = Depends(get_db),
current_user: str = Depends(get_current_user)):
requirement = db.query(Requirement).filter(Requirement.id == work_score.requirement_id).first()
if not requirement:
raise HTTPException(status_code=400, detail="需求不存在")
prompt = f"""
接下来需要您根据提供的需求对以下代码进行审核有如下要求
1.判断代码是否符合需求尽量详细地给出判断依据
2.对代码的整体质量进行打分满分为 100 打分时可以从代码的结构性能等方面综合考量
3..对代码的完成度进行打分满分为 100 主要看代码是否实现了需求中的主要功能
4.对代码的可读性进行打分满分为 100 依据代码的注释变量命名等是否规范易懂来评判
5.对代码的可维护性进行打分满分为 100 可从代码是否模块化是否易于修改等方面考虑
6.对代码的可扩展性进行打分满分为 100 评估代码是否方便增加新功能或修改现有功能
7.对代码是否符合需求业务进行打分满分为 100 判断代码是否契合业务逻辑和目标
8.综合结合 2-7 的分数整体打分满分为 100 给出一个综合的评判分数
9.最终以 markdown 表格格式输出尽量让表格呈现清晰易读
需求```
{requirement.description}
```
代码```
{work_score.prompt}
```
"""
print(">>> prompt: \n%s" % prompt)
messages.append({'role': 'system', 'content': prompt})
stream = client.chat.completions.create(
model="deepseek-r1",
messages=messages,
stream=True
)
reasoning_content = "" # 定义完整思考过程
answer_content = "" # 定义完整回复
is_answering = False # 判断是否结束思考过程并开始回复
for chunk in stream:
if not getattr(chunk, 'choices', None):
print("\n" + "=" * 20 + "Token 使用情况" + "=" * 20 + "\n")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# 处理空内容情况
if not getattr(delta, 'reasoning_content', None) and not getattr(delta, 'content', None):
continue
# 处理开始回答的情况
if not getattr(delta, 'reasoning_content', None) and not is_answering:
print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
is_answering = True
# 处理思考过程
if getattr(delta, 'reasoning_content', None):
print(delta.reasoning_content, end='', flush=True)
reasoning_content += delta.reasoning_content
# 处理回复内容
elif getattr(delta, 'content', None):
print(delta.content, end='', flush=True)
answer_content += delta.content
return SuccessData(answer_content)