forked from bramses/chatgpt-md
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.ts
192 lines (164 loc) · 4.46 KB
/
stream.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { Editor, Notice, Platform } from "obsidian";
import { SSE } from "sse";
import { unfinishedCodeBlock } from "helpers";
export interface OpenAIStreamPayload {
model: string;
messages: Array<{ role: string; content: string }>;
temperature: number;
top_p: number;
presence_penalty: number;
frequency_penalty: number;
stop: string[] | null;
n: number;
logit_bias?: any | null;
user?: string | null;
max_tokens: number;
stream: boolean;
}
export class StreamManager {
sse: any | null = null;
manualClose = false;
constructor() {}
stopStreaming = () => {
if (Platform.isMobile) {
new Notice("[ChatGPT MD] Mobile not supported.")
return;
}
if (this.sse) {
this.manualClose = true;
this.sse.close();
console.log("[ChatGPT MD] SSE manually closed");
this.sse = null;
}
};
streamSSE = async (
editor: Editor,
apiKey: string,
url: string,
options: OpenAIStreamPayload,
setAtCursor: boolean,
headingPrefix: string
) => {
return new Promise((resolve, reject) => {
try {
console.log("[ChatGPT MD] streamSSE", options);
const source = new SSE(url, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
method: "POST",
payload: JSON.stringify(options),
});
this.sse = source;
let txt = "";
let initialCursorPosCh = editor.getCursor().ch;
let initialCursorPosLine = editor.getCursor().line;
source.addEventListener("open", (e: any) => {
console.log("[ChatGPT MD] SSE Opened");
const newLine = `\n\n<hr class="__chatgpt_plugin">\n\n${headingPrefix}role::assistant\n\n`;
editor.replaceRange(newLine, editor.getCursor());
// move cursor to end of line
const cursor = editor.getCursor();
const newCursor = {
line: cursor.line,
ch: cursor.ch + newLine.length,
};
editor.setCursor(newCursor);
initialCursorPosCh = newCursor.ch;
initialCursorPosLine = newCursor.line;
});
source.addEventListener("message", (e: any) => {
if (e.data != "[DONE]") {
const payload = JSON.parse(e.data);
const text = payload.choices[0].delta.content;
// if text undefined, then do nothing
if (!text) {
return;
}
const cursor = editor.getCursor();
const convPos = editor.posToOffset(cursor);
// @ts-ignore
const cm6 = editor.cm;
const transaction = cm6.state.update({
changes: {
from: convPos,
to: convPos,
insert: text,
},
});
cm6.dispatch(transaction);
txt += text;
const newCursor = {
line: cursor.line,
ch: cursor.ch + text.length,
};
editor.setCursor(newCursor);
} else {
source.close();
console.log("[ChatGPT MD] SSE Closed");
if (unfinishedCodeBlock(txt)) {
txt += "\n```";
}
// replace the text from initialCursor to fix any formatting issues from streaming
const cursor = editor.getCursor();
editor.replaceRange(
txt,
{
line: initialCursorPosLine,
ch: initialCursorPosCh,
},
cursor
);
// set cursor to end of replacement text
const newCursor = {
line: initialCursorPosLine,
ch: initialCursorPosCh + txt.length,
};
editor.setCursor(newCursor);
if (!setAtCursor) {
// remove the text after the cursor
editor.replaceRange("", newCursor, {
line: Infinity,
ch: Infinity,
});
} else {
new Notice(
"[ChatGPT MD] Text pasted at cursor may leave artifacts. Please remove them manually. ChatGPT MD cannot safely remove text when pasting at cursor."
);
}
resolve(txt);
// return txt;
}
});
source.addEventListener("abort", (e: any) => {
console.log("[ChatGPT MD] SSE Closed Event");
// if e was triggered by stopStreaming, then resolve
if (this.manualClose) {
resolve(txt);
}
});
source.addEventListener("error", (e: any) => {
try {
console.log(
"[ChatGPT MD] SSE Error: ",
JSON.parse(e.data)
);
source.close();
console.log("[ChatGPT MD] SSE Closed");
reject(JSON.parse(e.data));
} catch (err) {
console.log("[ChatGPT MD] Unknown Error: ", e);
source.close();
console.log("[ChatGPT MD] SSE Closed");
reject(e);
}
});
source.stream();
} catch (err) {
console.log("SSE Error", err);
reject(err);
}
});
};
}