<!DOCTYPE html>
<html>
<head>
<title>Sloppacomplete</title>
<style>
:root {
--bg: #333; / Dark background to represent a night sky /
--bg-alt: #111; / Slightly darker background for some elements /
--text: #fff; / White text for the dark gray background /
--highlight: #424242; / A slightly lighter grey for highlights /
--border: #334652; / Slightly darker border color /
--border-hover: #485e6c; / Slightly lighter border on hover /
}
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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 | body {
font-family: serif;
font-size: 14px;
background-color: var(--bg);
color: var(--text);
margin: 0;
overflow: hidden;
height: 100vh;
scrollbar-gutter: stable;
scrollbar-width: thin;
outline: none;
}
:hover {
border-color: var(--border-hover);
}
::selection {
background-color: var(--highlight);
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-track {
background: var(--bg-alt);
}
::-webkit-scrollbar-thumb {
background: var(--highlight);
}
.flex {
display: flex;
height: 100vh;
}
#sidebar {
flex: 0 1 auto;
font-size: smaller;
width: 230px;
padding-left: 10px;
padding-right: 10px;
height: 100vh;
box-sizing: border-box;
background-color: var(--bg-alt);
overflow-y: auto;
border-right: 1px solid var(--border);
text-align: center;
}
.editorContainer {
display: flex;
flex: 1;
align-items: center;
width: 100%;
margin-left: auto;
margin-right: auto;
flex-direction: column;
position: relative;
background-color: var(--bg);
overflow: hidden;
}
#editor, #overlay, textarea {
display: block;
color: var(--text);
inset: 0;
width: 100%;
min-height: 100%;
background-color: var(--bg);
padding: 1.8em;
padding-top: 1.2em;
margin-left: auto;
margin-right: auto;
border-radius: 4px;
resize: none;
font-family: inherit;
font-size: 16px;
border: 1px solid var(--border);
background-color: var(--bg-alt);
box-sizing: border-box;
line-height: 1;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
white-space: pre-wrap;
padding-bottom: 2em;
overflow: hidden;
}
#overlay {
/* color: var(--border-hover); */
user-select: none;
pointer-events: none;
-webkit-user-select: none;
background: 0 0;
position: absolute;
border: 1px solid transparent;
z-index: 9;
overflow-clip-margin: 2em;
overflow: hidden;
}
:focus {
border: 1px solid var(--highlight);
outline: none;
}
label {
margin: 0px;
padding: 0px;
}
.autocomplete {
display: flex;
box-sizing: border-box;
border: 1px solid var(--border);
background-color: var(--bg-alt);
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
width: 100%;
height: 30%;
margin-top: 2px;
overflow-y: auto;
z-index: 10;
}
.autocomplete-item {
padding: 5px 10px;
cursor: pointer;
font-size: 16px;
max-height: 2.1em;
text-overflow: ellipsis;
text-wrap: nowrap;
overflow: hidden;
}
.autocomplete-item:hover,
.autocomplete-item.selected {
background-color: var(--border-hover);
}
input,
select,
button {
box-sizing: border-box;
margin-top: 2px;
margin-bottom: 2px;
background-color: var(--bg);
color: var(--text);
border: 1px solid var(--border);
margin: 4px;
text-align: center;
}
input[type="number"] {
width: 3rem;
}
/*********** Baseline, reset styles ***********/
input[type="range"] {
-webkit-appearance: none;
appearance: none;
background: transparent;
cursor: pointer;
width: 100%;
}
/* Removes default focus */
input[type="range"]:focus {
outline: none;
}
/******** Chrome, Safari, Opera and Edge Chromium styles ********/
/* slider track */
input[type="range"]::-webkit-slider-runnable-track {
background-color: var(--bg);
border-radius: 0.4rem;
height: 0.5rem;
}
/* slider thumb */
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
margin-top: -4px; /* Centers thumb on the track */
background-color: var(--text);
border-radius: 0.3rem;
height: 1rem;
width: 0.5rem;
}
input[type="range"]:focus::-webkit-slider-thumb {
outline: 1px solid var(--border-hover);
}
.toggle-container {
border: 1px solid var(--border);
}
.toggle-container input[type="checkbox"] {
display: none;
}
.toggle-container label {
display: block;
cursor: pointer;
padding: 0;
background-color: var(--bg-alt);
}
.toggle-container .content {
max-height: 0;
overflow-y: auto;
overflow-x: hidden;
transition: max-height 0.3s ease-out;
}
.toggle-container input[type="checkbox"]:checked ~ .content {
max-height: 250px;
}
#settings label {
display: block;
text-align: center;
margin-top: 5px;
}
.loading {
animation: pulse 2.5s infinite;
transition: border-color 0.5s ease;
transition: background-color 0.5s ease;
}
.reverseloading {
animation: revpulse 2.5s infinite;
transition: border-color 0.5s ease;
transition: background-color 0.5s ease;
}
@keyframes pulse {
0% {
border-color: var(--highlight);
background-color: var(--bg-alt);
}
50% {
border-color: var(--border-hover);
background-color: var(--bg-hover);
}
100% {
border-color: var(--highlight);
background-color: var(--bg-alt);
}
}
@keyframes revpulse {
0% {
border-color: var(--bg-alt);
background-color: var(--bg-hover);
}
50% {
border-color: var(--border);
background-color: var(--bg-alt);
}
100% {
border-color: var(--bg-alt);
background-color: var(--bg-hover);
}
}
.glowing {
animation: pulseglow 2.5s infinite;
transition: text-shadow 0.5s ease;
}
@keyframes pulseglow {
0% {
text-shadow: 0 0 10px var(--highlight);
}
50% {
text-shadow: 0 0 10px var(--border-hover),
0 0 20px var(--border-hover);
}
100% {
text-shadow: 0 0 10px var(--highlight);
}
}
.glow {
color: var(--text);
text-shadow: 0 0 10px var(--highlight),
0 0 20px var(--highlight);
transition: text-shadow 0.3s ease;
}
</style>
<script type="module">
/* The following WILL send shivers down your spine.
*/
const editor = document.getElementById("editor");
const autocompleteDiv = document.getElementById("autocomplete");
const apiKeyInput = document.getElementById("apiKey");
const contentTypeSelect = document.getElementById("contentType");
const numCompletions = document.getElementById("numCompletions");
const elmaxTokens = document.getElementById("maxTokens");
const maxN = document.getElementById("maxN");
const model = document.getElementById("model");
const endPointMode = document.getElementById("endPointMode");
const overlay = document.getElementById("overlay");
const editorContainer = document.getElementById("editorContainer");
const colorSchemePrompt = `<|im_start|>user
Code:
'''css
:root {
--bg: #1f2d34; /* Dark background to represent a night sky */
--bg-alt: #111a1d; /* Slightly darker background for some elements */
--text: #7ed6df; /* A light pastel blue for text */
--highlight: #4dc9df94; /* A slightly darker pastel blue for highlights, making them more prominent */
--border: #334652; /* Slightly darker border color */
--border-hover: #485e6c; /* Slightly lighter border on hover */
}
'''
Please rewrite the css colors in the provided code to look like PROMPT[ {PROMPT} ]. Analyze the PROMPT given and generate a new color scheme from it, for example, if a subject is given, determine the subjects signature colors and use them for the new color scheme. Ensure that the text remains well contrasted with the background color, ie. a bright background requires dark text, while a dark background requires lighter text. Only output the updated css, with only the values and comments changed, the variable naming stays the same. Write your brief reasoning for the change inside the css comment. Thank you Sloppa.
<|im_end|>
<|im_start|>assistant
root {`
let timeoutId;
let selectedIndex = 0;
let tokenProbs = [];
let autoCompleteRunning = false;
let autoCompleteAbort = new AbortController();
window.addEventListener('load', () => {
loadSettings();
const samplerNumberInputs = document.querySelectorAll("#samplerSettings input[type=range],#samplerSettings input[type=number]");
samplerNumberInputs.forEach(input => {
input.addEventListener("input", (event) => {
if (parseInt(elmaxTokens.value) === 1){
debounce(100);
}
});
});
});
document.getElementById("save").addEventListener("click", () => {
saveSettings();
})
document.getElementById("clear").addEventListener("click", () => {
console.debug(localStorage.removeItem("SloppacompleteSettings"));
})
document.getElementById("generate").addEventListener("click", () => {
Generate();
})
document.getElementById("default-endpoints").addEventListener("input", () => {
document.getElementById('endpoint').value = document.getElementById("default-endpoints").value;
switch (document.getElementById("default-endpoints").value) {
case "http://localhost:11434/v1/completions":
document.getElementById('endPointMode').value = "openai";
break;
case "http://localhost:8080/completions":
document.getElementById('endPointMode').value = "llama.cpp";
break;
case "http://localhost:5001/v1/completions":
document.getElementById('endPointMode').value = "openai";
break;
case "http://localhost:5001/api/extra/generate/stream":
document.getElementById('endPointMode').value = "koboldcpp";
break;
default:
break;
}
})
document.getElementById("colorscheme").addEventListener("keyup", ({key}) => {
if (key === "Enter") {
console.debug("Trying new color scheme: ",document.getElementById("colorscheme").value)
updateColorScheme(colorSchemePrompt.replace("{PROMPT}",document.getElementById("colorscheme").value));
}
});
function resizeTextArea() {
if (overlay.getBoundingClientRect().height <= overlay.scrollHeight){
overlay.style.height = overlay.scrollHeight + "px";
editor.style.height = overlay.scrollHeight + "px";
} else if (overlay.getBoundingClientRect().height > overlay.scrollHeight) {
overlay.style.height = "";
editor.style.height = "";
overlay.style.height = overlay.scrollHeight + "px";
editor.style.height = overlay.scrollHeight + "px";
}
}
editor.addEventListener("input", () => {
autoCompleteAbort.abort();
document.getElementById("hiddentext").textContent = editor.value;
document.getElementById("ghosttext").textContent = "";
if (editor.selectionStart === editor.value.length){
debounce();
}
resizeTextArea();
});
editor.onselect = (event) => {
//getPrefixSuffixSelection(event.target);
};
function getPrefixSuffixSelection(element) {
let prefix, suffix, selection;
//todo max prefix and suffix length (lines) function for infill
prefix = (element.selectionStart > 0) ? element.value.substring(0, element.selectionStart) : "";
suffix = (element.selectionEnd < element.value.length) ? element.value.substring(element.selectionEnd, element.value.length) : "";
selection = element.value.substring(element.selectionStart, element.selectionEnd);
return {prefix,selection,suffix};
}
function debounce(timeMS = 350) {
clearTimeout(timeoutId);
timeoutId = setTimeout(async () => {
await updateAutocomplete();
}, timeMS);
}
editor.addEventListener("keydown", (event) => {
if (event.key === "ArrowDown") {
event.preventDefault();
selectedIndex =
(selectedIndex + 1) % autocompleteDiv.children.length;
updateSelection();
} else if (event.key === "ArrowUp") {
event.preventDefault();
selectedIndex =
(selectedIndex - 1 + autocompleteDiv.children.length) %
autocompleteDiv.children.length;
updateSelection();
} else if (event.key === "Tab") {
event.preventDefault();
insertCompletion();
} else if (event.key === "Escape") {
selectedIndex = 0;
clearPreviewText();
autoCompleteAbort.abort();
clearTimeout(timeoutId);
updateAutocomplete();
} else if (parseInt(event.key) !== null && parseInt(event.key) >= 0 && parseInt(event.key) <= 9 && parseInt(elmaxTokens.value) === 1 && tokenProbs.length > 0) {
event.preventDefault();
console.log(event.key);
clearPreviewText();
insertCompletion(tokenProbs[parseInt(event.key) === 0 ? 9 : parseInt(event.key) - 1].token);
tokenProbs = [];
autoCompleteAbort.abort();
clearTimeout(timeoutId);
updateAutocomplete();
}
});
async function updateColorScheme(prompt) {
if (!autoCompleteAbort || autoCompleteAbort.signal.aborted) {
autoCompleteAbort = new AbortController();
} else {
autoCompleteAbort.abort();
updateColorScheme(prompt);
return;
}
const { signal } = autoCompleteAbort;
const cssKeyValueColorHex = /(?:[\s]*(--[a-zA-Z-_]+): (.+);)/gm;
document.getElementById("colorscheme").classList.add("loading");
document.getElementById("colorscheme").classList.add("glow");
let text = ""
for await (const r of
sseCompletionStream(
document.getElementById("endpoint").value,
apiKeyInput.value,
getAPIParams(prompt,null,256),
signal,
endPointMode.value
)
){
if (r && r.length > 0) {
signal.throwIfAborted();
text += r
let match;
while((match = cssKeyValueColorHex.exec(text)) !== null){
signal.throwIfAborted();
if (match.index === cssKeyValueColorHex.lastIndex) {
cssKeyValueColorHex.lastIndex++;
}
let key = "";
let value = "";
match.forEach((m, group) => {
group === 1 ? key = m :
group === 2 ? value = m :
null;
if (key.length > 0 && value.length > 0){
console.debug("Set color prop",key,value,text)
text = "";
document.documentElement.style.setProperty(key, value);
}
});
}
if (text.includes("}")){ // break after css block is closed
console.log("updateColorScheme finished, remaining response:",text)
autoCompleteAbort.abort();
break;
}
}
}
document.getElementById("colorscheme").classList.remove("loading");
document.getElementById("colorscheme").classList.remove("glow");
}
async function Generate() {
if (!autoCompleteAbort || autoCompleteAbort.signal.aborted) {
autoCompleteAbort = new AbortController();
} else {
autoCompleteAbort.abort();
Generate();
return;
}
const { signal } = autoCompleteAbort;
for await (const r of
sseCompletionStream(
document.getElementById("endpoint").value,
apiKeyInput.value,
getAPIParams(),
signal,
endPointMode.value
)
){
if (r && r.length > 0)
signal.throwIfAborted();
insertText(editor,r)
editor.scrollTop = editor.scrollHeight;
}
updateAutocomplete();
}
async function updateAutocomplete() {
if (!autoCompleteAbort || autoCompleteAbort.signal.aborted) {
autoCompleteAbort = new AbortController();
} else {
autoCompleteAbort.abort();
updateAutocomplete();
return;
}
console.debug("updateAutocomplete started");
document.getElementById("hiddentext").textContent = editor.value;
document.getElementById("ghosttext").textContent = "";
resizeTextArea();
const { signal } = autoCompleteAbort;
autocompleteDiv.style.display = "block";
autocompleteDiv.innerHTML = "";
selectedIndex = 0;
autoCompleteRunning = true;
const maxResults = parseInt(maxN.value);
var elementSelected = false;
const regexp =
contentTypeSelect.value == "sentences"
? /([^.!?]*[.!?\t]["\s]?)/gm
: contentTypeSelect.value == "lines"
? /(.*$\n)/gm
: contentTypeSelect.value == "paragraphs"
? /(.*\n\n)/gm
: null;
let apiParams = getAPIParams();
let prefixSuffix = getPrefixSuffixSelection(editor);
let endPointURL;
if (prefixSuffix.suffix !== ""){ // infill, for now just remove the suffix
apiParams.prompt = prefixSuffix.prefix;
apiParams.suffix = prefixSuffix.suffix;
}
try {
for (let i = 0; i < numCompletions.value; i++) {
if (signal.aborted){
console.debug("cancelled single completion in numCompletions loop")
break;
}
let autoCompleteElement = null;
let results = 0;
let text = "";
//signal.throwIfAborted();
const singleCompletionAbortController = new AbortController();
const singleSignal = singleCompletionAbortController.signal;
for await (
const r of
sseCompletionStream(
endPointURL || document.getElementById("endpoint").value,
apiKeyInput.value,
apiParams,
singleSignal,
endPointMode.value
)
){
if (signal.aborted || results >= maxResults || singleSignal.aborted){
singleCompletionAbortController.abort();
console.debug("cancelled single completion in generate loop",results,signal.aborted)
continue;
}
if (r && r.length > 0){
if (regexp) {
let match;
text += r
while ((match = regexp.exec(text)) !== null) {
if (signal.aborted || results >= maxResults || singleSignal.aborted) {
singleCompletionAbortController.abort();
console.debug("cancelled single completion in RegEx loop",results,signal.aborted)
break;
}
if (match.index === regexp.lastIndex) {
regexp.lastIndex++;
}
console.debug(`Found match${match.index}:\n${match[0]}\nin\n${text}`);
if (!autoCompleteElement) {
autoCompleteElement = addAutocompleteItem();
autoCompleteElement.classList.add("glowing");
autoCompleteElement.classList.add("reverseloading");
if (!autocompleteDiv.classList.contains("loading")){
autocompleteDiv.classList.add("loading");
}
if (!elementSelected) {
updateSelection();
elementSelected = true;
}
}
autoCompleteElement.textContent += match[0]
results++;
text = "";
}
} else {
// Tokens
if (!autoCompleteElement) {
autoCompleteElement = addAutocompleteItem();
autoCompleteElement.classList.add("glowing");
autoCompleteElement.classList.add("reverseloading");
if (!autocompleteDiv.classList.contains("loading")){
autocompleteDiv.classList.add("loading");
}
if (!elementSelected) {
updateSelection();
elementSelected = true;
}
}
autoCompleteElement.textContent += r;
}
if (autoCompleteElement) {
updatePreviewText(autoCompleteElement);
}
}
}
if (autoCompleteElement) {
autoCompleteElement.classList.remove("glowing");
autoCompleteElement.classList.remove("reverseloading");
if (autocompleteDiv.classList.contains("loading")){
autocompleteDiv.classList.remove("loading");
}
}
}
} catch (error) {
if (error.name !== "AbortError") {
throw error;
} else {
console.log("updateAutocomplete aborted")
}
} finally {
autoCompleteRunning = false;
}
}
function addAutocompleteItem() {
const item = document.createElement("div");
item.classList.add("autocomplete-item");
item.textContent = "";
item.addEventListener("click", () => {
insertCompletion(item.textContent);
});
autocompleteDiv.appendChild(item);
return item;
}
function updatePreviewText(item, invokeScroll = true) {
if (item.classList.contains("selected")){
/* let sel = getPrefixSuffixSelection(editor);
if (sel.suffix !== ""){
if (document.getElementById("hiddentext").textContent !== sel.prefix){
document.getElementById("hiddentext").textContent = sel.prefix;
document.getElementById("suffix").textContent = sel.suffix;
}
} else {
if (document.getElementById("hiddentext").textContent !== editor.value){
document.getElementById("hiddentext").textContent = editor.value;
}
document.getElementById("suffix").textContent = "";
}
*/
document.getElementById("token_selection").innerHTML = "";
if (parseInt(elmaxTokens.value) === 1){
// single token, display token prob selection, todo: maybe refactor later, could display accumulated probs for multiple tokens
let tokstr = "\n<table>";
let count = 1;
tokenProbs.forEach((obj) => {
tokstr += (`<tr><td><span style="color: lightgray">${count === 10 ? 0 : count} </span></td><td><span style="color: lightgray"></span>${obj.prob.toFixed(3)}</td><td><span style="color: ${obj.token === item.textContent ? "green;" : "lightgray"}">${tokenEscape(obj.token)}</span></td></tr>\n`);
count++;
})
tokstr += `</table>`;
document.getElementById("token_selection").innerHTML = tokstr;
}
if (document.getElementById("hiddentext").textContent !== editor.value){
document.getElementById("hiddentext").textContent = editor.value;
}
if (document.getElementById("hiddentext").textContent !== item.textContent){
document.getElementById("ghosttext").textContent = item.textContent;
}
resizeTextArea();
//console.debug(`resize and scroll in updateAutocompleteItem`)
if (document.getElementById("autoscroll").checked && invokeScroll){
editorContainer.scrollTop = editorContainer.scrollHeight;
}
}
}
function tokenEscape(token){
return token.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '\\n')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function clearPreviewText() {
document.getElementById("hiddentext").textContent = editor.value;
document.getElementById("ghosttext").textContent = "";
resizeTextArea();
if (document.getElementById("autoscroll").checked){
editorContainer.scrollTop = editor.scrollHeight;
}
}
function updateSelection() {
for (let i = 0; i < autocompleteDiv.children.length; i++) {
autocompleteDiv.children[i].classList.toggle("selected", i === selectedIndex);
if (i === selectedIndex) {
clearPreviewText();
updatePreviewText(autocompleteDiv.children[i]);
// scroll to selected item if it's outside the visible area
const item = autocompleteDiv.children[i];
const itemRect = item.getBoundingClientRect();
const autocompleteRect = autocompleteDiv.getBoundingClientRect();
if (itemRect.bottom > autocompleteRect.bottom || itemRect.top < autocompleteRect.top) {
item.scrollIntoView({ block: "nearest", behavior: "instant" });
}
}
}
}
function insertCompletion(completionText = null) {
const prompt = editor.value;
const selectedCompletion =
completionText ||
autocompleteDiv.children[selectedIndex]?.textContent;
if (selectedCompletion) {
insertText(editor, selectedCompletion);
resizeTextArea();
if (document.getElementById("autoscroll").checked){
editorContainer.scrollTop = editorContainer.scrollHeight;
}
autocompleteDiv.innerHTML = "";
selectedIndex = 0;
clearTimeout(timeoutId);
updateAutocomplete();
}
}
function insertText(element, text) {
// browser undo/redo, propably better to implement natively
element.focus();
//element.setSelectionRange(-1, -1);
if (!document.execCommand('insertText', false, text)){
elemt.value = element.value + text;
}
}
function getAPIParams(prompt = null, model = null, max_tokens = null, extra = {}) {
// todo
const mode = endPointMode.value;
const max_token_key = mode === "llama.cpp" ? "n_predict" : "max_tokens";
const repeat_penalty_key = mode === "koboldcpp" ? "rep_pen" : "repeat_penalty";
const repeat_penalty_range_key = mode === "koboldcpp" ? "rep_pen_range" : "repeat_last_n";
const logprobs_key = mode === "llama.cpp" || mode === "koboldcpp" ? "n_probs" : "logprobs";
const logprobs_default = mode === "llama.cpp" || mode === "koboldcpp" ? 10 : true;
extra = mode === "openai" ? { ...extra, top_logprobs: 5} : extra;
extra = mode === "llama.cpp" || mode === "koboldcpp" ? { ...extra, cache_prompt: true } : extra;
return {
model: model || document.getElementById("model").value,
prompt: prompt || editor.value,
[max_token_key]: max_tokens || parseInt(document.getElementById("maxTokens").value),
[logprobs_key]: logprobs_default,
temperature: parseFloat(document.getElementById("temp").value),
[repeat_penalty_key]: parseFloat(document.getElementById("rep_pen").value),
[repeat_penalty_range_key]: parseInt(document.getElementById("rep_pen_range").value),
presence_penalty: parseFloat(document.getElementById("pres_pen").value),
frequency_penalty: parseFloat(document.getElementById("freq_pen").value),
min_p: parseFloat(document.getElementById("min_p").value),
top_p: parseFloat(document.getElementById("top_p").value),
top_k: parseInt(document.getElementById("top_k").value),
n: 1,
stream: true,
...extra
};
}
async function parseCompletionChunk(data, mode) {
let token = "";
let probs = [];
if (mode == "raw"){
if (data) return data;
} else if (data && data.content && data.content.length > 0) {
token = data.content;
if (data.completion_probabilities && data.completion_probabilities[0].probs){
probs = data.completion_probabilities[0].probs;
tokenProbs = [];
probs.forEach((el) => {
tokenProbs.push({token: el.tok_str, prob: el.prob});
}
);
}
} else if (data && data.choices && data.choices.length > 0){
token = data.choices[0].text;
if (data.choices[0].logprobs){
// todo
probs = data.choices[0].logprobs.content[0].top_logprobs;
probs.forEach((el) => console.log(el));
}
} else if (data && data.results && data.results.length > 0){ // https://lite.koboldai.net/koboldcpp_api#/api%2Fextra/post_api_extra_generate_stream
token = data.results[0].text;
} else {
if (data) return data;
}
return token;
}
async function* sseCompletionStream(endPoint,apiKey, requestObj, abortSignal = undefined, mode = "llama.cpp") {
const response = await fetch(endPoint,
{
signal: abortSignal,
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(requestObj),
},
);
if (!response.ok) {
const errorData = await response.json(); // Get error details (for OAI only atm)
throw new Error(
`API Error: ${response.status} - ${errorData.error.message}`
);
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
const results = [];
let buffer = "";
try {
while (true) {
if (abortSignal.aborted) throw new DOMException("Aborted", "AbortError");
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value);
let newlineIndex;
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
if (abortSignal.aborted) throw new DOMException("Aborted", "AbortError");
const line = buffer.substring(0, newlineIndex);
buffer = buffer.substring(newlineIndex + 1);
if (line.startsWith("data:")) {
if (!line.substring(6).startsWith("[DONE]")) { // Remove "data: " prefix, [DONE] handling for oai api
const data = JSON.parse(line.substring(6));
console.debug(data);
yield await parseCompletionChunk(data,mode);
}
}
}
}
} catch (e) {
if (e.name !== "AbortError") {
throw e;
} else {
console.debug("api call cancelled",e);
}
} finally {
reader.releaseLock();
}
return;
}
function saveSettings() {
const settings = {};
const sidebarInputs = document.querySelectorAll("#sidebar input, #sidebar select");
sidebarInputs.forEach(input => {
settings[input.id] = input.type === "checkbox" ? input.checked : input.value;
});
const cssVariables = {};
const root = Array.from(document.styleSheets) // https://stackoverflow.com/a/54851636
.filter(
sheet =>
sheet.href === null || sheet.href.startsWith(window.location.origin)
)
.reduce(
(acc, sheet) =>
(acc = [
...acc,
...Array.from(sheet.cssRules).reduce(
(def, rule) =>
(def =
rule.selectorText === ":root"
? [
...def,
...Array.from(rule.style).filter(name =>
name.startsWith("--")
)
]
: def),
[]
)
]),
[]
);;
for (let i = 0; i < root.length; i++) {
if (root[i].length > 0){
cssVariables[root[i]] = document.documentElement.style.getPropertyValue(root[i]);
}
}
settings["cssVariables"] = cssVariables;
localStorage.setItem("SloppacompleteSettings", JSON.stringify(settings));
}
function loadSettings() {
const savedSettings = JSON.parse(localStorage.getItem("SloppacompleteSettings"));
if (savedSettings) {
for (const key in savedSettings) {
if (key !== "cssVariables") {
const element = document.getElementById(key);
if (element) {
if (element.type === "checkbox") {
element.checked = savedSettings[key];
} else {
element.value = savedSettings[key];
}
}
}
}
const cssVariables = savedSettings["cssVariables"];
if (cssVariables) {
for (const variableName in cssVariables) {
document.documentElement.style.setProperty(variableName, cssVariables[variableName]);
}
}
}
}
</script>
|
</head>
<body>
<div class="flex">
<div id="sidebar">
<div id="settings">
<h2>Sloppacomplete</h2>
<h4><u>Color Scheme:</u></h4>
<label for="colorscheme">Prompt (Enter to apply):
<input type="text" id="colorscheme" value="dark pastel shades, pastel pink text, with a dark, soft background"/>
</label>
<h4><u>Auto-completion settings:</u></h4>
<label for="numCompletions">Suggestions:
<input type="number" id="numCompletions" value="7" min="1" />
</label>
<label for="contentType">Output filter:
<select id="contentType">
<option value="tokens">none (tokens)</option>
<option value="sentences">sentences</option>
<option value="lines">lines</option>
<option value="paragraphs">paragraphs</option>
</select>
</label>
<label for="maxN">Filter match limit (sentences, lines, paragraphs):
<input type="number" id="maxN" value="3" />
</label>
<label for="autoscroll">Auto-scroll
<input type="checkbox" id="autoscroll" checked />
</label>
<h4><u>Prediction settings:</u></h4>
<label for="maxTokens">Max tokens:
<input type="number" id="maxTokens" value="10" min="1"/>
</label>
<label for="default-endpoints">Endpoint preset:
<select id="default-endpoints">
<option value="http://localhost:8080/completions">llama.cpp</option>
<option value="http://localhost:11434/v1/completions">ollama</option>
<option value="http://localhost:5001/v1/completions">KoboldCPP OAI</option>
<option value="http://localhost:5001/api/extra/generate/stream">KoboldCPP Native</option>
</select>
</label>
<label for="endPointMode">Backend mode:
<select id="endPointMode">
<option value="llama.cpp">llama.cpp</option>
<option value="openai">ollama / OpenAI</option>
<option value="koboldcpp">KoboldCPP Native</option>
</select>
</label>
<label for="endpoint">API Url:
<input type="text" id="endpoint" value="http://192.168.0.20:6969/completions" />
</label>
<label for="model">Model:
<input type="text" id="model" value="" />
</label>
<label for="apiKey">API Key:
<input type="password" id="apiKey" value="shivers" />
</label>
<div class="toggle-container">
<input type="checkbox" id="samplertoggle">
<label for="samplertoggle"><h4><u>Samplers:</u></h4></label>
<div class="content" id="samplerSettings">
<label for="temp">Temperature (<input type="number" value="1" min="0" max="5" step="0.05" id="temp_out" oninput="document.getElementById('temp').value = this.value"/>)
<input type="range" id="temp" value="1" min="0" max="5" step="0.05" oninput="document.getElementById('temp_out').value = this.value"/>
</label>
<label for="rep_pen">rep_pen (<input type="number" value="1" min="1" max="3" id="rep_pen_out" oninput="document.getElementById('rep_pen').value = this.value"/>)
<input type="range" id="rep_pen" value="1" min="1" max="3" step="0.01" oninput="document.getElementById('rep_pen_out').value = this.value"/>
</label>
<label for="rep_pen_range">rep_pen_range (<input type="number" value="64" min="0" max="200000" id="rep_pen_range_out" oninput="document.getElementById('rep_pen_range').value = this.value"/>)
<input type="range" id="rep_pen_range" value="64" min="1" max="200000" step="8" oninput="document.getElementById('rep_pen_range_out').value = this.value"/>
</label>
<label for="pres_pen">pres_pen (<input type="number" value="0" min="-2" max="2" id="pres_pen_out" oninput="document.getElementById('pres_pen').value = this.value"/>)
<input type="range" id="pres_pen" value="0" min="-2" max="2" step="0.01" oninput="document.getElementById('pres_pen_out').value = this.value"/>
</label>
<label for="freq_pen">freq_pen (<input type="number" value="0" min="-2" max="2" id="freq_pen_out" oninput="document.getElementById('freq_pen').value = this.value"/>)
<input type="range" id="freq_pen" value="0" min="-2" max="2" step="0.01" oninput="document.getElementById('freq_pen_out').value = this.value"/>
</label>
<label for="min_p">min_p (<input type="number" value="0.05" min="0" max="1" id="min_p_out" oninput="document.getElementById('min_p').value = this.value"/>)
<input type="range" id="min_p" value="0.05" min="0" max="1" step="0.01" oninput="document.getElementById('min_p_out').value = this.value"/>
</label>
<label for="top_p">top_p (<input type="number" value="1" min="0" max="1" id="top_p_out" oninput="document.getElementById('top_p').value = this.value"/>)
<input type="range" id="top_p" value="1" min="0" max="1" step="0.05" oninput="document.getElementById('top_p_out').value = this.value"/>
</label>
<label for="top_k">top_k (<input type="number" value="0" min="-1" max="400" id="top_k_out" oninput="document.getElementById('top_k').value = this.value"/>)
<input type="range" id="top_k" value="0" min="-1" max="400" step="1" oninput="document.getElementById('top_k_out').value = this.value"/>
</label>
</div>
</div>
- If you want to use instruct mode use the appropriate tokens from your chosen model.
- To use the filter (sentences, lines and paragraphs) ensure that the Max tokens value is high enough for the model to generate a suitable amount of text to filter.
- Only for llama.cpp backend: setting Max tokens to 1 enables token probability preview, this will show the probability of the next token and updates automatically when sampler values are changed. You can either press Tab to select the chosen token or enter a number to pick a different one.
Note: Download this html to try it with local tools such as ollama.
Hotkeys:
Esc Run Autocomplete (Reroll)
Arrow Up/Down Scroll through completions
Tab -> Insert selected completion.
F12 (Console) for debug and error info.
-
Sloppa"></textarea>
<div id="overlay" aria-hidden="true"><span id="hiddentext" style="visibility: hidden;"></span></span><span id="ghosttext" style="opacity: 90%; color: grey"></span><span id="token_selection" style="color: var(--highlight);"></span><span id="suffix" style="visibility: hidden;"></span></div>
</div>
<div id="autocomplete" class="autocomplete"></div>
</div>
</div></body>
</html>