webscout 8.2.3__py3-none-any.whl → 8.2.5__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 (122) hide show
  1. webscout/AIutel.py +226 -14
  2. webscout/Bard.py +579 -206
  3. webscout/DWEBS.py +78 -35
  4. webscout/Extra/gguf.py +2 -0
  5. webscout/Extra/tempmail/base.py +1 -1
  6. webscout/Provider/AISEARCH/hika_search.py +4 -0
  7. webscout/Provider/AISEARCH/scira_search.py +2 -5
  8. webscout/Provider/Aitopia.py +75 -51
  9. webscout/Provider/AllenAI.py +181 -147
  10. webscout/Provider/ChatGPTClone.py +97 -86
  11. webscout/Provider/ChatSandbox.py +342 -0
  12. webscout/Provider/Cloudflare.py +79 -32
  13. webscout/Provider/Deepinfra.py +135 -94
  14. webscout/Provider/ElectronHub.py +103 -39
  15. webscout/Provider/ExaChat.py +36 -20
  16. webscout/Provider/GPTWeb.py +103 -47
  17. webscout/Provider/GithubChat.py +52 -49
  18. webscout/Provider/GizAI.py +283 -0
  19. webscout/Provider/Glider.py +39 -28
  20. webscout/Provider/Groq.py +222 -91
  21. webscout/Provider/HeckAI.py +93 -69
  22. webscout/Provider/HuggingFaceChat.py +113 -106
  23. webscout/Provider/Hunyuan.py +94 -83
  24. webscout/Provider/Jadve.py +104 -79
  25. webscout/Provider/LambdaChat.py +142 -123
  26. webscout/Provider/Llama3.py +94 -39
  27. webscout/Provider/MCPCore.py +315 -0
  28. webscout/Provider/Marcus.py +95 -37
  29. webscout/Provider/Netwrck.py +94 -52
  30. webscout/Provider/OPENAI/__init__.py +4 -1
  31. webscout/Provider/OPENAI/ai4chat.py +286 -0
  32. webscout/Provider/OPENAI/chatgptclone.py +35 -14
  33. webscout/Provider/OPENAI/deepinfra.py +37 -0
  34. webscout/Provider/OPENAI/exachat.py +4 -0
  35. webscout/Provider/OPENAI/groq.py +354 -0
  36. webscout/Provider/OPENAI/heckai.py +6 -2
  37. webscout/Provider/OPENAI/mcpcore.py +376 -0
  38. webscout/Provider/OPENAI/multichat.py +368 -0
  39. webscout/Provider/OPENAI/netwrck.py +3 -1
  40. webscout/Provider/OPENAI/scirachat.py +2 -4
  41. webscout/Provider/OPENAI/textpollinations.py +20 -22
  42. webscout/Provider/OPENAI/toolbaz.py +1 -0
  43. webscout/Provider/OpenGPT.py +48 -38
  44. webscout/Provider/PI.py +178 -93
  45. webscout/Provider/PizzaGPT.py +66 -36
  46. webscout/Provider/StandardInput.py +42 -30
  47. webscout/Provider/TeachAnything.py +95 -52
  48. webscout/Provider/TextPollinationsAI.py +138 -78
  49. webscout/Provider/TwoAI.py +162 -81
  50. webscout/Provider/TypliAI.py +305 -0
  51. webscout/Provider/Venice.py +97 -58
  52. webscout/Provider/VercelAI.py +33 -14
  53. webscout/Provider/WiseCat.py +65 -28
  54. webscout/Provider/Writecream.py +37 -11
  55. webscout/Provider/WritingMate.py +135 -63
  56. webscout/Provider/__init__.py +9 -27
  57. webscout/Provider/ai4chat.py +6 -7
  58. webscout/Provider/asksteve.py +53 -44
  59. webscout/Provider/cerebras.py +77 -31
  60. webscout/Provider/chatglm.py +47 -37
  61. webscout/Provider/copilot.py +0 -3
  62. webscout/Provider/elmo.py +109 -60
  63. webscout/Provider/granite.py +102 -54
  64. webscout/Provider/hermes.py +95 -48
  65. webscout/Provider/koala.py +1 -1
  66. webscout/Provider/learnfastai.py +113 -54
  67. webscout/Provider/llama3mitril.py +86 -51
  68. webscout/Provider/llmchat.py +88 -46
  69. webscout/Provider/llmchatco.py +110 -115
  70. webscout/Provider/meta.py +41 -37
  71. webscout/Provider/multichat.py +67 -28
  72. webscout/Provider/scira_chat.py +49 -30
  73. webscout/Provider/scnet.py +106 -53
  74. webscout/Provider/searchchat.py +87 -88
  75. webscout/Provider/sonus.py +113 -63
  76. webscout/Provider/toolbaz.py +115 -82
  77. webscout/Provider/turboseek.py +90 -43
  78. webscout/Provider/tutorai.py +82 -64
  79. webscout/Provider/typefully.py +85 -35
  80. webscout/Provider/typegpt.py +118 -61
  81. webscout/Provider/uncovr.py +132 -76
  82. webscout/Provider/x0gpt.py +69 -26
  83. webscout/Provider/yep.py +79 -66
  84. webscout/cli.py +256 -0
  85. webscout/conversation.py +34 -22
  86. webscout/exceptions.py +23 -0
  87. webscout/prompt_manager.py +56 -42
  88. webscout/version.py +1 -1
  89. webscout/webscout_search.py +65 -47
  90. webscout/webscout_search_async.py +81 -126
  91. webscout/yep_search.py +93 -43
  92. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/METADATA +183 -50
  93. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/RECORD +97 -113
  94. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/WHEEL +1 -1
  95. webscout-8.2.5.dist-info/entry_points.txt +3 -0
  96. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/top_level.txt +0 -1
  97. inferno/__init__.py +0 -6
  98. inferno/__main__.py +0 -9
  99. inferno/cli.py +0 -6
  100. webscout/Local/__init__.py +0 -12
  101. webscout/Local/__main__.py +0 -9
  102. webscout/Local/api.py +0 -576
  103. webscout/Local/cli.py +0 -516
  104. webscout/Local/config.py +0 -75
  105. webscout/Local/llm.py +0 -287
  106. webscout/Local/model_manager.py +0 -253
  107. webscout/Local/server.py +0 -721
  108. webscout/Local/utils.py +0 -93
  109. webscout/Provider/C4ai.py +0 -432
  110. webscout/Provider/ChatGPTES.py +0 -237
  111. webscout/Provider/Chatify.py +0 -175
  112. webscout/Provider/DeepSeek.py +0 -196
  113. webscout/Provider/Llama.py +0 -200
  114. webscout/Provider/Phind.py +0 -535
  115. webscout/Provider/WebSim.py +0 -228
  116. webscout/Provider/askmyai.py +0 -158
  117. webscout/Provider/gaurish.py +0 -244
  118. webscout/Provider/labyrinth.py +0 -340
  119. webscout/Provider/lepton.py +0 -194
  120. webscout/Provider/llamatutor.py +0 -192
  121. webscout-8.2.3.dist-info/entry_points.txt +0 -5
  122. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info/licenses}/LICENSE.md +0 -0
