chat_service.py 8.3 KB

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