ReplicateHome.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. from __future__ import annotations
  2. import json
  3. import asyncio
  4. from aiohttp import ClientSession, ContentTypeError
  5. from ..typing import AsyncResult, Messages
  6. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  7. from .helper import format_prompt
  8. from ..image import ImageResponse
  9. class ReplicateHome(AsyncGeneratorProvider, ProviderModelMixin):
  10. url = "https://replicate.com"
  11. api_endpoint = "https://homepage.replicate.com/api/prediction"
  12. working = True
  13. supports_stream = True
  14. supports_system_message = True
  15. supports_message_history = True
  16. default_model = 'yorickvp/llava-13b'
  17. image_models = [
  18. 'stability-ai/stable-diffusion-3',
  19. 'bytedance/sdxl-lightning-4step',
  20. 'playgroundai/playground-v2.5-1024px-aesthetic',
  21. ]
  22. text_models = [
  23. 'meta/meta-llama-3-70b-instruct',
  24. 'mistralai/mixtral-8x7b-instruct-v0.1',
  25. 'google-deepmind/gemma-2b-it',
  26. 'yorickvp/llava-13b',
  27. ]
  28. models = text_models + image_models
  29. model_aliases = {
  30. # image_models
  31. "sd-3": "stability-ai/stable-diffusion-3",
  32. "sdxl": "bytedance/sdxl-lightning-4step",
  33. "playground-v2.5": "playgroundai/playground-v2.5-1024px-aesthetic",
  34. # text_models
  35. "gemma-2b": "google-deepmind/gemma-2b-it",
  36. "llava-13b": "yorickvp/llava-13b",
  37. }
  38. model_versions = {
  39. # image_models
  40. 'stability-ai/stable-diffusion-3': "527d2a6296facb8e47ba1eaf17f142c240c19a30894f437feee9b91cc29d8e4f",
  41. 'bytedance/sdxl-lightning-4step': "5f24084160c9089501c1b3545d9be3c27883ae2239b6f412990e82d4a6210f8f",
  42. 'playgroundai/playground-v2.5-1024px-aesthetic': "a45f82a1382bed5c7aeb861dac7c7d191b0fdf74d8d57c4a0e6ed7d4d0bf7d24",
  43. # text_models
  44. "google-deepmind/gemma-2b-it": "dff94eaf770e1fc211e425a50b51baa8e4cac6c39ef074681f9e39d778773626",
  45. "yorickvp/llava-13b": "80537f9eead1a5bfa72d5ac6ea6414379be41d4d4f6679fd776e9535d1eb58bb",
  46. }
  47. @classmethod
  48. def get_model(cls, model: str) -> str:
  49. if model in cls.models:
  50. return model
  51. elif model in cls.model_aliases:
  52. return cls.model_aliases[model]
  53. else:
  54. return cls.default_model
  55. @classmethod
  56. async def create_async_generator(
  57. cls,
  58. model: str,
  59. messages: Messages,
  60. proxy: str = None,
  61. **kwargs
  62. ) -> AsyncResult:
  63. model = cls.get_model(model)
  64. headers = {
  65. "accept": "*/*",
  66. "accept-language": "en-US,en;q=0.9",
  67. "cache-control": "no-cache",
  68. "content-type": "application/json",
  69. "origin": "https://replicate.com",
  70. "pragma": "no-cache",
  71. "priority": "u=1, i",
  72. "referer": "https://replicate.com/",
  73. "sec-ch-ua": '"Not;A=Brand";v="24", "Chromium";v="128"',
  74. "sec-ch-ua-mobile": "?0",
  75. "sec-ch-ua-platform": '"Linux"',
  76. "sec-fetch-dest": "empty",
  77. "sec-fetch-mode": "cors",
  78. "sec-fetch-site": "same-site",
  79. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
  80. }
  81. async with ClientSession(headers=headers) as session:
  82. if model in cls.image_models:
  83. prompt = messages[-1]['content'] if messages else ""
  84. else:
  85. prompt = format_prompt(messages)
  86. data = {
  87. "model": model,
  88. "version": cls.model_versions[model],
  89. "input": {"prompt": prompt},
  90. }
  91. async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
  92. response.raise_for_status()
  93. result = await response.json()
  94. prediction_id = result['id']
  95. poll_url = f"https://homepage.replicate.com/api/poll?id={prediction_id}"
  96. max_attempts = 30
  97. delay = 5
  98. for _ in range(max_attempts):
  99. async with session.get(poll_url, proxy=proxy) as response:
  100. response.raise_for_status()
  101. try:
  102. result = await response.json()
  103. except ContentTypeError:
  104. text = await response.text()
  105. try:
  106. result = json.loads(text)
  107. except json.JSONDecodeError:
  108. raise ValueError(f"Unexpected response format: {text}")
  109. if result['status'] == 'succeeded':
  110. if model in cls.image_models:
  111. image_url = result['output'][0]
  112. yield ImageResponse(image_url, "Generated image")
  113. return
  114. else:
  115. for chunk in result['output']:
  116. yield chunk
  117. break
  118. elif result['status'] == 'failed':
  119. raise Exception(f"Prediction failed: {result.get('error')}")
  120. await asyncio.sleep(delay)
  121. if result['status'] != 'succeeded':
  122. raise Exception("Prediction timed out")