TalkAi.py 2.6 KB

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