zhusc пре 2 месеци
родитељ
комит
c649d87edb
2 измењених фајлова са 133 додато и 80 уклоњено
  1. 69 44
      coze_bot_api.py
  2. 64 36
      coze_bot_api_test.py

+ 69 - 44
coze_bot_api.py

@@ -118,8 +118,15 @@ def call_llm(prompt: str, bot_id: str,coze_access_token:str):
             return coze_response
         # 如果状态为completed,则获取消息
         if status == "completed":
-            res_message = requests.get(f"https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={conversation_id}", headers=req_head)
-            coze_response = res_message.json()['data'][1]['content'].replace(" ", "")  # v3 删除图片url中的空格
+            res_message = requests.get(
+                f"https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={conversation_id}",
+                headers=req_head)
+            # 假设res_message是已经获取到的响应对象
+            data = res_message.json()['data']
+
+            # 使用列表推导式找到所有type为'answer'的记录,然后取最后一个
+            last_answer_record = next((record for record in reversed(data) if record['type'] == 'answer'), None)
+            coze_response = last_answer_record['content'].replace(" ", "")  # v3 删除图片url中的空格
             # coze_response = coze_response['data'][1]['content'].replace(" ", "")  # v3 删除图片url中的空格
             return coze_response
         time.sleep(1)
@@ -155,12 +162,11 @@ def qiwei_post(username: str, answer: str,agentid:str):
 
 
 # 问题传入字节服务器进行回答后发送给企业微信,行内服务器只进行接收然后发给字节,防止网络延迟
-def post_consumer_api(user_query, decrypt_data, request_id, bot_id):
+def post_consumer_api(user_query, decrypt_data, request_id):
     data = {
         "user_query": user_query,
         "decrypt_data": decrypt_data,
         "request_id": request_id,
-        "bot_id": bot_id,
     }
     request_id_context.set(request_id)
     url = "https://101.126.81.2:18088/consumer"
@@ -168,7 +174,6 @@ def post_consumer_api(user_query, decrypt_data, request_id, bot_id):
         logger.info(f"post_consumer_api 被执行{user_query}")
         t1 = threading.Thread(target=requests.post, kwargs={"url": url, "json": data, "verify": False})
         t1.start()
-        logger.info(f"post_consumer_api 请求成功: {t1}")
         # response = requests.post(url, json=data, verify=False)  # 忽略SSL证书验证
         # response.raise_for_status()  # 检查响应状态码是否为200
         # logger.info(f"post_consumer_api 请求成功: {response.json()}")
@@ -176,31 +181,75 @@ def post_consumer_api(user_query, decrypt_data, request_id, bot_id):
         logger.error(f"post_consumer_api 请求失败: {e}")
 
 
+# 创建一个字典来存储用户的bot_id状态
+user_bot_id_mapping = {}
+
+# 新增:存储用户是否已收到欢迎消息的状态
+user_welcome_status = {}
+
+
 @app.post("/consumer")
 def consumer(
         request_id: str = Body(...),
         user_query: str = Body(...),
         decrypt_data: dict = Body(...),
-        bot_id: str = Body(...),
 ):
     # print(f"请求:{user_query}")
+    # {
+    #     "request_id":"",
+    #     "user_query": "",
+    #     "bot_id": "",
+    #     "decrypt_data": {'ToUserName': 'ww5541cfeea51e3188', 'FromUserName': 'ZhuSanCheng', 'CreateTime': '1739241434', 'MsgType': 'text', 'Content': '产品介绍', 'MsgId': '7469985082764423235', 'AgentID': '1000002'}
+    # }
     # body = body.decode()
     # body = json.loads(body)
     # request_id = body["request_id"]
     request_id_context.set(request_id)
-    user_query = user_query if user_query else "回答图片中的问题"
+
+    # user_query = body["user_query"] if body["user_query"] else "回答图片中的问题"
     # user_query = "回答图片中的问题"
     # decrypt_data = body["decrypt_data"]
     # bot_id = body["bot_id"]
     # decrypt_data = json.loads(decrypt_data)
+
     username = decrypt_data.get('FromUserName', '')
     agentid = decrypt_data.get('AgentID', '')
     msgtype = decrypt_data.get('MsgType', '')
     picurl = decrypt_data.get('PicUrl', '')
