feat:电信中台-代码整理合入

This commit is contained in:
雷雨
2025-08-18 16:37:01 +08:00
parent fb336dd712
commit caa59d2c82
5 changed files with 112 additions and 2 deletions

8
.env
View File

@@ -41,3 +41,11 @@ DEFAULT_QUERY_SIZE = 30
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
#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

View File

View File

@@ -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

View File

@@ -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'),
]

View File

@@ -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')