HuggingChat.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from __future__ import annotations
  2. import json
  3. import requests
  4. from curl_cffi import requests as cf_reqs
  5. from ..typing import CreateResult, Messages
  6. from .base_provider import ProviderModelMixin, AbstractProvider
  7. from .helper import format_prompt
  8. class HuggingChat(AbstractProvider, ProviderModelMixin):
  9. url = "https://huggingface.co/chat"
  10. working = True
  11. supports_stream = True
  12. default_model = "meta-llama/Meta-Llama-3.1-70B-Instruct"
  13. models = [
  14. 'meta-llama/Meta-Llama-3.1-70B-Instruct',
  15. 'CohereForAI/c4ai-command-r-plus-08-2024',
  16. 'Qwen/Qwen2.5-72B-Instruct',
  17. 'nvidia/Llama-3.1-Nemotron-70B-Instruct-HF',
  18. 'Qwen/Qwen2.5-Coder-32B-Instruct',
  19. 'meta-llama/Llama-3.2-11B-Vision-Instruct',
  20. 'NousResearch/Hermes-3-Llama-3.1-8B',
  21. 'mistralai/Mistral-Nemo-Instruct-2407',
  22. 'microsoft/Phi-3.5-mini-instruct',
  23. ]
  24. model_aliases = {
  25. "llama-3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct",
  26. "command-r-plus": "CohereForAI/c4ai-command-r-plus-08-2024",
  27. "qwen-2-72b": "Qwen/Qwen2.5-72B-Instruct",
  28. "nemotron-70b": "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",
  29. "qwen-2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
  30. "llama-3.2-11b": "meta-llama/Llama-3.2-11B-Vision-Instruct",
  31. "hermes-3": "NousResearch/Hermes-3-Llama-3.1-8B",
  32. "mistral-nemo": "mistralai/Mistral-Nemo-Instruct-2407",
  33. "phi-3.5-mini": "microsoft/Phi-3.5-mini-instruct",
  34. }
  35. @classmethod
  36. def get_model(cls, model: str) -> str:
  37. if model in cls.models:
  38. return model
  39. elif model in cls.model_aliases:
  40. return cls.model_aliases[model]
  41. else:
  42. return cls.default_model
  43. @classmethod
  44. def create_completion(
  45. cls,
  46. model: str,
  47. messages: Messages,
  48. stream: bool,
  49. **kwargs
  50. ) -> CreateResult:
  51. model = cls.get_model(model)
  52. if model in cls.models:
  53. session = cf_reqs.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. if response.status_code != 200:
  75. raise RuntimeError(f"Request failed with status code: {response.status_code}, response: {response.text}")
  76. conversationId = response.json().get('conversationId')
  77. # Get the data response and parse it properly
  78. response = session.get(f'https://huggingface.co/chat/conversation/{conversationId}/__data.json?x-sveltekit-invalidated=11')
  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. full_response = ""
  133. for line in response.iter_lines():
  134. if not line:
  135. continue
  136. try:
  137. line = json.loads(line)
  138. except json.JSONDecodeError as e:
  139. print(f"Failed to decode JSON: {line}, error: {e}")
  140. continue
  141. if "type" not in line:
  142. raise RuntimeError(f"Response: {line}")
  143. elif line["type"] == "stream":
  144. token = line["token"].replace('\u0000', '')
  145. full_response += token
  146. if stream:
  147. yield token
  148. elif line["type"] == "finalAnswer":
  149. break
  150. full_response = full_response.replace('<|im_end|', '').replace('\u0000', '').strip()
  151. if not stream:
  152. yield full_response
  153. @classmethod
  154. def supports_model(cls, model: str) -> bool:
  155. """Check if the model is supported by the provider."""
  156. return model in cls.models or model in cls.model_aliases