Raycast.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from __future__ import annotations
  2. import json
  3. import requests
  4. from ...typing import CreateResult, Messages
  5. from ..base_provider import AbstractProvider
  6. class Raycast(AbstractProvider):
  7. url = "https://raycast.com"
  8. supports_stream = True
  9. needs_auth = True
  10. working = True
  11. models = [
  12. "gpt-3.5-turbo",
  13. "gpt-4"
  14. ]
  15. @staticmethod
  16. def create_completion(
  17. model: str,
  18. messages: Messages,
  19. stream: bool,
  20. proxy: str = None,
  21. **kwargs,
  22. ) -> CreateResult:
  23. auth = kwargs.get('auth')
  24. if not auth:
  25. raise ValueError("Raycast needs an auth token, pass it with the `auth` parameter")
  26. headers = {
  27. 'Accept': 'application/json',
  28. 'Accept-Language': 'en-US,en;q=0.9',
  29. 'Authorization': f'Bearer {auth}',
  30. 'Content-Type': 'application/json',
  31. 'User-Agent': 'Raycast/0 CFNetwork/1410.0.3 Darwin/22.6.0',
  32. }
  33. parsed_messages = [
  34. {'author': message['role'], 'content': {'text': message['content']}}
  35. for message in messages
  36. ]
  37. data = {
  38. "debug": False,
  39. "locale": "en-CN",
  40. "messages": parsed_messages,
  41. "model": model,
  42. "provider": "openai",
  43. "source": "ai_chat",
  44. "system_instruction": "markdown",
  45. "temperature": 0.5
  46. }
  47. response = requests.post(
  48. "https://backend.raycast.com/api/v1/ai/chat_completions",
  49. headers=headers,
  50. json=data,
  51. stream=True,
  52. proxies={"https": proxy}
  53. )
  54. for token in response.iter_lines():
  55. if b'data: ' not in token:
  56. continue
  57. completion_chunk = json.loads(token.decode().replace('data: ', ''))
  58. token = completion_chunk['text']
  59. if token != None:
  60. yield token