webscout 6.2b0__py3-none-any.whl → 6.3__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.

@@ -1,198 +1,208 @@
1
- """
2
- Install the Google AI Python SDK
3
-
4
- $ pip install google-generativeai
5
- """
6
-
7
- import os
8
- import google.generativeai as genai
9
-
10
- import requests
11
- from webscout.AIutel import Optimizers
12
- from webscout.AIutel import Conversation
13
- from webscout.AIutel import AwesomePrompts
14
- from webscout.AIbase import Provider
15
-
16
-
17
- class GEMINIAPI(Provider):
18
- """
19
- A class to interact with the Gemini API using the google-generativeai library.
20
- """
21
-
22
- def __init__(
23
- self,
24
- api_key,
25
- model_name: str = "gemini-1.5-flash-latest",
26
- temperature: float = 1,
27
- top_p: float = 0.95,
28
- top_k: int = 64,
29
- max_output_tokens: int = 8192,
30
- is_conversation: bool = True,
31
- timeout: int = 30,
32
- intro: str = None,
33
- filepath: str = None,
34
- update_file: bool = True,
35
- proxies: dict = {},
36
- history_offset: int = 10250,
37
- act: str = None,
38
- system_instruction: str = "You are a helpful and informative AI assistant.",
39
- ):
40
- """
41
- Initializes the Gemini API with the given parameters.
42
-
43
- Args:
44
- api_key (str, optional): Your Gemini API key. If None, it will use the environment variable "GEMINI_API_KEY".
45
- Defaults to None.
46
- model_name (str, optional): The name of the Gemini model to use.
47
- Defaults to "gemini-1.5-flash-exp-0827".
48
- temperature (float, optional): The temperature parameter for the model. Defaults to 1.
49
- top_p (float, optional): The top_p parameter for the model. Defaults to 0.95.
50
- top_k (int, optional): The top_k parameter for the model. Defaults to 64.
51
- max_output_tokens (int, optional): The maximum number of output tokens. Defaults to 8192.
52
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
53
- timeout (int, optional): Http request timeout. Defaults to 30.
54
- intro (str, optional): Conversation introductory prompt. Defaults to None.
55
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
56
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
57
- proxies (dict, optional): Http request proxies. Defaults to {}.
58
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
59
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
60
- system_instruction (str, optional): System instruction to guide the AI's behavior.
61
- Defaults to "You are a helpful and informative AI assistant.".
62
- """
63
- self.api_key = api_key
64
- self.model_name = model_name
65
- self.temperature = temperature
66
- self.top_p = top_p
67
- self.top_k = top_k
68
- self.max_output_tokens = max_output_tokens
69
- self.system_instruction = system_instruction
70
-
71
- self.session = requests.Session() # Not directly used for Gemini API calls, but can be used for other requests
72
- self.is_conversation = is_conversation
73
- self.max_tokens_to_sample = max_output_tokens
74
- self.timeout = timeout
75
- self.last_response = {}
76
-
77
- self.__available_optimizers = (
78
- method
79
- for method in dir(Optimizers)
80
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
81
- )
82
- Conversation.intro = (
83
- AwesomePrompts().get_act(
84
- act, raise_not_found=True, default=None, case_insensitive=True
85
- )
86
- if act
87
- else intro or Conversation.intro
88
- )
89
- self.conversation = Conversation(
90
- is_conversation, self.max_tokens_to_sample, filepath, update_file
91
- )
92
- self.conversation.history_offset = history_offset
93
- self.session.proxies = proxies
94
-
95
- # Configure the Gemini API
96
- genai.configure(api_key=self.api_key)
97
-
98
- # Create the model with generation config
99
- self.generation_config = {
100
- "temperature": self.temperature,
101
- "top_p": self.top_p,
102
- "top_k": self.top_k,
103
- "max_output_tokens": self.max_output_tokens,
104
- "response_mime_type": "text/plain",
105
- }
106
- self.model = genai.GenerativeModel(
107
- model_name=self.model_name,
108
- generation_config=self.generation_config,
109
- system_instruction=self.system_instruction,
110
- )
111
-
112
- # Start the chat session
113
- self.chat_session = self.model.start_chat()
114
-
115
- def ask(
116
- self,
117
- prompt: str,
118
- stream: bool = False,
119
- raw: bool = False,
120
- optimizer: str = None,
121
- conversationally: bool = False,
122
- ) -> dict:
123
- """Chat with AI
124
-
125
- Args:
126
- prompt (str): Prompt to be send.
127
- stream (bool, optional): Not used for Gemini API. Defaults to False.
128
- raw (bool, optional): Not used for Gemini API. Defaults to False.
129
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
130
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
131
- Returns:
132
- dict : {}
133
- ```json
134
- {
135
- "text" : "How may I assist you today?"
136
- }
137
- ```
138
- """
139
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
140
- if optimizer:
141
- if optimizer in self.__available_optimizers:
142
- conversation_prompt = getattr(Optimizers, optimizer)(
143
- conversation_prompt if conversationally else prompt
144
- )
145
- else:
146
- raise Exception(
147
- f"Optimizer is not one of {self.__available_optimizers}"
148
- )
149
-
150
- # Send the message to the chat session and get the response
151
- response = self.chat_session.send_message(conversation_prompt)
152
- self.last_response.update(dict(text=response.text))
153
- self.conversation.update_chat_history(
154
- prompt, self.get_message(self.last_response)
155
- )
156
- return self.last_response
157
-
158
- def chat(
159
- self,
160
- prompt: str,
161
- stream: bool = False, # Streaming not supported by the current google-generativeai library
162
- optimizer: str = None,
163
- conversationally: bool = False,
164
- ) -> str:
165
- """Generate response `str`
166
-
167
- Args:
168
- prompt (str): Prompt to be send.
169
- stream (bool, optional): Not used for Gemini API. Defaults to False.
170
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
171
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
172
- Returns:
173
- str: Response generated
174
- """
175
- return self.get_message(
176
- self.ask(
177
- prompt,
178
- optimizer=optimizer,
179
- conversationally=conversationally,
180
- )
181
- )
182
-
183
- def get_message(self, response: dict) -> str:
184
- """Retrieves message only from response
185
-
186
- Args:
187
- response (dict): Response generated by `self.ask`
188
-
189
- Returns:
190
- str: Message extracted
191
- """
192
- assert isinstance(response, dict), "Response should be of dict data-type only"
193
- return response["text"]
194
- if __name__ == "__main__":
195
- ai = GEMINIAPI(api_key="")
196
- res = ai.chat(input(">>> "))
197
- for r in res:
198
- print(r, end="", flush=True)
1
+ """
2
+ Install the Google AI Python SDK
3
+
4
+ $ pip install google-generativeai
5
+ """
6
+
7
+ import os
8
+ import google.generativeai as genai
9
+
10
+ from google.generativeai.types import HarmCategory, HarmBlockThreshold
11
+ import requests
12
+ from webscout.AIutel import Optimizers
13
+ from webscout.AIutel import Conversation
14
+ from webscout.AIutel import AwesomePrompts
15
+ from webscout.AIbase import Provider
16
+
17
+
18
+ class GEMINIAPI(Provider):
19
+ """
20
+ A class to interact with the Gemini API using the google-generativeai library.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ api_key,
26
+ model_name: str = "gemini-1.5-flash-latest",
27
+ temperature: float = 1,
28
+ top_p: float = 0.95,
29
+ top_k: int = 64,
30
+ max_output_tokens: int = 8192,
31
+ is_conversation: bool = True,
32
+ timeout: int = 30,
33
+ intro: str = None,
34
+ filepath: str = None,
35
+ update_file: bool = True,
36
+ proxies: dict = {},
37
+ history_offset: int = 10250,
38
+ act: str = None,
39
+ system_instruction: str = "You are a helpful and informative AI assistant.",
40
+ safety_settings: dict = None,
41
+ ):
42
+ """
43
+ Initializes the Gemini API with the given parameters.
44
+
45
+ Args:
46
+ api_key (str, optional): Your Gemini API key. If None, it will use the environment variable "GEMINI_API_KEY".
47
+ Defaults to None.
48
+ model_name (str, optional): The name of the Gemini model to use.
49
+ Defaults to "gemini-1.5-flash-exp-0827".
50
+ temperature (float, optional): The temperature parameter for the model. Defaults to 1.
51
+ top_p (float, optional): The top_p parameter for the model. Defaults to 0.95.
52
+ top_k (int, optional): The top_k parameter for the model. Defaults to 64.
53
+ max_output_tokens (int, optional): The maximum number of output tokens. Defaults to 8192.
54
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
55
+ timeout (int, optional): Http request timeout. Defaults to 30.
56
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
57
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
58
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
59
+ proxies (dict, optional): Http request proxies. Defaults to {}.
60
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
61
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
62
+ system_instruction (str, optional): System instruction to guide the AI's behavior.
63
+ Defaults to "You are a helpful and informative AI assistant.".
64
+ """
65
+ self.api_key = api_key
66
+ self.model_name = model_name
67
+ self.temperature = temperature
68
+ self.top_p = top_p
69
+ self.top_k = top_k
70
+ self.max_output_tokens = max_output_tokens
71
+ self.system_instruction = system_instruction
72
+ self.safety_settings = safety_settings if safety_settings else {}
73
+ self.session = requests.Session() # Not directly used for Gemini API calls, but can be used for other requests
74
+ self.is_conversation = is_conversation
75
+ self.max_tokens_to_sample = max_output_tokens
76
+ self.timeout = timeout
77
+ self.last_response = {}
78
+
79
+ self.__available_optimizers = (
80
+ method
81
+ for method in dir(Optimizers)
82
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
83
+ )
84
+ Conversation.intro = (
85
+ AwesomePrompts().get_act(
86
+ act, raise_not_found=True, default=None, case_insensitive=True
87
+ )
88
+ if act
89
+ else intro or Conversation.intro
90
+ )
91
+ self.conversation = Conversation(
92
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
93
+ )
94
+ self.conversation.history_offset = history_offset
95
+ self.session.proxies = proxies
96
+
97
+ # Configure the Gemini API
98
+ genai.configure(api_key=self.api_key)
99
+
100
+ # Create the model with generation config
101
+ self.generation_config = {
102
+ "temperature": self.temperature,
103
+ "top_p": self.top_p,
104
+ "top_k": self.top_k,
105
+ "max_output_tokens": self.max_output_tokens,
106
+ "response_mime_type": "text/plain",
107
+ }
108
+
109
+ self.model = genai.GenerativeModel(
110
+ model_name=self.model_name,
111
+ generation_config=self.generation_config,
112
+ safety_settings=self.safety_settings,
113
+ system_instruction=self.system_instruction,
114
+ )
115
+
116
+ # Start the chat session
117
+ self.chat_session = self.model.start_chat()
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
+ ) -> dict:
127
+ """Chat with AI
128
+
129
+ Args:
130
+ prompt (str): Prompt to be send.
131
+ stream (bool, optional): Not used for Gemini API. Defaults to False.
132
+ raw (bool, optional): Not used for Gemini API. Defaults to False.
133
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
134
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
135
+ Returns:
136
+ dict : {}
137
+ ```json
138
+ {
139
+ "text" : "How may I assist you today?"
140
+ }
141
+ ```
142
+ """
143
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
144
+ if optimizer:
145
+ if optimizer in self.__available_optimizers:
146
+ conversation_prompt = getattr(Optimizers, optimizer)(
147
+ conversation_prompt if conversationally else prompt
148
+ )
149
+ else:
150
+ raise Exception(
151
+ f"Optimizer is not one of {self.__available_optimizers}"
152
+ )
153
+
154
+ # Send the message to the chat session and get the response
155
+ response = self.chat_session.send_message(conversation_prompt)
156
+ self.last_response.update(dict(text=response.text))
157
+ self.conversation.update_chat_history(
158
+ prompt, self.get_message(self.last_response)
159
+ )
160
+ return self.last_response
161
+
162
+ def chat(
163
+ self,
164
+ prompt: str,
165
+ stream: bool = False, # Streaming not supported by the current google-generativeai library
166
+ optimizer: str = None,
167
+ conversationally: bool = False,
168
+ ) -> str:
169
+ """Generate response `str`
170
+
171
+ Args:
172
+ prompt (str): Prompt to be send.
173
+ stream (bool, optional): Not used for Gemini API. Defaults to False.
174
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
175
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
176
+ Returns:
177
+ str: Response generated
178
+ """
179
+ return self.get_message(
180
+ self.ask(
181
+ prompt,
182
+ optimizer=optimizer,
183
+ conversationally=conversationally,
184
+ )
185
+ )
186
+
187
+ def get_message(self, response: dict) -> str:
188
+ """Retrieves message only from response
189
+
190
+ Args:
191
+ response (dict): Response generated by `self.ask`
192
+
193
+ Returns:
194
+ str: Message extracted
195
+ """
196
+ assert isinstance(response, dict), "Response should be of dict data-type only"
197
+ return response["text"]
198
+ if __name__ == "__main__":
199
+ safety_settings = {
200
+ HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
201
+ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
202
+ HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
203
+ HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
204
+ }
205
+ ai = GEMINIAPI(api_key="" , safety_settings=safety_settings)
206
+ res = ai.chat(input(">>> "))
207
+ for r in res:
208
+ print(r, end="", flush=True)
@@ -0,0 +1,181 @@
1
+ import requests
2
+ import json
3
+ import re
4
+ from typing import 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
+
12
+
13
+ class Llama3Mitril(Provider):
14
+ """
15
+ A class to interact with the Llama3 Mitril API. Implements the WebScout provider interface.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ is_conversation: bool = True,
21
+ max_tokens: int = 2048,
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, respectful and honest assistant.",
30
+ temperature: float = 0.8,
31
+ ):
32
+ """Initializes the Llama3Mitril API."""
33
+ self.session = requests.Session()
34
+ self.is_conversation = is_conversation
35
+ self.max_tokens = max_tokens
36
+ self.temperature = temperature
37
+ self.api_endpoint = "https://llama3.mithrilsecurity.io/generate_stream"
38
+ self.timeout = timeout
39
+ self.last_response = {}
40
+ self.system_prompt = system_prompt
41
+ self.headers = {
42
+ "Content-Type": "application/json",
43
+ "DNT": "1",
44
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
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, filepath, update_file
60
+ )
61
+ self.conversation.history_offset = history_offset
62
+ self.session.proxies = proxies
63
+
64
+ def _format_prompt(self, prompt: str) -> str:
65
+ """Format the prompt for the Llama3 model"""
66
+ return (
67
+ f"<|begin_of_text|>"
68
+ f"<|start_header_id|>system<|end_header_id|>{self.system_prompt}<|eot_id|>"
69
+ f"<|start_header_id|>user<|end_header_id|>{prompt}<|eot_id|>"
70
+ f"<|start_header_id|>assistant<|end_header_id|><|eot_id|>"
71
+ f"<|start_header_id|>assistant<|end_header_id|>"
72
+ )
73
+
74
+ def ask(
75
+ self,
76
+ prompt: str,
77
+ stream: bool = True,
78
+ raw: bool = False,
79
+ optimizer: str = None,
80
+ conversationally: bool = False,
81
+ ) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
82
+ """Sends a prompt to the Llama3 Mitril API and returns the response."""
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 exceptions.FailedToGenerateResponseError(
91
+ f"Optimizer is not one of {self.__available_optimizers}"
92
+ )
93
+
94
+ data = {
95
+ "inputs": self._format_prompt(conversation_prompt),
96
+ "parameters": {
97
+ "max_new_tokens": self.max_tokens,
98
+ "temperature": self.temperature,
99
+ "return_full_text": False
100
+ }
101
+ }
102
+
103
+ def for_stream():
104
+ response = self.session.post(
105
+ self.api_endpoint,
106
+ headers=self.headers,
107
+ json=data,
108
+ stream=True,
109
+ timeout=self.timeout
110
+ )
111
+ if not response.ok:
112
+ raise exceptions.FailedToGenerateResponseError(
113
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
114
+ )
115
+
116
+ streaming_response = ""
117
+ for line in response.iter_lines(decode_unicode=True):
118
+ if line:
119
+ try:
120
+ chunk = json.loads(line.split('data: ')[1])
121
+ if token_text := chunk.get('token', {}).get('text'):
122
+ if '<|eot_id|>' not in token_text:
123
+ streaming_response += token_text
124
+ yield token_text if raw else {"text": token_text}
125
+ except (json.JSONDecodeError, IndexError) as e:
126
+ continue
127
+
128
+ self.last_response.update({"text": streaming_response})
129
+ self.conversation.update_chat_history(
130
+ prompt, self.get_message(self.last_response)
131
+ )
132
+
133
+ def for_non_stream():
134
+ full_response = ""
135
+ for chunk in for_stream():
136
+ full_response += chunk if raw else chunk['text']
137
+ return {"text": full_response}
138
+
139
+ return for_stream() if stream else for_non_stream()
140
+
141
+ def chat(
142
+ self,
143
+ prompt: str,
144
+ stream: bool = True,
145
+ optimizer: str = None,
146
+ conversationally: bool = False,
147
+ ) -> str | Generator[str, None, None]:
148
+ """Generates a response from the Llama3 Mitril API."""
149
+
150
+ def for_stream():
151
+ for response in self.ask(
152
+ prompt, stream=True, optimizer=optimizer, conversationally=conversationally
153
+ ):
154
+ yield self.get_message(response)
155
+
156
+ def for_non_stream():
157
+ return self.get_message(
158
+ self.ask(
159
+ prompt, stream=False, optimizer=optimizer, conversationally=conversationally
160
+ )
161
+ )
162
+
163
+ return for_stream() if stream else for_non_stream()
164
+
165
+ def get_message(self, response: Dict[str, Any]) -> str:
166
+ """Extracts the message from the API response."""
167
+ assert isinstance(response, dict), "Response should be of dict data-type only"
168
+ return response["text"]
169
+
170
+
171
+ if __name__ == "__main__":
172
+ from rich import print
173
+
174
+ ai = Llama3Mitril(
175
+ max_tokens=2048,
176
+ temperature=0.8,
177
+ timeout=30
178
+ )
179
+
180
+ for response in ai.chat("Hello", stream=True):
181
+ print(response)