chat_service.py 7.8 KB

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