ReplicateHome.py 5.1 KB

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