llm_call.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. # content_type text object_string
  23. req_head = {
  24. "Authorization": BaseConfig.token,
  25. "Content-Type": "application/json",
  26. }
  27. req_data = {
  28. "bot_id": BaseConfig.bot_id,
  29. "user_id": "test",
  30. "stream": False,
  31. "auto_save_history": True,
  32. "additional_messages": [
  33. {
  34. "role": "user",
  35. "content": prompt,
  36. "content_type": content_type
  37. }
  38. ]
  39. }
  40. res_create = requests.post(" https://api.coze.cn/v1/conversation/create",
  41. headers=req_head)
  42. coversition_id = res_create.json()["data"]["id"]
  43. res_chat = requests.post(f" https://api.coze.cn/v3/chat?conversation_id={coversition_id}",
  44. headers=req_head, json=req_data)
  45. chat_id = res_chat.json()["data"]["id"]
  46. while True:
  47. res_retrieve = requests.get(
  48. f" https://api.coze.cn/v3/chat/retrieve?chat_id={chat_id}&conversation_id={coversition_id}",
  49. headers=req_head)
  50. # print(res_retrieve.json()["data"]["status"])
  51. status = res_retrieve.json()["data"]["status"]
  52. if status == "completed":
  53. res_message = requests.get(
  54. f" https://api.coze.cn/v3/chat/message/list?chat_id={chat_id}&conversation_id={coversition_id}",
  55. headers=req_head)
  56. res_json = res_message.json()
  57. print(res_json)
  58. data = res_json['data']
  59. for msg in data:
  60. if msg["type"] == "answer":
  61. return msg["content"]
  62. time.sleep(1)