ChatForAi.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from __future__ import annotations
  2. import time
  3. import hashlib
  4. from ..typing import AsyncResult, Messages
  5. from ..requests import StreamSession
  6. from .base_provider import AsyncGeneratorProvider
  7. class ChatForAi(AsyncGeneratorProvider):
  8. url = "https://chatforai.store"
  9. working = True
  10. supports_message_history = True
  11. supports_gpt_35_turbo = True
  12. @classmethod
  13. async def create_async_generator(
  14. cls,
  15. model: str,
  16. messages: Messages,
  17. proxy: str = None,
  18. timeout: int = 120,
  19. **kwargs
  20. ) -> AsyncResult:
  21. headers = {
  22. "Content-Type": "text/plain;charset=UTF-8",
  23. "Origin": cls.url,
  24. "Referer": f"{cls.url}/?r=b",
  25. }
  26. async with StreamSession(impersonate="chrome107", headers=headers, proxies={"https": proxy}, timeout=timeout) as session:
  27. prompt = messages[-1]["content"]
  28. timestamp = int(time.time() * 1e3)
  29. conversation_id = f"id_{timestamp-123}"
  30. data = {
  31. "conversationId": conversation_id,
  32. "conversationType": "chat_continuous",
  33. "botId": "chat_continuous",
  34. "globalSettings":{
  35. "baseUrl": "https://api.openai.com",
  36. "model": model if model else "gpt-3.5-turbo",
  37. "messageHistorySize": 5,
  38. "temperature": 0.7,
  39. "top_p": 1,
  40. **kwargs
  41. },
  42. "botSettings": {},
  43. "prompt": prompt,
  44. "messages": messages,
  45. "timestamp": timestamp,
  46. "sign": generate_signature(timestamp, prompt, conversation_id)
  47. }
  48. async with session.post(f"{cls.url}/api/handle/provider-openai", json=data) as response:
  49. response.raise_for_status()
  50. async for chunk in response.iter_content():
  51. if b"https://chatforai.store" in chunk:
  52. raise RuntimeError(f"Response: {chunk.decode()}")
  53. yield chunk.decode()
  54. def generate_signature(timestamp: int, message: str, id: str):
  55. buffer = f"{timestamp}:{id}:{message}:7YN8z6d6"
  56. return hashlib.sha256(buffer.encode()).hexdigest()