TalkAi.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from __future__ import annotations
  2. import time, json, time
  3. from ...typing import CreateResult, Messages
  4. from ..base_provider import AbstractProvider
  5. from ...webdriver import WebDriver, WebDriverSession
  6. class TalkAi(AbstractProvider):
  7. url = "https://talkai.info"
  8. working = False
  9. supports_gpt_35_turbo = True
  10. supports_stream = True
  11. @classmethod
  12. def create_completion(
  13. cls,
  14. model: str,
  15. messages: Messages,
  16. stream: bool,
  17. proxy: str = None,
  18. webdriver: WebDriver = None,
  19. **kwargs
  20. ) -> CreateResult:
  21. with WebDriverSession(webdriver, "", virtual_display=True, proxy=proxy) as driver:
  22. from selenium.webdriver.common.by import By
  23. from selenium.webdriver.support.ui import WebDriverWait
  24. from selenium.webdriver.support import expected_conditions as EC
  25. driver.get(f"{cls.url}/chat/")
  26. # Wait for page load
  27. WebDriverWait(driver, 240).until(
  28. EC.presence_of_element_located((By.CSS_SELECTOR, "body.chat-page"))
  29. )
  30. data = {
  31. "type": "chat",
  32. "message": messages[-1]["content"],
  33. "messagesHistory": [{
  34. "from": "you" if message["role"] == "user" else "chatGPT",
  35. "content": message["content"]
  36. } for message in messages],
  37. "model": model if model else "gpt-3.5-turbo",
  38. "max_tokens": 2048,
  39. "temperature": 1,
  40. "top_p": 1,
  41. "presence_penalty": 0,
  42. "frequency_penalty": 0,
  43. **kwargs
  44. }
  45. script = """
  46. const response = await fetch("/chat/send2/", {
  47. "headers": {
  48. "Accept": "application/json",
  49. "Content-Type": "application/json",
  50. },
  51. "body": {body},
  52. "method": "POST"
  53. });
  54. window._reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
  55. """
  56. driver.execute_script(
  57. script.replace("{body}", json.dumps(json.dumps(data)))
  58. )
  59. # Read response
  60. while True:
  61. chunk = driver.execute_script("""
  62. chunk = await window._reader.read();
  63. if (chunk.done) {
  64. return null;
  65. }
  66. content = "";
  67. for (line of chunk.value.split("\\n")) {
  68. if (line.startsWith('data: ')) {
  69. content += line.substring('data: '.length);
  70. }
  71. }
  72. return content;
  73. """)
  74. if chunk:
  75. yield chunk.replace("\\n", "\n")
  76. elif chunk != "":
  77. break
  78. else:
  79. time.sleep(0.1)