webscout 8.3.5__py3-none-any.whl → 8.3.7__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 (159) hide show
  1. webscout/AIutel.py +2 -0
  2. webscout/Bard.py +12 -6
  3. webscout/DWEBS.py +66 -57
  4. webscout/Provider/{UNFINISHED → AISEARCH}/PERPLEXED_search.py +34 -74
  5. webscout/Provider/AISEARCH/__init__.py +18 -11
  6. webscout/Provider/AISEARCH/scira_search.py +3 -1
  7. webscout/Provider/Aitopia.py +2 -3
  8. webscout/Provider/Andi.py +3 -3
  9. webscout/Provider/ChatGPTClone.py +1 -1
  10. webscout/Provider/ChatSandbox.py +1 -0
  11. webscout/Provider/Cloudflare.py +1 -1
  12. webscout/Provider/Cohere.py +1 -0
  13. webscout/Provider/Deepinfra.py +13 -10
  14. webscout/Provider/ExaAI.py +1 -1
  15. webscout/Provider/ExaChat.py +1 -80
  16. webscout/Provider/Flowith.py +6 -1
  17. webscout/Provider/Gemini.py +7 -5
  18. webscout/Provider/GeminiProxy.py +1 -0
  19. webscout/Provider/GithubChat.py +4 -1
  20. webscout/Provider/Groq.py +1 -1
  21. webscout/Provider/HeckAI.py +8 -4
  22. webscout/Provider/Jadve.py +23 -38
  23. webscout/Provider/K2Think.py +308 -0
  24. webscout/Provider/Koboldai.py +8 -186
  25. webscout/Provider/LambdaChat.py +2 -4
  26. webscout/Provider/Nemotron.py +3 -4
  27. webscout/Provider/Netwrck.py +6 -8
  28. webscout/Provider/OLLAMA.py +1 -0
  29. webscout/Provider/OPENAI/Cloudflare.py +6 -7
  30. webscout/Provider/OPENAI/FalconH1.py +2 -7
  31. webscout/Provider/OPENAI/FreeGemini.py +6 -8
  32. webscout/Provider/OPENAI/{monochat.py → K2Think.py} +180 -77
  33. webscout/Provider/OPENAI/NEMOTRON.py +3 -6
  34. webscout/Provider/OPENAI/PI.py +5 -4
  35. webscout/Provider/OPENAI/Qwen3.py +2 -3
  36. webscout/Provider/OPENAI/README.md +2 -1
  37. webscout/Provider/OPENAI/TogetherAI.py +52 -57
  38. webscout/Provider/OPENAI/TwoAI.py +3 -4
  39. webscout/Provider/OPENAI/__init__.py +17 -56
  40. webscout/Provider/OPENAI/ai4chat.py +313 -303
  41. webscout/Provider/OPENAI/base.py +9 -29
  42. webscout/Provider/OPENAI/chatgpt.py +7 -2
  43. webscout/Provider/OPENAI/chatgptclone.py +4 -7
  44. webscout/Provider/OPENAI/chatsandbox.py +84 -59
  45. webscout/Provider/OPENAI/deepinfra.py +12 -6
  46. webscout/Provider/OPENAI/e2b.py +60 -8
  47. webscout/Provider/OPENAI/flowith.py +4 -3
  48. webscout/Provider/OPENAI/generate_api_key.py +48 -0
  49. webscout/Provider/OPENAI/heckai.py +4 -1
  50. webscout/Provider/OPENAI/netwrck.py +9 -12
  51. webscout/Provider/OPENAI/refact.py +274 -0
  52. webscout/Provider/OPENAI/scirachat.py +6 -0
  53. webscout/Provider/OPENAI/textpollinations.py +3 -14
  54. webscout/Provider/OPENAI/toolbaz.py +14 -10
  55. webscout/Provider/OpenGPT.py +1 -1
  56. webscout/Provider/Openai.py +150 -402
  57. webscout/Provider/PI.py +1 -0
  58. webscout/Provider/Perplexitylabs.py +1 -2
  59. webscout/Provider/QwenLM.py +107 -89
  60. webscout/Provider/STT/__init__.py +17 -2
  61. webscout/Provider/{Llama3.py → Sambanova.py} +9 -10
  62. webscout/Provider/StandardInput.py +1 -1
  63. webscout/Provider/TTI/__init__.py +18 -12
  64. webscout/Provider/TTI/bing.py +14 -2
  65. webscout/Provider/TTI/together.py +10 -9
  66. webscout/Provider/TTS/README.md +0 -1
  67. webscout/Provider/TTS/__init__.py +18 -11
  68. webscout/Provider/TTS/base.py +479 -159
  69. webscout/Provider/TTS/deepgram.py +409 -156
  70. webscout/Provider/TTS/elevenlabs.py +425 -111
  71. webscout/Provider/TTS/freetts.py +317 -140
  72. webscout/Provider/TTS/gesserit.py +192 -128
  73. webscout/Provider/TTS/murfai.py +248 -113
  74. webscout/Provider/TTS/openai_fm.py +347 -129
  75. webscout/Provider/TTS/speechma.py +620 -586
  76. webscout/Provider/TeachAnything.py +1 -0
  77. webscout/Provider/TextPollinationsAI.py +5 -15
  78. webscout/Provider/TogetherAI.py +136 -142
  79. webscout/Provider/TwoAI.py +53 -309
  80. webscout/Provider/TypliAI.py +2 -1
  81. webscout/Provider/{GizAI.py → UNFINISHED/GizAI.py} +1 -1
  82. webscout/Provider/UNFINISHED/VercelAIGateway.py +339 -0
  83. webscout/Provider/Venice.py +2 -1
  84. webscout/Provider/VercelAI.py +1 -0
  85. webscout/Provider/WiseCat.py +2 -1
  86. webscout/Provider/WrDoChat.py +2 -1
  87. webscout/Provider/__init__.py +18 -174
  88. webscout/Provider/ai4chat.py +1 -1
  89. webscout/Provider/akashgpt.py +7 -10
  90. webscout/Provider/cerebras.py +194 -38
  91. webscout/Provider/chatglm.py +170 -83
  92. webscout/Provider/cleeai.py +1 -2
  93. webscout/Provider/deepseek_assistant.py +1 -1
  94. webscout/Provider/elmo.py +1 -1
  95. webscout/Provider/geminiapi.py +1 -1
  96. webscout/Provider/granite.py +1 -1
  97. webscout/Provider/hermes.py +1 -3
  98. webscout/Provider/julius.py +1 -0
  99. webscout/Provider/learnfastai.py +1 -1
  100. webscout/Provider/llama3mitril.py +1 -1
  101. webscout/Provider/llmchat.py +1 -1
  102. webscout/Provider/llmchatco.py +1 -1
  103. webscout/Provider/meta.py +3 -3
  104. webscout/Provider/oivscode.py +2 -2
  105. webscout/Provider/scira_chat.py +51 -124
  106. webscout/Provider/searchchat.py +1 -0
  107. webscout/Provider/sonus.py +1 -1
  108. webscout/Provider/toolbaz.py +15 -11
  109. webscout/Provider/turboseek.py +31 -22
  110. webscout/Provider/typefully.py +2 -1
  111. webscout/Provider/x0gpt.py +1 -0
  112. webscout/Provider/yep.py +2 -1
  113. webscout/conversation.py +22 -20
  114. webscout/sanitize.py +14 -10
  115. webscout/scout/README.md +20 -23
  116. webscout/scout/core/crawler.py +125 -38
  117. webscout/scout/core/scout.py +26 -5
  118. webscout/tempid.py +6 -0
  119. webscout/version.py +1 -1
  120. webscout/webscout_search.py +13 -6
  121. webscout/webscout_search_async.py +10 -8
  122. webscout/yep_search.py +13 -5
  123. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/METADATA +3 -1
  124. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/RECORD +132 -155
  125. webscout/Provider/AllenAI.py +0 -440
  126. webscout/Provider/Blackboxai.py +0 -793
  127. webscout/Provider/FreeGemini.py +0 -250
  128. webscout/Provider/Glider.py +0 -225
  129. webscout/Provider/Hunyuan.py +0 -283
  130. webscout/Provider/MCPCore.py +0 -322
  131. webscout/Provider/MiniMax.py +0 -207
  132. webscout/Provider/OPENAI/BLACKBOXAI.py +0 -1045
  133. webscout/Provider/OPENAI/MiniMax.py +0 -298
  134. webscout/Provider/OPENAI/autoproxy.py +0 -1067
  135. webscout/Provider/OPENAI/c4ai.py +0 -394
  136. webscout/Provider/OPENAI/copilot.py +0 -305
  137. webscout/Provider/OPENAI/glider.py +0 -330
  138. webscout/Provider/OPENAI/mcpcore.py +0 -431
  139. webscout/Provider/OPENAI/multichat.py +0 -378
  140. webscout/Provider/Reka.py +0 -214
  141. webscout/Provider/TTS/sthir.py +0 -94
  142. webscout/Provider/UNFINISHED/fetch_together_models.py +0 -90
  143. webscout/Provider/asksteve.py +0 -220
  144. webscout/Provider/copilot.py +0 -422
  145. webscout/Provider/freeaichat.py +0 -294
  146. webscout/Provider/koala.py +0 -182
  147. webscout/Provider/lmarena.py +0 -198
  148. webscout/Provider/monochat.py +0 -275
  149. webscout/Provider/multichat.py +0 -375
  150. webscout/Provider/scnet.py +0 -244
  151. webscout/Provider/talkai.py +0 -194
  152. /webscout/Provider/{Marcus.py → UNFINISHED/Marcus.py} +0 -0
  153. /webscout/Provider/{Qodo.py → UNFINISHED/Qodo.py} +0 -0
  154. /webscout/Provider/{XenAI.py → UNFINISHED/XenAI.py} +0 -0
  155. /webscout/Provider/{samurai.py → UNFINISHED/samurai.py} +0 -0
  156. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/WHEEL +0 -0
  157. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/entry_points.txt +0 -0
  158. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/licenses/LICENSE.md +0 -0
  159. {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/top_level.txt +0 -0
@@ -1,250 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- FreeGemini API client for the free-gemini.vercel.app service.
4
- Supports streaming responses from Gemini 2.0 Flash model.
5
- """
6
-
7
- import json
8
- from curl_cffi.requests import Session
9
- from curl_cffi import CurlError
10
- from typing import Dict, Generator, Any, Union, Optional
11
-
12
- from webscout import exceptions
13
- from webscout.AIutel import Optimizers, AwesomePrompts, sanitize_stream
14
- from webscout.conversation import Conversation
15
- from webscout.litagent import LitAgent
16
- from webscout.AIbase import Provider
17
-
18
-
19
- class FreeGemini(Provider):
20
- """
21
- A class to interact with the free-gemini.vercel.app API,
22
- which provides access to Gemini models.
23
- """
24
- AVAILABLE_MODELS = ["gemini-2.0-flash"]
25
-
26
- @staticmethod
27
- def _gemini_extractor(data: Dict) -> Optional[str]:
28
- """Extract text content from Gemini API response."""
29
- try:
30
- if "candidates" in data and data["candidates"]:
31
- candidate = data["candidates"][0]
32
- if "content" in candidate and "parts" in candidate["content"]:
33
- parts = candidate["content"]["parts"]
34
- if parts and "text" in parts[0]:
35
- return parts[0]["text"]
36
- except (KeyError, IndexError, TypeError):
37
- pass
38
- return None
39
-
40
- def __init__(
41
- self,
42
- is_conversation: bool = True,
43
- max_tokens: int = 4000,
44
- temperature: float = 0.5,
45
- top_p: float = 1.0,
46
- timeout: int = 120, # Default timeout for this specific API
47
- proxies: dict = {}, # Standard proxy support
48
- filepath: str = None,
49
- update_file: bool = True,
50
- history_offset: int = 10250,
51
- intro: str = None,
52
- act: str = None,
53
- model: str = "gemini-2.0-flash",
54
- system_prompt: str = "You are a helpful assistant.", # For consistency, though not directly used in payload
55
- ):
56
- """Initialize the FreeGemini client.
57
-
58
- Args:
59
- is_conversation (bool): Enable conversation history. Defaults to True.
60
- max_tokens (int): Maximum tokens to sample. Defaults to 4000.
61
- temperature (float): Sampling temperature. Defaults to 0.5.
62
- top_p (float): Nucleus sampling parameter. Defaults to 1.0.
63
- timeout (int): Request timeout in seconds. Defaults to 120.
64
- proxies (dict): HTTP proxies. Defaults to {}.
65
- filepath (str, optional): Path to save conversation history. Defaults to None.
66
- update_file (bool): Update conversation history file. Defaults to True.
67
- history_offset (int): Limit conversation history. Defaults to 10250.
68
- intro (str, optional): Introduction for the conversation.
69
- act (str, optional): Act for AwesomePrompts.
70
- model (str): Model to use. Defaults to "gemini-2.0-flash".
71
- system_prompt (str): System prompt (primarily for API consistency).
72
- """
73
- if model not in self.AVAILABLE_MODELS:
74
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
75
-
76
- self.session = Session()
77
- self.model = model
78
- self.is_conversation = is_conversation
79
- self.max_tokens_to_sample = max_tokens # Consistent naming
80
- self.temperature = temperature
81
- self.top_p = top_p
82
- self.timeout = timeout
83
- self.last_response = {}
84
- self.system_prompt = system_prompt # Stored for consistency
85
-
86
- self.api_endpoint = "https://free-gemini.vercel.app/api/google/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
87
-
88
- self.agent = LitAgent()
89
- self.headers = {
90
- "Content-Type": "application/json",
91
- "Accept": "application/json, text/event-stream",
92
- "User-Agent": self.agent.random(),
93
- "Origin": "https://free-gemini.vercel.app",
94
- "Referer": "https://free-gemini.vercel.app/",
95
- }
96
-
97
- self.session.headers.update(self.headers)
98
- self.session.proxies = proxies
99
-
100
- self.__available_optimizers = (
101
- method for method in dir(Optimizers)
102
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
103
- )
104
- Conversation.intro = (
105
- AwesomePrompts().get_act(act, raise_not_found=True, default=None, case_insensitive=True)
106
- if act else intro or Conversation.intro
107
- )
108
- self.conversation = Conversation(
109
- is_conversation, self.max_tokens_to_sample, filepath, update_file
110
- )
111
- self.conversation.history_offset = history_offset
112
-
113
- def ask(
114
- self,
115
- prompt: str,
116
- stream: bool = False, # Default to False for consistency
117
- raw: bool = False,
118
- optimizer: str = None,
119
- conversationally: bool = False,
120
- ) -> Union[Dict[str, Any], Generator]:
121
- """Sends a prompt to the FreeGemini API and returns the response.
122
-
123
- Args:
124
- prompt (str): The prompt to send to the model.
125
- stream (bool): Whether to stream the response. Defaults to False.
126
- raw (bool): Return raw response instead of parsed text. Defaults to False.
127
- optimizer (str, optional): Optimizer to use for the prompt.
128
- conversationally (bool, optional): Whether to apply optimizer conversationally.
129
-
130
- Returns:
131
- Union[Dict[str, Any], Generator[Dict[str, Any], None, None]]:
132
- The generated response as a dictionary or generator.
133
- """
134
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
135
- if optimizer:
136
- if optimizer in self.__available_optimizers:
137
- conversation_prompt = getattr(Optimizers, optimizer)(
138
- conversation_prompt if conversationally else prompt
139
- )
140
- else:
141
- raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
142
-
143
- payload = {
144
- "contents": [{"role": "user", "parts": [{"text": conversation_prompt}]}],
145
- "generationConfig": {
146
- "temperature": self.temperature,
147
- "maxOutputTokens": self.max_tokens_to_sample,
148
- "topP": self.top_p
149
- },
150
- "safetySettings": [
151
- # Default safety settings from original class
152
- {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"},
153
- {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_ONLY_HIGH"},
154
- {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_ONLY_HIGH"},
155
- {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_ONLY_HIGH"}
156
- ]
157
- }
158
-
159
- # Internal generator for handling API call and history update
160
- def _generate_content_and_update_history():
161
- streaming_text_accumulator = ""
162
- try:
163
- response = self.session.post(
164
- self.api_endpoint,
165
- json=payload,
166
- stream=True, # API always streams
167
- timeout=self.timeout,
168
- impersonate="chrome120"
169
- )
170
- response.raise_for_status()
171
-
172
- processed_stream = sanitize_stream(
173
- data=response.iter_content(chunk_size=None),
174
- intro_value="data:",
175
- to_json=True,
176
- content_extractor=self._gemini_extractor,
177
- yield_raw_on_error=False
178
- )
179
-
180
- for content_chunk_str in processed_stream: # yields string
181
- if content_chunk_str and isinstance(content_chunk_str, str):
182
- streaming_text_accumulator += content_chunk_str
183
- yield content_chunk_str # Yield the raw text chunk
184
-
185
- except CurlError as e:
186
- raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
187
- except Exception as e:
188
- raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {str(e)}") from e
189
- finally:
190
- if streaming_text_accumulator:
191
- self.last_response = {"text": streaming_text_accumulator}
192
- self.conversation.update_chat_history(prompt, streaming_text_accumulator)
193
-
194
- if stream:
195
- def stream_wrapper():
196
- for text_chunk in _generate_content_and_update_history():
197
- yield {"text": text_chunk} if not raw else text_chunk
198
- return stream_wrapper()
199
- else: # Not streaming from the perspective of the caller of `ask`
200
- full_text_response = ""
201
- for text_chunk in _generate_content_and_update_history():
202
- full_text_response += text_chunk
203
-
204
- # self.last_response and history are updated by the generator's `finally`
205
- return {"text": full_text_response} if not raw else full_text_response
206
-
207
- def chat(
208
- self,
209
- prompt: str,
210
- stream: bool = False,
211
- optimizer: str = None,
212
- conversationally: bool = False,
213
- ) -> Union[str, Generator[str, None, None]]:
214
- """Generates a response from the FreeGemini API.
215
-
216
- Args:
217
- prompt (str): The prompt to send to the API.
218
- stream (bool): Whether to stream the response.
219
- optimizer (str): Optimizer to use for the prompt.
220
- conversationally (bool): Whether to generate the prompt conversationally.
221
-
222
- Returns:
223
- Union[str, Generator[str, None, None]]: The API response.
224
- """
225
- def for_stream_chat():
226
- gen = self.ask(
227
- prompt, stream=True, raw=False, # Ensure ask yields dicts
228
- optimizer=optimizer, conversationally=conversationally
229
- )
230
- for response_dict in gen:
231
- yield self.get_message(response_dict)
232
-
233
- def for_non_stream_chat():
234
- response_data = self.ask(
235
- prompt, stream=False, raw=False, # Ensure ask returns dict
236
- optimizer=optimizer, conversationally=conversationally
237
- )
238
- return self.get_message(response_data)
239
-
240
- return for_stream_chat() if stream else for_non_stream_chat()
241
-
242
- def get_message(self, response: dict) -> str:
243
- assert isinstance(response, dict), "Response should be of dict data-type only"
244
- return response.get("text", "")
245
-
246
- if __name__ == "__main__":
247
- # Example usage
248
- free_gemini = FreeGemini()
249
- response = free_gemini.chat("how many r in strawberry", stream=False)
250
- print(response) # Should print the response from the API
@@ -1,225 +0,0 @@
1
- import cloudscraper
2
- # from curl_cffi.requests import Session
3
- import json
4
- from typing import Union, Any, Dict, Generator, Optional, List
5
-
6
- from curl_cffi import CurlError
7
-
8
- from webscout.AIutel import Optimizers, Conversation, AwesomePrompts, sanitize_stream # Import sanitize_stream
9
- from webscout.AIbase import Provider
10
- from webscout import exceptions
11
- from webscout.litagent import LitAgent as Lit
12
-
13
- class GliderAI(Provider):
14
- """
15
- A class to interact with the Glider.so API.
16
- """
17
-
18
- AVAILABLE_MODELS = [
19
- "chat-llama-3-1-8b",
20
- "chat-llama-3-2-3b",
21
- "chat-deepseek-r1-qwen-32b",
22
- "chat-qwen-2-5-7b",
23
- "chat-qwen-qwq-32b",
24
- "deepseek-ai/DeepSeek-R1",
25
- ]
26
-
27
- def __init__(
28
- self,
29
- is_conversation: bool = True,
30
- max_tokens: int = 600,
31
- timeout: int = 30,
32
- intro: Optional[str] = None,
33
- filepath: Optional[str] = None,
34
- update_file: bool = True,
35
- proxies: dict = {},
36
- history_offset: int = 10250,
37
- act: Optional[str] = None,
38
- model: str = "chat-llama-3-1-8b",
39
- system_prompt: str = "You are a helpful AI assistant."
40
- ):
41
- """Initializes the GliderAI API client."""
42
- if model not in self.AVAILABLE_MODELS:
43
- raise ValueError(f"Invalid model: {model}. Choose from: {', '.join(self.AVAILABLE_MODELS)}")
44
-
45
- self.session = cloudscraper.create_scraper() # Use cloudscraper Session
46
- self.is_conversation = is_conversation
47
- self.max_tokens_to_sample = max_tokens
48
- self.api_endpoint = "https://glider.so/api/chat"
49
- self.stream_chunk_size = 64
50
- self.timeout = timeout
51
- self.last_response = {}
52
- self.model = model
53
- self.system_prompt = system_prompt
54
- self.headers = {
55
- "accept": "*/*",
56
- "accept-language": "en-US,en;q=0.9",
57
- "content-type": "text/plain;charset=UTF-8",
58
- "origin": "https://glider.so",
59
- "referer": "https://glider.so/",
60
- "user-agent": Lit().random(),
61
- "cookie": "_vcrcs=1.1746977094.3600.NDlmNmM5YWFmNzMxZWUyNzE4ZjBhOTJlZGZlZDU3MGU=.850a77f5f36f60ae5da2f51b55231a54",
62
- }
63
- self.session.headers.update(self.headers)
64
- self.session.proxies = proxies # Assign proxies directly
65
-
66
- self.__available_optimizers = (
67
- method for method in dir(Optimizers)
68
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
69
- )
70
-
71
- Conversation.intro = (
72
- AwesomePrompts().get_act(
73
- act, raise_not_found=True, default=None, case_insensitive=True
74
- )
75
- if act
76
- else intro or Conversation.intro
77
- )
78
- self.conversation = Conversation(
79
- is_conversation, self.max_tokens_to_sample, filepath, update_file
80
- )
81
- self.conversation.history_offset = history_offset
82
-
83
- @staticmethod
84
- def _glider_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
85
- """Extracts content from Glider stream JSON objects."""
86
- if isinstance(chunk, dict):
87
- # Handle both standard and DeepSeek response formats within choices
88
- return chunk.get("choices", [{}])[0].get("delta", {}).get("content")
89
- return None
90
-
91
- def ask(
92
- self,
93
- prompt: str,
94
- stream: bool = False,
95
- raw: bool = False,
96
- optimizer: Optional[str] = None,
97
- conversationally: bool = False,
98
- ) -> Union[Dict[str, Any], Generator[Any, None, None]]:
99
- """Chat with AI.
100
-
101
- Args:
102
- prompt (str): Prompt to be sent.
103
- stream (bool, optional): Flag for streaming response. Defaults to False.
104
- raw (bool, optional): Return raw response chunks instead of dict. Defaults to False.
105
- optimizer (str, optional): Prompt optimizer name. Defaults to None.
106
- conversationally (bool, optional): Use conversationally modified prompt when optimizer specified. Defaults to False.
107
- Returns:
108
- dict or Generator[dict, None, None]: The response from the API.
109
- """
110
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
111
- if optimizer:
112
- if optimizer in self.__available_optimizers:
113
- conversation_prompt = getattr(Optimizers, optimizer)(
114
- conversation_prompt if conversationally else prompt
115
- )
116
- else:
117
- raise Exception(f"Optimizer is not one of {list(self.__available_optimizers)}")
118
-
119
- payload = {
120
- "messages": [
121
- {"role": "system", "content": self.system_prompt},
122
- {"role": "user", "content": conversation_prompt}
123
- ],
124
- "model": self.model,
125
- }
126
-
127
- def for_stream():
128
- streaming_text = ""
129
- try:
130
- import json
131
- response = self.session.post(
132
- self.api_endpoint, data=json.dumps(payload), stream=True, timeout=self.timeout
133
- )
134
- response.raise_for_status()
135
-
136
- # Use sanitize_stream
137
- processed_stream = sanitize_stream(
138
- data=response.iter_content(chunk_size=None), # Pass byte iterator
139
- intro_value="data:",
140
- to_json=True, # Stream sends JSON
141
- content_extractor=self._glider_extractor, # Use the specific extractor
142
- yield_raw_on_error=False # Skip non-JSON lines or lines where extractor fails
143
- )
144
-
145
- for content_chunk in processed_stream:
146
- # content_chunk is the string extracted by _glider_extractor
147
- if content_chunk and isinstance(content_chunk, str):
148
- streaming_text += content_chunk
149
- yield content_chunk if raw else {"text": content_chunk}
150
- except CurlError as e:
151
- raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}") from e
152
- except Exception as e:
153
- raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}") from e
154
- self.last_response.update(dict(text=streaming_text))
155
- self.conversation.update_chat_history(prompt, self.get_message(self.last_response))
156
-
157
- def for_non_stream():
158
- for _ in for_stream():
159
- pass
160
- return self.last_response
161
-
162
- return for_stream() if stream else for_non_stream()
163
-
164
- def chat(
165
- self,
166
- prompt: str,
167
- stream: bool = False,
168
- optimizer: Optional[str] = None,
169
- conversationally: bool = False,
170
- ) -> Union[str, Generator[str, None, None]]:
171
- """Generate response as a string.
172
-
173
- Args:
174
- prompt (str): Prompt to be sent.
175
- stream (bool, optional): Flag for streaming response. Defaults to False.
176
- optimizer (str, optional): Prompt optimizer name. Defaults to None.
177
- conversationally (bool, optional): Use conversationally modified prompt when optimizer specified. Defaults to False.
178
- Returns:
179
- str or Generator[str, None, None]: The response generated.
180
- """
181
- def for_stream():
182
- for response in self.ask(
183
- prompt, stream=True, optimizer=optimizer, conversationally=conversationally
184
- ):
185
- yield self.get_message(response)
186
- def for_non_stream():
187
- return self.get_message(
188
- self.ask(
189
- prompt,
190
- stream=False,
191
- optimizer=optimizer,
192
- conversationally=conversationally,
193
- )
194
- )
195
- return for_stream() if stream else for_non_stream()
196
-
197
- def get_message(self, response: dict) -> str:
198
- """Retrieves message only from response."""
199
- assert isinstance(response, dict), "Response should be of dict data-type only"
200
- return response["text"]
201
-
202
- if __name__ == "__main__":
203
- print("-" * 80)
204
- print(f"{'Model':<50} {'Status':<10} {'Response'}")
205
- print("-" * 80)
206
-
207
- for model in GliderAI.AVAILABLE_MODELS:
208
- try:
209
- test_ai = GliderAI(model=model, timeout=60)
210
- response = test_ai.chat("Say 'Hello' in one word", stream=True)
211
- response_text = ""
212
- for chunk in response:
213
- response_text += chunk
214
- print(f"\r{model:<50} {'Testing...':<10}", end="", flush=True)
215
-
216
- if response_text and len(response_text.strip()) > 0:
217
- status = "✓"
218
- # Truncate response if too long
219
- display_text = response_text.strip()[:50] + "..." if len(response_text.strip()) > 50 else response_text.strip()
220
- else:
221
- status = "✗"
222
- display_text = "Empty or invalid response"
223
- print(f"\r{model:<50} {status:<10} {display_text}")
224
- except Exception as e:
225
- print(f"\r{model:<50} {'✗':<10} {str(e)}")