File size: 14,556 Bytes
a7634ef |
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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
import { isWebGPUAvailable } from "./webGpu";
import {
updatePrompt,
updateSearchResults,
getDisableAiResponseSetting,
getSummarizeLinksSetting,
getUseLargerModelSetting,
updateResponse,
getSearchResults,
updateUrlsDescriptions,
getUrlsDescriptions,
getDisableWebGpuUsageSetting,
} from "./pubSub";
import { SearchResults, search } from "./search";
import { query, debug } from "./urlParams";
import toast from "react-hot-toast";
import { isRunningOnMobile } from "./mobileDetection";
export async function prepareTextGeneration() {
if (query === null) return;
document.title = query;
updatePrompt(query);
updateLoadingToast("Searching the web...");
let searchResults = await search(
query.length > 2000 ? (await getKeywords(query, 20)).join(" ") : query,
30,
);
if (searchResults.length === 0) {
const queryKeywords = await getKeywords(query, 10);
searchResults = await search(queryKeywords.join(" "), 30);
}
if (searchResults.length === 0) {
toast(
"It looks like your current search did not return any results. Try refining your search by adding more keywords or rephrasing your query.",
{
position: "bottom-center",
duration: 10000,
icon: "💡",
},
);
}
updateSearchResults(searchResults);
updateUrlsDescriptions(
searchResults.reduce(
(acc, [, snippet, url]) => ({ ...acc, [url]: snippet }),
{},
),
);
dismissLoadingToast();
if (getDisableAiResponseSetting() && !getSummarizeLinksSetting()) return;
if (debug) console.time("Response Generation Time");
updateLoadingToast("Loading AI model...");
try {
try {
if (!isWebGPUAvailable) throw Error("WebGPU is not available.");
if (getDisableWebGpuUsageSetting()) throw Error("WebGPU is disabled.");
if (getUseLargerModelSetting()) {
try {
await generateTextWithWebLlm();
} catch (error) {
await generateTextWithRatchet();
}
} else {
try {
await generateTextWithRatchet();
} catch (error) {
await generateTextWithWebLlm();
}
}
} catch (error) {
await generateTextWithWllama();
}
} catch (error) {
console.error("Error while generating response with wllama:", error);
toast.error(
"Could not generate response. The browser may be out of memory. Please close this tab and run this search again in a new one.",
{ duration: 10000 },
);
} finally {
dismissLoadingToast();
}
if (debug) {
console.timeEnd("Response Generation Time");
}
}
function updateLoadingToast(text: string) {
toast.loading(text, {
id: "text-generation-loading-toast",
position: "bottom-center",
});
}
function dismissLoadingToast() {
toast.dismiss("text-generation-loading-toast");
}
async function generateTextWithWebLlm() {
const { CreateWebWorkerEngine, CreateEngine, hasModelInCache } = await import(
"@mlc-ai/web-llm"
);
const availableModels = {
Llama: "Llama-3-8B-Instruct-q4f16_1",
Mistral: "Mistral-7B-Instruct-v0.2-q4f16_1",
Gemma: "gemma-2b-it-q4f16_1",
Phi: "Phi2-q4f16_1",
TinyLlama: "TinyLlama-1.1B-Chat-v0.4-q0f16",
};
const selectedModel = getUseLargerModelSetting()
? availableModels.Llama
: availableModels.Gemma;
const isModelCached = await hasModelInCache(selectedModel);
let initProgressCallback:
| import("@mlc-ai/web-llm").InitProgressCallback
| undefined;
if (isModelCached) {
updateLoadingToast("Generating response...");
} else {
initProgressCallback = (report) => {
updateLoadingToast(
`Loading: ${report.text.replaceAll("[", "(").replaceAll("]", ")")}`,
);
};
}
const engine = Worker
? await CreateWebWorkerEngine(
new Worker(new URL("./webLlmWorker.ts", import.meta.url), {
type: "module",
}),
selectedModel,
{ initProgressCallback },
)
: await CreateEngine(selectedModel, { initProgressCallback });
if (!getDisableAiResponseSetting()) {
updateLoadingToast("Generating response...");
const completion = await engine.chat.completions.create({
stream: true,
messages: [{ role: "user", content: getMainPrompt() }],
max_gen_len: 768,
});
let streamedMessage = "";
for await (const chunk of completion) {
const deltaContent = chunk.choices[0].delta.content;
if (deltaContent) streamedMessage += deltaContent;
updateResponse(streamedMessage);
}
}
await engine.resetChat();
if (getSummarizeLinksSetting()) {
updateLoadingToast("Summarizing links...");
for (const [title, snippet, url] of getSearchResults()) {
const completion = await engine.chat.completions.create({
stream: true,
messages: [
{
role: "user",
content: await getLinkSummarizationPrompt([title, snippet, url]),
},
],
max_gen_len: 768,
});
let streamedMessage = "";
for await (const chunk of completion) {
const deltaContent = chunk.choices[0].delta.content;
if (deltaContent) streamedMessage += deltaContent;
updateUrlsDescriptions({
...getUrlsDescriptions(),
[url]: streamedMessage,
});
}
await engine.resetChat();
}
}
if (debug) {
console.info(await engine.runtimeStatsText());
}
engine.unload();
}
async function generateTextWithWllama() {
const { initializeWllama, runCompletion, exitWllama } = await import(
"./wllama"
);
const commonSamplingConfig: import("@wllama/wllama").SamplingConfig = {
temp: 0.35,
dynatemp_range: 0.25,
top_k: 0,
top_p: 1,
min_p: 0.05,
tfs_z: 0.95,
typical_p: 0.85,
penalty_freq: 0.5,
penalty_repeat: 1.176,
penalty_last_n: -1,
mirostat: 2,
mirostat_tau: 3.5,
};
const availableModels: {
[key in
| "mobileDefault"
| "mobileLarger"
| "desktopDefault"
| "desktopLarger"]: {
url: string;
userPrefix: string;
assistantPrefix: string;
messageSuffix: string;
sampling: import("@wllama/wllama").SamplingConfig;
};
} = {
mobileDefault: {
url: "https://huggingface.co/Felladrin/gguf-vicuna-160m/resolve/main/vicuna-160m.Q8_0.gguf",
userPrefix: "USER:\n",
assistantPrefix: "ASSISTANT:\n",
messageSuffix: "</s>\n",
sampling: commonSamplingConfig,
},
mobileLarger: {
url: "https://huggingface.co/Felladrin/gguf-zephyr-220m-dpo-full/resolve/main/zephyr-220m-dpo-full.Q8_0.gguf",
userPrefix: "<|user|>\n",
assistantPrefix: "<|assistant|>\n",
messageSuffix: "</s>\n",
sampling: commonSamplingConfig,
},
desktopDefault: {
url: "https://huggingface.co/Felladrin/gguf-TinyLlama-1.1B-1T-OpenOrca/resolve/main/tinyllama-1.1b-1t-openorca.Q8_0.gguf",
userPrefix: "<|im_start|>user\n",
assistantPrefix: "<|im_start|>assistant\n",
messageSuffix: "<|im_end|>\n",
sampling: commonSamplingConfig,
},
desktopLarger: {
url: "https://huggingface.co/Felladrin/gguf-stablelm-2-1_6b-chat/resolve/main/stablelm-2-1_6b-chat.Q8_0.gguf",
userPrefix: "<|im_start|>user\n",
assistantPrefix: "<|im_start|>assistant\n",
messageSuffix: "<|im_end|>\n",
sampling: commonSamplingConfig,
},
};
const defaultModel = isRunningOnMobile
? availableModels.mobileDefault
: availableModels.desktopDefault;
const largerModel = isRunningOnMobile
? availableModels.mobileLarger
: availableModels.desktopLarger;
const selectedModel = getUseLargerModelSetting() ? largerModel : defaultModel;
await initializeWllama({
modelUrl: selectedModel.url,
modelConfig: {
n_ctx: 2048,
},
});
if (!getDisableAiResponseSetting()) {
const prompt = [
selectedModel.userPrefix,
"Hello!",
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
"Hi! How can I help you?",
selectedModel.messageSuffix,
selectedModel.userPrefix,
["Take a look at this info:", getFormattedSearchResults(5)].join("\n\n"),
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
"Alright!",
selectedModel.messageSuffix,
selectedModel.userPrefix,
"Now I'm going to write my question, and if this info is useful you can use them in your answer. Ready?",
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
"I'm ready to answer!",
selectedModel.messageSuffix,
selectedModel.userPrefix,
query,
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
].join("");
if (!query) throw Error("Query is empty.");
updateLoadingToast("Generating response...");
const completion = await runCompletion({
prompt,
nPredict: 768,
sampling: selectedModel.sampling,
onNewToken: (_token, _piece, currentText) => {
updateResponse(currentText);
},
});
updateResponse(completion);
}
if (getSummarizeLinksSetting()) {
updateLoadingToast("Summarizing links...");
for (const [title, snippet, url] of getSearchResults()) {
const prompt = [
selectedModel.userPrefix,
"Hello!",
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
"Hi! How can I help you?",
selectedModel.messageSuffix,
selectedModel.userPrefix,
["Context:", `${title}: ${snippet}`].join("\n"),
"\n",
["Question:", "What is this text about?"].join("\n"),
selectedModel.messageSuffix,
selectedModel.assistantPrefix,
["Answer:", "This text is about"].join("\n"),
].join("");
const completion = await runCompletion({
prompt,
nPredict: 128,
sampling: selectedModel.sampling,
onNewToken: (_token, _piece, currentText) => {
updateUrlsDescriptions({
...getUrlsDescriptions(),
[url]: `This link is about ${currentText}`,
});
},
});
updateUrlsDescriptions({
...getUrlsDescriptions(),
[url]: `This link is about ${completion}`,
});
}
}
await exitWllama();
}
async function generateTextWithRatchet() {
const { initializeRatchet, runCompletion, exitRatchet } = await import(
"./ratchet"
);
await initializeRatchet((loadingProgressPercentage) =>
updateLoadingToast(`Loading: ${Math.floor(loadingProgressPercentage)}%`),
);
if (!getDisableAiResponseSetting()) {
if (!query) throw Error("Query is empty.");
updateLoadingToast("Generating response...");
let response = "";
await runCompletion(getMainPrompt(), (completionChunk) => {
response += completionChunk;
updateResponse(response);
});
if (!endsWithASign(response)) {
response += ".";
updateResponse(response);
}
}
if (getSummarizeLinksSetting()) {
updateLoadingToast("Summarizing links...");
for (const [title, snippet, url] of getSearchResults()) {
let response = "";
await runCompletion(
await getLinkSummarizationPrompt([title, snippet, url]),
(completionChunk) => {
response += completionChunk;
updateUrlsDescriptions({
...getUrlsDescriptions(),
[url]: response,
});
},
);
if (!endsWithASign(response)) {
response += ".";
updateUrlsDescriptions({
...getUrlsDescriptions(),
[url]: response,
});
}
}
}
await exitRatchet();
}
async function fetchPageContent(
url: string,
options?: {
maxLength?: number;
},
) {
const response = await fetch(`https://r.jina.ai/${url}`);
if (!response) {
throw new Error("No response from server");
} else if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
return text.trim().substring(0, options?.maxLength);
}
function endsWithASign(text: string) {
return text.endsWith(".") || text.endsWith("!") || text.endsWith("?");
}
function getMainPrompt() {
return [
"Provide a concise response to the request below.",
"If the information from the Web Search Results below is useful, you can use it to complement your response. Otherwise, ignore it.",
"",
"Web Search Results:",
"",
getFormattedSearchResults(5),
"",
"Request:",
"",
query,
].join("\n");
}
async function getLinkSummarizationPrompt([
title,
snippet,
url,
]: SearchResults[0]) {
let prompt = "";
try {
const pageContent = await fetchPageContent(url, { maxLength: 2500 });
prompt = [
`The context below is related to a link found when searching for "${query}":`,
"",
"[BEGIN OF CONTEXT]",
`Snippet: ${snippet}`,
"",
pageContent,
"[END OF CONTEXT]",
"",
"Now, tell me: What is this link about and how is it related to the search?",
"",
"Note: Don't cite the link in your response. Just write a few sentences to indicate if it's worth visiting.",
].join("\n");
} catch (error) {
prompt = [
`When searching for "${query}", this link was found: [${title}](${url} "${snippet}")`,
"",
"Now, tell me: What is this link about and how is it related to the search?",
"",
"Note: Don't cite the link in your response. Just write a few sentences to indicate if it's worth visiting.",
].join("\n");
}
return prompt;
}
function getFormattedSearchResults(limit?: number) {
return getSearchResults()
.slice(0, limit)
.map(([title, snippet, url]) => `${title}\n${url}\n${snippet}`)
.join("\n\n");
}
async function getKeywords(text: string, limit?: number) {
return (await import("keyword-extractor")).default
.extract(text, { language: "english" })
.slice(0, limit);
}
|