-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstream.py
64 lines (55 loc) · 1.89 KB
/
stream.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import uuid
import json
import config
from auth import Auth
from errors import ResponseError
class Stream:
def __init__(self, session):
self.session = session
def _process_chunks(self, chunks):
if type(chunks) == bytes:
chunks = chunks.decode()
chunks = chunks.split("\n\n")
elif type(chunks) == list:
chunks = [c.decode() for c in chunks]
else:
raise ResponseError("Unknown response")
chunks = [c for c in chunks if c and "message" in c]
if not chunks:
raise ResponseError("No response in stream")
chunk = chunks[-1]
chunk = chunk.replace("data: ", "").strip()
chunk = json.loads(chunk)
return chunk.get("message", {}).get("content", {}).get("parts", [None])[0]
def send_message(self, message):
token = Auth.get_token(self.session)
self.session.headers.update({
"accept": "text/event-stream",
"X-OpenAI-Assistant-App-Id": "",
"Authorization": f"Bearer {token}"
})
params = {
"action": "next",
"messages": [
{
"id": str(uuid.uuid4()),
"role": "user",
"content": {
"content_type": "text",
"parts": [message]
}
}
],
"parent_message_id": "",
"model": config.model
}
with self.session.stream(
"POST", "https://chat.openai.com/backend-api/conversation",
json=params, headers={"content-type": "application/json"},
timeout=None
) as response:
chunks = []
for chunk in response.iter_bytes():
chunks.append(chunk)
response = self._process_chunks(chunks)
return response