llm_call.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding:utf-8 -*-
  2. """
  3. @author: isaacqyang
  4. @time: 2023/9/19
  5. @desc:
  6. """
  7. import time
  8. import requests
  9. from config import BaseConfig
  10. from .logger import get_logger
  11. logger_error = get_logger("error")
  12. def f_file_upload(file_path: str):
  13. req_head = {
  14. "Authorization": BaseConfig.token,
  15. }
  16. with open(file_path, 'rb') as file:
  17. res = requests.post(BaseConfig.file_upload_url, headers=req_head, files={'file': file})
  18. res_json = res.json()
  19. print(res_json)
  20. return res_json['data']['id']
  21. def call_llm(prompt: str, content_type="text"):
  22. req_head = {
  23. "Authorization": BaseConfig.token,
  24. "Content-Type": "application/json",
  25. }
  26. req_data = {
  27. "bot_id": BaseConfig.bot_id,
  28. "user_id": "test",
  29. "stream": False,
  30. "auto_save_history": True,
  31. "additional_messages": [
  32. {
  33. "role": "user",
  34. "content": prompt,
  35. "content_type": content_type
  36. }
  37. ]
  38. }
  39. res_create = requests.post(" https://api.coze.cn/v1/conversation/create",
  40. headers=req_head)
  41. coversition_id = res_create.json()["data"]["id"]
  42. res_chat = requests.post(f" https://api.coze.cn/v3/chat?conversation_id={coversition_id}",
  43. headers=req_head, json=req_data)
  44. chat_id = res_chat.json()["data"]["id"]
  45. while True:
  46. res_retrieve = requests.get(
  47. f" https://api.coze.cn/v3/chat/retrieve?chat_id={chat_id}&conversation_id={coversition_id}",
  48. headers=req_head)
  49. # print(res_retrieve.json()["data"]["status"])
  50. status = res_retrieve.json()["data"]["status"]
  51. if status == "completed":
  52. res_message = requests.get(
  53. f" https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={coversition_id}",
  54. headers=req_head)
  55. res_json = res_message.json()
  56. print(res_json)
  57. data = res_json['data']
  58. for msg in data:
  59. if msg["type"] == "answer":
  60. return msg["content"]
  61. time.sleep(1)