File size: 5,491 Bytes
cf07b75 |
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 |
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { d as private_env } from './shared-server-49TKSBDM.js';
class LlamaCppService {
url = "";
constructor(url) {
this.url = url;
}
async health() {
const r = await fetch(`${this.url}/health`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const data = await r.json();
if (data.status === "ok" || data.status === "error" || data.status === "loading model") {
return data.status;
}
return "unavailable";
}
async tokenize(prompt, abortController) {
const response = await fetch(`${this.url}/tokenize`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"content": prompt
}),
signal: abortController.signal
});
if (response.ok) {
const data = await response.json();
if (data.tokens) {
return data.tokens;
}
} else if (response.status === 404) {
console.log("Tokenization endpoint not found (404).");
} else {
console.log(`Failed to tokenize: ${await response.text()}`);
}
return null;
}
async detokenize(tokens, abortController) {
const response = await fetch(`${this.url}/detokenize`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"tokens": tokens
}),
signal: abortController.signal
});
if (response.ok) {
const data = await response.json();
if (data.content) {
return data.content.trim();
}
} else if (response.status === 404) {
console.log("Detokenization endpoint not found (404).");
} else {
console.log(`Failed to detokenize: ${await response.text()}`);
}
return null;
}
predict(prompt, { abortController }) {
return async ({ prompt: prompt2 }) => {
console.log(prompt2.length);
let tokens = await this.tokenize(prompt2, abortController);
if (tokens !== null) {
console.log("tokens: " + tokens.length);
tokens = tokens.slice(0, 30700);
const detokenizedPrompt = await this.detokenize(tokens, abortController);
if (detokenizedPrompt !== null) {
prompt2 = detokenizedPrompt;
} else {
prompt2 = prompt2.substring(0, 32768);
}
} else {
prompt2 = prompt2.substring(0, 32768);
}
console.log(prompt2.length);
const r = await fetch(`${this.url}/completion`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "text/event-stream"
},
body: JSON.stringify({
"stream": true,
"n_predict": 2e3,
"temperature": 0.2,
"stop": ["</s>", "bot:", "user:"],
// "repeat_last_n": 256,
"repeat_penalty": 1,
"top_k": 40,
"top_p": 0.95,
"min_p": 0.05,
"seed": 42,
"n_keep": 0,
// "tfs_z": 1,
// "typical_p": 1,
// "presence_penalty": 0,
// "frequency_penalty": 0,
// "mirostat": 0,
// "mirostat_tau": 5,
// "mirostat_eta": 0.1,
// // "grammar": "",
// "n_probs": 0,
// "image_data": [],
"cache_prompt": false,
// "api_key": "",
// "slot_id": 0,
"prompt": "[INST]" + prompt2 + "[/INST]"
}),
signal: abortController.signal
});
if (!r.ok) {
throw new Error(`Failed to generate text: ${await r.text()}`);
}
const encoder = new TextDecoderStream();
const reader = r.body?.pipeThrough(encoder).getReader();
let t = this;
return async function* () {
let stop = false;
let generatedText = "";
let tokenId = 0;
while (!stop) {
const out = await reader?.read() ?? { done: false, value: void 0 };
if (out.done) {
reader?.cancel();
t.createLogFile(`Request:
${prompt2}
Response:
${generatedText}`);
return;
}
if (!out.value) {
reader?.cancel();
return;
}
let tokenValue = "";
if (out.value.startsWith("data: ")) {
try {
let data2 = JSON.parse(out.value.slice(6));
tokenValue = data2.content;
} catch (e) {
}
} else if (private_env.LLM_API_VERSION == "v1") {
tokenValue = out.value;
}
generatedText += tokenValue.replace("</s>", "") ?? "";
yield {
token: {
id: tokenId++,
text: tokenValue.replace("</s>", "") ?? "",
logprob: 0,
special: false
},
generated_text: null,
details: null
};
}
}();
};
}
createLogFile(text) {
const logsDirectory = resolve("/logs");
if (!existsSync(logsDirectory)) {
mkdirSync(logsDirectory);
}
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "");
const logFilePath = resolve(logsDirectory, `${timestamp}.log`);
writeFileSync(logFilePath, text);
console.log(`Log file created: ${logFilePath}`);
}
}
export { LlamaCppService as L };
//# sourceMappingURL=LlamaCppService-Bqc2roDm.js.map
|