add ai-chat api

This commit is contained in:
Fam Zheng 2025-10-29 21:21:01 +00:00
parent 2f12c588b8
commit afef3a9e11

View File

@ -35,6 +35,7 @@ from .ip2region import *
from .miniprogram import mplink
from .sendmsg import admin_broadcast
from .article import gen_article_css
from .aichat import AIChatService
MANAGE_PY = os.path.join(settings.BASE_DIR, 'manage.py')
@ -1924,3 +1925,95 @@ class ScanDataLabelsView(BaseView):
return JsonResponse({
'items': ret,
})
class AIChatView(BaseView):
"""AI聊天API视图 - 仅支持发送消息,临时会话模式"""
name = 'ai-chat'
auth_check = None
def post(self, request):
"""发送消息给AI并获取回复"""
try:
# 获取请求参数
session_id = request.data.get('session_id')
message = request.data.get('message')
context = request.data.get('context', {})
chat_type = request.data.get('chat_type', 'platform')
product_id = request.data.get('product_id')
# 验证必需参数
if not message:
return JsonResponse({
'error': 'message is required'
}, status=400)
# 获取或创建会话
session = self._get_or_create_session(session_id, request.tenant, product_id)
# 确定聊天类型和产品ID
if chat_type == 'product' and product_id:
ai_chat_type = 'product'
ai_product_id = product_id
else:
ai_chat_type = 'platform'
ai_product_id = None
# 创建AI服务实例
ai_service = AIChatService(
chat_type=ai_chat_type,
product_id=ai_product_id
)
# 调用AI服务
response = ai_service.chat(message)
# 保存消息记录
self._save_message(session, 'user', message)
self._save_message(session, 'assistant', response)
return JsonResponse({
'session_id': session.session_id,
'response': response,
'chat_type': ai_chat_type,
'product_id': ai_product_id
})
except Exception as e:
return JsonResponse({
'error': f'AI chat failed: {str(e)}'
}, status=500)
def _get_or_create_session(self, session_id, tenant, product_id=None):
"""获取或创建聊天会话"""
if session_id:
# 尝试获取现有会话
session = ChatSession.objects.filter(
session_id=session_id,
tenant=tenant
).first()
if session:
return session
# 创建新会话
if not session_id:
session_id = str(uuid.uuid4())
session = ChatSession.objects.create(
session_id=session_id,
tenant=tenant,
product_id=product_id
)
return session
def _save_message(self, session, role, content, message_type='text'):
"""保存消息到数据库"""
ChatMessage.objects.create(
session=session,
role=role,
message_type=message_type,
text_content=content
)