webscout 8.3.2__py3-none-any.whl → 8.3.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (117) hide show
  1. webscout/AIutel.py +367 -41
  2. webscout/Bard.py +2 -22
  3. webscout/Bing_search.py +1 -2
  4. webscout/Provider/AISEARCH/__init__.py +1 -0
  5. webscout/Provider/AISEARCH/scira_search.py +24 -11
  6. webscout/Provider/AISEARCH/stellar_search.py +132 -0
  7. webscout/Provider/Deepinfra.py +75 -57
  8. webscout/Provider/ExaChat.py +93 -63
  9. webscout/Provider/Flowith.py +1 -1
  10. webscout/Provider/FreeGemini.py +2 -2
  11. webscout/Provider/Gemini.py +3 -10
  12. webscout/Provider/GeminiProxy.py +31 -5
  13. webscout/Provider/HeckAI.py +85 -80
  14. webscout/Provider/Jadve.py +56 -50
  15. webscout/Provider/LambdaChat.py +39 -31
  16. webscout/Provider/MiniMax.py +207 -0
  17. webscout/Provider/Nemotron.py +41 -13
  18. webscout/Provider/Netwrck.py +39 -59
  19. webscout/Provider/OLLAMA.py +8 -9
  20. webscout/Provider/OPENAI/BLACKBOXAI.py +0 -1
  21. webscout/Provider/OPENAI/MiniMax.py +298 -0
  22. webscout/Provider/OPENAI/README.md +31 -30
  23. webscout/Provider/OPENAI/TogetherAI.py +4 -17
  24. webscout/Provider/OPENAI/__init__.py +4 -2
  25. webscout/Provider/OPENAI/autoproxy.py +753 -18
  26. webscout/Provider/OPENAI/base.py +7 -76
  27. webscout/Provider/OPENAI/copilot.py +73 -26
  28. webscout/Provider/OPENAI/deepinfra.py +96 -132
  29. webscout/Provider/OPENAI/exachat.py +9 -5
  30. webscout/Provider/OPENAI/flowith.py +179 -166
  31. webscout/Provider/OPENAI/friendli.py +233 -0
  32. webscout/Provider/OPENAI/monochat.py +329 -0
  33. webscout/Provider/OPENAI/netwrck.py +4 -7
  34. webscout/Provider/OPENAI/pydantic_imports.py +1 -172
  35. webscout/Provider/OPENAI/qodo.py +630 -0
  36. webscout/Provider/OPENAI/scirachat.py +82 -49
  37. webscout/Provider/OPENAI/textpollinations.py +13 -12
  38. webscout/Provider/OPENAI/toolbaz.py +1 -0
  39. webscout/Provider/OPENAI/typegpt.py +4 -4
  40. webscout/Provider/OPENAI/utils.py +19 -42
  41. webscout/Provider/OPENAI/x0gpt.py +14 -2
  42. webscout/Provider/OpenGPT.py +54 -32
  43. webscout/Provider/PI.py +58 -84
  44. webscout/Provider/Qodo.py +454 -0
  45. webscout/Provider/StandardInput.py +32 -13
  46. webscout/Provider/TTI/README.md +9 -9
  47. webscout/Provider/TTI/__init__.py +2 -1
  48. webscout/Provider/TTI/aiarta.py +92 -78
  49. webscout/Provider/TTI/infip.py +212 -0
  50. webscout/Provider/TTI/monochat.py +220 -0
  51. webscout/Provider/TeachAnything.py +11 -3
  52. webscout/Provider/TextPollinationsAI.py +91 -82
  53. webscout/Provider/TogetherAI.py +32 -48
  54. webscout/Provider/Venice.py +37 -46
  55. webscout/Provider/VercelAI.py +27 -24
  56. webscout/Provider/WiseCat.py +35 -35
  57. webscout/Provider/WrDoChat.py +22 -26
  58. webscout/Provider/WritingMate.py +26 -22
  59. webscout/Provider/__init__.py +6 -6
  60. webscout/Provider/copilot.py +58 -61
  61. webscout/Provider/freeaichat.py +64 -55
  62. webscout/Provider/granite.py +48 -57
  63. webscout/Provider/koala.py +51 -39
  64. webscout/Provider/learnfastai.py +49 -64
  65. webscout/Provider/llmchat.py +79 -93
  66. webscout/Provider/llmchatco.py +63 -78
  67. webscout/Provider/monochat.py +275 -0
  68. webscout/Provider/multichat.py +51 -40
  69. webscout/Provider/oivscode.py +1 -1
  70. webscout/Provider/scira_chat.py +257 -104
  71. webscout/Provider/scnet.py +13 -13
  72. webscout/Provider/searchchat.py +13 -13
  73. webscout/Provider/sonus.py +12 -11
  74. webscout/Provider/toolbaz.py +25 -8
  75. webscout/Provider/turboseek.py +41 -42
  76. webscout/Provider/typefully.py +27 -12
  77. webscout/Provider/typegpt.py +43 -48
  78. webscout/Provider/uncovr.py +55 -90
  79. webscout/Provider/x0gpt.py +325 -299
  80. webscout/Provider/yep.py +79 -96
  81. webscout/__init__.py +7 -2
  82. webscout/auth/__init__.py +12 -1
  83. webscout/auth/providers.py +27 -5
  84. webscout/auth/routes.py +146 -105
  85. webscout/auth/server.py +367 -312
  86. webscout/client.py +121 -116
  87. webscout/litagent/Readme.md +68 -55
  88. webscout/litagent/agent.py +99 -9
  89. webscout/version.py +1 -1
  90. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/METADATA +102 -91
  91. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/RECORD +95 -107
  92. webscout/Provider/AI21.py +0 -177
  93. webscout/Provider/HuggingFaceChat.py +0 -469
  94. webscout/Provider/OPENAI/freeaichat.py +0 -363
  95. webscout/Provider/TTI/fastflux.py +0 -233
  96. webscout/Provider/Writecream.py +0 -246
  97. webscout/auth/static/favicon.svg +0 -11
  98. webscout/auth/swagger_ui.py +0 -203
  99. webscout/auth/templates/components/authentication.html +0 -237
  100. webscout/auth/templates/components/base.html +0 -103
  101. webscout/auth/templates/components/endpoints.html +0 -750
  102. webscout/auth/templates/components/examples.html +0 -491
  103. webscout/auth/templates/components/footer.html +0 -75
  104. webscout/auth/templates/components/header.html +0 -27
  105. webscout/auth/templates/components/models.html +0 -286
  106. webscout/auth/templates/components/navigation.html +0 -70
  107. webscout/auth/templates/static/api.js +0 -455
  108. webscout/auth/templates/static/icons.js +0 -168
  109. webscout/auth/templates/static/main.js +0 -784
  110. webscout/auth/templates/static/particles.js +0 -201
  111. webscout/auth/templates/static/styles.css +0 -3353
  112. webscout/auth/templates/static/ui.js +0 -374
  113. webscout/auth/templates/swagger_ui.html +0 -170
  114. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/WHEEL +0 -0
  115. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/entry_points.txt +0 -0
  116. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/licenses/LICENSE.md +0 -0
  117. {webscout-8.3.2.dist-info → webscout-8.3.4.dist-info}/top_level.txt +0 -0
