webscout 5.2__py3-none-any.whl → 5.4__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.
- webscout/AIauto.py +8 -12
- webscout/AIutel.py +10 -10
- webscout/Agents/Onlinesearcher.py +5 -5
- webscout/Agents/functioncall.py +123 -97
- webscout/DWEBS.py +99 -77
- webscout/Local/_version.py +2 -2
- webscout/Provider/Andi.py +1 -21
- webscout/Provider/BasedGPT.py +1 -21
- webscout/Provider/Blackboxai.py +1 -21
- webscout/Provider/Chatify.py +175 -0
- webscout/Provider/Cloudflare.py +1 -22
- webscout/Provider/Cohere.py +2 -23
- webscout/Provider/DARKAI.py +0 -1
- webscout/Provider/Deepinfra.py +2 -16
- webscout/Provider/EDITEE.py +3 -26
- webscout/Provider/Gemini.py +1 -24
- webscout/Provider/Groq.py +0 -2
- webscout/Provider/Koboldai.py +0 -21
- webscout/Provider/Llama.py +4 -21
- webscout/Provider/NetFly.py +21 -61
- webscout/Provider/OLLAMA.py +0 -17
- webscout/Provider/Openai.py +2 -22
- webscout/Provider/Perplexity.py +1 -2
- webscout/Provider/Phind.py +3 -508
- webscout/Provider/RUBIKSAI.py +11 -5
- webscout/Provider/Reka.py +4 -21
- webscout/Provider/TTS/streamElements.py +1 -22
- webscout/Provider/TTS/voicepod.py +11 -8
- webscout/Provider/ThinkAnyAI.py +17 -78
- webscout/Provider/Youchat.py +3 -20
- webscout/Provider/__init__.py +17 -8
- webscout/Provider/ai4chat.py +14 -8
- webscout/Provider/cerebras.py +199 -0
- webscout/Provider/{Berlin4h.py → cleeai.py} +68 -73
- webscout/Provider/{liaobots.py → elmo.py} +75 -106
- webscout/Provider/felo_search.py +29 -87
- webscout/Provider/geminiapi.py +198 -0
- webscout/Provider/genspark.py +222 -0
- webscout/Provider/julius.py +3 -20
- webscout/Provider/koala.py +1 -1
- webscout/Provider/lepton.py +194 -0
- webscout/Provider/turboseek.py +4 -21
- webscout/Provider/x0gpt.py +182 -0
- webscout/Provider/xdash.py +2 -22
- webscout/Provider/yep.py +391 -149
- webscout/YTdownloader.py +2 -3
- webscout/__init__.py +2 -2
- webscout/exceptions.py +2 -1
- webscout/transcriber.py +195 -140
- webscout/version.py +1 -1
- {webscout-5.2.dist-info → webscout-5.4.dist-info}/METADATA +47 -134
- webscout-5.4.dist-info/RECORD +98 -0
- webscout/voice.py +0 -34
- webscout-5.2.dist-info/RECORD +0 -93
- {webscout-5.2.dist-info → webscout-5.4.dist-info}/LICENSE.md +0 -0
- {webscout-5.2.dist-info → webscout-5.4.dist-info}/WHEEL +0 -0
- {webscout-5.2.dist-info → webscout-5.4.dist-info}/entry_points.txt +0 -0
- {webscout-5.2.dist-info → webscout-5.4.dist-info}/top_level.txt +0 -0
webscout/Provider/ThinkAnyAI.py
CHANGED
|
@@ -1,41 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
import uuid
|
|
3
|
-
from selenium import webdriver
|
|
4
|
-
from selenium.webdriver.chrome.options import Options
|
|
5
|
-
from selenium.webdriver.common.by import By
|
|
6
|
-
from selenium.webdriver.support import expected_conditions as EC
|
|
7
|
-
from selenium.webdriver.support.ui import WebDriverWait
|
|
8
|
-
import click
|
|
1
|
+
|
|
9
2
|
import requests
|
|
10
|
-
|
|
11
|
-
from
|
|
12
|
-
from
|
|
13
|
-
from
|
|
14
|
-
from
|
|
15
|
-
import g4f
|
|
16
|
-
from random import randint
|
|
17
|
-
from PIL import Image
|
|
18
|
-
import io
|
|
19
|
-
import re
|
|
20
|
-
import json
|
|
21
|
-
import yaml
|
|
22
|
-
from ..AIutel import Optimizers
|
|
23
|
-
from ..AIutel import Conversation
|
|
24
|
-
from ..AIutel import AwesomePrompts, sanitize_stream
|
|
25
|
-
from ..AIbase import Provider, AsyncProvider
|
|
26
|
-
from Helpingai_T2 import Perplexity
|
|
3
|
+
|
|
4
|
+
from webscout.AIutel import Optimizers
|
|
5
|
+
from webscout.AIutel import Conversation
|
|
6
|
+
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
7
|
+
from webscout.AIbase import Provider, AsyncProvider
|
|
27
8
|
from webscout import exceptions
|
|
28
9
|
from typing import Any, AsyncGenerator, Dict
|
|
29
|
-
|
|
30
|
-
import httpx
|
|
10
|
+
|
|
31
11
|
#------------------------------------ThinkAnyAI------------
|
|
32
12
|
class ThinkAnyAI(Provider):
|
|
33
13
|
def __init__(
|
|
34
14
|
self,
|
|
35
15
|
model: str = "claude-3-haiku",
|
|
36
16
|
locale: str = "en",
|
|
37
|
-
web_search: bool =
|
|
38
|
-
chunk_size: int =
|
|
17
|
+
web_search: bool = True,
|
|
18
|
+
chunk_size: int = 64,
|
|
39
19
|
streaming: bool = True,
|
|
40
20
|
is_conversation: bool = True,
|
|
41
21
|
max_tokens: int = 600,
|
|
@@ -101,54 +81,7 @@ class ThinkAnyAI(Provider):
|
|
|
101
81
|
optimizer: str = None,
|
|
102
82
|
conversationally: bool = False,
|
|
103
83
|
) -> dict | AsyncGenerator:
|
|
104
|
-
"""Chat with AI asynchronously.
|
|
105
|
-
|
|
106
|
-
Args:
|
|
107
|
-
prompt (str): Prompt to be send.
|
|
108
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
109
|
-
raw (bool, optional): Stream back raw response as received. Defaults to False.
|
|
110
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defeaults to None
|
|
111
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
112
|
-
Returns:
|
|
113
|
-
dict : {}
|
|
114
|
-
```json
|
|
115
|
-
{
|
|
116
|
-
"content": "General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]",
|
|
117
|
-
"conversation_id": "c_f13f6217f9a997aa",
|
|
118
|
-
"response_id": "r_d3665f95975c368f",
|
|
119
|
-
"factualityQueries": null,
|
|
120
|
-
"textQuery": [
|
|
121
|
-
"hello there",
|
|
122
|
-
1
|
|
123
|
-
],
|
|
124
|
-
"choices": [
|
|
125
|
-
{
|
|
126
|
-
"id": "rc_ea075c9671bfd8cb",
|
|
127
|
-
"content": [
|
|
128
|
-
"General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]"
|
|
129
|
-
]
|
|
130
|
-
},
|
|
131
|
-
{
|
|
132
|
-
"id": "rc_de6dd3fb793a5402",
|
|
133
|
-
"content": [
|
|
134
|
-
"General Kenobi! (or just a friendly hello, whichever you prefer!). \n\nI see you're a person of culture as well. *Star Wars* references are always appreciated. \n\nHow can I help you today?\n"
|
|
135
|
-
]
|
|
136
|
-
},
|
|
137
|
-
{
|
|
138
|
-
"id": "rc_a672ac089caf32db",
|
|
139
|
-
"content": [
|
|
140
|
-
"General Kenobi! (or just a friendly hello if you're not a Star Wars fan!). \n\nHow can I help you today? Feel free to ask me anything, or tell me what you'd like to chat about. I'm here to assist in any way I can.\n[Image of Obi-Wan Kenobi saying hello there]"
|
|
141
|
-
]
|
|
142
|
-
}
|
|
143
|
-
],
|
|
144
84
|
|
|
145
|
-
"images": [
|
|
146
|
-
"https://i.pinimg.com/originals/40/74/60/407460925c9e419d82b93313f0b42f71.jpg"
|
|
147
|
-
]
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
```
|
|
151
|
-
"""
|
|
152
85
|
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
153
86
|
if optimizer:
|
|
154
87
|
if optimizer in self.__available_optimizers:
|
|
@@ -204,7 +137,7 @@ class ThinkAnyAI(Provider):
|
|
|
204
137
|
conversation_uuid = initiate_conversation(conversation_prompt)
|
|
205
138
|
web_search_result, links = RAG_search(conversation_uuid)
|
|
206
139
|
if not web_search_result:
|
|
207
|
-
print("Failed to generate WEB response. Making normal
|
|
140
|
+
print("Failed to generate WEB response. Making normal Querywebscout..")
|
|
208
141
|
|
|
209
142
|
url = f"{self.base_url}/chat"
|
|
210
143
|
payload = {
|
|
@@ -277,4 +210,10 @@ class ThinkAnyAI(Provider):
|
|
|
277
210
|
str: Message extracted
|
|
278
211
|
"""
|
|
279
212
|
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
280
|
-
return response["text"]
|
|
213
|
+
return response["text"]
|
|
214
|
+
if __name__ == "__main__":
|
|
215
|
+
from rich import print
|
|
216
|
+
ai = ThinkAnyAI()
|
|
217
|
+
response = ai.chat(input(">>> "))
|
|
218
|
+
for chunk in response:
|
|
219
|
+
print(chunk, end="", flush=True)
|
webscout/Provider/Youchat.py
CHANGED
|
@@ -1,32 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
import uuid
|
|
3
|
-
from selenium import webdriver
|
|
4
|
-
from selenium.webdriver.chrome.options import Options
|
|
5
|
-
from selenium.webdriver.common.by import By
|
|
6
|
-
from selenium.webdriver.support import expected_conditions as EC
|
|
7
|
-
from selenium.webdriver.support.ui import WebDriverWait
|
|
8
|
-
import click
|
|
9
|
-
import requests
|
|
10
|
-
from requests import get
|
|
1
|
+
|
|
11
2
|
from uuid import uuid4
|
|
12
3
|
from re import findall
|
|
13
|
-
from requests.exceptions import RequestException
|
|
14
|
-
from curl_cffi.requests import get, RequestsError
|
|
15
|
-
import g4f
|
|
16
|
-
from random import randint
|
|
17
|
-
from PIL import Image
|
|
18
|
-
import io
|
|
19
|
-
import re
|
|
20
4
|
import json
|
|
21
|
-
|
|
5
|
+
|
|
22
6
|
from webscout.AIutel import Optimizers
|
|
23
7
|
from webscout.AIutel import Conversation
|
|
24
8
|
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
25
9
|
from webscout.AIbase import Provider, AsyncProvider
|
|
26
10
|
from webscout import exceptions
|
|
27
11
|
from typing import Any, AsyncGenerator, Dict
|
|
28
|
-
|
|
29
|
-
import httpx
|
|
12
|
+
|
|
30
13
|
import cloudscraper
|
|
31
14
|
|
|
32
15
|
|
webscout/Provider/__init__.py
CHANGED
|
@@ -15,17 +15,15 @@ from .Perplexity import *
|
|
|
15
15
|
from .Blackboxai import BLACKBOXAI
|
|
16
16
|
from .Blackboxai import AsyncBLACKBOXAI
|
|
17
17
|
from .Phind import PhindSearch
|
|
18
|
-
from .Phind import AsyncPhindSearch
|
|
19
18
|
from .Phind import Phindv2
|
|
20
|
-
from .Phind import AsyncPhindv2
|
|
21
19
|
from .ai4chat import *
|
|
22
20
|
from .Gemini import GEMINI
|
|
23
|
-
from .Berlin4h import Berlin4h
|
|
24
21
|
from .Poe import POE
|
|
25
22
|
from .BasedGPT import BasedGPT
|
|
26
23
|
from .Deepseek import DeepSeek
|
|
27
24
|
from .Deepinfra import DeepInfra, VLM, AsyncDeepInfra
|
|
28
25
|
from .Farfalle import *
|
|
26
|
+
from .cleeai import *
|
|
29
27
|
from .OLLAMA import OLLAMA
|
|
30
28
|
from .Andi import AndiSearch
|
|
31
29
|
from .PizzaGPT import *
|
|
@@ -34,7 +32,6 @@ from .DARKAI import *
|
|
|
34
32
|
from .koala import *
|
|
35
33
|
from .RUBIKSAI import *
|
|
36
34
|
from .meta import *
|
|
37
|
-
from .liaobots import *
|
|
38
35
|
from .DiscordRocks import *
|
|
39
36
|
from .felo_search import *
|
|
40
37
|
from .xdash import *
|
|
@@ -47,6 +44,13 @@ from .NetFly import *
|
|
|
47
44
|
from .EDITEE import *
|
|
48
45
|
from .TeachAnything import *
|
|
49
46
|
from .AI21 import *
|
|
47
|
+
from .Chatify import *
|
|
48
|
+
from .x0gpt import *
|
|
49
|
+
from .cerebras import *
|
|
50
|
+
from .lepton import *
|
|
51
|
+
from .geminiapi import *
|
|
52
|
+
from .elmo import *
|
|
53
|
+
from .genspark import *
|
|
50
54
|
__all__ = [
|
|
51
55
|
'ThinkAnyAI',
|
|
52
56
|
'Farfalle',
|
|
@@ -63,10 +67,8 @@ __all__ = [
|
|
|
63
67
|
'BLACKBOXAI',
|
|
64
68
|
'AsyncBLACKBOXAI',
|
|
65
69
|
'PhindSearch',
|
|
66
|
-
'AsyncPhindSearch',
|
|
67
70
|
'Felo',
|
|
68
71
|
'GEMINI',
|
|
69
|
-
'Berlin4h',
|
|
70
72
|
'POE',
|
|
71
73
|
'BasedGPT',
|
|
72
74
|
'DeepSeek',
|
|
@@ -74,7 +76,6 @@ __all__ = [
|
|
|
74
76
|
'VLM',
|
|
75
77
|
'AsyncDeepInfra',
|
|
76
78
|
'AI4Chat',
|
|
77
|
-
'AsyncPhindv2',
|
|
78
79
|
'Phindv2',
|
|
79
80
|
'OLLAMA',
|
|
80
81
|
'AndiSearch',
|
|
@@ -84,7 +85,6 @@ __all__ = [
|
|
|
84
85
|
'KOALA',
|
|
85
86
|
'RUBIKSAI',
|
|
86
87
|
'Meta',
|
|
87
|
-
'LiaoBots',
|
|
88
88
|
'DiscordRocks',
|
|
89
89
|
'PiAI',
|
|
90
90
|
'XDASH',
|
|
@@ -97,4 +97,13 @@ __all__ = [
|
|
|
97
97
|
'Editee',
|
|
98
98
|
'TeachAnything',
|
|
99
99
|
'AI21',
|
|
100
|
+
'Chatify',
|
|
101
|
+
'X0GPT',
|
|
102
|
+
'Cerebras',
|
|
103
|
+
'Lepton',
|
|
104
|
+
'GEMINIAPI',
|
|
105
|
+
'Cleeai',
|
|
106
|
+
'Elmo',
|
|
107
|
+
'Genspark'
|
|
108
|
+
|
|
100
109
|
]
|
webscout/Provider/ai4chat.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import requests
|
|
2
2
|
import json
|
|
3
3
|
import html
|
|
4
|
-
|
|
4
|
+
import re
|
|
5
5
|
from typing import Any, Dict
|
|
6
6
|
|
|
7
7
|
from webscout.AIutel import Optimizers
|
|
@@ -94,7 +94,7 @@ class AI4Chat(Provider):
|
|
|
94
94
|
def ask(
|
|
95
95
|
self,
|
|
96
96
|
prompt: str,
|
|
97
|
-
stream: bool = False,
|
|
97
|
+
stream: bool = False,
|
|
98
98
|
raw: bool = False,
|
|
99
99
|
optimizer: str = None,
|
|
100
100
|
conversationally: bool = False,
|
|
@@ -137,9 +137,17 @@ class AI4Chat(Provider):
|
|
|
137
137
|
response_data = response.json()
|
|
138
138
|
message_content = response_data.get('message', 'No message found')
|
|
139
139
|
|
|
140
|
-
# Decode HTML entities
|
|
140
|
+
# Decode HTML entities
|
|
141
141
|
decoded_message = html.unescape(message_content)
|
|
142
|
-
|
|
142
|
+
|
|
143
|
+
# Remove HTML tags while preserving newlines and list structure
|
|
144
|
+
cleaned_text = re.sub(r'<p>(.*?)</p>', r'\1\n\n', decoded_message)
|
|
145
|
+
cleaned_text = re.sub(r'<ol>|</ol>', '', cleaned_text)
|
|
146
|
+
cleaned_text = re.sub(r'<li><p>(.*?)</p></li>', r'• \1\n', cleaned_text)
|
|
147
|
+
cleaned_text = re.sub(r'</?[^>]+>', '', cleaned_text)
|
|
148
|
+
|
|
149
|
+
# Remove extra newlines
|
|
150
|
+
cleaned_text = re.sub(r'\n{3,}', '\n\n', cleaned_text.strip())
|
|
143
151
|
|
|
144
152
|
self.last_response.update(dict(text=cleaned_text))
|
|
145
153
|
self.conversation.update_chat_history(prompt, cleaned_text)
|
|
@@ -183,11 +191,9 @@ class AI4Chat(Provider):
|
|
|
183
191
|
"""
|
|
184
192
|
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
185
193
|
return response["text"]
|
|
194
|
+
|
|
186
195
|
if __name__ == "__main__":
|
|
187
196
|
from rich import print
|
|
188
|
-
|
|
189
197
|
ai = AI4Chat()
|
|
190
|
-
# Stream the response
|
|
191
198
|
response = ai.chat(input(">>> "))
|
|
192
|
-
|
|
193
|
-
print(chunk, end="", flush=True)
|
|
199
|
+
print(response)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import requests
|
|
3
|
+
from webscout.AIutel import Optimizers, Conversation, AwesomePrompts
|
|
4
|
+
from webscout.AIbase import Provider
|
|
5
|
+
from webscout import exceptions
|
|
6
|
+
from typing import Dict, Any
|
|
7
|
+
|
|
8
|
+
class Cerebras(Provider):
|
|
9
|
+
"""
|
|
10
|
+
A class to interact with the Cerebras AI API.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
AVAILABLE_MODELS = ["llama3.1-8b", "llama3.1-70b"]
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
api_key: str,
|
|
18
|
+
is_conversation: bool = True,
|
|
19
|
+
max_tokens: int = 4096,
|
|
20
|
+
timeout: int = 30,
|
|
21
|
+
intro: str = None,
|
|
22
|
+
filepath: str = None,
|
|
23
|
+
update_file: bool = True,
|
|
24
|
+
proxies: dict = {},
|
|
25
|
+
history_offset: int = 10250,
|
|
26
|
+
act: str = None,
|
|
27
|
+
model: str = "llama3.1-8b",
|
|
28
|
+
system_prompt: str = "Please try to provide useful, helpful and actionable answers.",
|
|
29
|
+
):
|
|
30
|
+
"""
|
|
31
|
+
Initializes the Cerebras AI API with given parameters.
|
|
32
|
+
"""
|
|
33
|
+
if model not in self.AVAILABLE_MODELS:
|
|
34
|
+
raise ValueError(f"Invalid model: {model}. Available models are: {', '.join(self.AVAILABLE_MODELS)}")
|
|
35
|
+
|
|
36
|
+
self.session = requests.Session()
|
|
37
|
+
self.is_conversation = is_conversation
|
|
38
|
+
self.max_tokens_to_sample = max_tokens
|
|
39
|
+
self.api_endpoint = "https://api.cerebras.ai/v1/chat/completions"
|
|
40
|
+
self.timeout = timeout
|
|
41
|
+
self.last_response = {}
|
|
42
|
+
self.model = model
|
|
43
|
+
self.system_prompt = system_prompt
|
|
44
|
+
self.headers = {
|
|
45
|
+
"accept": "application/json",
|
|
46
|
+
"accept-encoding": "gzip, deflate, br, zstd",
|
|
47
|
+
"accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
|
|
48
|
+
"authorization": f"Bearer {api_key}",
|
|
49
|
+
"content-type": "application/json",
|
|
50
|
+
"dnt": "1",
|
|
51
|
+
"origin": "https://inference.cerebras.ai",
|
|
52
|
+
"referer": "https://inference.cerebras.ai/",
|
|
53
|
+
"sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
|
|
54
|
+
"sec-ch-ua-mobile": "?0",
|
|
55
|
+
"sec-ch-ua-platform": '"Windows"',
|
|
56
|
+
"sec-fetch-dest": "empty",
|
|
57
|
+
"sec-fetch-mode": "cors",
|
|
58
|
+
"sec-fetch-site": "same-site",
|
|
59
|
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
self.__available_optimizers = (
|
|
63
|
+
method
|
|
64
|
+
for method in dir(Optimizers)
|
|
65
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
66
|
+
)
|
|
67
|
+
self.session.headers.update(self.headers)
|
|
68
|
+
Conversation.intro = (
|
|
69
|
+
AwesomePrompts().get_act(
|
|
70
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
71
|
+
)
|
|
72
|
+
if act
|
|
73
|
+
else intro or Conversation.intro
|
|
74
|
+
)
|
|
75
|
+
self.conversation = Conversation(
|
|
76
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
77
|
+
)
|
|
78
|
+
self.conversation.history_offset = history_offset
|
|
79
|
+
self.session.proxies = proxies
|
|
80
|
+
|
|
81
|
+
def ask(
|
|
82
|
+
self,
|
|
83
|
+
prompt: str,
|
|
84
|
+
stream: bool = False,
|
|
85
|
+
raw: bool = False,
|
|
86
|
+
optimizer: str = None,
|
|
87
|
+
conversationally: bool = False,
|
|
88
|
+
) -> Dict[str, Any]:
|
|
89
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
90
|
+
if optimizer:
|
|
91
|
+
if optimizer in self.__available_optimizers:
|
|
92
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
93
|
+
conversation_prompt if conversationally else prompt
|
|
94
|
+
)
|
|
95
|
+
else:
|
|
96
|
+
raise Exception(
|
|
97
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
payload = {
|
|
101
|
+
"messages": [
|
|
102
|
+
{"role": "system", "content": self.system_prompt},
|
|
103
|
+
{"role": "user", "content": conversation_prompt},
|
|
104
|
+
],
|
|
105
|
+
"model": self.model,
|
|
106
|
+
"stream": True,
|
|
107
|
+
"temperature": 0.2,
|
|
108
|
+
"top_p": 1,
|
|
109
|
+
"max_tokens": self.max_tokens_to_sample
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
def for_stream():
|
|
113
|
+
response = self.session.post(
|
|
114
|
+
self.api_endpoint, json=payload, stream=True, timeout=self.timeout
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
if not response.ok:
|
|
118
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
119
|
+
f"Failed to generate response - ({response.status_code}, {response.reason})"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
full_response = ""
|
|
123
|
+
for line in response.iter_lines():
|
|
124
|
+
if line:
|
|
125
|
+
line_data = line.decode('utf-8').strip()
|
|
126
|
+
if line_data.startswith("data: "):
|
|
127
|
+
json_str = line_data[6:]
|
|
128
|
+
if json_str != "[DONE]":
|
|
129
|
+
chunk = json.loads(json_str)
|
|
130
|
+
if 'choices' in chunk and 'delta' in chunk['choices'][0]:
|
|
131
|
+
content = chunk['choices'][0]['delta'].get('content', '')
|
|
132
|
+
full_response += content
|
|
133
|
+
yield content if raw else dict(text=content)
|
|
134
|
+
else:
|
|
135
|
+
break
|
|
136
|
+
|
|
137
|
+
self.last_response.update(dict(text=full_response))
|
|
138
|
+
self.conversation.update_chat_history(
|
|
139
|
+
prompt, self.get_message(self.last_response)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def for_non_stream():
|
|
143
|
+
full_response = ""
|
|
144
|
+
for chunk in for_stream():
|
|
145
|
+
if isinstance(chunk, dict):
|
|
146
|
+
full_response += chunk['text']
|
|
147
|
+
else:
|
|
148
|
+
full_response += chunk
|
|
149
|
+
return dict(text=full_response)
|
|
150
|
+
|
|
151
|
+
return for_stream() if stream else for_non_stream()
|
|
152
|
+
|
|
153
|
+
def chat(
|
|
154
|
+
self,
|
|
155
|
+
prompt: str,
|
|
156
|
+
stream: bool = False,
|
|
157
|
+
optimizer: str = None,
|
|
158
|
+
conversationally: bool = False,
|
|
159
|
+
) -> str:
|
|
160
|
+
def for_stream():
|
|
161
|
+
for response in self.ask(
|
|
162
|
+
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
163
|
+
):
|
|
164
|
+
yield self.get_message(response)
|
|
165
|
+
|
|
166
|
+
def for_non_stream():
|
|
167
|
+
return self.get_message(
|
|
168
|
+
self.ask(
|
|
169
|
+
prompt,
|
|
170
|
+
False,
|
|
171
|
+
optimizer=optimizer,
|
|
172
|
+
conversationally=conversationally,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return for_stream() if stream else for_non_stream()
|
|
177
|
+
|
|
178
|
+
def get_message(self, response: dict) -> str:
|
|
179
|
+
"""Retrieves message only from response
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
response (dict): Response generated by `self.ask`
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
str: Message extracted
|
|
186
|
+
"""
|
|
187
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
188
|
+
return response["text"]
|
|
189
|
+
|
|
190
|
+
if __name__ == '__main__':
|
|
191
|
+
from rich import print
|
|
192
|
+
|
|
193
|
+
# You can replace this with your actual API key
|
|
194
|
+
api_key = "YOUR_API_KEY_HERE"
|
|
195
|
+
|
|
196
|
+
ai = Cerebras(api_key=api_key)
|
|
197
|
+
response = ai.chat(input(">>> "), stream=True)
|
|
198
|
+
for chunk in response:
|
|
199
|
+
print(chunk, end="", flush=True)
|