-    qiwei_post(username, "正在加载,请稍后...", agentid)
-    logger.info("正在加载,请稍后...")
-    logger.info(f"consumer 请求:{user_query}")
+    event = decrypt_data.get('Event')
+    msg_type = decrypt_data.get('MsgType')
+    event_key = decrypt_data.get('EventKey')
+    print(f"event_key: {event_key}")
+    # 修改:仅在用户首次进入时发送欢迎消息
+    if msg_type == 'event' and event == 'enter_agent':
+        if not user_welcome_status.get(username, False):  # 检查是否首次进入
+            welcome_message = "Hi,我是小微AI助手~你可以在屏幕底部“产品选择”菜单栏选择想咨询的产品,我会随时为你解答问题~"
+            qiwei_post(username, welcome_message, agentid)
+            user_welcome_status[username] = True  # 标记为已发送
+        return Response(content="")
 
+    # 根据用户发送的消息内容切换bot_id
+    if msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_0#7599826213209000':
+        bot_id = "7456977536891846697"  # 当用户发送渝快振兴贷时使用的bot_id
+        # change_message = "您好,已切换为渝快振兴贷产品助手,请输入问题。"
+        # qiwei_post(username, change_message, agentid)
+        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
+        return Response(content="")
+    elif msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_1#7599826213209001':
+        bot_id = "7445101065005154313"  # 当用户发送房快贷时使用的bot_id
+        # change_message = "您好,已切换为房快贷产品助手,请输入问题。"
+        # qiwei_post(username, change_message, agentid)
+        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
+        return Response(content="")
+    else:
+        # 如果用户之前已经选择了bot_id,则使用之前的bot_id
+        bot_id = user_bot_id_mapping.get(username, "7456977536891846697")  # 默认bot_id
+
+
+    qiwei_post(username, "我正在思考,请稍等...", agentid)
+    logger.info("我正在思考,请稍等...")
+    logger.info(f"consumer 请求:{user_query}")
+    user_query = user_query if user_query else "回答图片中的问题"
     multimodal_content = [
         {"type": "text", "text": user_query},
         {"type": msgtype, "file_url": picurl},
@@ -208,6 +257,7 @@ def consumer(
         # {"type": "file", "file_url": "fileurl1"}
     ]
     user_query = json.dumps(multimodal_content, ensure_ascii=False)
+
     # 返回coze结果
     coze_response = call_llm(prompt=user_query, bot_id=bot_id, coze_access_token=coze_access_token)
     # answer = coze_response['messages'][1]['content']#v2
@@ -237,6 +287,7 @@ def consumer(
     # qiwei_post(username, choice_answer, agentid)
 
 
+
 @app.get("/ok")
 async def ok():
     return "ok"
@@ -251,12 +302,11 @@ async def verify(msg_signature: str, timestamp: str, nonce: str, echostr: str):
         # print(sEchoStr)
         logger.info(sEchoStr)
 
-# 创建一个字典来存储用户的bot_id状态
-user_bot_id_mapping = {}
+
 #
 @app.post("/bot")
-async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request):
-    #start_time = time.time()
+async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request, background_tasks: BackgroundTasks):
+    # start_time = time.time()
     body = await request.body()
     request_id = str(uuid.uuid4())
     request_id_context.set(request_id)
@@ -265,47 +315,22 @@ async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request)
     for node in list(fromstring(sMsg.decode('utf-8'))):
         decrypt_data[node.tag] = node.text
 
+    # decrypt_data = body
+    print(decrypt_data)
     # 获取用户发送的消息内容
     user_query = decrypt_data.get('Content', '')
     # logger.info(f"start: {user_query}")
-    username = decrypt_data.get('FromUserName', '')
-    agentid = decrypt_data.get('AgentID', '')
-    event = decrypt_data.get('Event')
-    msg_type = decrypt_data.get('MsgType')
-    event_key = decrypt_data.get('EventKey')
-    # print(event_key)
 
-    # 如果是用户进入对话,则发送欢迎消息
-    if msg_type == 'event' and event == 'enter_agent':
-        # welcome_message = "您好,请点击下方菜单栏选择您需要的产品助手?"
-        # qiwei_post(username, welcome_message, agentid)
-        return Response(content="")
+    # print(event_key)
 
-    # 根据用户发送的消息内容切换bot_id
-    if msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_0#7599827683207428':
-        bot_id = "7456977536891846697"  # 当用户发送渝快振兴贷时使用的bot_id
-        # change_message = "您好,已切换为渝快振兴贷产品助手,请输入问题。"
-        # qiwei_post(username, change_message, agentid)
-        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
-        return Response(content="")
-    elif msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_1#7599827683207427':
-        bot_id = "7445101065005154313"  # 当用户发送房快贷时使用的bot_id
-        # change_message = "您好,已切换为房快贷产品助手,请输入问题。"
-        # qiwei_post(username, change_message, agentid)
-        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
-        return Response(content="")
-    else:
-        # 如果用户之前已经选择了bot_id,则使用之前的bot_id
-        bot_id = user_bot_id_mapping.get(username, "7456977536891846697")  # 默认bot_id
 
 
     # 处理其他类型的消息
     logger.info(f"start: {user_query}")
     # background_tasks.add_task(post_consumer_api, user_query, decrypt_data, request_id, bot_id)