@@ -1,299 +1,325 @@
1
- from typing import Optional, Union, Any, Dict
2
- from uuid import uuid4
3
- from curl_cffi import CurlError
4
- from curl_cffi.requests import Session
5
- import re
6
-
7
- from webscout.AIutel import Optimizers
8
- from webscout.AIutel import Conversation
9
- from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
10
- from webscout.AIbase import Provider
11
- from webscout import exceptions
12
- from webscout.litagent import LitAgent
13
- # Import HTTPVersion enum
14
- from curl_cffi.const import CurlHttpVersion
15
-
16
- class X0GPT(Provider):
17
- """
18
- A class to interact with the x0-gpt.devwtf.in API.
19
-
20
- Attributes:
21
- system_prompt (str): The system prompt to define the assistant's role.
22
-
23
- Examples:
24
- >>> from webscout.Provider.x0gpt import X0GPT
25
- >>> ai = X0GPT()
26
- >>> response = ai.chat("What's the weather today?")
27
- >>> print(response)
28
- 'The weather today is sunny with a high of 75°F.'
29
- """
30
- AVAILABLE_MODELS = ["UNKNOWN"]
31
-
32
- def __init__(
33
- self,
34
- is_conversation: bool = True,
35
- max_tokens: int = 600,
36
- timeout: int = 30,
37
- intro: str = None,
38
- filepath: str = None,
39
- update_file: bool = True,
40
- proxies: dict = {},
41
- history_offset: int = 10250,
42
- act: str = None,
43
- system_prompt: str = "You are a helpful assistant.",
44
- model: str = "UNKNOWN"
45
- ):
46
- """
47
- Initializes the X0GPT API with given parameters.
48
-
49
- Args:
50
- is_conversation (bool): Whether the provider is in conversation mode.
51
- max_tokens (int): Maximum number of tokens to sample.
52
- timeout (int): Timeout for API requests.
53
- intro (str): Introduction message for the conversation.
54
- filepath (str): Filepath for storing conversation history.
55
- update_file (bool): Whether to update the conversation history file.
56
- proxies (dict): Proxies for the API requests.
57
- history_offset (int): Offset for conversation history.
58
- act (str): Act for the conversation.
59
- system_prompt (str): The system prompt to define the assistant's role.
60
-
61
- Examples:
62
- >>> ai = X0GPT(system_prompt="You are a friendly assistant.")
63
- >>> print(ai.system_prompt)
64
- 'You are a friendly assistant.'
65
- """
66
- # Initialize curl_cffi Session instead of requests.Session
67
- self.session = Session()
68
- self.is_conversation = is_conversation
69
- self.max_tokens_to_sample = max_tokens
70
- self.api_endpoint = "https://x0-gpt.devwtf.in/api/stream/reply"
71
- self.timeout = timeout
72
- self.last_response = {}
73
- self.system_prompt = system_prompt
74
-
75
- # Initialize LitAgent for user agent generation
76
- self.agent = LitAgent()
77
-
78
- self.headers = {
79
- "authority": "x0-gpt.devwtf.in",
80
- "method": "POST",
81
- "path": "/api/stream/reply",
82
- "scheme": "https",
83
- "accept": "*/*",
84
- "accept-encoding": "gzip, deflate, br, zstd", # Keep zstd for now
85
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
86
- # "content-length": "114", # Let curl_cffi handle content-length
87
- "content-type": "application/json",
88
- "dnt": "1",
89
- "origin": "https://x0-gpt.devwtf.in",
90
- # "priority": "u=1, i", # Remove priority header
91
- "referer": "https://x0-gpt.devwtf.in/chat",
92
- "sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
93
- "sec-ch-ua-mobile": "?0",
94
- "sec-ch-ua-platform": '"Windows"',
95
- "user-agent": self.agent.random()
96
- }
97
-
98
- self.__available_optimizers = (
99
- method
100
- for method in dir(Optimizers)
101
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
102
- )
103
- # Update curl_cffi session headers and proxies
104
- self.session.headers.update(self.headers)
105
- self.session.proxies = proxies
106
-
107
- Conversation.intro = (
108
- AwesomePrompts().get_act(
109
- act, raise_not_found=True, default=None, case_insensitive=True
110
- )
111
- if act
112
- else intro or Conversation.intro
113
- )
114
- self.conversation = Conversation(
115
- is_conversation, self.max_tokens_to_sample, filepath, update_file
116
- )
117
- self.conversation.history_offset = history_offset
118
-
119
- @staticmethod
120
- def _x0gpt_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
121
- """Extracts content from the x0gpt stream format '0:"..."'."""
122
- if isinstance(chunk, str):
123
- match = re.search(r'0:"(.*?)"', chunk)
124
- if match:
125
- # Decode potential unicode escapes like \u00e9
126
- content = match.group(1).encode().decode('unicode_escape')
127
- return content.replace('\\\\', '\\').replace('\\"', '"') # Handle escaped backslashes and quotes
128
- return None
129
-
130
- def ask(
131
- self,
132
- prompt: str,
133
- stream: bool = False,
134
- raw: bool = False,
135
- optimizer: str = None,
136
- conversationally: bool = False,
137
- ) -> Dict[str, Any]:
138
- """
139
- Sends a prompt to the x0-gpt.devwtf.in API and returns the response.
140
-
141
- Args:
142
- prompt (str): The prompt to send to the API.
143
- stream (bool): Whether to stream the response.
144
- raw (bool): Whether to return the raw response.
145
- optimizer (str): Optimizer to use for the prompt.
146
- conversationally (bool): Whether to generate the prompt conversationally.
147
-
148
- Returns:
149
- Dict[str, Any]: The API response.
150
-
151
- Examples:
152
- >>> ai = X0GPT()
153
- >>> response = ai.ask("Tell me a joke!")
154
- >>> print(response)
155
- {'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}
156
- """
157
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
158
- if optimizer:
159
- if optimizer in self.__available_optimizers:
160
- conversation_prompt = getattr(Optimizers, optimizer)(
161
- conversation_prompt if conversationally else prompt
162
- )
163
- else:
164
- raise Exception(
165
- f"Optimizer is not one of {self.__available_optimizers}"
166
- )
167
-
168
- payload = {
169
- "messages": [
170
- {"role": "system", "content": self.system_prompt},
171
- {"role": "user", "content": conversation_prompt}
172
- ],
173
- "chatId": uuid4().hex,
174
- "namespace": None
175
- }
176
-
177
- def for_stream():
178
- try:
179
- # Use curl_cffi session post with updated impersonate and http_version
180
- response = self.session.post(
181
- self.api_endpoint,
182
- headers=self.headers,
183
- json=payload,
184
- stream=True,
185
- timeout=self.timeout,
186
- impersonate="chrome120", # Try a different impersonation profile
187
- http_version=CurlHttpVersion.V1_1 # Force HTTP/1.1
188
- )
189
- if not response.ok:
190
- raise exceptions.FailedToGenerateResponseError(
191
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
192
- )
193
-
194
- streaming_response = ""
195
- # Use sanitize_stream with the custom extractor
196
- processed_stream = sanitize_stream(
197
- data=response.iter_content(chunk_size=None), # Pass byte iterator
198
- intro_value=None, # No simple prefix to remove here
199
- to_json=False, # Content is not JSON
200
- content_extractor=self._x0gpt_extractor # Use the specific extractor
201
- )
202
-
203
- for content_chunk in processed_stream:
204
- if content_chunk and isinstance(content_chunk, str):
205
- streaming_response += content_chunk
206
- yield content_chunk if raw else dict(text=content_chunk)
207
-
208
- self.last_response.update(dict(text=streaming_response))
209
- self.conversation.update_chat_history(
210
- prompt, self.get_message(self.last_response)
211
- )
212
- except CurlError as e: # Catch CurlError
213
- raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}")
214
- except Exception as e: # Catch other potential exceptions
215
- # Include the original exception type in the message for clarity
216
- raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}")
217
-
218
- def for_non_stream():
219
- # This function implicitly uses the updated for_stream
220
- for _ in for_stream():
221
- pass
222
- return self.last_response
223
-
224
- return for_stream() if stream else for_non_stream()
225
-
226
- def chat(
227
- self,
228
- prompt: str,
229
- stream: bool = False,
230
- optimizer: str = None,
231
- conversationally: bool = False,
232
- ) -> str:
233
- """
234
- Generates a response from the X0GPT API.
235
-
236
- Args:
237
- prompt (str): The prompt to send to the API.
238
- stream (bool): Whether to stream the response.
239
- optimizer (str): Optimizer to use for the prompt.
240
- conversationally (bool): Whether to generate the prompt conversationally.
241
-
242
- Returns:
243
- str: The API response.
244
-
245
- Examples:
246
- >>> ai = X0GPT()
247
- >>> response = ai.chat("What's the weather today?")
248
- >>> print(response)
249
- 'The weather today is sunny with a high of 75°F.'
250
- """
251
-
252
- def for_stream():
253
- for response in self.ask(
254
- prompt, True, optimizer=optimizer, conversationally=conversationally
255
- ):
256
- yield self.get_message(response)
257
-
258
- def for_non_stream():
259
- return self.get_message(
260
- self.ask(
261
- prompt,
262
- False,
263
- optimizer=optimizer,
264
- conversationally=conversationally,
265
- )
266
- )
267
-
268
- return for_stream() if stream else for_non_stream()
269
-
270
- def get_message(self, response: dict) -> str:
271
- """
272
- Extracts the message from the API response.
273
-
274
- Args:
275
- response (dict): The API response.
276
-
277
- Returns:
278
- str: The message content.
279
-
280
- Examples:
281
- >>> ai = X0GPT()
282
- >>> response = ai.ask("Tell me a joke!")
283
- >>> message = ai.get_message(response)
284
- >>> print(message)
285
- 'Why did the scarecrow win an award? Because he was outstanding in his field!'
286
- """
287
- assert isinstance(response, dict), "Response should be of dict data-type only"
288
- # Ensure text exists before processing
289
- text = response.get("text", "")
290
- # Formatting is now mostly handled by the extractor, just return
291
- formatted_text = text
292
- return formatted_text
293
-
294
- if __name__ == "__main__":
295
- from rich import print
296
- ai = X0GPT(timeout=5000)
297
- response = ai.chat("write a poem about AI", stream=True)
298
- for chunk in response:
299
- print(chunk, end="", flush=True)
1
+ from typing import Generator, Optional, Union, Any, Dict
2
+ from uuid import uuid4
3
+ from curl_cffi import CurlError
4
+ from curl_cffi.requests import Session
5
+ import re
6
+
7
+ from webscout.AIutel import Optimizers
8
+ from webscout.AIutel import Conversation
9
+ from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
10
+ from webscout.AIbase import Provider
11
+ from webscout import exceptions
12
+ from webscout.litagent import LitAgent
13
+ # Import HTTPVersion enum
14
+ from curl_cffi.const import CurlHttpVersion
15
+
16
+ class X0GPT(Provider):
17
+ """
18
+ A class to interact with the x0-gpt.devwtf.in API.
19
+
20
+ Attributes:
21
+ system_prompt (str): The system prompt to define the assistant's role.
22
+
23
+ Examples:
24
+ >>> from webscout.Provider.x0gpt import X0GPT
25
+ >>> ai = X0GPT()
26
+ >>> response = ai.chat("What's the weather today?")
27
+ >>> print(response)
28
+ 'The weather today is sunny with a high of 75°F.'
29
+ """
30
+ AVAILABLE_MODELS = ["UNKNOWN"]
31
+
32
+ def __init__(
33
+ self,
34
+ is_conversation: bool = True,
35
+ max_tokens: int = 600,
36
+ timeout: int = 30,
37
+ intro: str = None,
38
+ filepath: str = None,
39
+ update_file: bool = True,
40
+ proxies: dict = {},
41
+ history_offset: int = 10250,
42
+ act: str = None,
43
+ system_prompt: str = "You are a helpful assistant.",
44
+ model: str = "UNKNOWN"
45
+ ):
46
+ """
47
+ Initializes the X0GPT API with given parameters.
48
+
49
+ Args:
50
+ is_conversation (bool): Whether the provider is in conversation mode.
51
+ max_tokens (int): Maximum number of tokens to sample.
52
+ timeout (int): Timeout for API requests.
53
+ intro (str): Introduction message for the conversation.
54
+ filepath (str): Filepath for storing conversation history.
55
+ update_file (bool): Whether to update the conversation history file.
56
+ proxies (dict): Proxies for the API requests.
57
+ history_offset (int): Offset for conversation history.
58
+ act (str): Act for the conversation.
59
+ system_prompt (str): The system prompt to define the assistant's role.
60
+
61
+ Examples:
62
+ >>> ai = X0GPT(system_prompt="You are a friendly assistant.")
63
+ >>> print(ai.system_prompt)
64
+ 'You are a friendly assistant.'
65
+ """
66
+ # Initialize curl_cffi Session instead of requests.Session
67
+ self.session = Session()
68
+ self.is_conversation = is_conversation
69
+ self.max_tokens_to_sample = max_tokens
70
+ self.api_endpoint = "https://x0-gpt.devwtf.in/api/stream/reply"
71
+ self.timeout = timeout
72
+ self.last_response = {}
73
+ self.system_prompt = system_prompt
74
+
75
+ # Initialize LitAgent for user agent generation
76
+ self.agent = LitAgent()
77
+
78
+ self.headers = {
79
+ "authority": "x0-gpt.devwtf.in",
80
+ "method": "POST",
81
+ "path": "/api/stream/reply",
82
+ "scheme": "https",
83
+ "accept": "*/*",
84
+ "accept-encoding": "gzip, deflate, br, zstd", # Keep zstd for now
85
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
86
+ # "content-length": "114", # Let curl_cffi handle content-length
87
+ "content-type": "application/json",
88
+ "dnt": "1",
89
+ "origin": "https://x0-gpt.devwtf.in",
90
+ # "priority": "u=1, i", # Remove priority header
91
+ "referer": "https://x0-gpt.devwtf.in/chat",
92
+ "sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
93
+ "sec-ch-ua-mobile": "?0",
94
+ "sec-ch-ua-platform": '"Windows"',
95
+ "user-agent": self.agent.random()
96
+ }
97
+
98
+ self.__available_optimizers = (
99
+ method
100
+ for method in dir(Optimizers)
101
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
102
+ )
103
+ # Update curl_cffi session headers and proxies
104
+ self.session.headers.update(self.headers)
105
+ self.session.proxies = proxies
106
+
107
+ Conversation.intro = (
108
+ AwesomePrompts().get_act(
109
+ act, raise_not_found=True, default=None, case_insensitive=True
110
+ )
111
+ if act
112
+ else intro or Conversation.intro
113
+ )
114
+ self.conversation = Conversation(
115
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
116
+ )
117
+ self.conversation.history_offset = history_offset
118
+
119
+ def ask(
120
+ self,
121
+ prompt: str,
122
+ stream: bool = False,
123
+ raw: bool = False,
124
+ optimizer: str = None,
125
+ conversationally: bool = False,
126
+ ) -> Union[Dict[str, Any], Generator]:
127
+ """
128
+ Sends a prompt to the x0-gpt.devwtf.in API and returns the response.
129
+
130
+ Args:
131
+ prompt (str): The prompt to send to the API.
132
+ stream (bool): Whether to stream the response.
133
+ raw (bool): Whether to return the raw response.
134
+ optimizer (str): Optimizer to use for the prompt.
135
+ conversationally (bool): Whether to generate the prompt conversationally.
136
+
137
+ Returns:
138
+ Dict[str, Any]: The API response.
139
+
140
+ Examples:
141
+ >>> ai = X0GPT()
142
+ >>> response = ai.ask("Tell me a joke!")
143
+ >>> print(response)
144
+ {'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}
145
+ """
146
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
147
+ if optimizer:
148
+ if optimizer in self.__available_optimizers:
149
+ conversation_prompt = getattr(Optimizers, optimizer)(
150
+ conversation_prompt if conversationally else prompt
151
+ )
152
+ else:
153
+ raise Exception(
154
+ f"Optimizer is not one of {self.__available_optimizers}"
155
+ )
156
+
157
+ payload = {
158
+ "messages": [
159
+ {"role": "system", "content": self.system_prompt},
160
+ {"role": "user", "content": conversation_prompt}
161
+ ],
162
+ "chatId": uuid4().hex,
163
+ "namespace": None
164
+ }
165
+
166
+ def for_stream():
167
+ try:
168
+ # Use curl_cffi session post with updated impersonate and http_version
169
+ response = self.session.post(
170
+ self.api_endpoint,
171
+ headers=self.headers,
172
+ json=payload,
173
+ stream=True,
174
+ timeout=self.timeout,
175
+ impersonate="chrome120", # Try a different impersonation profile
176
+ http_version=CurlHttpVersion.V1_1 # Force HTTP/1.1
177
+ )
178
+ if not response.ok:
179
+ raise exceptions.FailedToGenerateResponseError(
180
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
181
+ )
182
+
183
+ streaming_response = ""
184
+ # Use sanitize_stream with regex-based extraction and filtering
185
+ processed_stream = sanitize_stream(
186
+ data=response.iter_content(chunk_size=None), # Pass byte iterator
187
+ intro_value=None, # No simple prefix to remove here
188
+ to_json=False, # Content is not JSON
189
+ # Use regex to extract content from x0gpt format '0:"..."'
190
+ extract_regexes=[r'0:"(.*?)"'],
191
+ # Skip empty chunks, connection status messages, and control characters
192
+ skip_regexes=[
193
+ r'^\s*$', # Empty lines
194
+ r'data:\s*\[DONE\]', # Stream end markers
195
+ r'event:\s*', # SSE event headers
196
+ r'^\d+:\s*$', # Standalone numbers
197
+ r'^:\s*$', # Colon-only lines
198
+ r'^\s*[\x00-\x1f]+\s*$' # Control characters
199
+ ],
200
+ raw=raw
201
+ )
202
+
203
+ for content_chunk in processed_stream:
204
+ # Always yield as string, even in raw mode
205
+ if isinstance(content_chunk, bytes):
206
+ content_chunk = content_chunk.decode('utf-8', errors='ignore')
207
+
208
+ if raw:
209
+ yield content_chunk
210
+ else:
211
+ if content_chunk and isinstance(content_chunk, str):
212
+ # Handle unicode escapes and clean up the content
213
+ try:
214
+ # Decode unicode escapes like \u00e9
215
+ clean_content = content_chunk.encode().decode('unicode_escape')
216
+ # Handle escaped backslashes and quotes
217
+ clean_content = clean_content.replace('\\\\', '\\').replace('\\"', '"')
218
+ streaming_response += clean_content
219
+ yield dict(text=clean_content)
220
+ except (UnicodeDecodeError, UnicodeEncodeError):
221
+ # Fallback to original content if unicode processing fails
222
+ streaming_response += content_chunk
223
+ yield dict(text=content_chunk)
224
+
225
+ self.last_response.update(dict(text=streaming_response))
226
+ self.conversation.update_chat_history(
227
+ prompt, self.get_message(self.last_response)
228
+ )
229
+ except CurlError as e: # Catch CurlError
230
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}")
231
+ except Exception as e: # Catch other potential exceptions
232
+ # Include the original exception type in the message for clarity
233
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}")
234
+
235
+ def for_non_stream():
236
+ # This function implicitly uses the updated for_stream
237
+ if stream:
238
+ return for_stream()
239
+ for _ in for_stream():
240
+ pass
241
+ return self.last_response
242
+
243
+ return for_stream() if stream else for_non_stream()
244
+
245
+ def chat(
246
+ self,
247
+ prompt: str,
248
+ stream: bool = False,
249
+ optimizer: str = None,
250
+ conversationally: bool = False,
251
+ raw: bool = False, # Added raw parameter
252
+ ) -> Union[str, Generator[str, None, None]]:
253
+ """
254
+ Generates a response from the X0GPT API.
255
+
256
+ Args:
257
+ prompt (str): The prompt to send to the API.
258
+ stream (bool): Whether to stream the response.
259
+ optimizer (str): Optimizer to use for the prompt.
260
+ conversationally (bool): Whether to generate the prompt conversationally.
261
+ raw (bool): Whether to return raw response chunks.
262
+
263
+ Returns:
264
+ str: The API response.
265
+
266
+ Examples:
267
+ >>> ai = X0GPT()
268
+ >>> response = ai.chat("What's the weather today?")
269
+ >>> print(response)
270
+ 'The weather today is sunny with a high of 75°F.'
271
+ """
272
+
273
+ def for_stream():
274
+ for response in self.ask(
275
+ prompt, True, raw=raw, optimizer=optimizer, conversationally=conversationally
276
+ ):
277
+ if raw:
278
+ yield response
279
+ else:
280
+ yield self.get_message(response)
281
+
282
+ def for_non_stream():
283
+ result = self.ask(
284
+ prompt,
285
+ False,
286
+ raw=raw,
287
+ optimizer=optimizer,
288
+ conversationally=conversationally,
289
+ )
290
+ if raw:
291
+ return result
292
+ else:
293
+ return self.get_message(result)
294
+
295
+ return for_stream() if stream else for_non_stream()
296
+
297
+ def get_message(self, response: dict) -> str:
298
+ """
299
+ Extracts the message from the API response.
300
+
301
+ Args:
302
+ response (dict): The API response.
303
+
304
+ Returns:
305
+ str: The message content.
306
+
307
+ Examples:
308
+ >>> ai = X0GPT()
309
+ >>> response = ai.ask("Tell me a joke!")
310
+ >>> message = ai.get_message(response)
311
+ >>> print(message)
312
+ 'Why did the scarecrow win an award? Because he was outstanding in his field!'
313
+ """
314
+ assert isinstance(response, dict), "Response should be of dict data-type only"
315
+ # Ensure text exists before processing
316
+ text = response.get("text", "")
317
+ # Text is now cleaned by the regex-based sanitize_stream processing
318
+ return text
319
+
320
+ if __name__ == "__main__":
321
+ from rich import print
322
+ ai = X0GPT(timeout=5000)
323
+ response = ai.chat("write a poem about AI", stream=True, raw=False)
324
+ for chunk in response:
325
+ print(chunk, end="", flush=True)