webscout 6.9__py3-none-any.whl → 7.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,155 +0,0 @@
1
- import requests
2
- import json
3
- import re
4
- from typing import Any, Dict, Generator, Optional
5
-
6
- from webscout.AIbase import Provider
7
- from webscout import exceptions
8
- from webscout.litagent import LitAgent
9
-
10
-
11
- class OOAi(Provider):
12
- """
13
- A class to interact with the oo.ai API.
14
- """
15
-
16
- def __init__(
17
- self,
18
- max_tokens: int = 600,
19
- timeout: int = 30,
20
- proxies: Optional[dict] = None,
21
- ):
22
- """Initializes the OOAi API client."""
23
- self.session = requests.Session()
24
- self.max_tokens_to_sample = max_tokens
25
- self.api_endpoint = "https://oo.ai/api/search"
26
- self.stream_chunk_size = 1024 # Adjust as needed
27
- self.timeout = timeout
28
- self.last_response = {}
29
- self.headers = {
30
- "Accept": "text/event-stream",
31
- "Accept-Encoding": "gzip, deflate, br, zstd",
32
- "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
33
- "Cache-Control": "no-cache",
34
- "Cookie": "_ga=GA1.1.1827087199.1734256606; _ga_P0EJPHF2EG=GS1.1.1734368698.4.1.1734368711.0.0.0",
35
- "DNT": "1",
36
- "Referer": "https://oo.ai/",
37
- "sec-ch-ua": '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A_Brand";v="24"',
38
- "sec-ch-ua-mobile": "?0",
39
- "sec-ch-ua-platform": "Windows",
40
- "sec-fetch-dest": "empty",
41
- "sec-fetch-mode": "cors",
42
- "sec-fetch-site": "same-origin",
43
- }
44
- self.session.headers.update(self.headers)
45
- self.proxies = proxies
46
- self.headers["User-Agent"] = LitAgent().random()
47
-
48
- def ask(
49
- self,
50
- prompt: str,
51
- stream: bool = False,
52
- raw: bool = False,
53
- optimizer: Optional[str] = None,
54
- conversationally: bool = False,
55
- ) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
56
- """Chat with AI
57
- Args:
58
- prompt (str): Prompt to be sent.
59
- stream (bool, optional): Flag for streaming response. Defaults to False.
60
- raw (bool, optional): Stream back raw response as received. Defaults to False.
61
- optimizer (str, optional): Not used. Defaults to None.
62
- conversationally (bool, optional): Not used. Defaults to False.
63
- Returns:
64
- Union[Dict, Generator[Dict, None, None]]: Response generated
65
- """
66
- params = {
67
- "q": prompt,
68
- "lang": "en-US",
69
- "tz": "Asia/Calcutta",
70
- }
71
-
72
- def for_stream():
73
- try:
74
- with self.session.get(
75
- self.api_endpoint,
76
- params=params,
77
- headers=self.headers,
78
- stream=True,
79
- timeout=self.timeout,
80
- ) as response:
81
-
82
- if not response.ok:
83
- raise exceptions.FailedToGenerateResponseError(
84
- f"Request failed with status code {response.status_code}: {response.text}"
85
- )
86
-
87
- streaming_text = ""
88
- for line in response.iter_lines(decode_unicode=True):
89
- if line and line.startswith('data: '):
90
- try:
91
- json_data = json.loads(line[6:])
92
- if "content" in json_data:
93
- content = self.clean_content(json_data["content"])
94
- streaming_text += content
95
- yield {"text": content} if not raw else {"text": content}
96
- except json.JSONDecodeError:
97
- continue
98
- self.last_response.update({"text": streaming_text})
99
-
100
- except requests.exceptions.RequestException as e:
101
- raise exceptions.APIConnectionError(f"Request failed: {e}")
102
-
103
- def for_non_stream():
104
- for _ in for_stream():
105
- pass
106
- return self.last_response
107
-
108
- return for_stream() if stream else for_non_stream()
109
-
110
- def chat(
111
- self,
112
- prompt: str,
113
- stream: bool = False,
114
- optimizer: Optional[str] = None,
115
- conversationally: bool = False,
116
- ) -> str | Generator[str, None, None]:
117
- """Generate response `str`"""
118
-
119
- def for_stream():
120
- for response in self.ask(
121
- prompt, True, optimizer=optimizer, conversationally=conversationally
122
- ):
123
- yield self.get_message(response)
124
-
125
- def for_non_stream():
126
- return self.get_message(
127
- self.ask(
128
- prompt,
129
- False,
130
- optimizer=optimizer,
131
- conversationally=conversationally,
132
- )
133
- )
134
-
135
- return for_stream() if stream else for_non_stream()
136
-
137
- def get_message(self, response: dict) -> str:
138
- """Retrieves message only from response"""
139
- assert isinstance(response, dict), "Response should be of dict data-type only"
140
- return response["text"]
141
-
142
- @staticmethod
143
- def clean_content(text: str) -> str:
144
- """Removes all webblock elements with research or detail classes."""
145
- cleaned_text = re.sub(
146
- r'<webblock class="(?:research|detail)">[^<]*</webblock>', "", text
147
- )
148
- return cleaned_text
149
-
150
- if __name__ == "__main__":
151
- from rich import print
152
- ai = OOAi()
153
- response = ai.chat(input(">>> "), stream=True)
154
- for chunk in response:
155
- print(chunk, end="", flush=True)