chat_service.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. #
  5. import os
  6. import threading
  7. from typing import List, Dict, Optional
  8. from enum import Enum, auto
  9. from logging_service import logger
  10. import cozepy
  11. from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageType, JWTOAuthApp, JWTAuth
  12. import time
  13. from openai import OpenAI
  14. COZE_API_TOKEN = os.getenv("COZE_API_TOKEN")
  15. COZE_CN_BASE_URL = 'https://api.coze.cn'
  16. VOLCENGINE_API_TOKEN = '5e275c38-44fd-415f-abcf-4b59f6377f72'
  17. VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3"
  18. VOLCENGINE_MODEL_DEEPSEEK_V3 = "deepseek-v3-250324"
  19. VOLCENGINE_MODEL_DOUBAO_PRO_1_5 = 'ep-20250307150409-4blz9'
  20. VOLCENGINE_MODEL_DOUBAO_PRO_32K = 'ep-20250414202859-6nkz5'
  21. VOLCENGINE_MODEL_DOUBAO_1_5_VISION_PRO = 'ep-20250421193334-nz5wd'
  22. DEEPSEEK_API_TOKEN = 'sk-67daad8f424f4854bda7f1fed7ef220b'
  23. DEEPSEEK_BASE_URL = 'https://api.deepseek.com/'
  24. DEEPSEEK_CHAT_MODEL = 'deepseek-chat'
  25. class ChatServiceType(Enum):
  26. OPENAI_COMPATIBLE = auto()
  27. COZE_CHAT = auto()
  28. class OpenAICompatible:
  29. @staticmethod
  30. def create_client(model_name):
  31. volcengine_models = [
  32. VOLCENGINE_MODEL_DOUBAO_PRO_32K,
  33. VOLCENGINE_MODEL_DOUBAO_PRO_1_5,
  34. VOLCENGINE_MODEL_DOUBAO_1_5_VISION_PRO,
  35. VOLCENGINE_MODEL_DEEPSEEK_V3
  36. ]
  37. deepseek_models = [
  38. DEEPSEEK_CHAT_MODEL,
  39. ]
  40. if model_name in volcengine_models:
  41. llm_client = OpenAI(api_key=VOLCENGINE_API_TOKEN, base_url=VOLCENGINE_BASE_URL)
  42. elif model_name in deepseek_models:
  43. llm_client = OpenAI(api_key=DEEPSEEK_API_TOKEN, base_url=DEEPSEEK_BASE_URL)
  44. else:
  45. raise Exception("Unsupported model: %s" % model_name)
  46. return llm_client
  47. class CrossAccountJWTOAuthApp(JWTOAuthApp):
  48. def __init__(self, account_id: str, client_id: str, private_key: str, public_key_id: str, base_url):
  49. self.account_id = account_id
  50. super().__init__(client_id, private_key, public_key_id, base_url)
  51. def get_access_token(
  52. self, ttl: int = 900, scope: Optional[cozepy.Scope] = None, session_name: Optional[str] = None
  53. ) -> cozepy.OAuthToken:
  54. jwt_token = self._gen_jwt(self._public_key_id, self._private_key, 3600, session_name)
  55. url = f"{self._base_url}/api/permission/oauth2/account/{self.account_id}/token"
  56. headers = {"Authorization": f"Bearer {jwt_token}"}
  57. body = {
  58. "duration_seconds": ttl,
  59. "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
  60. "scope": scope.model_dump() if scope else None,
  61. }
  62. return self._requester.request("post", url, False, cozepy.OAuthToken, headers=headers, body=body)
  63. class CozeChat:
  64. def __init__(self, base_url: str, auth_token: Optional[str] = None, auth_app: Optional[JWTOAuthApp] = None):
  65. if not auth_token and not auth_app:
  66. raise ValueError("Either auth_token or auth_app must be provided.")
  67. self.thread = None
  68. self.thread_running = False
  69. self.last_token_fresh = 0
  70. if auth_token:
  71. self.coze = Coze(auth=TokenAuth(auth_token), base_url=base_url)
  72. else:
  73. self.auth_app = auth_app
  74. oauth_token = auth_app.get_access_token(ttl=12*3600)
  75. self.last_token_fresh = time.time()
  76. self.coze = Coze(auth=JWTAuth(oauth_app=auth_app), base_url=base_url)
  77. self.setup_token_refresh()
  78. def create(self, bot_id: str, user_id: str, messages: List, custom_variables: Dict):
  79. response = self.coze.chat.create_and_poll(
  80. bot_id=bot_id, user_id=user_id, additional_messages=messages,
  81. custom_variables=custom_variables)
  82. logger.debug("Coze response size: {}".format(len(response.messages)))
  83. if response.chat.status != ChatStatus.COMPLETED:
  84. logger.error("Coze chat not completed: {}".format(response.chat.status))
  85. return None
  86. final_response = None
  87. for message in response.messages:
  88. if message.type == MessageType.ANSWER:
  89. final_response = message.content
  90. return final_response
  91. def setup_token_refresh(self):
  92. self.thread = threading.Thread(target=self.refresh_token_loop)
  93. self.thread.start()
  94. self.thread_running = True
  95. def refresh_token_loop(self):
  96. while self.thread_running:
  97. if time.time() - self.last_token_fresh < 11*3600:
  98. time.sleep(1)
  99. continue
  100. if self.auth_app:
  101. self.auth_app.get_access_token(ttl=12*3600)
  102. self.last_token_fresh = time.time()
  103. def __del__(self):
  104. self.thread_running = False
  105. @staticmethod
  106. def get_oauth_app(client_id, private_key_path, public_key_id, base_url=None, account_id=None) -> JWTOAuthApp:
  107. if not base_url:
  108. base_url = COZE_CN_BASE_URL
  109. with open(private_key_path, "r") as f:
  110. private_key = f.read()
  111. if not account_id:
  112. jwt_oauth_app = JWTOAuthApp(
  113. client_id=str(client_id),
  114. private_key=private_key,
  115. public_key_id=public_key_id,
  116. base_url=base_url,
  117. )
  118. else:
  119. jwt_oauth_app = CrossAccountJWTOAuthApp(
  120. account_id=account_id,
  121. client_id=str(client_id),
  122. private_key=private_key,
  123. public_key_id=public_key_id,
  124. base_url=base_url,
  125. )
  126. return jwt_oauth_app
  127. if __name__ == '__main__':
  128. # Init the Coze client through the access_token.
  129. coze = Coze(auth=TokenAuth(token=COZE_API_TOKEN), base_url=COZE_CN_BASE_URL)
  130. # Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
  131. bot_id = "7491250992952999973"
  132. # The user id identifies the identity of a user. Developers can use a custom business ID
  133. # or a random string.
  134. user_id = "dev_user"
  135. chat = coze.chat.create_and_poll(
  136. bot_id=bot_id,
  137. user_id=user_id,
  138. additional_messages=[Message.build_user_question_text("钱塘江边 樱花开得不错,推荐一个视频吧")],
  139. custom_variables={
  140. 'agent_name': '芳华',
  141. 'agent_age': '25',
  142. 'agent_region': '北京',
  143. 'name': '李明',
  144. 'preferred_nickname': '李叔',
  145. 'age': '70',
  146. 'last_interaction_interval': '12',
  147. 'current_time_period': '上午',
  148. 'if_first_interaction': 'False',
  149. 'if_active_greeting': 'False'
  150. }
  151. )
  152. for message in chat.messages:
  153. print(message, flush=True)
  154. if chat.chat.status == ChatStatus.COMPLETED:
  155. print("token usage:", chat.chat.usage.token_count)