From caa59d2c8265598991060ef7e6b8bd01e19f46c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=B7=E9=9B=A8?= Date: Mon, 18 Aug 2025 16:37:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E7=94=B5=E4=BF=A1=E4=B8=AD=E5=8F=B0-?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=95=B4=E7=90=86=E5=90=88=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 10 ++- yj_room_agent/tianyi_ai/__init__.py | 0 yj_room_agent/tianyi_ai/knowledge_chat.py | 88 +++++++++++++++++++++++ yj_room_agent/urls.py | 3 +- yj_room_agent/views.py | 13 ++++ 5 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 yj_room_agent/tianyi_ai/__init__.py create mode 100644 yj_room_agent/tianyi_ai/knowledge_chat.py diff --git a/.env b/.env index 619e54d..539c462 100644 --- a/.env +++ b/.env @@ -40,4 +40,12 @@ DEFAULT_QUERY_SIZE = 30 REDIS_HOST=127.0.0.1 REDIS_PORT=6379 -#REDIS_PASSWORD=xx \ No newline at end of file +#REDIS_PASSWORD=xx + +#天翼 AI 中台相关的配置,根据环境情况修改 +TIANYI_AI_CHATBOT_ACCESS_KEY=Fnrk6FDwdPe5uyHGmcvp +TIANYI_AI_CHATBOT_SECRET_KEY=1f1795b326e74b83b3ae1a60f127fa7e +TIANYI_AI_CHATBOT_X_TENANT_ID=ai +TIANYI_AI_CHATBOT_BASE_URL=http://10.226.128.2:31170 +TIANYI_AI_CHATBOT_X_USER_ID=8635843198371561472 +TIANYI_AI_CHATBOT_AGENT_CODE=bot1069877584247001088 diff --git a/yj_room_agent/tianyi_ai/__init__.py b/yj_room_agent/tianyi_ai/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/yj_room_agent/tianyi_ai/knowledge_chat.py b/yj_room_agent/tianyi_ai/knowledge_chat.py new file mode 100644 index 0000000..d73a38e --- /dev/null +++ b/yj_room_agent/tianyi_ai/knowledge_chat.py @@ -0,0 +1,88 @@ + +to_add_header_key = ['x-tenantid', 'x-userid', 'x-source'] +from datetime import datetime,timedelta +import hmac, uuid,time,logging +import hashlib, base64 +import copy,requests,json +hmacAlgorithm = "hmac-sha256" +from decouple import config + +logger = logging.getLogger('django') + +#-- openapi 对话请求所需配置参数 +tianyi_ai_chatbot_access_key=config('TIANYI_AI_CHATBOT_ACCESS_KEY',cast=str) +tianyi_ai_chatbot_secret_key=config('TIANYI_AI_CHATBOT_SECRET_KEY',cast=str) +tianyi_ai_chatbot_x_tenant_id=config('TIANYI_AI_CHATBOT_X_TENANT_ID',cast=str) +#user_id 前期默认,后期用友与电信平台打通了,可以由前端获取并传递 +tianyi_ai_chatbot_x_user_id=config('TIANYI_AI_CHATBOT_X_USER_ID',cast=str) +# 系统配置 的chatbot 的code +tianyi_ai_chatbot_agent_code=config('TIANYI_AI_CHATBOT_AGENT_CODE',cast=str) +#默认ks +tianyi_ai_chatbot_x_source=config('TIANYI_AI_CHATBOT_X_SOURCE',cast=str,default='KS') +#默认是2 +tianyi_ai_chatbot_channel_id=config('TIANYI_AI_CHATBOT_CHANNEL_ID',cast=int,default=2) +# 电信中台base url 地址 +tianyi_ai_chatbot_base_url=config('TIANYI_AI_CHATBOT_BASE_URL',cast=str,default='') +#对话的url地址 +tianyi_ai_chatbot_openapi_chat_url=config('TIANYI_AI_CHATBOT_OPENAPI_CHAT_URL',cast=str,default='/ais/bot/openapi/dcc/sseDialog') + +''' +按照加密要求,对数据使用hmac-sha256 算法加密,获取authkey +加密规则: 按照顺序拼接数据 +''' +def auth_key_encrypt(access_key, secret_key, url, method, header: {}) -> str: + to_encrypt_str = access_key + "\n" + to_encrypt_str = to_encrypt_str + method + " " + url + "\n" + to_encrypt_str = to_encrypt_str + "date: " + header.get('Date') + "\n" + for k in to_add_header_key: + to_encrypt_str = to_encrypt_str + k + ": " + header.get(k) + "\n" + #print(to_encrypt_str) + signature = hmac.new(secret_key.encode('utf-8'), to_encrypt_str.encode('utf-8'), hashlib.sha256) + base64_digest = base64.b64encode(signature.digest()).decode('utf-8') + #print(base64_digest) + return f'Signature keyId="{access_key}",algorithm="{hmacAlgorithm}",headers="@request-target date {" ".join(to_add_header_key)}",signature="{base64_digest}"' + + +''' +与天翼中台智能体对话入口 +目前所需参数 user_query,session +后期按需增加 改造 +''' +def do_chat_with_bot(user_query,session_id): + header = { + 'x-tenantid': tianyi_ai_chatbot_x_tenant_id, + 'x-userid': tianyi_ai_chatbot_x_user_id, + 'x-source': tianyi_ai_chatbot_x_source, + } + + dt = datetime.now() - timedelta(hours=8) + formatted = dt.strftime("%a, %d %b %Y %H:%M:%S GMT") + logger.info(f"format time is: {formatted}") + header['Date'] = formatted + auth_key=auth_key_encrypt(tianyi_ai_chatbot_access_key,tianyi_ai_chatbot_secret_key,tianyi_ai_chatbot_openapi_chat_url,'POST',header) + logger.debug(f'auth_key_encrypt auth key is {auth_key}') + body = { + 'sessionId': 'bot0.' + str(session_id), + "channelId": tianyi_ai_chatbot_channel_id, + "chatType": "chat", + "content": user_query, + "requestTime": int(time.time() * 1000), + "userId": tianyi_ai_chatbot_x_user_id, + "agentCode": tianyi_ai_chatbot_agent_code, + } + new_header = copy.deepcopy(header) + new_header['Content-Type'] = 'application/json' + new_header['Authorization'] = auth_key + req_url= tianyi_ai_chatbot_base_url+tianyi_ai_chatbot_openapi_chat_url + logger.debug(f"tianyi_ai_chatbot req url is :{req_url}") + resp = requests.post(url=req_url, stream=True, data=json.dumps(body, ensure_ascii=False), headers=new_header) + resp.encoding = 'utf-8' + if str(resp.status_code) == '200': + for chunk in resp.iter_content(chunk_size=2048): + if chunk: + text = chunk.decode('utf-8') + logger.debug(f'session {body.get('sessionId')} :\nchat with {body.get('agentCode')}: \ncontent is :{text}') + yield text + else: + logger.error(f"request chat with bot error,code is : {resp.status_code},\n error body is :{resp.content}") + yield resp.content \ No newline at end of file diff --git a/yj_room_agent/urls.py b/yj_room_agent/urls.py index d5adb4b..0f8cc46 100644 --- a/yj_room_agent/urls.py +++ b/yj_room_agent/urls.py @@ -27,6 +27,7 @@ urlpatterns = [ path('getMeetingBookingDetails/', views.query_meetingooking_info), path('bookMeeting/', views.book_meeting), path('cancelMeeting/', views.cancel_meeting), - path('editMeeting/',views.edit_meeting) + path('editMeeting/',views.edit_meeting), + path('yj-agent-api/tianyi_chatbot', views.tian_yi_chat_bot, name='tianyi_chatbot'), ] diff --git a/yj_room_agent/views.py b/yj_room_agent/views.py index 1cfac28..5f36e9d 100644 --- a/yj_room_agent/views.py +++ b/yj_room_agent/views.py @@ -5,6 +5,7 @@ from django.views.decorators.http import require_POST import json import requests from .tools import getinfo +from .tianyi_ai import knowledge_chat def hello(request): return JsonResponse({'msg': 'ok'}) @@ -241,3 +242,15 @@ def room_chat(request): body = json.loads(request.body) resp = process_chat(body, params) return JsonResponse(resp) + + +@require_POST +def tian_yi_chat_bot(request): + data = json.loads(request.body) + user_query = data.get('user_query') + session_id = data.get('session_id') + if not user_query: + return JsonResponse(data={'message':'user_query 不能为空'},status=400) + if not session_id: + return JsonResponse(data={'message': 'session_id 不能为空'},status=400) + return StreamingHttpResponse(knowledge_chat.do_chat_with_bot(user_query,session_id),content_type='text/html; charset=utf-8')