@@ -1,228 +0,0 @@
1
- import requests
2
- import json
3
- import string
4
- import random
5
- from typing import Any, Dict, Union
6
-
7
- from webscout.AIutel import Optimizers
8
- from webscout.AIutel import Conversation
9
- from webscout.AIutel import AwesomePrompts
10
- from webscout.AIbase import Provider
11
- from webscout import exceptions
12
- from webscout.litagent import LitAgent
13
-
14
- class WebSim(Provider):
15
- """
16
- A class to interact with the WebSim API.
17
- """
18
-
19
- url = "https://websim.ai"
20
- chat_api_endpoint = "https://websim.ai/api/v1/inference/run_chat_completion"
21
- image_api_endpoint = "https://websim.ai/api/v1/inference/run_image_generation"
22
-
23
- image_models = ['flux']
24
- AVAILABLE_MODELS = ['gemini-1.5-flash', 'gemini-1.5-pro', 'gemini-flash', 'gemini-pro', 'gemini-flash-thinking'] + image_models
25
-
26
- @staticmethod
27
- def generate_project_id(for_image=False):
28
- """
29
- Generate a project ID in the appropriate format
30
-
31
- For chat: format like 'ke3_xh5gai3gjkmruomu'
32
- For image: format like 'kx0m131_rzz66qb2xoy7'
33
- """
34
- chars = string.ascii_lowercase + string.digits
35
-
36
- if for_image:
37
- first_part = ''.join(random.choices(chars, k=7))
38
- second_part = ''.join(random.choices(chars, k=12))
39
- return f"{first_part}_{second_part}"
40
- else:
41
- prefix = ''.join(random.choices(chars, k=3))
42
- suffix = ''.join(random.choices(chars, k=15))
43
- return f"{prefix}_{suffix}"
44
-
45
- def __init__(
46
- self,
47
- is_conversation: bool = True,
48
- max_tokens: int = 2049,
49
- timeout: int = 30,
50
- intro: str = None,
51
- filepath: str = None,
52
- update_file: bool = True,
53
- proxies: dict = {},
54
- history_offset: int = 10250,
55
- act: str = None,
56
- model: str = 'gemini-1.5-pro',
57
- aspect_ratio: str = "1:1"
58
- ):
59
- """Initializes the WebSim API client."""
60
- if model not in self.AVAILABLE_MODELS:
61
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
62
- self.agent = LitAgent()
63
- self.headers = {
64
- 'accept': '*/*',
65
- 'accept-language': 'en-US,en;q=0.9',
66
- 'content-type': 'text/plain;charset=UTF-8',
67
- 'origin': 'https://websim.ai',
68
- 'user-agent': self.agent.random(),
69
- 'websim-flags;': ''
70
- }
71
-
72
- self.session = requests.Session()
73
- self.session.headers.update(self.headers)
74
- self.session.proxies.update(proxies)
75
-
76
- self.is_conversation = is_conversation
77
- self.max_tokens_to_sample = max_tokens
78
- self.timeout = timeout
79
- self.last_response = {}
80
- self.model = model
81
- self.aspect_ratio = aspect_ratio
82
-
83
- self.__available_optimizers = (
84
- method
85
- for method in dir(Optimizers)
86
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
87
- )
88
- Conversation.intro = (
89
- AwesomePrompts().get_act(
90
- act, raise_not_found=True, default=None, case_insensitive=True
91
- )
92
- if act
93
- else intro or Conversation.intro
94
- )
95
-
96
- self.conversation = Conversation(
97
- is_conversation, self.max_tokens_to_sample, filepath, update_file
98
- )
99
- self.conversation.history_offset = history_offset
100
-
101
- def ask(
102
- self,
103
- prompt: str,
104
- stream: bool = False,
105
- raw: bool = False,
106
- optimizer: str = None,
107
- conversationally: bool = False,
108
- ) -> Dict[str, Any]:
109
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
110
- if optimizer:
111
- if optimizer in self.__available_optimizers:
112
- conversation_prompt = getattr(Optimizers, optimizer)(
113
- conversation_prompt if conversationally else prompt
114
- )
115
- else:
116
- raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
117
-
118
- is_image_request = self.model in self.image_models
119
- project_id = self.generate_project_id(for_image=is_image_request)
120
-
121
- if is_image_request:
122
- self.headers['referer'] = 'https://websim.ai/@ISWEARIAMNOTADDICTEDTOPILLOW/ai-image-prompt-generator'
123
- return self._handle_image_request(project_id, conversation_prompt)
124
- else:
125
- self.headers['referer'] = 'https://websim.ai/@ISWEARIAMNOTADDICTEDTOPILLOW/zelos-ai-assistant'
126
- return self._handle_chat_request(project_id, conversation_prompt)
127
-
128
- def _handle_image_request(self, project_id: str, prompt: str) -> Dict[str, Any]:
129
- try:
130
- data = {
131
- "project_id": project_id,
132
- "prompt": prompt,
133
- "aspect_ratio": self.aspect_ratio
134
- }
135
- response = self.session.post(
136
- self.image_api_endpoint,
137
- json=data,
138
- timeout=self.timeout
139
- )
140
- response.raise_for_status()
141
- response_json = response.json()
142
- image_url = response_json.get("url")
143
- if image_url:
144
- self.last_response = {"text": image_url}
145
- self.conversation.update_chat_history(prompt, image_url)
146
- return {"text": image_url}
147
- raise exceptions.FailedToGenerateResponseError("No image URL found in response")
148
- except requests.RequestException as e:
149
- raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
150
-
151
- def _handle_chat_request(self, project_id: str, prompt: str) -> Dict[str, Any]:
152
- max_retries = 3
153
- retry_count = 0
154
- last_error = None
155
-
156
- while retry_count < max_retries:
157
- try:
158
- data = {
159
- "project_id": project_id,
160
- "messages": [{"role": "user", "content": prompt}]
161
- }
162
- response = self.session.post(
163
- self.chat_api_endpoint,
164
- json=data,
165
- timeout=self.timeout
166
- )
167
-
168
- if response.status_code == 429:
169
- last_error = exceptions.FailedToGenerateResponseError(
170
- f"Rate limit exceeded: {response.text}"
171
- )
172
- retry_count += 1
173
- if retry_count < max_retries:
174
- continue
175
- raise last_error
176
-
177
- response.raise_for_status()
178
- response_json = response.json()
179
- content = response_json.get("content", "")
180
-
181
- self.last_response = {"text": content}
182
- self.conversation.update_chat_history(prompt, content)
183
- return {"text": content.strip()}
184
-
185
- except requests.RequestException as e:
186
- if "Rate limit exceeded" in str(e) and retry_count < max_retries:
187
- retry_count += 1
188
- else:
189
- raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
190
-
191
- raise last_error or exceptions.FailedToGenerateResponseError("Max retries exceeded")
192
-
193
- def chat(
194
- self,
195
- prompt: str,
196
- stream: bool = False,
197
- optimizer: str = None,
198
- conversationally: bool = False,
199
- ) -> str:
200
- return self.get_message(
201
- self.ask(prompt, False, optimizer=optimizer, conversationally=conversationally)
202
- )
203
-
204
- def get_message(self, response: dict) -> str:
205
- assert isinstance(response, dict), "Response should be of dict data-type only"
206
- return response["text"]
207
-
208
- if __name__ == "__main__":
209
- print("-" * 80)
210
- print(f"{'Model':<50} {'Status':<10} {'Response'}")
211
- print("-" * 80)
212
-
213
- for model in WebSim.AVAILABLE_MODELS:
214
- try:
215
- test_ai = WebSim(model=model, timeout=60)
216
- response = test_ai.chat("Say 'Hello' in one word")
217
-
218
- if response and len(response.strip()) > 0:
219
- status = "✓"
220
- # Clean and truncate response
221
- clean_text = response.strip().encode('utf-8', errors='ignore').decode('utf-8')
222
- display_text = clean_text[:50] + "..." if len(clean_text) > 50 else clean_text
223
- else:
224
- status = "✗"
225
- display_text = "Empty or invalid response"
226
- print(f"\r{model:<50} {status:<10} {display_text}")
227
- except Exception as e:
228
- print(f"\r{model:<50} {'✗':<10} {str(e)}")
@@ -1,158 +0,0 @@
1
- import requests
2
- import json
3
- import re
4
- from typing import Union, Any, Dict, Optional, Generator
5
-
6
- from webscout.AIutel import Optimizers
7
- from webscout.AIutel import Conversation
8
- from webscout.AIutel import AwesomePrompts
9
- from webscout.AIbase import Provider
10
- from webscout import exceptions
11
- from webscout.litagent import LitAgent as UserAgent
12
-
13
- class AskMyAI(Provider):
14
- """
15
- A class to interact with the askmyai.chat API. Improved to match webscout standards.
16
- """
17
-
18
- def __init__(
19
- self,
20
- is_conversation: bool = True,
21
- max_tokens: int = 2048, # Added max_tokens parameter
22
- timeout: int = 30,
23
- intro: str = None,
24
- filepath: str = None,
25
- update_file: bool = True,
26
- proxies: dict = {},
27
- history_offset: int = 10250,
28
- act: str = None,
29
- system_prompt: str = "You are a helpful assistant.", # Added system prompt
30
- ):
31
- """Initializes the AskMyAI API."""
32
- self.session = requests.Session()
33
- self.is_conversation = is_conversation
34
- self.max_tokens_to_sample = max_tokens
35
- self.api_endpoint = "https://www.askmyai.chat/api/chat"
36
- self.timeout = timeout
37
- self.last_response = {}
38
- self.system_prompt = system_prompt # Use system prompt
39
- self.headers = {
40
- "Content-Type": "application/json",
41
- "Accept": "*/*",
42
- "Accept-Encoding": "gzip, deflate, br",
43
- "Accept-Language": "en-US,en;q=0.9",
44
- 'user-agent': UserAgent().random()
45
- }
46
- self.__available_optimizers = (
47
- method
48
- for method in dir(Optimizers)
49
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
50
- )
51
- Conversation.intro = (
52
- AwesomePrompts().get_act(
53
- act, raise_not_found=True, default=None, case_insensitive=True
54
- )
55
- if act
56
- else intro or Conversation.intro
57
- )
58
- self.conversation = Conversation(
59
- is_conversation, self.max_tokens_to_sample, filepath, update_file
60
- )
61
- self.conversation.history_offset = history_offset
62
- self.session.proxies = proxies
63
-
64
- def ask(
65
- self,
66
- prompt: str,
67
- stream: bool = False,
68
- raw: bool = False,
69
- optimizer: str = None,
70
- conversationally: bool = False,
71
- ) -> Union[Dict[str, Any], Generator[Any, None, None]]:
72
- """Sends a prompt to the askmyai.chat API and returns the response."""
73
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
74
- if optimizer:
75
- if optimizer in self.__available_optimizers:
76
- conversation_prompt = getattr(Optimizers, optimizer)(
77
- conversation_prompt if conversationally else prompt
78
- )
79
- else:
80
- raise exceptions.FailedToGenerateResponseError(
81
- f"Optimizer is not one of {self.__available_optimizers}"
82
- )
83
-
84
- payload = {
85
- "messages": [
86
- {"role": "system", "content": self.system_prompt},
87
- {"role": "user", "content": conversation_prompt}
88
- ],
89
- "data": {"datasource": "thucpn"}
90
- }
91
-
92
- def for_stream():
93
- response = self.session.post(
94
- self.api_endpoint, json=payload, stream=True, timeout=self.timeout
95
- )
96
- if not response.ok:
97
- raise exceptions.FailedToGenerateResponseError(
98
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
99
- )
100
-
101
- streaming_response = ""
102
- for line in response.iter_lines(decode_unicode=True):
103
- if line:
104
- match = re.search(r'0:"(.*?)"', line)
105
- if match:
106
- content = match.group(1)
107
- streaming_response += content
108
- yield content if raw else {"text": content}
109
- self.last_response.update({"text": streaming_response})
110
- self.conversation.update_chat_history(
111
- prompt, self.get_message(self.last_response)
112
- )
113
-
114
- def for_non_stream():
115
- full_response = ""
116
- for chunk in for_stream():
117
- full_response += chunk if raw else chunk['text']
118
- return {"text": full_response}
119
-
120
- return for_stream() if stream else for_non_stream()
121
-
122
- def chat(
123
- self,
124
- prompt: str,
125
- stream: bool = False,
126
- optimizer: str = None,
127
- conversationally: bool = False,
128
- ) -> Union[str, Generator[str, None, None]]:
129
- """Generates a response from the AskMyAI API."""
130
-
131
- def for_stream():
132
- for response in self.ask(
133
- prompt, stream=True, optimizer=optimizer, conversationally=conversationally
134
- ):
135
- yield self.get_message(response)
136
-
137
- def for_non_stream():
138
- return self.get_message(
139
- self.ask(
140
- prompt, stream=False, optimizer=optimizer, conversationally=conversationally
141
- )
142
- )
143
-
144
- return for_stream() if stream else for_non_stream()
145
-
146
- def get_message(self, response: Dict[str, Any]) -> str:
147
- """Extracts the message from the API response."""
148
- assert isinstance(response, dict), "Response should be of dict data-type only"
149
- return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
150
-
151
- if __name__ == "__main__":
152
- from rich import print
153
-
154
- ai = AskMyAI(timeout=30)
155
- response = ai.chat("write a poem about AI", stream=True)
156
-
157
- for chunk in response:
158
- print(chunk, end="", flush=True)
@@ -1,244 +0,0 @@
1
- import requests
2
- import json
3
- from typing import Dict, Generator, Union
4
-
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts
8
- from webscout.AIbase import Provider
9
- from webscout import exceptions
10
- from webscout.Litlogger import Logger, LogFormat
11
-
12
- class GaurishCerebras(Provider):
13
- """
14
- A class to interact with the Gaurish Cerebras API with comprehensive logging.
15
- """
16
-
17
- def __init__(
18
- self,
19
- is_conversation: bool = True,
20
- max_tokens: int = 2049,
21
- timeout: int = 30,
22
- intro: str = None,
23
- filepath: str = None,
24
- update_file: bool = True,
25
- proxies: dict = {},
26
- history_offset: int = 10250,
27
- act: str = None,
28
- system_prompt: str = "You are a helpful assistant.",
29
- logging: bool = False
30
- ):
31
- """Initializes the Gaurish Cerebras API client with logging capabilities."""
32
- self.logger = Logger(
33
- name="GaurishCerebras",
34
- format=LogFormat.MODERN_EMOJI,
35
- ) if logging else None
36
-
37
- if self.logger:
38
- self.logger.info("Initializing GaurishCerebras client")
39
-
40
- self.chat_endpoint = "https://proxy.gaurish.xyz/api/cerebras/v1/chat/completions"
41
-
42
- self.headers = {
43
- "Content-Type": "application/json",
44
- "Accept": "application/json",
45
- "authorization": "Bearer 123",
46
- "accept-encoding": "gzip, deflate, br, zstd",
47
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
48
- "dnt": "1",
49
- "origin": "https://chat.gaurish.xyz",
50
- "priority": "u=1, i",
51
- "referer": "https://chat.gaurish.xyz/",
52
- "sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Microsoft Edge";v="132"',
53
- "sec-ch-ua-mobile": "?0",
54
- "sec-ch-ua-platform": '"Windows"',
55
- "sec-fetch-dest": "empty",
56
- "sec-fetch-mode": "cors",
57
- "sec-fetch-site": "same-site",
58
- "user-agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
59
- "AppleWebKit/537.36 (KHTML, like Gecko) "
60
- "Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0"),
61
- }
62
- self.session = requests.Session()
63
- self.session.headers.update(self.headers)
64
- self.session.proxies.update(proxies)
65
- self.timeout = timeout
66
- self.last_response = {}
67
-
68
- self.is_conversation = is_conversation
69
- self.max_tokens_to_sample = max_tokens
70
-
71
- if self.logger:
72
- self.logger.debug(f"Session configured with timeout: {timeout}")
73
- self.logger.debug(f"Max tokens set to: {max_tokens}")
74
-
75
- self.__available_optimizers = (
76
- method
77
- for method in dir(Optimizers)
78
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
79
- )
80
- Conversation.intro = (
81
- AwesomePrompts().get_act(
82
- act, raise_not_found=True, default=None, case_insensitive=True
83
- )
84
- if act
85
- else intro or system_prompt or Conversation.intro
86
- )
87
- self.conversation = Conversation(
88
- is_conversation, self.max_tokens_to_sample, filepath, update_file
89
- )
90
- self.conversation.history_offset = history_offset
91
- self.system_prompt = system_prompt
92
-
93
- if self.logger:
94
- self.logger.info("GaurishCerebras initialization completed successfully")
95
-
96
- def ask(
97
- self,
98
- prompt: str,
99
- stream: bool = False,
100
- raw: bool = False,
101
- optimizer: str = None,
102
- conversationally: bool = False,
103
- ) -> Union[Dict, Generator]:
104
- """
105
- Sends a prompt to the API and returns the response with logging.
106
- If stream is True, returns a generator for streamed responses.
107
- """
108
- if self.logger:
109
- self.logger.debug(f"Processing request - Prompt: {prompt[:50]}...")
110
- self.logger.debug(f"Stream: {stream}, Optimizer: {optimizer}")
111
-
112
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
113
- if optimizer:
114
- if optimizer in self.__available_optimizers:
115
- conversation_prompt = getattr(Optimizers, optimizer)(
116
- conversation_prompt if conversationally else prompt
117
- )
118
- if self.logger:
119
- self.logger.debug(f"Applied optimizer: {optimizer}")
120
- else:
121
- if self.logger:
122
- self.logger.error(f"Invalid optimizer requested: {optimizer}")
123
- raise Exception(f"Optimizer is not one of {list(self.__available_optimizers)}")
124
-
125
- payload = {
126
- "messages": [
127
- {"role": "system", "content": self.system_prompt},
128
- {"role": "user", "content": conversation_prompt},
129
- ],
130
- "model": "llama3.3-70b",
131
- "max_tokens": self.max_tokens_to_sample,
132
- "temperature": 0.75,
133
- "stream": stream,
134
- }
135
-
136
- def for_stream():
137
- try:
138
- if self.logger:
139
- self.logger.debug("Initiating streaming request to API")
140
-
141
- with self.session.post(self.chat_endpoint, json=payload, stream=True, timeout=self.timeout) as response:
142
- if response.status_code != 200:
143
- if self.logger:
144
- self.logger.error(f"API request failed. Status: {response.status_code}")
145
- raise exceptions.FailedToGenerateResponseError(
146
- f"Request failed with status code {response.status_code}"
147
- )
148
-
149
- if self.logger:
150
- self.logger.info(f"API connection established successfully. Status: {response.status_code}")
151
-
152
- streaming_text = ""
153
- for line in response.iter_lines(decode_unicode=True):
154
- if line:
155
- line = line.strip()
156
- if line.startswith("data: "):
157
- json_str = line[6:]
158
- if json_str == "[DONE]":
159
- if self.logger:
160
- self.logger.debug("Stream completed")
161
- break
162
- try:
163
- json_data = json.loads(json_str)
164
- if 'choices' in json_data:
165
- choice = json_data['choices'][0]
166
- if 'delta' in choice and 'content' in choice['delta']:
167
- content = choice['delta']['content']
168
- streaming_text += content
169
- yield dict(text=content) if raw else dict(text=content)
170
- except json.JSONDecodeError as e:
171
- if self.logger:
172
- self.logger.error(f"JSON parsing error: {str(e)}")
173
- pass
174
-
175
- self.conversation.update_chat_history(prompt, streaming_text)
176
- if self.logger:
177
- self.logger.debug("Response processing completed")
178
-
179
- except requests.RequestException as e:
180
- if self.logger:
181
- self.logger.error(f"Request failed: {str(e)}")
182
- raise exceptions.FailedToGenerateResponseError(f"Request failed: {e}")
183
-
184
- def for_non_stream():
185
- if self.logger:
186
- self.logger.debug("Processing non-streaming request")
187
- for _ in for_stream():
188
- pass
189
- return self.last_response
190
-
191
- return for_stream() if stream else for_non_stream()
192
-
193
- def chat(
194
- self,
195
- prompt: str,
196
- stream: bool = False,
197
- optimizer: str = None,
198
- conversationally: bool = False,
199
- ) -> Union[str, Generator]:
200
- """
201
- A convenience method to return just the text message from the response with logging.
202
- """
203
- if self.logger:
204
- self.logger.debug(f"Chat request initiated - Prompt: {prompt[:50]}...")
205
-
206
- def for_stream():
207
- for response in self.ask(
208
- prompt, stream=True, optimizer=optimizer, conversationally=conversationally
209
- ):
210
- yield response if isinstance(response, str) else self.get_message(response)
211
-
212
- def for_non_stream():
213
- resp = self.ask(
214
- prompt, stream=False, optimizer=optimizer, conversationally=conversationally
215
- )
216
- return resp if isinstance(resp, str) else self.get_message(resp)
217
-
218
- return for_stream() if stream else for_non_stream()
219
-
220
- def get_message(self, response: dict) -> str:
221
- """
222
- Retrieve the message text from the API response with logging.
223
- """
224
- if not isinstance(response, dict):
225
- if self.logger:
226
- self.logger.warning("Invalid response format received")
227
- return ""
228
-
229
- if "text" in response and response["text"]:
230
- return response["text"]
231
-
232
- if self.logger:
233
- self.logger.warning("No valid message content found in response")
234
- return ""
235
-
236
- if __name__ == "__main__":
237
- from rich import print
238
- bot = GaurishCerebras(logging=True)
239
- try:
240
- response = bot.chat("what is meaning of life", stream=True)
241
- for chunk in response:
242
- print(chunk, end="", flush=True)
243
- except Exception as e:
244
- print(f"An error occurred: {e}")