feat;代码整理提交

This commit is contained in:
雷雨
2025-06-04 12:10:45 +08:00
parent ac201894e1
commit fb7a2d7eca
4 changed files with 371 additions and 1 deletions

2
.env Normal file
View File

@@ -0,0 +1,2 @@
API_KEY=sk-WK7dkfpYfaXYtOQGMOfax5DmQF5itLZ2WXvi8ReVpQfGmbCN
MODEL_BASE_URL=https://www.chataiapi.com

View File

@@ -0,0 +1,128 @@
from threading import Lock
from datetime import datetime
import requests, json
from openai_client import call_openai_api
MODEL_NAME = ''
BASE_URL = ''
def is_json(myjson):
try:
json_object = json.loads(myjson)
return True
except ValueError:
return False
def build_prompt():
"""构建增强提示词"""
# 获取可用会议室信息
room_info = {}
for_mart_str = '''
{
"room_id":"11", //会议室ID
"capacity":20,
"start_time":"2025-06-04 09:30:10",
"end_time":"2025-06-04 12:30:10",
"user_confirm":1 //用户是否确认
}
'''
time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 增强提示词模板
template = f"""你是一个专业的OA会议预订助手请根据以下信息提供服务
现在时间是 :{time_now}
可用会议室信息:
{room_info}
请按以下步骤处理:
1. 解析用户需求(时间、人数、设备要求等)
2. 根据可用会议室列表推荐合适选项,推荐选项请不要返回json格式数据
3. 如果用户确定要预订某间会议室请帮我提取用户预订信息并返回结果请以json结果返回且不需要包含多余的描述内容,输出结果示例如下:
{for_mart_str}
4. 用户其他需求,请按照自然语言对话返回
"""
return template
class DialogManager:
def __init__(self):
self.dialogs = {}
self.lock = Lock()
def get_history(self, session_id: str) -> list:
return self.dialogs.get(session_id, [])
def add_message(self, session_id, role, content):
with self.lock:
if session_id not in self.dialogs:
self.dialogs[session_id] = []
# 自动维护对话历史
self.dialogs[session_id].append({
"role": role,
"timestamp": datetime.now().isoformat(),
"content": content
})
# 上下文压缩(超长对话处理)
if len(self.dialogs[session_id]) > 10:
self.compress_context(session_id)
def compress_context(self, session_id):
"""对话历史压缩算法"""
history = self.dialogs[session_id]
# 保留最近3条完整记录
recent = history[-3:]
# 摘要生成中间对话内容
summary = self.generate_summary(history[3:-3])
# 重组会话历史
self.dialogs[session_id] = [
{"role": "system", "content": f"对话摘要:{summary}"},
*recent
]
def generate_summary(self, messages):
"""生成对话摘要(调用本地模型)"""
text = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
payload = {
"model": MODEL_NAME,
"prompt": f"请生成以下对话的简明摘要(保留关键信息):\n\n{text}"
}
response = requests.post(f"{BASE_URL}", json=payload, timeout=10)
return response.json().get("response", "摘要生成失败")
dialog_manager = DialogManager()
def process_chat(user_id: str, user_input: str):
history = dialog_manager.get_history(user_id)
prompt = ''
if history is None or len(history) == 0:
prompt = build_prompt()
resp = call_openai_api(model=MODEL_NAME, system_prompt=prompt, user_query=user_input,
api_key='sk-KnfrPFFnNDOCFkPkWsvRE7uJGNR0QMDCZ1Ie83ARhtOKMMWa',
history=history)
content = resp["choices"][0]["message"]["content"]
reasoning_content = resp["choices"][0]["message"]["reasoning_content"]
print(content)
if 'json' in content or is_json(content):
new_content = content.replace("json", '')
new_content = new_content.replace("`", '')
print(type(new_content))
print(new_content)
data = json.loads(new_content)
# 触发预订函数------
result = {}
book_promot = f'''
用户预订会议室的结果如下:
{result}
请解析预订会议室的结果,并根据结果给予用户相应反馈
'''
resp = call_openai_api(model=MODEL_NAME, system_prompt=book_promot, user_query=None,
api_key='sk-KnfrPFFnNDOCFkPkWsvRE7uJGNR0QMDCZ1Ie83ARhtOKMMWa',
history=history)
return {'response': resp}
else:
dialog_manager.add_message(dialog_manager, 'assistant', reasoning_content)
return {'response': resp}

File diff suppressed because one or more lines are too long

View File

@@ -12,12 +12,16 @@ https://docs.djangoproject.com/en/5.2/ref/settings/
from pathlib import Path
from dotenv import load_dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
load_dotenv()
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-i(fm5c2v*=vgfwmgdl^qi7iezv(xfwovbqu=+^=vm72e$gnx&l'