TeachAnything.py 3.0 KB

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