-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlocalChat.ts
212 lines (187 loc) · 5.33 KB
/
localChat.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import * as vscode from "vscode";
import { randomUUID } from "crypto";
import Logger from "../logger";
import { servers } from "../server";
const logCompletion = (uuid = randomUUID() as string) => {
return {
info: (text: any) =>
Logger.info(text, { component: `Chat: ${uuid.slice(-8)}` }),
uuid: () => uuid,
};
};
const defualtParameters = {
stream: true,
n_predict: 1024,
temperature: 0.7,
stop: [],
repeat_last_n: 256,
repeat_penalty: 1,
penalize_nl: false,
top_k: 20,
top_p: 0.5,
min_p: 0.05,
tfs_z: 1,
typical_p: 1,
presence_penalty: 0,
frequency_penalty: 0,
mirostat: 0,
mirostat_tau: 5,
mirostat_eta: 0.1,
n_probs: 0,
cache_prompt: true,
slot_id: -1,
};
export async function* sendChatRequestLocal(
prompt: string,
parameters: Record<string, any>,
uuid: string
) {
const loggerCompletion = logCompletion(uuid);
const url = servers["chat-medium"].serverUrl;
const parametersForCompletion = {
...defualtParameters,
...parameters,
prompt: prompt,
};
try {
loggerCompletion.info("Request: started");
const startTime = performance.now();
let timings;
for await (const chunk of llama(prompt, parametersForCompletion, {
url,
controller: parameters.controller,
})) {
// @ts-ignore
if (chunk.data) {
// @ts-ignore
yield chunk.data.content;
}
// @ts-ignore
if (chunk.data.timings) {
// @ts-ignore
timings = chunk.data.timings;
}
}
loggerCompletion.info(
`Total time: ${(performance.now() - startTime).toFixed(2)}; ` +
`PP: ${timings?.prompt_per_second?.toFixed(2)}; [t/s] ` +
`TG: ${timings?.predicted_per_second?.toFixed(2)}; [t/s]`
);
loggerCompletion.info("Request: finished");
return;
} catch (error) {
const Error = error as Error;
if (Error.name === "AbortError") {
loggerCompletion.info("Request: canceled by new completion abort");
return null;
}
Logger.error(error);
const errorMessage = Error.message;
vscode.window.showErrorMessage(errorMessage);
return null;
}
}
export async function* llama(
prompt: string,
params = {},
config: { controller?: AbortController; url?: string } = {}
) {
let controller = config.controller;
if (!controller) {
controller = new AbortController();
}
const completionParams = { ...params, prompt };
const response = await fetch(`${config.url}/completion`, {
method: "POST",
body: JSON.stringify(completionParams),
headers: {
Connection: "keep-alive",
"Content-Type": "application/json",
Accept: "text/event-stream",
},
signal: controller.signal,
});
// @ts-ignore
const reader = response.body.getReader<any>();
const decoder = new TextDecoder();
let content = "";
let leftover = ""; // Buffer for partially read lines
try {
let cont = true;
while (cont) {
const result = await reader.read();
if (result.done) {
break;
}
// Add any leftover data to the current chunk of data
const text = leftover + decoder.decode(result.value);
// Check if the last character is a line break
const endsWithLineBreak = text.endsWith("\n");
// Split the text into lines
let lines = text.split("\n");
// If the text doesn't end with a line break, then the last line is incomplete
// Store it in leftover to be added to the next chunk of data
if (!endsWithLineBreak) {
// @ts-ignore
leftover = lines.pop();
} else {
leftover = ""; // Reset leftover if we have a line break at the end
}
// Parse all sse events and add them to result
const regex = /^(\S+):\s(.*)$/gm;
for (const line of lines) {
const match = regex.exec(line);
if (match) {
// @ts-ignore
result[match[1]] = match[2];
// since we know this is llama.cpp, let's just decode the json in data
// @ts-ignore
if (result.data) {
// @ts-ignore
result.data = JSON.parse(result.data);
// @ts-ignore
content += result.data.content;
// yield
yield result;
// if we got a stop token from server, we will break here
// @ts-ignore
if (result.data.stop) {
// @ts-ignore
cont = false;
break;
}
}
// @ts-ignore
if (result.error) {
// @ts-ignore
result.error = JSON.parse(result.error);
// @ts-ignore
if (result.error.content.includes("slot unavailable")) {
// Throw an error to be caught by upstream callers
throw new Error("slot unavailable");
} else {
// @ts-ignore
console.error(`llama.cpp error: ${result.error.content}`);
}
}
// @ts-ignore
if (result.error) {
// @ts-ignore
result.error = JSON.parse(result.error);
// @ts-ignore
console.error(`llama.cpp error: ${result.error.content}`);
}
}
}
}
} catch (e) {
// @ts-ignore
if (e.name !== "AbortError") {
console.error("llama error: ", e);
}
throw e;
} finally {
controller.abort();
}
return content;
}