Abhaykoul commited on
Commit
fc223bf
1 Parent(s): c70bca0

Create v2.py

Browse files
Files changed (1) hide show
  1. v2.py +127 -0
v2.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from dotenv import load_dotenv
3
+ import requests
4
+ from uuid import uuid4
5
+ import json
6
+ from typing import Any, AsyncGenerator, Dict
7
+ import os
8
+
9
+ # Load environment variables from .env file
10
+ load_dotenv()
11
+
12
+
13
+ class v2:
14
+ def __init__(
15
+ self,
16
+ timeout: int = 100,
17
+ proxies: dict = {},
18
+ ):
19
+ self.session = requests.Session()
20
+ self.chat_endpoint = os.getenv("v2")
21
+ self.stream_chunk_size = 64
22
+ self.timeout = timeout
23
+ self.last_response = {}
24
+ self.headers = {
25
+ "accept": "*/*",
26
+ "accept-encoding": "gzip, deflate, br, zstd",
27
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
28
+ "content-type": "application/json",
29
+ }
30
+
31
+ self.session.headers.update(self.headers)
32
+ self.session.proxies = proxies
33
+
34
+
35
+ def ask(
36
+ self,
37
+ prompt: str,
38
+ stream: bool = False,
39
+ raw: bool = False,
40
+ ) -> dict:
41
+ conversation_prompt =f"Tell me evrything about {prompt}"
42
+
43
+ self.session.headers.update(self.headers)
44
+ payload = {
45
+ "query": conversation_prompt,
46
+ "search_uuid": uuid4().hex,
47
+ "lang": "",
48
+ "agent_lang": "en",
49
+ "search_options": {
50
+ "langcode": "en-US"
51
+ },
52
+ "search_video": True,
53
+ "contexts_from": "google"
54
+ }
55
+
56
+ def for_stream():
57
+ response = self.session.post(
58
+ self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
59
+ )
60
+ if not response.ok:
61
+ raise Exception(
62
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
63
+ )
64
+
65
+ streaming_text = ""
66
+ for line in response.iter_lines(decode_unicode=True):
67
+ if line.startswith('data:'):
68
+ try:
69
+ data = json.loads(line[5:].strip())
70
+ if data['type'] == 'answer' and 'text' in data['data']:
71
+ new_text = data['data']['text']
72
+ if len(new_text) > len(streaming_text):
73
+ delta = new_text[len(streaming_text):]
74
+ streaming_text = new_text
75
+ resp = dict(text=delta)
76
+ self.last_response.update(dict(text=streaming_text))
77
+ yield line if raw else resp
78
+ except json.JSONDecodeError:
79
+ pass
80
+
81
+ def for_non_stream():
82
+ full_response = ""
83
+ for chunk in for_stream():
84
+ if not raw:
85
+ full_response += chunk['text']
86
+ self.last_response = dict(text=full_response)
87
+ return self.last_response
88
+
89
+ return for_stream() if stream else for_non_stream()
90
+
91
+ def chat(
92
+ self,
93
+ prompt: str,
94
+ stream: bool = False,
95
+ ) -> str:
96
+ def for_stream():
97
+ for response in self.ask(
98
+ prompt, True
99
+ ):
100
+ yield self.get_message(response)
101
+
102
+ def for_non_stream():
103
+ return self.get_message(
104
+ self.ask(
105
+ prompt,
106
+ False,
107
+ )
108
+ )
109
+
110
+ return for_stream() if stream else for_non_stream()
111
+
112
+ def get_message(self, response: dict) -> str:
113
+ assert isinstance(response, dict), "Response should be of dict data-type only"
114
+
115
+ if "text" in response:
116
+ text = re.sub(r'\[\[\d+\]\]', '', response["text"])
117
+ return text
118
+ else:
119
+ return ""
120
+
121
+
122
+ if __name__ == '__main__':
123
+ from rich import print
124
+ ai = v2()
125
+ response = ai.chat("HelpingAI-9B", stream=True)
126
+ for chunk in response:
127
+ print(chunk, end="", flush=True)