webscout 8.2.4__py3-none-any.whl → 8.2.6__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 (110) hide show
  1. webscout/AIauto.py +112 -22
  2. webscout/AIutel.py +240 -344
  3. webscout/Extra/autocoder/autocoder.py +66 -5
  4. webscout/Extra/gguf.py +2 -0
  5. webscout/Provider/AISEARCH/scira_search.py +3 -5
  6. webscout/Provider/Aitopia.py +75 -51
  7. webscout/Provider/AllenAI.py +64 -67
  8. webscout/Provider/ChatGPTClone.py +33 -34
  9. webscout/Provider/ChatSandbox.py +342 -0
  10. webscout/Provider/Cloudflare.py +79 -32
  11. webscout/Provider/Deepinfra.py +69 -56
  12. webscout/Provider/ElectronHub.py +48 -39
  13. webscout/Provider/ExaChat.py +36 -20
  14. webscout/Provider/GPTWeb.py +24 -18
  15. webscout/Provider/GithubChat.py +52 -49
  16. webscout/Provider/GizAI.py +285 -0
  17. webscout/Provider/Glider.py +39 -28
  18. webscout/Provider/Groq.py +48 -20
  19. webscout/Provider/HeckAI.py +18 -36
  20. webscout/Provider/Jadve.py +30 -37
  21. webscout/Provider/LambdaChat.py +36 -59
  22. webscout/Provider/MCPCore.py +18 -21
  23. webscout/Provider/Marcus.py +23 -14
  24. webscout/Provider/Nemotron.py +218 -0
  25. webscout/Provider/Netwrck.py +35 -26
  26. webscout/Provider/OPENAI/__init__.py +1 -1
  27. webscout/Provider/OPENAI/exachat.py +4 -0
  28. webscout/Provider/OPENAI/scirachat.py +3 -4
  29. webscout/Provider/OPENAI/textpollinations.py +20 -22
  30. webscout/Provider/OPENAI/toolbaz.py +1 -0
  31. webscout/Provider/PI.py +22 -13
  32. webscout/Provider/StandardInput.py +42 -30
  33. webscout/Provider/TeachAnything.py +24 -12
  34. webscout/Provider/TextPollinationsAI.py +78 -76
  35. webscout/Provider/TwoAI.py +120 -88
  36. webscout/Provider/TypliAI.py +305 -0
  37. webscout/Provider/Venice.py +24 -22
  38. webscout/Provider/VercelAI.py +31 -12
  39. webscout/Provider/WiseCat.py +1 -1
  40. webscout/Provider/WrDoChat.py +370 -0
  41. webscout/Provider/__init__.py +11 -13
  42. webscout/Provider/ai4chat.py +5 -3
  43. webscout/Provider/akashgpt.py +59 -66
  44. webscout/Provider/asksteve.py +53 -44
  45. webscout/Provider/cerebras.py +77 -31
  46. webscout/Provider/chatglm.py +47 -37
  47. webscout/Provider/elmo.py +38 -32
  48. webscout/Provider/freeaichat.py +57 -43
  49. webscout/Provider/granite.py +24 -21
  50. webscout/Provider/hermes.py +27 -20
  51. webscout/Provider/learnfastai.py +25 -20
  52. webscout/Provider/llmchatco.py +48 -78
  53. webscout/Provider/multichat.py +13 -3
  54. webscout/Provider/scira_chat.py +50 -30
  55. webscout/Provider/scnet.py +27 -21
  56. webscout/Provider/searchchat.py +16 -24
  57. webscout/Provider/sonus.py +37 -39
  58. webscout/Provider/toolbaz.py +24 -46
  59. webscout/Provider/turboseek.py +37 -41
  60. webscout/Provider/typefully.py +30 -22
  61. webscout/Provider/typegpt.py +47 -51
  62. webscout/Provider/uncovr.py +46 -40
  63. webscout/__init__.py +0 -1
  64. webscout/cli.py +256 -0
  65. webscout/conversation.py +305 -448
  66. webscout/exceptions.py +3 -0
  67. webscout/swiftcli/__init__.py +80 -794
  68. webscout/swiftcli/core/__init__.py +7 -0
  69. webscout/swiftcli/core/cli.py +297 -0
  70. webscout/swiftcli/core/context.py +104 -0
  71. webscout/swiftcli/core/group.py +241 -0
  72. webscout/swiftcli/decorators/__init__.py +28 -0
  73. webscout/swiftcli/decorators/command.py +221 -0
  74. webscout/swiftcli/decorators/options.py +220 -0
  75. webscout/swiftcli/decorators/output.py +252 -0
  76. webscout/swiftcli/exceptions.py +21 -0
  77. webscout/swiftcli/plugins/__init__.py +9 -0
  78. webscout/swiftcli/plugins/base.py +135 -0
  79. webscout/swiftcli/plugins/manager.py +262 -0
  80. webscout/swiftcli/utils/__init__.py +59 -0
  81. webscout/swiftcli/utils/formatting.py +252 -0
  82. webscout/swiftcli/utils/parsing.py +267 -0
  83. webscout/version.py +1 -1
  84. {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/METADATA +166 -45
  85. {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/RECORD +89 -89
  86. {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/WHEEL +1 -1
  87. webscout-8.2.6.dist-info/entry_points.txt +3 -0
  88. {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/top_level.txt +0 -1
  89. inferno/__init__.py +0 -6
  90. inferno/__main__.py +0 -9
  91. inferno/cli.py +0 -6
  92. inferno/lol.py +0 -589
  93. webscout/LLM.py +0 -442
  94. webscout/Local/__init__.py +0 -12
  95. webscout/Local/__main__.py +0 -9
  96. webscout/Local/api.py +0 -576
  97. webscout/Local/cli.py +0 -516
  98. webscout/Local/config.py +0 -75
  99. webscout/Local/llm.py +0 -287
  100. webscout/Local/model_manager.py +0 -253
  101. webscout/Local/server.py +0 -721
  102. webscout/Local/utils.py +0 -93
  103. webscout/Provider/Chatify.py +0 -175
  104. webscout/Provider/PizzaGPT.py +0 -228
  105. webscout/Provider/askmyai.py +0 -158
  106. webscout/Provider/gaurish.py +0 -244
  107. webscout/Provider/promptrefine.py +0 -193
  108. webscout/Provider/tutorai.py +0 -270
  109. webscout-8.2.4.dist-info/entry_points.txt +0 -5
  110. {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/licenses/LICENSE.md +0 -0
webscout/Local/utils.py DELETED
@@ -1,93 +0,0 @@
1
- """
2
- Utility functions for webscout.local
3
- """
4
-
5
- import base64
6
- import logging
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
- def parse_duration(duration_str: str) -> float:
11
- """
12
- Parse a duration string into seconds.
13
-
14
- Args:
15
- duration_str (str): Duration string (e.g., '5m', '1h', '30s', '500ms', '0').
16
- Returns:
17
- float: Duration in seconds.
18
- """
19
- if not duration_str:
20
- return 300.0 # Default 5 minutes
21
- if duration_str.endswith("ms"):
22
- return int(duration_str[:-2]) / 1000.0
23
- elif duration_str.endswith("s"):
24
- return int(duration_str[:-1])
25
- elif duration_str.endswith("m"):
26
- return int(duration_str[:-1]) * 60
27
- elif duration_str.endswith("h"):
28
- return int(duration_str[:-1]) * 3600
29
- elif duration_str == "0":
30
- return 0.0
31
- else:
32
- try:
33
- return float(duration_str)
34
- except ValueError:
35
- return 300.0 # Default 5 minutes
36
-
37
- def format_duration(seconds: float) -> str:
38
- """
39
- Format seconds into a human-readable duration string.
40
- Args:
41
- seconds (float): Duration in seconds.
42
- Returns:
43
- str: Human-readable duration string.
44
- """
45
- if seconds < 1:
46
- return f"{int(seconds * 1000)}ms"
47
- elif seconds < 60:
48
- return f"{int(seconds)}s"
49
- elif seconds < 3600:
50
- return f"{int(seconds / 60)}m"
51
- else:
52
- return f"{int(seconds / 3600)}h"
53
-
54
- def decode_image(image_str: str) -> bytes:
55
- """
56
- Decode a base64 image string to bytes.
57
- Args:
58
- image_str (str): Base64-encoded image string (optionally with data URI prefix).
59
- Returns:
60
- bytes: Decoded image bytes.
61
- """
62
- if image_str.startswith("data:"):
63
- image_str = image_str.split(",", 1)[1]
64
- return base64.b64decode(image_str)
65
-
66
- def encode_image(image_bytes: bytes, mime_type: str = "image/png") -> str:
67
- """
68
- Encode image bytes to a base64 data URI.
69
- Args:
70
- image_bytes (bytes): Image data.
71
- mime_type (str): MIME type for the image.
72
- Returns:
73
- str: Base64-encoded data URI string.
74
- """
75
- encoded = base64.b64encode(image_bytes).decode("utf-8")
76
- return f"data:{mime_type};base64,{encoded}"
77
-
78
- def get_file_size_str(size_bytes: int) -> str:
79
- """
80
- Convert file size in bytes to a human-readable string.
81
- Args:
82
- size_bytes (int): File size in bytes.
83
- Returns:
84
- str: Human-readable file size string.
85
- """
86
- if size_bytes < 1024:
87
- return f"{size_bytes} B"
88
- elif size_bytes < 1024 * 1024:
89
- return f"{size_bytes / 1024:.2f} KB"
90
- elif size_bytes < 1024 * 1024 * 1024:
91
- return f"{size_bytes / (1024 * 1024):.2f} MB"
92
- else:
93
- return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
@@ -1,175 +0,0 @@
1
- from webscout.AIutel import Optimizers
2
- from webscout.AIutel import Conversation
3
- from webscout.AIutel import AwesomePrompts
4
- from webscout.AIbase import Provider
5
- from webscout import exceptions
6
- import requests
7
- from webscout.litagent import LitAgent
8
- class Chatify(Provider):
9
- """
10
- A class to interact with the Chatify AI API.
11
- """
12
-
13
- def __init__(
14
- self,
15
- is_conversation: bool = True,
16
- max_tokens: int = 600,
17
- timeout: int = 30,
18
- intro: str = None,
19
- filepath: str = None,
20
- update_file: bool = True,
21
- proxies: dict = {},
22
- history_offset: int = 10250,
23
- act: str = None,
24
- system_prompt: str = "You are a helpful and informative AI assistant.",
25
- ):
26
- """
27
- Initializes the Chatify AI API with given parameters.
28
- """
29
- self.session = requests.Session()
30
- self.is_conversation = is_conversation
31
- self.max_tokens_to_sample = max_tokens
32
- self.api_endpoint = "https://chatify-ai.vercel.app/api/chat"
33
- self.timeout = timeout
34
- self.last_response = {}
35
- self.headers = {
36
- 'Accept': '*/*',
37
- 'Accept-Encoding': 'gzip, deflate, br, zstd',
38
- 'Accept-Language': 'en-US,en;q=0.9,en-IN;q=0.8',
39
- 'Content-Type': 'application/json',
40
- 'DNT': '1',
41
- 'Origin': 'https://chatify-ai.vercel.app',
42
- 'Referer': 'https://chatify-ai.vercel.app/',
43
- 'Sec-CH-UA': '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
44
- 'Sec-CH-UA-Mobile': '?0',
45
- 'Sec-CH-UA-Platform': '"Windows"',
46
- 'Sec-Fetch-Dest': 'empty',
47
- 'Sec-Fetch-Mode': 'cors',
48
- 'Sec-Fetch-Site': 'same-origin',
49
- 'User-Agent': LitAgent().random(),
50
- }
51
-
52
- self.__available_optimizers = (
53
- method
54
- for method in dir(Optimizers)
55
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
56
- )
57
- self.session.headers.update(self.headers)
58
- Conversation.intro = (
59
- AwesomePrompts().get_act(
60
- act, raise_not_found=True, default=None, case_insensitive=True
61
- )
62
- if act
63
- else intro or Conversation.intro
64
- )
65
- self.conversation = Conversation(
66
- is_conversation, self.max_tokens_to_sample, filepath, update_file
67
- )
68
- self.conversation.history_offset = history_offset
69
- self.session.proxies = proxies
70
- self.system_prompt = system_prompt
71
-
72
- def ask(
73
- self,
74
- prompt: str,
75
- stream: bool = False,
76
- raw: bool = False,
77
- optimizer: str = None,
78
- conversationally: bool = False,
79
- ) -> dict:
80
- """
81
- Sends a prompt to the Chatify API and returns the response.
82
- """
83
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
84
- if optimizer:
85
- if optimizer in self.__available_optimizers:
86
- conversation_prompt = getattr(Optimizers, optimizer)(
87
- conversation_prompt if conversationally else prompt
88
- )
89
- else:
90
- raise Exception(
91
- f"Optimizer is not one of {self.__available_optimizers}"
92
- )
93
-
94
- messages = []
95
- if self.system_prompt:
96
- messages.append({"role": "system", "content": self.system_prompt})
97
- messages.append({"role": "user", "content": conversation_prompt})
98
-
99
- payload = {
100
- "messages": messages
101
- }
102
-
103
- def for_stream():
104
- response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True, timeout=self.timeout)
105
- if not response.ok:
106
- raise exceptions.FailedToGenerateResponseError(
107
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
108
- )
109
-
110
- streaming_text = ""
111
- for line in response.iter_lines():
112
- if line:
113
- decoded_line = line.decode('utf-8') # Decode the line
114
- parts = decoded_line.split(':', 1)
115
- if len(parts) > 1:
116
- content = parts[1].strip().strip('"')
117
- streaming_text += content
118
- yield content if raw else dict(text=content)
119
- self.last_response.update(dict(text=streaming_text))
120
- self.conversation.update_chat_history(
121
- prompt, self.get_message(self.last_response)
122
- )
123
-
124
- def for_non_stream():
125
- for _ in for_stream():
126
- pass
127
- return self.last_response
128
-
129
- return for_stream() if stream else for_non_stream()
130
-
131
- def chat(
132
- self,
133
- prompt: str,
134
- stream: bool = False,
135
- optimizer: str = None,
136
- conversationally: bool = False,
137
- ) -> str:
138
- """
139
- Generates a response from the Chatify API.
140
- """
141
-
142
- def for_stream():
143
- for response in self.ask(
144
- prompt, True, optimizer=optimizer, conversationally=conversationally
145
- ):
146
- yield self.get_message(response)
147
-
148
- def for_non_stream():
149
- return self.get_message(
150
- self.ask(
151
- prompt,
152
- False,
153
- optimizer=optimizer,
154
- conversationally=conversationally,
155
- )
156
- )
157
-
158
- return for_stream() if stream else for_non_stream()
159
-
160
- def get_message(self, response: dict) -> str:
161
- """
162
- Extracts the message from the API response and formats it.
163
- """
164
- assert isinstance(response, dict), "Response should be of dict data-type only"
165
- return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
166
-
167
-
168
- # Example usage
169
- if __name__ == "__main__":
170
- from rich import print
171
-
172
- ai = Chatify(timeout=5000)
173
- response = ai.chat("write a poem about AI", stream=True)
174
- for chunk in response:
175
- print(chunk, end="", flush=True)
@@ -1,228 +0,0 @@
1
- from curl_cffi.requests import Session
2
- from curl_cffi import CurlError
3
- import json
4
- import re
5
- from typing import Any, Dict, Optional, Union, Generator
6
- from webscout.AIutel import Optimizers, Conversation, AwesomePrompts
7
- from webscout.AIbase import Provider
8
- from webscout import exceptions
9
- from webscout.litagent import LitAgent as Lit
10
-
11
- class PIZZAGPT(Provider):
12
- """
13
- PIZZAGPT is a provider class for interacting with the PizzaGPT API.
14
- Supports web search integration and handles responses using regex.
15
- """
16
- AVAILABLE_MODELS = ["gpt-4o-mini"]
17
-
18
- def __init__(
19
- self,
20
- is_conversation: bool = True,
21
- max_tokens: int = 600, # Note: max_tokens is not used by this API
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
- model: str = "gpt-4o-mini"
30
- ) -> None:
31
- """Initialize PizzaGPT with enhanced configuration options."""
32
- if model not in self.AVAILABLE_MODELS:
33
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
34
-
35
- # Initialize curl_cffi Session
36
- self.session = Session()
37
- self.is_conversation = is_conversation
38
- self.max_tokens_to_sample = max_tokens
39
- self.api_endpoint = "https://www.pizzagpt.it/api/chatx-completion"
40
- self.stream_chunk_size = 64
41
- self.timeout = timeout
42
- self.last_response = {}
43
- self.model = model
44
-
45
- self.headers = {
46
- "accept": "application/json",
47
- "accept-language": "en-US,en;q=0.9",
48
- "content-type": "application/json",
49
- "origin": "https://www.pizzagpt.it",
50
- "referer": "https://www.pizzagpt.it/en",
51
- "user-agent": Lit().random(),
52
- "x-secret": "Marinara",
53
- }
54
-
55
- self.__available_optimizers = (
56
- method for method in dir(Optimizers)
57
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
58
- )
59
-
60
- # Update curl_cffi session headers and proxies
61
- self.session.headers.update(self.headers)
62
- self.session.proxies = proxies # Assign proxies directly
63
-
64
- Conversation.intro = (
65
- AwesomePrompts().get_act(
66
- act, raise_not_found=True, default=None, case_insensitive=True
67
- )
68
- if act
69
- else intro or Conversation.intro
70
- )
71
-
72
- self.conversation = Conversation(
73
- is_conversation, self.max_tokens_to_sample, filepath, update_file
74
- )
75
- self.conversation.history_offset = history_offset
76
-
77
- def _extract_content(self, text: str) -> Dict[str, Any]:
78
- """
79
- Extract content from response text using regex.
80
- """
81
- try:
82
- # Look for content pattern
83
- content_match = re.search(r'"content"\s*:\s*"(.*?)"(?=\s*[,}])', text, re.DOTALL)
84
- if not content_match:
85
- raise exceptions.FailedToGenerateResponseError("Content not found in response")
86
-
87
- content = content_match.group(1)
88
- # Unescape special characters
89
- content = content.encode().decode('unicode_escape')
90
-
91
- # Look for citations if present
92
- citations = []
93
- citations_match = re.search(r'"citations"\s*:\s*\[(.*?)\]', text, re.DOTALL)
94
- if citations_match:
95
- citations_text = citations_match.group(1)
96
- citations = re.findall(r'"(.*?)"', citations_text)
97
-
98
- return {
99
- "content": content,
100
- "citations": citations
101
- }
102
-
103
- except Exception as e:
104
- raise exceptions.FailedToGenerateResponseError(f"Failed to extract content: {str(e)}")
105
-
106
- def ask(
107
- self,
108
- prompt: str,
109
- stream: bool = False, # Note: API does not support streaming
110
- raw: bool = False, # Keep raw param for interface consistency
111
- optimizer: str = None,
112
- conversationally: bool = False,
113
- web_search: bool = False,
114
- ) -> Dict[str, Any]:
115
- """
116
- Send a prompt to PizzaGPT API with optional web search capability.
117
- """
118
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
119
- if optimizer:
120
- if optimizer in self.__available_optimizers:
121
- conversation_prompt = getattr(Optimizers, optimizer)(conversation_prompt if conversationally else prompt)
122
- else:
123
- raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
124
-
125
- payload = {
126
- "question": conversation_prompt,
127
- "model": self.model,
128
- "searchEnabled": web_search
129
- }
130
-
131
- try:
132
- # Use curl_cffi session post with impersonate
133
- response = self.session.post(
134
- self.api_endpoint,
135
- # headers are set on the session
136
- json=payload,
137
- timeout=self.timeout,
138
- # proxies are set on the session
139
- impersonate="chrome110" # Use a common impersonation profile
140
- )
141
-
142
- response.raise_for_status() # Check for HTTP errors
143
-
144
- response_text = response.text
145
- if not response_text:
146
- raise exceptions.FailedToGenerateResponseError("Empty response received from API")
147
-
148
- try:
149
- resp = self._extract_content(response_text)
150
-
151
- self.last_response = {"text": resp['content']} # Store only text in last_response
152
- self.conversation.update_chat_history(
153
- prompt, self.get_message(self.last_response)
154
- )
155
- # Return the full extracted data (content + citations) or raw text
156
- return response_text if raw else resp
157
-
158
- except Exception as e:
159
- raise exceptions.FailedToGenerateResponseError(f"Failed to parse response: {str(e)}")
160
-
161
- except CurlError as e: # Catch CurlError
162
- raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
163
- except Exception as e: # Catch other potential exceptions (like HTTPError)
164
- err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
165
- raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e} - {err_text}") from e
166
-
167
- def chat(
168
- self,
169
- prompt: str,
170
- stream: bool = False, # Keep stream param for interface consistency
171
- optimizer: str = None,
172
- conversationally: bool = False,
173
- web_search: bool = False,
174
- # Add raw parameter for consistency
175
- raw: bool = False
176
- ) -> str:
177
- """
178
- Chat with PizzaGPT with optional web search capability.
179
- """
180
- # API doesn't stream, call ask directly
181
- response_data = self.ask(
182
- prompt,
183
- stream=False, # Call ask in non-stream mode
184
- raw=raw, # Pass raw flag to ask
185
- optimizer=optimizer,
186
- conversationally=conversationally,
187
- web_search=web_search
188
- )
189
- # If raw=True, ask returns string, otherwise dict
190
- return response_data if raw else self.get_message(response_data)
191
-
192
-
193
- def get_message(self, response: dict) -> str:
194
- """Extract message from response dictionary."""
195
- # Handle case where raw response (string) might be passed mistakenly
196
- if isinstance(response, str):
197
- # Attempt to parse if it looks like the expected structure, otherwise return as is
198
- try:
199
- extracted = self._extract_content(response)
200
- return extracted.get("content", "")
201
- except:
202
- return response # Return raw string if parsing fails
203
- elif isinstance(response, dict):
204
- # If it's already the extracted dict from ask(raw=False)
205
- if "content" in response:
206
- return response.get("content", "")
207
- # If it's the last_response format
208
- elif "text" in response:
209
- return response.get("text", "")
210
- return "" # Default empty string
211
-
212
- if __name__ == "__main__":
213
- # Ensure curl_cffi is installed
214
- from rich import print
215
-
216
- # Example usage with web search enabled
217
- ai = PIZZAGPT(timeout=60)
218
- try:
219
- print("[bold blue]Testing Chat (Web Search Disabled):[/bold blue]")
220
- response = ai.chat("hi", web_search=False)
221
- print(response)
222
-
223
- # print("\n[bold blue]Testing Chat (Web Search Enabled):[/bold blue]")
224
- # response_web = ai.chat("What's the weather in Rome?", web_search=True)
225
- # print(response_web)
226
-
227
- except Exception as e:
228
- print(f"[bold red]Error:[/bold red] {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)