coze_bot_api.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. -----------------File Info-----------------------
  5. Name: web.py
  6. Description: web api support
  7. Author: GentleCP
  8. Email: me@gentlecp.com
  9. Create Date: 2021/6/19
  10. -----------------End-----------------------------
  11. """
  12. import re
  13. import time
  14. from django.db.models.fields import return_None
  15. from fastapi import FastAPI, Response, Request, BackgroundTasks
  16. from WXBizMsgCrypt3 import WXBizMsgCrypt
  17. from xml.etree.ElementTree import fromstring
  18. import uvicorn
  19. import requests
  20. import json
  21. # 加载配置文件
  22. with open('config.json', 'r') as f:
  23. config = json.load(f)
  24. # 从配置文件中提取参数
  25. token = config['token']
  26. aeskey = config['aeskey']
  27. corpid = config['corpid']
  28. corpsecret = config['corpsecret']
  29. coze_access_token = config['coze_access_token']
  30. bot_id = config['bot_id']
  31. port = config['port']
  32. # token = "EcSp"#企业微信应用api信息
  33. # aeskey = "OTZoY8N67kOnGosEpS3jw4Rsjea0Gu6D7X4IWxoYKtY"#企业微信应用api信息
  34. # corpid = "ww5541cfeea51e3188"#企业id
  35. # corpsecret = "SbyG25s1LsMsW0nAMiaNprrQIHYrWKQP4f2mNLLDnwE"##api成功后的secret
  36. # coze_access_token = "pat_HNBYQOWE5h4r1tzXi8S2PuY4ddoVRH3DpTbE3NsYBjtcWHTYw5ffrVmKPh26hSLW"#豆包access_token
  37. # bot_id="7397619068440182793"#豆包机器人id
  38. # port = 18090#服务器端口
  39. wxcpt = WXBizMsgCrypt(token, aeskey, corpid)
  40. app = FastAPI()
  41. # def call_llm(prompt: str, bot_id: str,coze_access_token:str):
  42. # req_head = {
  43. # "Authorization":f"Bearer {coze_access_token}",
  44. # "Content-Type": "application/json",
  45. # }
  46. # req_data = {
  47. # "conversation_id": "123",
  48. # "bot_id": bot_id,
  49. # "user": "test",
  50. # "query": prompt,
  51. # "stream": False
  52. # }
  53. # res = requests.post("https://api.coze.cn/open_api/v2/chat", headers=req_head, json=req_data)
  54. # res.raise_for_status() # 检查响应状态码是否为200
  55. # return res.json()
  56. def call_llm(prompt: str, bot_id: str,coze_access_token:str):
  57. req_head = {
  58. "Authorization":f"Bearer {coze_access_token}",
  59. "Content-Type": "application/json",
  60. }
  61. req_data ={
  62. "bot_id": bot_id,
  63. "user_id": "123456789",
  64. "stream": False,
  65. "auto_save_history": True,
  66. "additional_messages": [
  67. {
  68. "role": "user",
  69. "content": prompt,
  70. "content_type": "text"
  71. }
  72. ]
  73. }
  74. res_create = requests.post(" https://api.coze.cn/v1/conversation/create", headers=req_head)
  75. conversation_id = res_create.json()["data"]["id"]
  76. res_chat = requests.post(f" https://api.coze.cn/v3/chat?conversation_id={conversation_id}", headers=req_head,json=req_data)
  77. chat_id = res_chat.json()["data"]["id"]
  78. while True:
  79. res_retrieve = requests.get(f" https://api.coze.cn/v3/chat/retrieve?chat_id={chat_id}&conversation_id={conversation_id}", headers=req_head)
  80. print(res_retrieve.json()["data"]["status"])
  81. status = res_retrieve.json()["data"]["status"]
  82. if status == "completed":
  83. res_message = requests.get(f" https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={conversation_id}", headers=req_head)
  84. # print(res_message.json())
  85. return res_message.json()
  86. time.sleep(1)
  87. def qiwei_get():
  88. res = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}")
  89. qw_access_token = res.json()["access_token"]
  90. return qw_access_token
  91. def qiwei_post(username: str, answer: str,agentid:str):
  92. req_data = {
  93. "touser": username,
  94. "toparty": "",
  95. "totag": "",
  96. "msgtype": "text",
  97. "agentid": agentid,
  98. "text": {"content": answer},
  99. "image": {
  100. "media_id": "MEDIA_ID"
  101. },
  102. "safe": 0,
  103. "enable_id_trans": 0,
  104. "enable_duplicate_check": 0,
  105. "duplicate_check_interval": 1800
  106. }
  107. res = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={qiwei_get()}", json=req_data)
  108. print(res.json())
  109. #return res.json()
  110. def consumer(user_query,decrypt_data):
  111. print(f"请求:{user_query}")
  112. username = decrypt_data.get('FromUserName', '')
  113. agentid = decrypt_data.get('AgentID', '')
  114. # 返回coze结果
  115. coze_response = call_llm(prompt=user_query,bot_id=bot_id,coze_access_token = coze_access_token)
  116. # answer = coze_response['messages'][1]['content']#v2
  117. answer = coze_response['data'][1]['content'].replace(" ","") #v3 删除图片url中的空格
  118. ##处理图片链接
  119. image_counter = 1
  120. # 定义一个替换函数,用于在替换时添加序号
  121. def replace_with_counter(match):
  122. nonlocal image_counter
  123. alt_text = match.group(1) or f"示例图片{image_counter}"
  124. url = match.group(2)
  125. replacement = f'<a href="{url}">{alt_text}</a>'
  126. image_counter += 1
  127. return replacement
  128. # 将Markdown格式的图片链接转换为HTML格式的文字链接,并添加序号
  129. answer = re.sub(r'!\[(.*?)\]\((https?://[^)]+)\)', replace_with_counter, answer)
  130. print(f"结果:{answer}")
  131. # 主动发结果给qiwei
  132. qiwei_post(username, answer, agentid)
  133. # @app.get("/ok")
  134. # async def ok():
  135. # return "ok"
  136. @app.get("/bot")
  137. async def verify(msg_signature: str, timestamp: str, nonce: str, echostr: str):
  138. ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
  139. if ret == 0:
  140. return Response(content=sEchoStr.decode('utf-8'))
  141. else:
  142. print(sEchoStr)
  143. @app.post("/bot")
  144. async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request, background_tasks: BackgroundTasks):
  145. #start_time = time.time()
  146. body = await request.body()
  147. ret, sMsg = wxcpt.DecryptMsg(body.decode('utf-8'), msg_signature, timestamp, nonce)
  148. decrypt_data = {}
  149. for node in list(fromstring(sMsg.decode('utf-8'))):
  150. decrypt_data[node.tag] = node.text
  151. user_query = decrypt_data.get('Content', '')
  152. background_tasks.add_task(consumer, user_query, decrypt_data)
  153. return Response(content="")
  154. if __name__ == "__main__":
  155. # coze_response = call_llm(prompt="房快贷是什么",bot_id=bot_id,coze_access_token = coze_access_token)
  156. # print(coze_response)
  157. uvicorn.run("coze_bot_api:app", port=port, host='0.0.0.0', reload=False,ssl_keyfile="./key.pem", ssl_certfile="./cert.pem")