当前位置:   article > 正文

撸chatgpt3.5 api backend-api 对接wxbot

撸chatgpt3.5 api backend-api 对接wxbot

功能是实现 web  转api 对接wxbot用,

直接上代码,

1.获取wss url

  1. def get_register_websocket():
  2. # 请求头
  3. url = "https://chat.openai.com/backend-api/register-websocket"
  4. payload = {}
  5. headers = {
  6. 'Authorization': 'Bearer eyJhbGxxxxxxxxxxxxxxxxxP89g',
  7. 'User-Agent': 'PostmanRuntime/7.36.3',
  8. 'Cookie':'__cf_bm=IH7tNQ0qLZkExG1S.9bR8UWdTyUJnvwLVW1hWWAZnjs-1709515826-1.0.1.1-NpxvrgB8g61jflrQqxxxxxxxxxx4w9.McqlfewwIgDg; __cflb=0H28vVfFxgNcKEuU2yRkHrTNV; _cfuvid=VBhrtMcQ4dxRz1xNPv4WWk1.c-1709461045475-0.0.1.1-604800000'
  9. }
  10. response = requests.request("POST", url, headers=headers, data=payload, allow_redirects=False)
  11. # 将文本内容转换为Python字典/列表
  12. try:
  13. json_data = json.loads(response.text)
  14. except json.JSONDecodeError:
  15. print("无法将响应内容解析为JSON格式")
  16. else:
  17. return json_data['wss_url']

返回信息

2.监听wss

 

  1. import asyncio
  2. import websockets
  3. import base64
  4. import json
  5. import os
  6. from urllib.parse import urlparse, parse_qs
  7. import requests
  8. os.environ["http_proxy"] = "http://127.0.0.1:1080"
  9. os.environ["https_proxy"] = "http://127.0.0.1:1080"
  10. def get_register_websocket():
  11. # 请求头
  12. url = "https://chat.openai.com/backend-api/register-websocket"
  13. payload = {}
  14. headers = {
  15. 'Authorization': 'Bearer eyJ***********9g',
  16. 'User-Agent': 'PostmanRuntime/7.36.3',
  17. 'Cookie':'__cf_bm=IH****9515826-1.0.1.1-NpxvrgB8g61jflrQqvaxwnF*******2M1bSfmWkqmJpuyy4w9.McqlfewwIgDg; __cflb=0H28vVfF4aAyg2*yRkHrTNV; _cfuvid=VBhrtMcQ4d***iIs1nWA1Rz1xNPv4WWk1.c-1709461045475-0.0.1.1-604800000'
  18. }
  19. response = requests.request("POST", url, headers=headers, data=payload, allow_redirects=False)
  20. # 将文本内容转换为Python字典/列表
  21. try:
  22. json_data = json.loads(response.text)
  23. except json.JSONDecodeError:
  24. print("无法将响应内容解析为JSON格式")
  25. else:
  26. return json_data['wss_url']
  27. async def listen_to_websocket(url, access_token):
  28. headers = {'Authorization': f'Bearer {access_token}'}
  29. final_message = "" # 初始化空字符串用于累积信息
  30. async with websockets.connect(url, extra_headers=headers) as websocket:
  31. while True:
  32. try:
  33. message = await websocket.recv()
  34. # 解析消息为JSON
  35. message_data = json.loads(message)
  36. # 提取并解码body字段
  37. body_encoded = message_data.get("body", "")
  38. body_decoded = base64.b64decode(body_encoded).decode('utf-8')
  39. # 移除前缀"data: ",然后解析JSON
  40. message_data_json = json.loads(body_decoded[6:])
  41. # 提取parts
  42. parts = message_data_json["message"]["content"]["parts"][0]
  43. # 这里不再直接打印parts,而是更新final_message
  44. final_message = parts # 更新最后一条消息
  45. except websockets.exceptions.ConnectionClosedOK:
  46. print("Connection closed successfully.")
  47. #break
  48. except Exception as e:
  49. print(f"Error occurred: {e}")
  50. break
  51. # 循环结束后,打印最后一次更新的信息
  52. print(final_message)
  53. if __name__ == "__main__":
  54. url = get_register_websocket()
  55. print(url)
  56. parsed_url = urlparse(get_register_websocket())
  57. query_params = parse_qs(parsed_url.query)
  58. # 提取 access_token 的值
  59. access_token_value = query_params['access_token'][0]
  60. asyncio.get_event_loop().run_until_complete(listen_to_websocket(get_register_websocket(), access_token_value))

3.发送问题给gpt

  1. import requests
  2. import json
  3. import os
  4. import uuid
  5. import asyncio
  6. import websockets
  7. import base64
  8. import json
  9. import os
  10. os.environ["http_proxy"] = "http://127.0.0.1:1080"
  11. os.environ["https_proxy"] = "http://127.0.0.1:1080"
  12. url = "https://chat.openai.com/backend-api/conversation"
  13. def askgpt(prompt, conversation_id=None):
  14. # 基本请求结构
  15. message_structure = {
  16. "id": str(uuid.uuid4()),
  17. "author": {"role": "user"},
  18. "content": {"content_type": "text", "parts": [prompt]},
  19. "metadata": {}
  20. }
  21. # 初始化请求payload
  22. payload = {
  23. "action": "next",
  24. "messages": [message_structure],
  25. "model": "text-davinci-002-render-sha",
  26. "timezone_offset_min": -480,
  27. "suggestions": [],
  28. "history_and_training_disabled": False,
  29. "conversation_mode": {"kind": "primary_assistant"},
  30. "force_paragen": False,
  31. "force_rate_limit": False
  32. }
  33. # 根据是否提供conversation_id调整payload
  34. if conversation_id:
  35. payload["conversation_id"] = conversation_id
  36. payload["parent_message_id"] = str(uuid.uuid4()) # 假设每次调用都有新的parent_message_id
  37. # 特定于长对话的字段
  38. payload["websocket_request_id"] = "5e3e28e1-5943-4fce-ae81-8cc0710e61c0"
  39. else:
  40. payload["parent_message_id"] = str(uuid.uuid4()) # 第一次对话的parent_message_id
  41. # 请求头
  42. headers = {
  43. 'Authorization': 'Bearer eyJhb********************P89g',
  44. 'User-Agent': 'PostmanRuntime/7.36.3',
  45. 'Content-Type': 'application/json',
  46. 'Cookie':'__cf_bm=IH7tNQ0qLZkExG1S.9bR8UWdTyUJnvwLVW1hWWAZnjs-1709515826-1.0.1.1-NpxvrgB8g61jflr*********wIgDg; __cflb=0H28*V; _cfuvid=VBhrtMcQ4d******WWk1.c-1709461045475-0.0.1.1-604800000'
  47. }
  48. response = requests.post( url, headers=headers, json=payload, allow_redirects=False)
  49. print(response.text)
  50. conversation_id = None # conversation ID here
  51. #conversation_id = str(uuid.uuid4())
  52. #askgpt("10+1",conversation_id)
  53. askgpt("你的模型","4af92768-50c4-425b-b63e-35e3eaede0ce")

在监听窗口可以获取到gpt3.5回答的广播信息 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/193454
推荐阅读
相关标签
  

闽ICP备14008679号