-    post_consumer_api(user_query, decrypt_data, request_id, bot_id)
-    return Response(content="")
-
 
+    post_consumer_api(user_query, decrypt_data, request_id)
+    return Response(content="")
 
     # user_query = decrypt_data.get('Content', '')
     # logger.info(f"start: {user_query}")

+ 64 - 36
coze_bot_api_test.py

@@ -124,7 +124,12 @@ def call_llm(prompt: str, bot_id: str, coze_access_token: str):
             res_message = requests.get(
                 f"https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={conversation_id}",
                 headers=req_head)
-            coze_response = res_message.json()['data'][1]['content'].replace(" ", "")  # v3 删除图片url中的空格
+            # 假设res_message是已经获取到的响应对象
+            data = res_message.json()['data']
+
+            # 使用列表推导式找到所有type为'answer'的记录,然后取最后一个
+            last_answer_record = next((record for record in reversed(data) if record['type'] == 'answer'), None)
+            coze_response = last_answer_record['content'].replace(" ", "")  # v3 删除图片url中的空格
             # coze_response = coze_response['data'][1]['content'].replace(" ", "")  # v3 删除图片url中的空格
             return coze_response
         time.sleep(1)
@@ -159,12 +164,11 @@ def qiwei_post(username: str, answer: str, agentid: str):
 
 
 # 问题传入字节服务器进行回答后发送给企业微信,行内服务器只进行接收然后发给字节,防止网络延迟
-def post_consumer_api(user_query, decrypt_data, request_id, bot_id):
+def post_consumer_api(user_query, decrypt_data, request_id):
     data = {
         "user_query": user_query,
         "decrypt_data": decrypt_data,
         "request_id": request_id,
-        "bot_id": bot_id,
     }
     request_id_context.set(request_id)
     url = "https://101.126.81.2:18090/consumer"
@@ -179,31 +183,78 @@ def post_consumer_api(user_query, decrypt_data, request_id, bot_id):
         logger.error(f"post_consumer_api 请求失败: {e}")
 
 
+# 创建一个字典来存储用户的bot_id状态
+user_bot_id_mapping = {}
+
+# 新增:存储用户是否已收到欢迎消息的状态
+user_welcome_status = {}
+
+
+
+
+
 @app.post("/consumer")
 def consumer(
         request_id: str = Body(...),
         user_query: str = Body(...),
         decrypt_data: dict = Body(...),
-        bot_id: str = Body(...),
 ):
     # print(f"请求:{user_query}")
+    # {
+    #     "request_id":"",
+    #     "user_query": "",
+    #     "bot_id": "",
+    #     "decrypt_data": {'ToUserName': 'ww5541cfeea51e3188', 'FromUserName': 'ZhuSanCheng', 'CreateTime': '1739241434', 'MsgType': 'text', 'Content': '产品介绍', 'MsgId': '7469985082764423235', 'AgentID': '1000002'}
+    # }
     # body = body.decode()
     # body = json.loads(body)
     # request_id = body["request_id"]
     request_id_context.set(request_id)
+
     # user_query = body["user_query"] if body["user_query"] else "回答图片中的问题"
     # user_query = "回答图片中的问题"
     # decrypt_data = body["decrypt_data"]
     # bot_id = body["bot_id"]
     # decrypt_data = json.loads(decrypt_data)
+
     username = decrypt_data.get('FromUserName', '')
     agentid = decrypt_data.get('AgentID', '')
     msgtype = decrypt_data.get('MsgType', '')
     picurl = decrypt_data.get('PicUrl', '')
