Qwen_Qwen_2_72B.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from __future__ import annotations
  2. import aiohttp
  3. import json
  4. import uuid
  5. import re
  6. from ...typing import AsyncResult, Messages
  7. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  8. from ..helper import format_prompt
  9. from ... import debug
  10. class Qwen_Qwen_2_72B(AsyncGeneratorProvider, ProviderModelMixin):
  11. label = "Qwen Qwen-2.72B"
  12. url = "https://qwen-qwen2-72b-instruct.hf.space"
  13. api_endpoint = "https://qwen-qwen2-72b-instruct.hf.space/queue/join?"
  14. working = True
  15. supports_stream = True
  16. supports_system_message = True
  17. supports_message_history = False
  18. default_model = "qwen-qwen2-72b-instruct"
  19. model_aliases = {"qwen-2-72b": default_model}
  20. models = list(model_aliases.keys())
  21. @classmethod
  22. async def create_async_generator(
  23. cls,
  24. model: str,
  25. messages: Messages,
  26. proxy: str = None,
  27. **kwargs
  28. ) -> AsyncResult:
  29. def generate_session_hash():
  30. """Generate a unique session hash."""
  31. return str(uuid.uuid4()).replace('-', '')[:12]
  32. # Generate a unique session hash
  33. session_hash = generate_session_hash()
  34. headers_join = {
  35. 'accept': '*/*',
  36. 'accept-language': 'en-US,en;q=0.9',
  37. 'content-type': 'application/json',
  38. 'origin': f'{cls.url}',
  39. 'referer': f'{cls.url}/',
  40. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
  41. }
  42. # Prepare the prompt
  43. system_prompt = "\n".join([message["content"] for message in messages if message["role"] == "system"])
  44. messages = [message for message in messages if message["role"] != "system"]
  45. prompt = format_prompt(messages)
  46. payload_join = {
  47. "data": [prompt, [], system_prompt],
  48. "event_data": None,
  49. "fn_index": 0,
  50. "trigger_id": 11,
  51. "session_hash": session_hash
  52. }
  53. async with aiohttp.ClientSession() as session:
  54. # Send join request
  55. async with session.post(cls.api_endpoint, headers=headers_join, json=payload_join) as response:
  56. event_id = (await response.json())['event_id']
  57. # Prepare data stream request
  58. url_data = f'{cls.url}/queue/data'
  59. headers_data = {
  60. 'accept': 'text/event-stream',
  61. 'accept-language': 'en-US,en;q=0.9',
  62. 'referer': f'{cls.url}/',
  63. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
  64. }
  65. params_data = {
  66. 'session_hash': session_hash
  67. }
  68. # Send data stream request
  69. async with session.get(url_data, headers=headers_data, params=params_data) as response:
  70. full_response = ""
  71. final_full_response = ""
  72. async for line in response.content:
  73. decoded_line = line.decode('utf-8')
  74. if decoded_line.startswith('data: '):
  75. try:
  76. json_data = json.loads(decoded_line[6:])
  77. # Look for generation stages
  78. if json_data.get('msg') == 'process_generating':
  79. if 'output' in json_data and 'data' in json_data['output']:
  80. output_data = json_data['output']['data']
  81. if len(output_data) > 1 and len(output_data[1]) > 0:
  82. for item in output_data[1]:
  83. if isinstance(item, list) and len(item) > 1:
  84. fragment = str(item[1])
  85. # Ignore [0, 1] type fragments and duplicates
  86. if not re.match(r'^\[.*\]$', fragment) and not full_response.endswith(fragment):
  87. full_response += fragment
  88. yield fragment
  89. # Check for completion
  90. if json_data.get('msg') == 'process_completed':
  91. # Final check to ensure we get the complete response
  92. if 'output' in json_data and 'data' in json_data['output']:
  93. output_data = json_data['output']['data']
  94. if len(output_data) > 1 and len(output_data[1]) > 0:
  95. final_full_response = output_data[1][0][1]
  96. # Clean up the final response
  97. if final_full_response.startswith(full_response):
  98. final_full_response = final_full_response[len(full_response):]
  99. # Yield the remaining part of the final response
  100. if final_full_response:
  101. yield final_full_response
  102. break
  103. except json.JSONDecodeError:
  104. debug.log("Could not parse JSON:", decoded_line)