coze_bot_api.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 time
  13. from django.db.models.fields import return_None
  14. from fastapi import FastAPI, Response, Request, BackgroundTasks
  15. from WXBizMsgCrypt3 import WXBizMsgCrypt
  16. from xml.etree.ElementTree import fromstring
  17. import uvicorn
  18. import requests
  19. import json
  20. # 加载配置文件
  21. with open('config.json', 'r') as f:
  22. config = json.load(f)
  23. # 从配置文件中提取参数
  24. token = config['token']
  25. aeskey = config['aeskey']
  26. corpid = config['corpid']
  27. corpsecret = config['corpsecret']
  28. coze_access_token = config['coze_access_token']
  29. bot_id = config['bot_id']
  30. port = config['port']
  31. # token = "EcSp"#企业微信应用api信息
  32. # aeskey = "OTZoY8N67kOnGosEpS3jw4Rsjea0Gu6D7X4IWxoYKtY"#企业微信应用api信息
  33. # corpid = "ww5541cfeea51e3188"#企业id
  34. # corpsecret = "SbyG25s1LsMsW0nAMiaNprrQIHYrWKQP4f2mNLLDnwE"##api成功后的secret
  35. # coze_access_token = "pat_HNBYQOWE5h4r1tzXi8S2PuY4ddoVRH3DpTbE3NsYBjtcWHTYw5ffrVmKPh26hSLW"#豆包access_token
  36. # bot_id="7397619068440182793"#豆包机器人id
  37. # port = 18090#服务器端口
  38. wxcpt = WXBizMsgCrypt(token, aeskey, corpid)
  39. app = FastAPI()
  40. # def call_llm(prompt: str, bot_id: str,coze_access_token:str):
  41. # req_head = {
  42. # "Authorization":f"Bearer {coze_access_token}",
  43. # "Content-Type": "application/json",
  44. # }
  45. # req_data = {
  46. # "conversation_id": "123",
  47. # "bot_id": bot_id,
  48. # "user": "test",
  49. # "query": prompt,
  50. # "stream": False
  51. # }
  52. # res = requests.post("https://api.coze.cn/open_api/v2/chat", headers=req_head, json=req_data)
  53. # res.raise_for_status() # 检查响应状态码是否为200
  54. # return res.json()
  55. def call_llm(prompt: str, bot_id: str,coze_access_token:str):
  56. req_head = {
  57. "Authorization":f"Bearer {coze_access_token}",
  58. "Content-Type": "application/json",
  59. }
  60. # req_data = {
  61. # "conversation_id": "123",
  62. # "bot_id": bot_id,
  63. # "user": "test",
  64. # "query": prompt,
  65. # "stream": False
  66. # }
  67. req_data ={
  68. "bot_id": bot_id,
  69. "user_id": "123456789",
  70. "stream": False,
  71. "auto_save_history": True,
  72. "additional_messages": [
  73. {
  74. "role": "user",
  75. "content": prompt,
  76. "content_type": "text"
  77. }
  78. ]
  79. }
  80. res_create = requests.post(" https://api.coze.cn/v1/conversation/create", headers=req_head)
  81. # print(res_create.json()["data"]["id"])
  82. coversition_id = res_create.json()["data"]["id"]
  83. res_chat = requests.post(f" https://api.coze.cn/v3/chat?conversation_id={coversition_id}", headers=req_head,json=req_data)
  84. # print(res_chat.json()["data"]["id"])
  85. chat_id = res_chat.json()["data"]["id"]
  86. while True:
  87. res_retrieve = requests.get(f" https://api.coze.cn/v3/chat/retrieve?chat_id={chat_id}&conversation_id={coversition_id}", headers=req_head)
  88. print(res_retrieve.json()["data"]["status"])
  89. status = res_retrieve.json()["data"]["status"]
  90. if status == "completed":
  91. res_message = requests.get(f" https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={coversition_id}", headers=req_head)
  92. # print(res_message.json())
  93. return res_message.json()
  94. time.sleep(1)
  95. # res.raise_for_status() # 检查响应状态码是否为200
  96. # return res.json()
  97. def qiwei_get():
  98. res = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}")
  99. qw_access_token = res.json()["access_token"]
  100. return qw_access_token
  101. def qiwei_post(username: str, answer: str,agentid:str):
  102. req_data = {
  103. "touser": username,
  104. "toparty": "",
  105. "totag": "",
  106. "msgtype": "text",
  107. "agentid": agentid,
  108. "text": {"content": answer},
  109. "safe": 0,
  110. "enable_id_trans": 0,
  111. "enable_duplicate_check": 0,
  112. "duplicate_check_interval": 1800
  113. }
  114. res = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={qiwei_get()}", json=req_data)
  115. print(res.json())
  116. #return res.json()
  117. def consumer(user_query,decrypt_data):
  118. print(f"请求:{user_query}")
  119. username = decrypt_data.get('FromUserName', '')
  120. agentid = decrypt_data.get('AgentID', '')
  121. # 返回coze结果
  122. coze_response = call_llm(prompt=user_query,bot_id=bot_id,coze_access_token = coze_access_token)
  123. answer = coze_response['data'][1]['content']
  124. print(f"结果:{answer}")
  125. # 主动发结果给qiwei
  126. qiwei_post(username, answer, agentid)
  127. @app.get("/bot")
  128. async def verify(msg_signature: str, timestamp: str, nonce: str, echostr: str):
  129. ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
  130. if ret == 0:
  131. return Response(content=sEchoStr.decode('utf-8'))
  132. else:
  133. print(sEchoStr)
  134. @app.post("/bot")
  135. async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request, background_tasks: BackgroundTasks):
  136. #start_time = time.time()
  137. body = await request.body()
  138. ret, sMsg = wxcpt.DecryptMsg(body.decode('utf-8'), msg_signature, timestamp, nonce)
  139. decrypt_data = {}
  140. for node in list(fromstring(sMsg.decode('utf-8'))):
  141. decrypt_data[node.tag] = node.text
  142. user_query = decrypt_data.get('Content', '')
  143. background_tasks.add_task(consumer, user_query, decrypt_data)
  144. return Response(content="")
  145. if __name__ == "__main__":
  146. uvicorn.run("coze_bot_api:app", port=port, host='0.0.0.0', reload=False,ssl_keyfile="./key.pem", ssl_certfile="./cert.pem")