PollinationsAI.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from __future__ import annotations
  2. from urllib.parse import quote
  3. import random
  4. import requests
  5. from aiohttp import ClientSession
  6. from ..typing import AsyncResult, Messages
  7. from ..image import ImageResponse
  8. from ..requests.raise_for_status import raise_for_status
  9. from ..requests.aiohttp import get_connector
  10. from .needs_auth.OpenaiAPI import OpenaiAPI
  11. from .helper import format_prompt
  12. class PollinationsAI(OpenaiAPI):
  13. label = "Pollinations.AI"
  14. url = "https://pollinations.ai"
  15. working = True
  16. supports_stream = True
  17. default_model = "openai"
  18. @classmethod
  19. def get_models(cls):
  20. if not cls.image_models:
  21. url = "https://image.pollinations.ai/models"
  22. response = requests.get(url)
  23. raise_for_status(response)
  24. cls.image_models = response.json()
  25. if not cls.models:
  26. url = "https://text.pollinations.ai/models"
  27. response = requests.get(url)
  28. raise_for_status(response)
  29. cls.models = [model.get("name") for model in response.json()]
  30. cls.models.extend(cls.image_models)
  31. return cls.models
  32. @classmethod
  33. async def create_async_generator(
  34. cls,
  35. model: str,
  36. messages: Messages,
  37. prompt: str = None,
  38. api_base: str = "https://text.pollinations.ai/openai",
  39. api_key: str = None,
  40. proxy: str = None,
  41. seed: str = None,
  42. **kwargs
  43. ) -> AsyncResult:
  44. if model:
  45. model = cls.get_model(model)
  46. if model in cls.image_models:
  47. if prompt is None:
  48. prompt = messages[-1]["content"]
  49. if seed is None:
  50. seed = random.randint(0, 100000)
  51. image = f"https://image.pollinations.ai/prompt/{quote(prompt)}?width=1024&height=1024&seed={int(seed)}&nofeed=true&nologo=true&model={quote(model)}"
  52. yield ImageResponse(image, prompt)
  53. return
  54. if api_key is None:
  55. async with ClientSession(connector=get_connector(proxy=proxy)) as session:
  56. prompt = format_prompt(messages)
  57. async with session.get(f"https://text.pollinations.ai/{quote(prompt)}?model={quote(model)}") as response:
  58. await raise_for_status(response)
  59. async for line in response.content.iter_any():
  60. yield line.decode(errors="ignore")
  61. else:
  62. async for chunk in super().create_async_generator(
  63. model, messages, api_base=api_base, proxy=proxy, **kwargs
  64. ):
  65. yield chunk