-    qiwei_post(username, "正在加载,请稍后...", agentid)
-    logger.info("正在加载,请稍后...")
-    logger.info(f"consumer 请求:{user_query}")
+    event = decrypt_data.get('Event')
+    msg_type = decrypt_data.get('MsgType')
+    event_key = decrypt_data.get('EventKey')
+    print(f"event_key: {event_key}")
+    # 修改:仅在用户首次进入时发送欢迎消息
+    if msg_type == 'event' and event == 'enter_agent':
+        if not user_welcome_status.get(username, False):  # 检查是否首次进入
+            welcome_message = "Hi,我是小微AI助手~你可以在屏幕底部“产品选择”菜单栏选择想咨询的产品,我会随时为你解答问题~"
+            qiwei_post(username, welcome_message, agentid)
+            user_welcome_status[username] = True  # 标记为已发送
+        return Response(content="")
+
+    # 根据用户发送的消息内容切换bot_id
+    if msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_0#7599826213209000':
+        bot_id = "7456977536891846697"  # 当用户发送渝快振兴贷时使用的bot_id
+        # change_message = "您好,已切换为渝快振兴贷产品助手,请输入问题。"
+        # qiwei_post(username, change_message, agentid)
+        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
+        return Response(content="")
+    elif msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_1#7599826213209001':
+        bot_id = "7445101065005154313"  # 当用户发送房快贷时使用的bot_id
+        # change_message = "您好,已切换为房快贷产品助手,请输入问题。"
+        # qiwei_post(username, change_message, agentid)
+        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
+        return Response(content="")
+    else:
+        # 如果用户之前已经选择了bot_id,则使用之前的bot_id
+        bot_id = user_bot_id_mapping.get(username, "7456977536891846697")  # 默认bot_id
+
 
+    qiwei_post(username, "我正在思考,请稍等...", agentid)
+    logger.info("我正在思考,请稍等...")
+    logger.info(f"consumer 请求:{user_query}")
+    user_query = user_query if user_query else "回答图片中的问题"
     multimodal_content = [
         {"type": "text", "text": user_query},
         {"type": msgtype, "file_url": picurl},
@@ -211,6 +262,7 @@ def consumer(
         # {"type": "file", "file_url": "fileurl1"}
     ]
     user_query = json.dumps(multimodal_content, ensure_ascii=False)
+
     # 返回coze结果
     coze_response = call_llm(prompt=user_query, bot_id=bot_id, coze_access_token=coze_access_token)
     # answer = coze_response['messages'][1]['content']#v2
@@ -255,8 +307,7 @@ async def verify(msg_signature: str, timestamp: str, nonce: str, echostr: str):
         logger.info(sEchoStr)
 
 
-# 创建一个字典来存储用户的bot_id状态
-user_bot_id_mapping = {}
+
 
 
 #
@@ -271,44 +322,21 @@ async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request,
     for node in list(fromstring(sMsg.decode('utf-8'))):
         decrypt_data[node.tag] = node.text
 
+    # decrypt_data = body
+    print(decrypt_data)
     # 获取用户发送的消息内容
     user_query = decrypt_data.get('Content', '')
     # logger.info(f"start: {user_query}")
-    username = decrypt_data.get('FromUserName', '')
-    agentid = decrypt_data.get('AgentID', '')
-    event = decrypt_data.get('Event')
-    msg_type = decrypt_data.get('MsgType')
-    event_key = decrypt_data.get('EventKey')
+
     # print(event_key)
 
-    # # 如果是用户进入对话,则发送欢迎消息
-    if msg_type == 'event' and event == 'enter_agent':
-        # welcome_message = "您好,请点击下方菜单栏选择您需要的产品助手?"
-        # qiwei_post(username, welcome_message, agentid)
-        return Response(content="")
 
-    # 根据用户发送的消息内容切换bot_id
-    if msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_0#7599824797208680':
-        bot_id = "7456977536891846697"  # 当用户发送渝快振兴贷时使用的bot_id
-        # change_message = "您好,已切换为渝快振兴贷产品助手,请输入问题。"
-        # qiwei_post(username, change_message, agentid)
-        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
-        return Response(content="")
-    elif msg_type == 'event' and event == 'click' and event_key == '#sendmsg#_0_1#7599824797208679':
-        bot_id = "7445101065005154313"  # 当用户发送房快贷时使用的bot_id
-        # change_message = "您好,已切换为房快贷产品助手,请输入问题。"
-        # qiwei_post(username, change_message, agentid)
-        user_bot_id_mapping[username] = bot_id  # 更新用户的bot_id状态
-        return Response(content="")
-    else:
-        # 如果用户之前已经选择了bot_id,则使用之前的bot_id
-        bot_id = user_bot_id_mapping.get(username, "7456977536891846697")  # 默认bot_id
 
     # 处理其他类型的消息
     logger.info(f"start: {user_query}")
     # background_tasks.add_task(post_consumer_api, user_query, decrypt_data, request_id, bot_id)
 
-    post_consumer_api(user_query, decrypt_data, request_id, bot_id)
+    post_consumer_api(user_query, decrypt_data, request_id)
     return Response(content="")
 
     # user_query = decrypt_data.get('Content', '')