191 lines
7.3 KiB
Python
191 lines
7.3 KiB
Python
![]() |
from django.shortcuts import render
|
|||
|
import json
|
|||
|
from http import HTTPStatus
|
|||
|
from dashscope import Application
|
|||
|
from django.http import JsonResponse
|
|||
|
from .models import User, ChatRecord
|
|||
|
from django.utils.crypto import get_random_string
|
|||
|
from Crypto.Cipher import AES
|
|||
|
import base64
|
|||
|
from .views import update_usage_count
|
|||
|
|
|||
|
def decrypt_param(x, t):
|
|||
|
# 创建AES解密器对象
|
|||
|
key = b'qw5w6SFE2D1jmxyd'
|
|||
|
iv = b'345GDFED433223DF'
|
|||
|
|
|||
|
# 检查 x 和 t 是否为空
|
|||
|
if not x or not t:
|
|||
|
return False
|
|||
|
|
|||
|
try:
|
|||
|
cipher = AES.new(key, AES.MODE_CBC, iv)
|
|||
|
# 将密文进行Base64解码
|
|||
|
ciphertext_bytes = base64.b64decode(x)
|
|||
|
# 使用解密器解密密文
|
|||
|
plaintext_bytes = cipher.decrypt(ciphertext_bytes)
|
|||
|
# 删除填充字符
|
|||
|
plaintext = plaintext_bytes.rstrip(b'\0').decode('utf-8')
|
|||
|
# 比较解密后的明文和 t
|
|||
|
if plaintext.rstrip('\x03') == t.rstrip('\x03'):
|
|||
|
return True
|
|||
|
else:
|
|||
|
return False
|
|||
|
except Exception as e:
|
|||
|
print(f"解密过程出现错误: {e}")
|
|||
|
return False
|
|||
|
|
|||
|
def call_bailian_app(request):
|
|||
|
body = request.body.decode("utf-8")
|
|||
|
data = json.loads(body)
|
|||
|
user_id = data.get("user_id")
|
|||
|
openid = data.get("openid")
|
|||
|
role_name = data.get("role", "AI助手") # 默认角色为“默认AI聊天”
|
|||
|
prompt = data.get("prompt")
|
|||
|
x = request.headers.get('X', '')
|
|||
|
t = request.headers.get('T', '')
|
|||
|
increment = -1
|
|||
|
function_type = 'call_bailian_app'
|
|||
|
result = update_usage_count(openid, increment, function_type)
|
|||
|
if decrypt_param(x, t):
|
|||
|
if result['success']:
|
|||
|
print(f"收到请求: user_id={user_id}, role_name={role_name}, prompt={prompt}")
|
|||
|
try:
|
|||
|
user = User.objects.get(nickname=user_id)
|
|||
|
print(f"找到用户: {user.nickname}")
|
|||
|
except User.DoesNotExist:
|
|||
|
print("用户不存在")
|
|||
|
return JsonResponse({"message": "用户不存在"}, status=404)
|
|||
|
|
|||
|
# 检查是否已有该用户和角色的会话
|
|||
|
conversation = ChatRecord.objects.filter(nickname=user.nickname, role=role_name).first()
|
|||
|
if not conversation:
|
|||
|
print(f"新会话ID")
|
|||
|
response = Application.call(
|
|||
|
app_id=get_app_id(role_name),
|
|||
|
prompt=prompt,
|
|||
|
api_key="sk-9458cae1bed7460c9780e52ca6005cae",
|
|||
|
)
|
|||
|
conversation_id = response.output.get('session_id')
|
|||
|
else:
|
|||
|
conversation_id = conversation.conversation_id
|
|||
|
response = Application.call(
|
|||
|
app_id=get_app_id(role_name),
|
|||
|
prompt=prompt,
|
|||
|
api_key="sk-9458cae1bed7460c9780e52ca6005cae",
|
|||
|
session_id=conversation_id
|
|||
|
)
|
|||
|
print(f"已有会话ID: {conversation_id}")
|
|||
|
|
|||
|
print(f"API调用响应状态: {response.status_code}")
|
|||
|
|
|||
|
if response.status_code != HTTPStatus.OK:
|
|||
|
print(f"API调用失败: request_id={response.request_id}, message={response.message}")
|
|||
|
return JsonResponse({
|
|||
|
"message": "调用应用程序失败",
|
|||
|
"request_id": response.request_id,
|
|||
|
"code": response.status_code,
|
|||
|
"details": response.message
|
|||
|
}, status=response.status_code)
|
|||
|
|
|||
|
ai_response = response.output.get('text') if response.output else "AI无回复"
|
|||
|
print(f"AI回复: {ai_response}")
|
|||
|
|
|||
|
ChatRecord.objects.create(
|
|||
|
openid=user.openid,
|
|||
|
nickname=user.nickname,
|
|||
|
conversation_id=conversation_id,
|
|||
|
role=role_name,
|
|||
|
message_content=prompt,
|
|||
|
is_response=False
|
|||
|
)
|
|||
|
|
|||
|
# 保存AI回复
|
|||
|
ChatRecord.objects.create(
|
|||
|
openid=user.openid,
|
|||
|
nickname=user.nickname,
|
|||
|
conversation_id=conversation_id,
|
|||
|
role=role_name,
|
|||
|
message_content=ai_response,
|
|||
|
is_response=True
|
|||
|
)
|
|||
|
|
|||
|
# 检索会话的最近10条消息
|
|||
|
last_messages = ChatRecord.objects.filter(nickname=user.nickname, conversation_id=conversation_id).order_by('-timestamp')[:10]
|
|||
|
last_messages_list = [
|
|||
|
{
|
|||
|
"content": msg.message_content,
|
|||
|
"is_response": msg.is_response,
|
|||
|
"role":msg.role,
|
|||
|
"timestamp": msg.timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
|||
|
} for msg in reversed(last_messages)
|
|||
|
]
|
|||
|
|
|||
|
print(f"最近10条消息: {last_messages_list}")
|
|||
|
|
|||
|
return JsonResponse({
|
|||
|
"message": "成功",
|
|||
|
"ai_response": ai_response,
|
|||
|
"conversation_id": conversation_id,
|
|||
|
"last_messages": last_messages_list
|
|||
|
}, status=HTTPStatus.OK)
|
|||
|
else:
|
|||
|
return JsonResponse(result)
|
|||
|
else:
|
|||
|
return JsonResponse({'error': '非法参数'}, status=400)
|
|||
|
|
|||
|
# 新增接口:获取用户和角色的最近10条聊天记录
|
|||
|
def get_recent_chat_records(request):
|
|||
|
body = request.body.decode("utf-8")
|
|||
|
data = json.loads(body)
|
|||
|
user_id = data.get("user_id")
|
|||
|
role_name = data.get("role", "AI助手") # 默认角色为“默认AI聊天”
|
|||
|
x = request.headers.get('X', '')
|
|||
|
t = request.headers.get('T', '')
|
|||
|
if decrypt_param(x, t):
|
|||
|
print(f"收到请求: user_id={user_id}, role_name={role_name}")
|
|||
|
|
|||
|
try:
|
|||
|
user = User.objects.get(nickname=user_id)
|
|||
|
print(f"找到用户: {user.nickname}")
|
|||
|
except User.DoesNotExist:
|
|||
|
print("用户不存在")
|
|||
|
return JsonResponse({"message": "用户不存在"}, status=404)
|
|||
|
|
|||
|
# 获取该用户和角色的最近10条聊天记录
|
|||
|
last_messages = ChatRecord.objects.filter(nickname=user.nickname, role=role_name).order_by('-timestamp')[:10]
|
|||
|
last_messages_list = [
|
|||
|
{
|
|||
|
"content": msg.message_content,
|
|||
|
"is_response": msg.is_response,
|
|||
|
"role": msg.role,
|
|||
|
"timestamp": msg.timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
|||
|
} for msg in reversed(last_messages)
|
|||
|
]
|
|||
|
|
|||
|
print(f"最近10条消息: {last_messages_list}")
|
|||
|
|
|||
|
return JsonResponse({
|
|||
|
"message": "成功",
|
|||
|
"last_messages": last_messages_list
|
|||
|
}, status=HTTPStatus.OK)
|
|||
|
else:
|
|||
|
return JsonResponse({'error': '非法参数'}, status=400)
|
|||
|
def get_app_id(role_name):
|
|||
|
role_app_id_map = {
|
|||
|
"法律咨询": "446cde34829e4d6490667b1271dee537",
|
|||
|
"行业分析师": "bdce7fba11b147ca846a1b4d1f5e7e72",
|
|||
|
"写工作报告": "f340613da5574815975acdc10bac4e47",
|
|||
|
"产品顾问": "f9b0612793e94a669fe7ad2fecbda50e",
|
|||
|
"写爆款文案": "2c8d6675a9794711a886a5e8cf714afe",
|
|||
|
"写公众号文章": "4fb69f6bd9bb49c9a6329202c6f28c84",
|
|||
|
"文案改写": "b94734c09c414814bc0505a4e5b636c6",
|
|||
|
"招聘助理": "c70caf3fd67b44c4947df70f05cf9f10",
|
|||
|
"AI助手": "92d23cd2c5d64ef5ac6ad02692fc510b",
|
|||
|
"小红书文案": "c5211023cbf64d548ea55a47c516007a",
|
|||
|
"写广告文案": "6c9770da90ec47979ce899cec49c396c",
|
|||
|
}
|
|||
|
|
|||
|
return role_app_id_map.get(role_name, "app_id_default")
|
|||
|
|