HuggingChat.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. from __future__ import annotations
  2. import json
  3. import requests
  4. try:
  5. from curl_cffi.requests import Session
  6. has_curl_cffi = True
  7. except ImportError:
  8. has_curl_cffi = False
  9. from ..typing import CreateResult, Messages
  10. from ..errors import MissingRequirementsError
  11. from ..requests.raise_for_status import raise_for_status
  12. from .base_provider import ProviderModelMixin, AbstractProvider
  13. from .helper import format_prompt
  14. class HuggingChat(AbstractProvider, ProviderModelMixin):
  15. url = "https://huggingface.co/chat"
  16. working = True
  17. supports_stream = True
  18. default_model = "meta-llama/Meta-Llama-3.1-70B-Instruct"
  19. models = [
  20. 'meta-llama/Meta-Llama-3.1-70B-Instruct',
  21. 'CohereForAI/c4ai-command-r-plus-08-2024',
  22. 'Qwen/Qwen2.5-72B-Instruct',
  23. 'nvidia/Llama-3.1-Nemotron-70B-Instruct-HF',
  24. 'Qwen/Qwen2.5-Coder-32B-Instruct',
  25. 'meta-llama/Llama-3.2-11B-Vision-Instruct',
  26. 'NousResearch/Hermes-3-Llama-3.1-8B',
  27. 'mistralai/Mistral-Nemo-Instruct-2407',
  28. 'microsoft/Phi-3.5-mini-instruct',
  29. ]
  30. model_aliases = {
  31. "llama-3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct",
  32. "command-r-plus": "CohereForAI/c4ai-command-r-plus-08-2024",
  33. "qwen-2-72b": "Qwen/Qwen2.5-72B-Instruct",
  34. "nemotron-70b": "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",
  35. "qwen-2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
  36. "llama-3.2-11b": "meta-llama/Llama-3.2-11B-Vision-Instruct",
  37. "hermes-3": "NousResearch/Hermes-3-Llama-3.1-8B",
  38. "mistral-nemo": "mistralai/Mistral-Nemo-Instruct-2407",
  39. "phi-3.5-mini": "microsoft/Phi-3.5-mini-instruct",
  40. }
  41. @classmethod
  42. def create_completion(
  43. cls,
  44. model: str,
  45. messages: Messages,
  46. stream: bool,
  47. **kwargs
  48. ) -> CreateResult:
  49. if not has_curl_cffi:
  50. raise MissingRequirementsError('Install "curl_cffi" package | pip install -U curl_cffi')
  51. model = cls.get_model(model)
  52. if model in cls.models:
  53. session = Session()
  54. session.headers = {
  55. 'accept': '*/*',
  56. 'accept-language': 'en',
  57. 'cache-control': 'no-cache',
  58. 'origin': 'https://huggingface.co',
  59. 'pragma': 'no-cache',
  60. 'priority': 'u=1, i',
  61. 'referer': 'https://huggingface.co/chat/',
  62. 'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
  63. 'sec-ch-ua-mobile': '?0',
  64. 'sec-ch-ua-platform': '"macOS"',
  65. 'sec-fetch-dest': 'empty',
  66. 'sec-fetch-mode': 'cors',
  67. 'sec-fetch-site': 'same-origin',
  68. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
  69. }
  70. json_data = {
  71. 'model': model,
  72. }
  73. response = session.post('https://huggingface.co/chat/conversation', json=json_data)
  74. raise_for_status(response)
  75. conversationId = response.json().get('conversationId')
  76. # Get the data response and parse it properly
  77. response = session.get(f'https://huggingface.co/chat/conversation/{conversationId}/__data.json?x-sveltekit-invalidated=11')
  78. raise_for_status(response)
  79. # Split the response content by newlines and parse each line as JSON
  80. try:
  81. json_data = None
  82. for line in response.text.split('\n'):
  83. if line.strip():
  84. try:
  85. parsed = json.loads(line)
  86. if isinstance(parsed, dict) and "nodes" in parsed:
  87. json_data = parsed
  88. break
  89. except json.JSONDecodeError:
  90. continue
  91. if not json_data:
  92. raise RuntimeError("Failed to parse response data")
  93. data: list = json_data["nodes"][1]["data"]
  94. keys: list[int] = data[data[0]["messages"]]
  95. message_keys: dict = data[keys[0]]
  96. messageId: str = data[message_keys["id"]]
  97. except (KeyError, IndexError, TypeError) as e:
  98. raise RuntimeError(f"Failed to extract message ID: {str(e)}")
  99. settings = {
  100. "inputs": format_prompt(messages),
  101. "id": messageId,
  102. "is_retry": False,
  103. "is_continue": False,
  104. "web_search": False,
  105. "tools": []
  106. }
  107. headers = {
  108. 'accept': '*/*',
  109. 'accept-language': 'en',
  110. 'cache-control': 'no-cache',
  111. 'origin': 'https://huggingface.co',
  112. 'pragma': 'no-cache',
  113. 'priority': 'u=1, i',
  114. 'referer': f'https://huggingface.co/chat/conversation/{conversationId}',
  115. 'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
  116. 'sec-ch-ua-mobile': '?0',
  117. 'sec-ch-ua-platform': '"macOS"',
  118. 'sec-fetch-dest': 'empty',
  119. 'sec-fetch-mode': 'cors',
  120. 'sec-fetch-site': 'same-origin',
  121. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
  122. }
  123. files = {
  124. 'data': (None, json.dumps(settings, separators=(',', ':'))),
  125. }
  126. response = requests.post(
  127. f'https://huggingface.co/chat/conversation/{conversationId}',
  128. cookies=session.cookies,
  129. headers=headers,
  130. files=files,
  131. )
  132. raise_for_status(response)
  133. full_response = ""
  134. for line in response.iter_lines():
  135. if not line:
  136. continue
  137. try:
  138. line = json.loads(line)
  139. except json.JSONDecodeError as e:
  140. print(f"Failed to decode JSON: {line}, error: {e}")
  141. continue
  142. if "type" not in line:
  143. raise RuntimeError(f"Response: {line}")
  144. elif line["type"] == "stream":
  145. token = line["token"].replace('\u0000', '')
  146. full_response += token
  147. if stream:
  148. yield token
  149. elif line["type"] == "finalAnswer":
  150. break
  151. full_response = full_response.replace('<|im_end|', '').replace('\u0000', '').strip()
  152. if not stream:
  153. yield full_response