webscout 2.9__py3-none-any.whl → 3.0__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,211 +1,211 @@
1
- import requests
2
- import json
3
- import uuid
4
- from typing import Any, Dict, Optional
5
- from ..AIutel import Optimizers
6
- from ..AIutel import Conversation
7
- from ..AIutel import AwesomePrompts, sanitize_stream
8
- from ..AIbase import Provider, AsyncProvider
9
- from webscout import exceptions
10
-
11
- class Berlin4h(Provider):
12
- """
13
- A class to interact with the Berlin4h AI API.
14
- """
15
-
16
- def __init__(
17
- self,
18
- api_token: str = "3bf369cd84339603f8a5361e964f9ebe",
19
- api_endpoint: str = "https://ai.berlin4h.top/api/chat/completions",
20
- model: str = "gpt-3.5-turbo",
21
- temperature: float = 0.9,
22
- presence_penalty: float = 0,
23
- frequency_penalty: float = 0,
24
- max_tokens: int = 4000,
25
- is_conversation: bool = True,
26
- timeout: int = 30,
27
- intro: str = None,
28
- filepath: str = None,
29
- update_file: bool = True,
30
- proxies: dict = {},
31
- history_offset: int = 10250,
32
- act: str = None,
33
- ) -> None:
34
- """
35
- Initializes the Berlin4h API with given parameters.
36
-
37
- Args:
38
- api_token (str): The API token for authentication.
39
- api_endpoint (str): The API endpoint to use for requests.
40
- model (str): The AI model to use for text generation.
41
- temperature (float): The temperature parameter for the model.
42
- presence_penalty (float): The presence penalty parameter for the model.
43
- frequency_penalty (float): The frequency penalty parameter for the model.
44
- max_tokens (int): The maximum number of tokens to generate.
45
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
46
- timeout (int, optional): Http request timeout. Defaults to 30.
47
- intro (str, optional): Conversation introductory prompt. Defaults to None.
48
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
49
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
50
- proxies (dict, optional): Http request proxies. Defaults to {}.
51
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
52
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
53
- """
54
- self.api_token = api_token
55
- self.api_endpoint = api_endpoint
56
- self.model = model
57
- self.temperature = temperature
58
- self.presence_penalty = presence_penalty
59
- self.frequency_penalty = frequency_penalty
60
- self.max_tokens = max_tokens
61
- self.parent_message_id: Optional[str] = None
62
- self.session = requests.Session()
63
- self.is_conversation = is_conversation
64
- self.max_tokens_to_sample = max_tokens
65
- self.stream_chunk_size = 1
66
- self.timeout = timeout
67
- self.last_response = {}
68
- self.headers = {"Content-Type": "application/json", "Token": self.api_token}
69
- self.__available_optimizers = (
70
- method
71
- for method in dir(Optimizers)
72
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
73
- )
74
- self.session.headers.update(self.headers)
75
- Conversation.intro = (
76
- AwesomePrompts().get_act(
77
- act, raise_not_found=True, default=None, case_insensitive=True
78
- )
79
- if act
80
- else intro or Conversation.intro
81
- )
82
- self.conversation = Conversation(
83
- is_conversation, self.max_tokens_to_sample, filepath, update_file
84
- )
85
- self.conversation.history_offset = history_offset
86
- self.session.proxies = proxies
87
-
88
- def ask(
89
- self,
90
- prompt: str,
91
- stream: bool = False,
92
- raw: bool = False,
93
- optimizer: str = None,
94
- conversationally: bool = False,
95
- ) -> Dict[str, Any]:
96
- """
97
- Sends a prompt to the Berlin4h AI API and returns the response.
98
-
99
- Args:
100
- prompt: The text prompt to generate text from.
101
- stream (bool, optional): Whether to stream the response. Defaults to False.
102
- raw (bool, optional): Whether to return the raw response. Defaults to False.
103
- optimizer (str, optional): The name of the optimizer to use. Defaults to None.
104
- conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
105
-
106
- Returns:
107
- The response from the API.
108
- """
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(
117
- f"Optimizer is not one of {self.__available_optimizers}"
118
- )
119
-
120
- payload: Dict[str, any] = {
121
- "prompt": conversation_prompt,
122
- "parentMessageId": self.parent_message_id or str(uuid.uuid4()),
123
- "options": {
124
- "model": self.model,
125
- "temperature": self.temperature,
126
- "presence_penalty": self.presence_penalty,
127
- "frequency_penalty": self.frequency_penalty,
128
- "max_tokens": self.max_tokens,
129
- },
130
- }
131
-
132
- def for_stream():
133
- response = self.session.post(
134
- self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
135
- )
136
-
137
- if not response.ok:
138
- raise exceptions.FailedToGenerateResponseError(
139
- f"Failed to generate response - ({response.status_code}, {response.reason})"
140
- )
141
-
142
- streaming_response = ""
143
- # Collect the entire line before processing
144
- for line in response.iter_lines(decode_unicode=True):
145
- if line:
146
- try:
147
- json_data = json.loads(line)
148
- content = json_data['content']
149
- if ">" in content: break
150
- streaming_response += content
151
- yield content if raw else dict(text=streaming_response) # Yield accumulated response
152
- except:
153
- continue
154
- self.last_response.update(dict(text=streaming_response))
155
- self.conversation.update_chat_history(
156
- prompt, self.get_message(self.last_response)
157
- )
158
-
159
- def for_non_stream():
160
- for _ in for_stream():
161
- pass
162
- return self.last_response
163
-
164
- return for_stream() if stream else for_non_stream()
165
-
166
- def chat(
167
- self,
168
- prompt: str,
169
- stream: bool = False,
170
- optimizer: str = None,
171
- conversationally: bool = False,
172
- ) -> str:
173
- """Generate response `str`
174
- Args:
175
- prompt (str): Prompt to be send.
176
- stream (bool, optional): Flag for streaming response. Defaults to False.
177
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
178
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
179
- Returns:
180
- str: Response generated
181
- """
182
-
183
- def for_stream():
184
- for response in self.ask(
185
- prompt, True, optimizer=optimizer, conversationally=conversationally
186
- ):
187
- yield self.get_message(response)
188
-
189
- def for_non_stream():
190
- return self.get_message(
191
- self.ask(
192
- prompt,
193
- False,
194
- optimizer=optimizer,
195
- conversationally=conversationally,
196
- )
197
- )
198
-
199
- return for_stream() if stream else for_non_stream()
200
-
201
- def get_message(self, response: dict) -> str:
202
- """Retrieves message only from response
203
-
204
- Args:
205
- response (dict): Response generated by `self.ask`
206
-
207
- Returns:
208
- str: Message extracted
209
- """
210
- assert isinstance(response, dict), "Response should be of dict data-type only"
1
+ import requests
2
+ import json
3
+ import uuid
4
+ from typing import Any, Dict, Optional
5
+ from ..AIutel import Optimizers
6
+ from ..AIutel import Conversation
7
+ from ..AIutel import AwesomePrompts, sanitize_stream
8
+ from ..AIbase import Provider, AsyncProvider
9
+ from webscout import exceptions
10
+
11
+ class Berlin4h(Provider):
12
+ """
13
+ A class to interact with the Berlin4h AI API.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ api_token: str = "3bf369cd84339603f8a5361e964f9ebe",
19
+ api_endpoint: str = "https://ai.berlin4h.top/api/chat/completions",
20
+ model: str = "gpt-3.5-turbo",
21
+ temperature: float = 0.9,
22
+ presence_penalty: float = 0,
23
+ frequency_penalty: float = 0,
24
+ max_tokens: int = 4000,
25
+ is_conversation: bool = True,
26
+ timeout: int = 30,
27
+ intro: str = None,
28
+ filepath: str = None,
29
+ update_file: bool = True,
30
+ proxies: dict = {},
31
+ history_offset: int = 10250,
32
+ act: str = None,
33
+ ) -> None:
34
+ """
35
+ Initializes the Berlin4h API with given parameters.
36
+
37
+ Args:
38
+ api_token (str): The API token for authentication.
39
+ api_endpoint (str): The API endpoint to use for requests.
40
+ model (str): The AI model to use for text generation.
41
+ temperature (float): The temperature parameter for the model.
42
+ presence_penalty (float): The presence penalty parameter for the model.
43
+ frequency_penalty (float): The frequency penalty parameter for the model.
44
+ max_tokens (int): The maximum number of tokens to generate.
45
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
46
+ timeout (int, optional): Http request timeout. Defaults to 30.
47
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
48
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
49
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
50
+ proxies (dict, optional): Http request proxies. Defaults to {}.
51
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
52
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
53
+ """
54
+ self.api_token = api_token
55
+ self.api_endpoint = api_endpoint
56
+ self.model = model
57
+ self.temperature = temperature
58
+ self.presence_penalty = presence_penalty
59
+ self.frequency_penalty = frequency_penalty
60
+ self.max_tokens = max_tokens
61
+ self.parent_message_id: Optional[str] = None
62
+ self.session = requests.Session()
63
+ self.is_conversation = is_conversation
64
+ self.max_tokens_to_sample = max_tokens
65
+ self.stream_chunk_size = 1
66
+ self.timeout = timeout
67
+ self.last_response = {}
68
+ self.headers = {"Content-Type": "application/json", "Token": self.api_token}
69
+ self.__available_optimizers = (
70
+ method
71
+ for method in dir(Optimizers)
72
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
73
+ )
74
+ self.session.headers.update(self.headers)
75
+ Conversation.intro = (
76
+ AwesomePrompts().get_act(
77
+ act, raise_not_found=True, default=None, case_insensitive=True
78
+ )
79
+ if act
80
+ else intro or Conversation.intro
81
+ )
82
+ self.conversation = Conversation(
83
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
84
+ )
85
+ self.conversation.history_offset = history_offset
86
+ self.session.proxies = proxies
87
+
88
+ def ask(
89
+ self,
90
+ prompt: str,
91
+ stream: bool = False,
92
+ raw: bool = False,
93
+ optimizer: str = None,
94
+ conversationally: bool = False,
95
+ ) -> Dict[str, Any]:
96
+ """
97
+ Sends a prompt to the Berlin4h AI API and returns the response.
98
+
99
+ Args:
100
+ prompt: The text prompt to generate text from.
101
+ stream (bool, optional): Whether to stream the response. Defaults to False.
102
+ raw (bool, optional): Whether to return the raw response. Defaults to False.
103
+ optimizer (str, optional): The name of the optimizer to use. Defaults to None.
104
+ conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
105
+
106
+ Returns:
107
+ The response from the API.
108
+ """
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(
117
+ f"Optimizer is not one of {self.__available_optimizers}"
118
+ )
119
+
120
+ payload: Dict[str, any] = {
121
+ "prompt": conversation_prompt,
122
+ "parentMessageId": self.parent_message_id or str(uuid.uuid4()),
123
+ "options": {
124
+ "model": self.model,
125
+ "temperature": self.temperature,
126
+ "presence_penalty": self.presence_penalty,
127
+ "frequency_penalty": self.frequency_penalty,
128
+ "max_tokens": self.max_tokens,
129
+ },
130
+ }
131
+
132
+ def for_stream():
133
+ response = self.session.post(
134
+ self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
135
+ )
136
+
137
+ if not response.ok:
138
+ raise exceptions.FailedToGenerateResponseError(
139
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
140
+ )
141
+
142
+ streaming_response = ""
143
+ # Collect the entire line before processing
144
+ for line in response.iter_lines(decode_unicode=True):
145
+ if line:
146
+ try:
147
+ json_data = json.loads(line)
148
+ content = json_data['content']
149
+ if ">" in content: break
150
+ streaming_response += content
151
+ yield content if raw else dict(text=streaming_response) # Yield accumulated response
152
+ except:
153
+ continue
154
+ self.last_response.update(dict(text=streaming_response))
155
+ self.conversation.update_chat_history(
156
+ prompt, self.get_message(self.last_response)
157
+ )
158
+
159
+ def for_non_stream():
160
+ for _ in for_stream():
161
+ pass
162
+ return self.last_response
163
+
164
+ return for_stream() if stream else for_non_stream()
165
+
166
+ def chat(
167
+ self,
168
+ prompt: str,
169
+ stream: bool = False,
170
+ optimizer: str = None,
171
+ conversationally: bool = False,
172
+ ) -> str:
173
+ """Generate response `str`
174
+ Args:
175
+ prompt (str): Prompt to be send.
176
+ stream (bool, optional): Flag for streaming response. Defaults to False.
177
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
178
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
179
+ Returns:
180
+ str: Response generated
181
+ """
182
+
183
+ def for_stream():
184
+ for response in self.ask(
185
+ prompt, True, optimizer=optimizer, conversationally=conversationally
186
+ ):
187
+ yield self.get_message(response)
188
+
189
+ def for_non_stream():
190
+ return self.get_message(
191
+ self.ask(
192
+ prompt,
193
+ False,
194
+ optimizer=optimizer,
195
+ conversationally=conversationally,
196
+ )
197
+ )
198
+
199
+ return for_stream() if stream else for_non_stream()
200
+
201
+ def get_message(self, response: dict) -> str:
202
+ """Retrieves message only from response
203
+
204
+ Args:
205
+ response (dict): Response generated by `self.ask`
206
+
207
+ Returns:
208
+ str: Message extracted
209
+ """
210
+ assert isinstance(response, dict), "Response should be of dict data-type only"
211
211
  return response["text"]