TeachAnything.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from __future__ import annotations
  2. from typing import Any, Dict
  3. from aiohttp import ClientSession, ClientTimeout
  4. from ..typing import AsyncResult, Messages
  5. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  6. from .helper import format_prompt
  7. class TeachAnything(AsyncGeneratorProvider, ProviderModelMixin):
  8. url = "https://www.teach-anything.com"
  9. api_endpoint = "/api/generate"
  10. working = True
  11. default_model = 'gemini-1.5-pro'
  12. models = [default_model, 'gemini-1.5-flash']
  13. @classmethod
  14. async def create_async_generator(
  15. cls,
  16. model: str,
  17. messages: Messages,
  18. proxy: str | None = None,
  19. **kwargs: Any
  20. ) -> AsyncResult:
  21. headers = cls._get_headers()
  22. model = cls.get_model(model)
  23. async with ClientSession(headers=headers) as session:
  24. prompt = format_prompt(messages)
  25. data = {"prompt": prompt}
  26. timeout = ClientTimeout(total=60)
  27. async with session.post(
  28. f"{cls.url}{cls.api_endpoint}",
  29. json=data,
  30. proxy=proxy,
  31. timeout=timeout
  32. ) as response:
  33. response.raise_for_status()
  34. buffer = b""
  35. async for chunk in response.content.iter_any():
  36. buffer += chunk
  37. try:
  38. decoded = buffer.decode('utf-8')
  39. yield decoded
  40. buffer = b""
  41. except UnicodeDecodeError:
  42. # If we can't decode, we'll wait for more data
  43. continue
  44. # Handle any remaining data in the buffer
  45. if buffer:
  46. try:
  47. yield buffer.decode('utf-8', errors='replace')
  48. except Exception as e:
  49. print(f"Error decoding final buffer: {e}")
  50. @staticmethod
  51. def _get_headers() -> Dict[str, str]:
  52. return {
  53. "accept": "*/*",
  54. "accept-language": "en-US,en;q=0.9",
  55. "cache-control": "no-cache",
  56. "content-type": "application/json",
  57. "dnt": "1",
  58. "origin": "https://www.teach-anything.com",
  59. "pragma": "no-cache",
  60. "priority": "u=1, i",
  61. "referer": "https://www.teach-anything.com/",
  62. "sec-ch-us": '"Not?A_Brand";v="99", "Chromium";v="130"',
  63. "sec-ch-us-mobile": "?0",
  64. "sec-ch-us-platform": '"Linux"',
  65. "sec-fetch-dest": "empty",
  66. "sec-fetch-mode": "cors",
  67. "sec-fetch-site": "same-origin",
  68. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
  69. }