index.html 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  5. <meta name="color-scheme" content="light dark">
  6. <title>llama.cpp - chat</title>
  7. <style>
  8. body {
  9. font-family: system-ui;
  10. font-size: 90%;
  11. }
  12. .grid-container {
  13. display: grid;
  14. grid-template-columns: auto auto auto;
  15. padding: 10px;
  16. }
  17. .grid-item {
  18. padding: 5px;
  19. /* font-size: 30px; */
  20. text-align: center;
  21. }
  22. #container {
  23. margin: 0em auto;
  24. display: flex;
  25. flex-direction: column;
  26. justify-content: space-between;
  27. height: 100%;
  28. }
  29. main {
  30. margin: 3px;
  31. display: flex;
  32. flex-direction: column;
  33. justify-content: space-between;
  34. gap: 1em;
  35. flex-grow: 1;
  36. overflow-y: auto;
  37. border: 1px solid #ccc;
  38. border-radius: 5px;
  39. padding: 0.5em;
  40. }
  41. h1 {
  42. text-align: center;
  43. }
  44. .customlink:link {
  45. color: white;
  46. background-color: #007aff;
  47. font-weight: 600;
  48. text-decoration: none;
  49. float: right;
  50. margin-top: 30px;
  51. display: flex;
  52. flex-direction: row;
  53. gap: 0.5em;
  54. justify-content: flex-end;
  55. border-radius: 4px;
  56. padding: 8px;
  57. }
  58. .customlink:visited {
  59. color: white;
  60. background-color: #007aff;
  61. font-weight: 600;
  62. text-decoration: none;
  63. float: right;
  64. margin-top: 30px;
  65. display: flex;
  66. flex-direction: row;
  67. gap: 0.5em;
  68. justify-content: flex-end;
  69. padding: 8px;
  70. }
  71. .customlink:hover {
  72. color: white;
  73. background-color: #0070ee;
  74. font-weight: 600;
  75. text-decoration: none;
  76. float: right;
  77. margin-top: 30px;
  78. display: flex;
  79. flex-direction: row;
  80. gap: 0.5em;
  81. justify-content: flex-end;
  82. padding: 8px;
  83. }
  84. .customlink:active {
  85. color: #0070ee;
  86. background-color: #80b3ef;
  87. font-weight: 600;
  88. text-decoration: none;
  89. float: right;
  90. margin-top: 30px;
  91. display: flex;
  92. flex-direction: row;
  93. gap: 0.5em;
  94. justify-content: flex-end;
  95. padding: 8px;
  96. }
  97. body {
  98. max-width: 600px;
  99. min-width: 300px;
  100. line-height: 1.2;
  101. margin: 0 auto;
  102. padding: 0 0.5em;
  103. }
  104. p {
  105. overflow-wrap: break-word;
  106. word-wrap: break-word;
  107. hyphens: auto;
  108. margin-top: 0.5em;
  109. margin-bottom: 0.5em;
  110. }
  111. #write form {
  112. margin: 1em 0 0 0;
  113. display: flex;
  114. flex-direction: column;
  115. gap: 0.5em;
  116. align-items: stretch;
  117. }
  118. .message-controls {
  119. display: flex;
  120. justify-content: flex-end;
  121. }
  122. .message-controls > div:nth-child(2) {
  123. display: flex;
  124. flex-direction: column;
  125. gap: 0.5em;
  126. }
  127. .message-controls > div:nth-child(2) > div {
  128. display: flex;
  129. margin-left: auto;
  130. gap: 0.5em;
  131. }
  132. fieldset {
  133. border: none;
  134. padding: 0;
  135. margin: 0;
  136. }
  137. fieldset.two {
  138. display: grid;
  139. grid-template: "a a";
  140. gap: 1em;
  141. }
  142. fieldset.three {
  143. display: grid;
  144. grid-template: "a a a";
  145. gap: 1em;
  146. }
  147. details {
  148. border: 1px solid #aaa;
  149. border-radius: 4px;
  150. padding: 0.5em 0.5em 0;
  151. margin-top: 0.5em;
  152. }
  153. summary {
  154. font-weight: bold;
  155. margin: -0.5em -0.5em 0;
  156. padding: 0.5em;
  157. cursor: pointer;
  158. }
  159. details[open] {
  160. padding: 0.5em;
  161. }
  162. .prob-set {
  163. padding: 0.3em;
  164. border-bottom: 1px solid #ccc;
  165. }
  166. .popover-content {
  167. position: absolute;
  168. background-color: white;
  169. padding: 0.2em;
  170. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  171. }
  172. textarea {
  173. padding: 5px;
  174. flex-grow: 1;
  175. width: 100%;
  176. }
  177. pre code {
  178. display: block;
  179. background-color: #222;
  180. color: #ddd;
  181. }
  182. code {
  183. font-family: monospace;
  184. padding: 0.1em 0.3em;
  185. border-radius: 3px;
  186. }
  187. fieldset label {
  188. margin: 0.5em 0;
  189. display: block;
  190. }
  191. fieldset label.slim {
  192. margin: 0 0.5em;
  193. display: inline;
  194. }
  195. header,
  196. footer {
  197. text-align: center;
  198. }
  199. footer {
  200. font-size: 80%;
  201. color: #888;
  202. }
  203. .mode-chat textarea[name=prompt] {
  204. height: 4.5em;
  205. }
  206. .mode-completion textarea[name=prompt] {
  207. height: 10em;
  208. }
  209. [contenteditable] {
  210. display: inline-block;
  211. white-space: pre-wrap;
  212. outline: 0px solid transparent;
  213. }
  214. @keyframes loading-bg-wipe {
  215. 0% {
  216. background-position: 0%;
  217. }
  218. 100% {
  219. background-position: 100%;
  220. }
  221. }
  222. .loading {
  223. --loading-color-1: #eeeeee00;
  224. --loading-color-2: #eeeeeeff;
  225. background-size: 50% 100%;
  226. background-image: linear-gradient(90deg, var(--loading-color-1), var(--loading-color-2), var(--loading-color-1));
  227. animation: loading-bg-wipe 2s linear infinite;
  228. }
  229. @media (prefers-color-scheme: dark) {
  230. .loading {
  231. --loading-color-1: #22222200;
  232. --loading-color-2: #222222ff;
  233. }
  234. .popover-content {
  235. background-color: black;
  236. }
  237. }
  238. </style>
  239. <script type="module">
  240. import {
  241. html, h, signal, effect, computed, render, useSignal, useEffect, useRef, Component
  242. } from './index.js';
  243. import { llama } from './completion.js';
  244. import { SchemaConverter } from './json-schema-to-grammar.mjs';
  245. let selected_image = false;
  246. var slot_id = -1;
  247. const session = signal({
  248. prompt: "This is a conversation between User and Llama, a friendly chatbot. Llama is helpful, kind, honest, good at writing, and never fails to answer any requests immediately and with precision.",
  249. template: "{{prompt}}\n\n{{history}}\n{{char}}:",
  250. historyTemplate: "{{name}}: {{message}}",
  251. transcript: [],
  252. type: "chat", // "chat" | "completion"
  253. char: "Llama",
  254. user: "User",
  255. image_selected: ''
  256. })
  257. const params = signal({
  258. n_predict: 400,
  259. temperature: 0.7,
  260. repeat_last_n: 256, // 0 = disable penalty, -1 = context size
  261. repeat_penalty: 1.18, // 1.0 = disabled
  262. penalize_nl: false,
  263. top_k: 40, // <= 0 to use vocab size
  264. top_p: 0.95, // 1.0 = disabled
  265. min_p: 0.05, // 0 = disabled
  266. tfs_z: 1.0, // 1.0 = disabled
  267. typical_p: 1.0, // 1.0 = disabled
  268. presence_penalty: 0.0, // 0.0 = disabled
  269. frequency_penalty: 0.0, // 0.0 = disabled
  270. mirostat: 0, // 0/1/2
  271. mirostat_tau: 5, // target entropy
  272. mirostat_eta: 0.1, // learning rate
  273. grammar: '',
  274. n_probs: 0, // no completion_probabilities,
  275. min_keep: 0, // min probs from each sampler,
  276. image_data: [],
  277. cache_prompt: true,
  278. api_key: ''
  279. })
  280. /* START: Support for storing prompt templates and parameters in browsers LocalStorage */
  281. const local_storage_storageKey = "llamacpp_server_local_storage";
  282. function local_storage_setDataFromObject(tag, content) {
  283. localStorage.setItem(local_storage_storageKey + '/' + tag, JSON.stringify(content));
  284. }
  285. function local_storage_setDataFromRawText(tag, content) {
  286. localStorage.setItem(local_storage_storageKey + '/' + tag, content);
  287. }
  288. function local_storage_getDataAsObject(tag) {
  289. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  290. if (!item) {
  291. return null;
  292. } else {
  293. return JSON.parse(item);
  294. }
  295. }
  296. function local_storage_getDataAsRawText(tag) {
  297. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  298. if (!item) {
  299. return null;
  300. } else {
  301. return item;
  302. }
  303. }
  304. // create a container for user templates and settings
  305. const savedUserTemplates = signal({})
  306. const selectedUserTemplate = signal({ name: '', template: { session: {}, params: {} } })
  307. // let's import locally saved templates and settings if there are any
  308. // user templates and settings are stored in one object
  309. // in form of { "templatename": "templatedata" } and { "settingstemplatename":"settingsdata" }
  310. console.log('Importing saved templates')
  311. let importedTemplates = local_storage_getDataAsObject('user_templates')
  312. if (importedTemplates) {
  313. // saved templates were successfully imported.
  314. console.log('Processing saved templates and updating default template')
  315. params.value = { ...params.value, image_data: [] };
  316. //console.log(importedTemplates);
  317. savedUserTemplates.value = importedTemplates;
  318. //override default template
  319. savedUserTemplates.value.default = { session: session.value, params: params.value }
  320. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  321. } else {
  322. // no saved templates detected.
  323. console.log('Initializing LocalStorage and saving default template')
  324. savedUserTemplates.value = { "default": { session: session.value, params: params.value } }
  325. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  326. }
  327. function userTemplateResetToDefault() {
  328. console.log('Resetting template to default')
  329. selectedUserTemplate.value.name = 'default';
  330. selectedUserTemplate.value.data = savedUserTemplates.value['default'];
  331. }
  332. function userTemplateApply(t) {
  333. session.value = t.data.session;
  334. session.value = { ...session.value, image_selected: '' };
  335. params.value = t.data.params;
  336. params.value = { ...params.value, image_data: [] };
  337. }
  338. function userTemplateResetToDefaultAndApply() {
  339. userTemplateResetToDefault()
  340. userTemplateApply(selectedUserTemplate.value)
  341. }
  342. function userTemplateLoadAndApplyAutosaved() {
  343. // get autosaved last used template
  344. let lastUsedTemplate = local_storage_getDataAsObject('user_templates_last')
  345. if (lastUsedTemplate) {
  346. console.log('Autosaved template found, restoring')
  347. selectedUserTemplate.value = lastUsedTemplate
  348. }
  349. else {
  350. console.log('No autosaved template found, using default template')
  351. // no autosaved last used template was found, so load from default.
  352. userTemplateResetToDefault()
  353. }
  354. console.log('Applying template')
  355. // and update internal data from templates
  356. userTemplateApply(selectedUserTemplate.value)
  357. }
  358. //console.log(savedUserTemplates.value)
  359. //console.log(selectedUserTemplate.value)
  360. function userTemplateAutosave() {
  361. console.log('Template Autosave...')
  362. if (selectedUserTemplate.value.name == 'default') {
  363. // we don't want to save over default template, so let's create a new one
  364. let newTemplateName = 'UserTemplate-' + Date.now().toString()
  365. let newTemplate = { 'name': newTemplateName, 'data': { 'session': session.value, 'params': params.value } }
  366. console.log('Saving as ' + newTemplateName)
  367. // save in the autosave slot
  368. local_storage_setDataFromObject('user_templates_last', newTemplate)
  369. // and load it back and apply
  370. userTemplateLoadAndApplyAutosaved()
  371. } else {
  372. local_storage_setDataFromObject('user_templates_last', { 'name': selectedUserTemplate.value.name, 'data': { 'session': session.value, 'params': params.value } })
  373. }
  374. }
  375. console.log('Checking for autosaved last used template')
  376. userTemplateLoadAndApplyAutosaved()
  377. /* END: Support for storing prompt templates and parameters in browsers LocalStorage */
  378. const tts = window.speechSynthesis;
  379. const ttsVoice = signal(null)
  380. const llamaStats = signal(null)
  381. const controller = signal(null)
  382. // currently generating a completion?
  383. const generating = computed(() => controller.value != null)
  384. // has the user started a chat?
  385. const chatStarted = computed(() => session.value.transcript.length > 0)
  386. const transcriptUpdate = (transcript) => {
  387. session.value = {
  388. ...session.value,
  389. transcript
  390. }
  391. }
  392. // simple template replace
  393. const template = (str, extraSettings) => {
  394. let settings = session.value;
  395. if (extraSettings) {
  396. settings = { ...settings, ...extraSettings };
  397. }
  398. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  399. }
  400. async function runLlama(prompt, llamaParams, char) {
  401. const currentMessages = [];
  402. const history = session.value.transcript;
  403. if (controller.value) {
  404. throw new Error("already running");
  405. }
  406. controller.value = new AbortController();
  407. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value, api_url: new URL('.', document.baseURI).href })) {
  408. const data = chunk.data;
  409. if (data.stop) {
  410. while (
  411. currentMessages.length > 0 &&
  412. currentMessages[currentMessages.length - 1].content.match(/\n$/) != null
  413. ) {
  414. currentMessages.pop();
  415. }
  416. transcriptUpdate([...history, [char, currentMessages]])
  417. console.log("Completion finished: '", currentMessages.map(msg => msg.content).join(''), "', summary: ", data);
  418. } else {
  419. currentMessages.push(data);
  420. slot_id = data.slot_id;
  421. if (selected_image && !data.multimodal) {
  422. alert("The server was not compiled for multimodal or the model projector can't be loaded.");
  423. return;
  424. }
  425. transcriptUpdate([...history, [char, currentMessages]])
  426. }
  427. if (data.timings) {
  428. llamaStats.value = data;
  429. }
  430. }
  431. controller.value = null;
  432. }
  433. // send message to server
  434. const chat = async (msg) => {
  435. if (controller.value) {
  436. console.log('already running...');
  437. return;
  438. }
  439. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  440. let prompt = template(session.value.template, {
  441. message: msg,
  442. history: session.value.transcript.flatMap(
  443. ([name, data]) =>
  444. template(
  445. session.value.historyTemplate,
  446. {
  447. name,
  448. message: Array.isArray(data) ?
  449. data.map(msg => msg.content).join('').replace(/^\s/, '') :
  450. data,
  451. }
  452. )
  453. ).join("\n"),
  454. });
  455. if (selected_image) {
  456. prompt = `A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\nUSER:[img-10]${msg}\nASSISTANT:`;
  457. }
  458. await runLlama(prompt, {
  459. ...params.value,
  460. slot_id: slot_id,
  461. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  462. }, "{{char}}");
  463. }
  464. const runCompletion = () => {
  465. if (controller.value) {
  466. console.log('already running...');
  467. return;
  468. }
  469. const { prompt } = session.value;
  470. transcriptUpdate([...session.value.transcript, ["", prompt]]);
  471. runLlama(prompt, {
  472. ...params.value,
  473. slot_id: slot_id,
  474. stop: [],
  475. }, "").finally(() => {
  476. session.value.prompt = session.value.transcript.map(([_, data]) =>
  477. Array.isArray(data) ? data.map(msg => msg.content).join('') : data
  478. ).join('');
  479. session.value.transcript = [];
  480. })
  481. }
  482. const stop = (e) => {
  483. e.preventDefault();
  484. if (controller.value) {
  485. controller.value.abort();
  486. controller.value = null;
  487. }
  488. }
  489. const reset = (e) => {
  490. stop(e);
  491. transcriptUpdate([]);
  492. }
  493. const uploadImage = (e) => {
  494. e.preventDefault();
  495. document.getElementById("fileInput").click();
  496. document.getElementById("fileInput").addEventListener("change", function (event) {
  497. const selectedFile = event.target.files[0];
  498. if (selectedFile) {
  499. const reader = new FileReader();
  500. reader.onload = function () {
  501. const image_data = reader.result;
  502. session.value = { ...session.value, image_selected: image_data };
  503. params.value = {
  504. ...params.value, image_data: [
  505. { data: image_data.replace(/data:image\/[^;]+;base64,/, ''), id: 10 }]
  506. }
  507. };
  508. selected_image = true;
  509. reader.readAsDataURL(selectedFile);
  510. }
  511. });
  512. }
  513. const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  514. const talkRecognition = SpeechRecognition ? new SpeechRecognition() : null;
  515. function MessageInput() {
  516. const message = useSignal("");
  517. const talkActive = useSignal(false);
  518. const sendOnTalk = useSignal(false);
  519. const talkStop = (e) => {
  520. if (e) e.preventDefault();
  521. talkActive.value = false;
  522. talkRecognition?.stop();
  523. }
  524. const talk = (e) => {
  525. e.preventDefault();
  526. if (talkRecognition)
  527. talkRecognition.start();
  528. else
  529. alert("Speech recognition is not supported by this browser.");
  530. }
  531. if(talkRecognition) {
  532. talkRecognition.onstart = () => {
  533. talkActive.value = true;
  534. }
  535. talkRecognition.onresult = (e) => {
  536. if (event.results.length > 0) {
  537. message.value = event.results[0][0].transcript;
  538. if (sendOnTalk.value) {
  539. submit(e);
  540. }
  541. }
  542. }
  543. talkRecognition.onspeechend = () => {
  544. talkStop();
  545. }
  546. }
  547. const ttsVoices = useSignal(tts?.getVoices() || []);
  548. const ttsVoiceDefault = computed(() => ttsVoices.value.find(v => v.default));
  549. if (tts) {
  550. tts.onvoiceschanged = () => {
  551. ttsVoices.value = tts.getVoices();
  552. }
  553. }
  554. const submit = (e) => {
  555. stop(e);
  556. chat(message.value);
  557. message.value = "";
  558. }
  559. const enterSubmits = (event) => {
  560. if (event.which === 13 && !event.shiftKey) {
  561. submit(event);
  562. }
  563. }
  564. return html`
  565. <form onsubmit=${submit}>
  566. <div>
  567. <textarea
  568. className=${generating.value ? "loading" : null}
  569. oninput=${(e) => message.value = e.target.value}
  570. onkeypress=${enterSubmits}
  571. placeholder="Say something..."
  572. rows=2
  573. type="text"
  574. value="${message}"
  575. />
  576. </div>
  577. <div class="message-controls">
  578. <div> </div>
  579. <div>
  580. <div>
  581. <button type="submit" disabled=${generating.value || talkActive.value}>Send</button>
  582. <button disabled=${generating.value || talkActive.value} onclick=${uploadImage}>Upload Image</button>
  583. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  584. <button onclick=${reset}>Reset</button>
  585. </div>
  586. <div>
  587. <a href="#" style="cursor: help;" title="Help" onclick=${e => {
  588. e.preventDefault();
  589. alert(`STT supported by your browser: ${SpeechRecognition ? 'Yes' : 'No'}\n` +
  590. `(TTS and speech recognition are not provided by llama.cpp)\n` +
  591. `Note: STT requires HTTPS to work.`);
  592. }}>[?]</a>
  593. <button disabled=${generating.value} onclick=${talkActive.value ? talkStop : talk}>${talkActive.value ? "Stop Talking" : "Talk"}</button>
  594. <div>
  595. <input type="checkbox" id="send-on-talk" name="send-on-talk" checked="${sendOnTalk}" onchange=${(e) => sendOnTalk.value = e.target.checked} />
  596. <label for="send-on-talk" style="line-height: initial;">Send after talking</label>
  597. </div>
  598. </div>
  599. <div>
  600. <a href="#" style="cursor: help;" title="Help" onclick=${e => {
  601. e.preventDefault();
  602. alert(`TTS supported by your browser: ${tts ? 'Yes' : 'No'}\n(TTS and speech recognition are not provided by llama.cpp)`);
  603. }}>[?]</a>
  604. <label for="tts-voices" style="line-height: initial;">Bot Voice:</label>
  605. <select id="tts-voices" name="tts-voices" onchange=${(e) => ttsVoice.value = e.target.value} style="max-width: 100px;">
  606. <option value="" selected="${!ttsVoice.value}">None</option>
  607. ${[
  608. ...(ttsVoiceDefault.value ? [ttsVoiceDefault.value] : []),
  609. ...ttsVoices.value.filter(v => !v.default),
  610. ].map(
  611. v => html`<option value="${v.name}" selected="${ttsVoice.value === v.name}">${v.name} (${v.lang}) ${v.default ? '(default)' : ''}</option>`
  612. )}
  613. </select>
  614. </div>
  615. </div>
  616. </div>
  617. </form>
  618. `
  619. }
  620. function CompletionControls() {
  621. const submit = (e) => {
  622. stop(e);
  623. runCompletion();
  624. }
  625. return html`
  626. <div>
  627. <button onclick=${submit} type="button" disabled=${generating.value}>Start</button>
  628. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  629. <button onclick=${reset}>Reset</button>
  630. </div>`;
  631. }
  632. const ChatLog = (props) => {
  633. const messages = session.value.transcript;
  634. const container = useRef(null)
  635. useEffect(() => {
  636. // scroll to bottom (if needed)
  637. const parent = container.current.parentElement;
  638. if (parent && parent.scrollHeight <= parent.scrollTop + parent.offsetHeight + 300) {
  639. parent.scrollTo(0, parent.scrollHeight)
  640. }
  641. }, [messages])
  642. const ttsChatLineActiveIx = useSignal(undefined);
  643. const ttsChatLine = (e, ix, msg) => {
  644. if (e) e.preventDefault();
  645. if (!tts || !ttsVoice.value || !('SpeechSynthesisUtterance' in window)) return;
  646. const ttsVoices = tts.getVoices();
  647. const voice = ttsVoices.find(v => v.name === ttsVoice.value);
  648. if (!voice) return;
  649. if (ttsChatLineActiveIx.value !== undefined) {
  650. tts.cancel();
  651. if (ttsChatLineActiveIx.value === ix) {
  652. ttsChatLineActiveIx.value = undefined;
  653. return;
  654. }
  655. }
  656. ttsChatLineActiveIx.value = ix;
  657. let ttsUtter = new SpeechSynthesisUtterance(msg);
  658. ttsUtter.voice = voice;
  659. ttsUtter.onend = e => {
  660. ttsChatLineActiveIx.value = undefined;
  661. };
  662. tts.speak(ttsUtter);
  663. }
  664. const isCompletionMode = session.value.type === 'completion'
  665. // Try play the last bot message
  666. const lastCharChatLinesIxs = useSignal([]);
  667. const lastCharChatLinesIxsOld = useSignal([]);
  668. useEffect(() => {
  669. if (
  670. !isCompletionMode
  671. && lastCharChatLinesIxs.value.length !== lastCharChatLinesIxsOld.value.length
  672. && !generating.value
  673. ) {
  674. const ix = lastCharChatLinesIxs.value[lastCharChatLinesIxs.value.length - 1];
  675. if (ix !== undefined) {
  676. const msg = messages[ix];
  677. ttsChatLine(null, ix, Array.isArray(msg) ? msg[1].map(m => m.content).join('') : msg);
  678. }
  679. lastCharChatLinesIxsOld.value = structuredClone(lastCharChatLinesIxs.value);
  680. }
  681. }, [generating.value]);
  682. const chatLine = ([user, data], index) => {
  683. let message
  684. const isArrayMessage = Array.isArray(data);
  685. const text = isArrayMessage ?
  686. data.map(msg => msg.content).join('') :
  687. data;
  688. if (params.value.n_probs > 0 && isArrayMessage) {
  689. message = html`<${Probabilities} data=${data} />`
  690. } else {
  691. message = isCompletionMode ?
  692. text :
  693. html`<${Markdownish} text=${template(text)} />`
  694. }
  695. const fromBot = user && user === '{{char}}';
  696. if (fromBot && !lastCharChatLinesIxs.value.includes(index))
  697. lastCharChatLinesIxs.value.push(index);
  698. if (user) {
  699. return html`
  700. <div>
  701. <p key=${index}><strong>${template(user)}:</strong> ${message}</p>
  702. ${
  703. fromBot && ttsVoice.value
  704. && html`<button disabled=${generating.value} onclick=${e => ttsChatLine(e, index, text)} aria-label=${ttsChatLineActiveIx.value === index ? 'Pause' : 'Play'}>${ ttsChatLineActiveIx.value === index ? '⏸️' : '▶️' }</div>`
  705. }
  706. </div>
  707. `;
  708. } else {
  709. return isCompletionMode ?
  710. html`<span key=${index}>${message}</span>` :
  711. html`<div><p key=${index}>${message}</p></div>`
  712. }
  713. };
  714. const handleCompletionEdit = (e) => {
  715. session.value.prompt = e.target.innerText;
  716. session.value.transcript = [];
  717. }
  718. return html`
  719. <div id="chat" ref=${container} key=${messages.length}>
  720. <img style="width: 60%;${!session.value.image_selected ? `display: none;` : ``}" src="${session.value.image_selected}"/>
  721. <span contenteditable=${isCompletionMode} ref=${container} oninput=${handleCompletionEdit}>
  722. ${messages.flatMap(chatLine)}
  723. </span>
  724. </div>`;
  725. };
  726. const ConfigForm = (props) => {
  727. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  728. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  729. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  730. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  731. const updateParamsBool = (el) => params.value = { ...params.value, [el.target.name]: el.target.checked }
  732. const grammarJsonSchemaPropOrder = signal('')
  733. const updateGrammarJsonSchemaPropOrder = (el) => grammarJsonSchemaPropOrder.value = el.target.value
  734. const convertJSONSchemaGrammar = async () => {
  735. try {
  736. let schema = JSON.parse(params.value.grammar)
  737. const converter = new SchemaConverter({
  738. prop_order: grammarJsonSchemaPropOrder.value
  739. .split(',')
  740. .reduce((acc, cur, i) => ({ ...acc, [cur.trim()]: i }), {}),
  741. allow_fetch: true,
  742. })
  743. schema = await converter.resolveRefs(schema, 'input')
  744. converter.visit(schema, '')
  745. params.value = {
  746. ...params.value,
  747. grammar: converter.formatGrammar(),
  748. }
  749. } catch (e) {
  750. alert(`Convert failed: ${e.message}`)
  751. }
  752. }
  753. const FloatField = ({ label, max, min, name, step, value }) => {
  754. return html`
  755. <div>
  756. <label for="${name}">${label}</label>
  757. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  758. <span>${value}</span>
  759. </div>
  760. `
  761. };
  762. const IntField = ({ label, max, min, name, value }) => {
  763. return html`
  764. <div>
  765. <label for="${name}">${label}</label>
  766. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  767. <span>${value}</span>
  768. </div>
  769. `
  770. };
  771. const BoolField = ({ label, name, value }) => {
  772. return html`
  773. <div>
  774. <label for="${name}">${label}</label>
  775. <input type="checkbox" id="${name}" name="${name}" checked="${value}" onclick=${updateParamsBool} />
  776. </div>
  777. `
  778. };
  779. const userTemplateReset = (e) => {
  780. e.preventDefault();
  781. userTemplateResetToDefaultAndApply()
  782. }
  783. const UserTemplateResetButton = () => {
  784. if (selectedUserTemplate.value.name == 'default') {
  785. return html`
  786. <button disabled>Using default template</button>
  787. `
  788. }
  789. return html`
  790. <button onclick=${userTemplateReset}>Reset all to default</button>
  791. `
  792. };
  793. useEffect(() => {
  794. // autosave template on every change
  795. userTemplateAutosave()
  796. }, [session.value, params.value])
  797. const GrammarControl = () => (
  798. html`
  799. <div>
  800. <label for="template">Grammar</label>
  801. <textarea id="grammar" name="grammar" placeholder="Use gbnf or JSON Schema+convert" value="${params.value.grammar}" rows=4 oninput=${updateParams}/>
  802. <input type="text" name="prop-order" placeholder="order: prop1,prop2,prop3" oninput=${updateGrammarJsonSchemaPropOrder} />
  803. <button type="button" onclick=${convertJSONSchemaGrammar}>Convert JSON Schema</button>
  804. </div>
  805. `
  806. );
  807. const PromptControlFieldSet = () => (
  808. html`
  809. <fieldset>
  810. <div>
  811. <label htmlFor="prompt">Prompt</label>
  812. <textarea type="text" name="prompt" value="${session.value.prompt}" oninput=${updateSession}/>
  813. </div>
  814. </fieldset>
  815. `
  816. );
  817. const ChatConfigForm = () => (
  818. html`
  819. ${PromptControlFieldSet()}
  820. <fieldset class="two">
  821. <div>
  822. <label for="user">User name</label>
  823. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  824. </div>
  825. <div>
  826. <label for="bot">Bot name</label>
  827. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  828. </div>
  829. </fieldset>
  830. <fieldset>
  831. <div>
  832. <label for="template">Prompt template</label>
  833. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  834. </div>
  835. <div>
  836. <label for="template">Chat history template</label>
  837. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  838. </div>
  839. ${GrammarControl()}
  840. </fieldset>
  841. `
  842. );
  843. const CompletionConfigForm = () => (
  844. html`
  845. ${PromptControlFieldSet()}
  846. <fieldset>${GrammarControl()}</fieldset>
  847. `
  848. );
  849. return html`
  850. <form>
  851. <fieldset class="two">
  852. <${UserTemplateResetButton}/>
  853. <div>
  854. <label class="slim"><input type="radio" name="type" value="chat" checked=${session.value.type === "chat"} oninput=${updateSession} /> Chat</label>
  855. <label class="slim"><input type="radio" name="type" value="completion" checked=${session.value.type === "completion"} oninput=${updateSession} /> Completion</label>
  856. </div>
  857. </fieldset>
  858. ${session.value.type === 'chat' ? ChatConfigForm() : CompletionConfigForm()}
  859. <fieldset class="two">
  860. ${IntField({ label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict })}
  861. ${FloatField({ label: "Temperature", max: 2.0, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature })}
  862. ${FloatField({ label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty })}
  863. ${IntField({ label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n })}
  864. ${BoolField({ label: "Penalize repetition of newlines", name: "penalize_nl", value: params.value.penalize_nl })}
  865. ${IntField({ label: "Top-K sampling", max: 100, min: -1, name: "top_k", value: params.value.top_k })}
  866. ${FloatField({ label: "Top-P sampling", max: 1.0, min: 0.0, name: "top_p", step: 0.01, value: params.value.top_p })}
  867. ${FloatField({ label: "Min-P sampling", max: 1.0, min: 0.0, name: "min_p", step: 0.01, value: params.value.min_p })}
  868. </fieldset>
  869. <details>
  870. <summary>More options</summary>
  871. <fieldset class="two">
  872. ${FloatField({ label: "TFS-Z", max: 1.0, min: 0.0, name: "tfs_z", step: 0.01, value: params.value.tfs_z })}
  873. ${FloatField({ label: "Typical P", max: 1.0, min: 0.0, name: "typical_p", step: 0.01, value: params.value.typical_p })}
  874. ${FloatField({ label: "Presence penalty", max: 1.0, min: 0.0, name: "presence_penalty", step: 0.01, value: params.value.presence_penalty })}
  875. ${FloatField({ label: "Frequency penalty", max: 1.0, min: 0.0, name: "frequency_penalty", step: 0.01, value: params.value.frequency_penalty })}
  876. </fieldset>
  877. <hr />
  878. <fieldset class="three">
  879. <div>
  880. <label><input type="radio" name="mirostat" value="0" checked=${params.value.mirostat == 0} oninput=${updateParamsInt} /> no Mirostat</label>
  881. <label><input type="radio" name="mirostat" value="1" checked=${params.value.mirostat == 1} oninput=${updateParamsInt} /> Mirostat v1</label>
  882. <label><input type="radio" name="mirostat" value="2" checked=${params.value.mirostat == 2} oninput=${updateParamsInt} /> Mirostat v2</label>
  883. </div>
  884. ${FloatField({ label: "Mirostat tau", max: 10.0, min: 0.0, name: "mirostat_tau", step: 0.01, value: params.value.mirostat_tau })}
  885. ${FloatField({ label: "Mirostat eta", max: 1.0, min: 0.0, name: "mirostat_eta", step: 0.01, value: params.value.mirostat_eta })}
  886. </fieldset>
  887. <fieldset>
  888. ${IntField({ label: "Show Probabilities", max: 10, min: 0, name: "n_probs", value: params.value.n_probs })}
  889. </fieldset>
  890. <fieldset>
  891. ${IntField({ label: "Min Probabilities from each Sampler", max: 10, min: 0, name: "min_keep", value: params.value.min_keep })}
  892. </fieldset>
  893. <fieldset>
  894. <label for="api_key">API Key</label>
  895. <input type="text" name="api_key" value="${params.value.api_key}" placeholder="Enter API key" oninput=${updateParams} />
  896. </fieldset>
  897. </details>
  898. </form>
  899. `
  900. }
  901. const probColor = (p) => {
  902. const r = Math.floor(192 * (1 - p));
  903. const g = Math.floor(192 * p);
  904. return `rgba(${r},${g},0,0.3)`;
  905. }
  906. const Probabilities = (params) => {
  907. return params.data.map(msg => {
  908. const { completion_probabilities } = msg;
  909. if (
  910. !completion_probabilities ||
  911. completion_probabilities.length === 0
  912. ) return msg.content
  913. if (completion_probabilities.length > 1) {
  914. // Not for byte pair
  915. if (completion_probabilities[0].content.startsWith('byte: \\')) return msg.content
  916. const splitData = completion_probabilities.map(prob => ({
  917. content: prob.content,
  918. completion_probabilities: [prob]
  919. }))
  920. return html`<${Probabilities} data=${splitData} />`
  921. }
  922. const { probs, content } = completion_probabilities[0]
  923. const found = probs.find(p => p.tok_str === msg.content)
  924. const pColor = found ? probColor(found.prob) : 'transparent'
  925. const popoverChildren = html`
  926. <div class="prob-set">
  927. ${probs.map((p, index) => {
  928. return html`
  929. <div
  930. key=${index}
  931. title=${`prob: ${p.prob}`}
  932. style=${{
  933. padding: '0.3em',
  934. backgroundColor: p.tok_str === content ? probColor(p.prob) : 'transparent'
  935. }}
  936. >
  937. <span>${p.tok_str}: </span>
  938. <span>${Math.floor(p.prob * 100)}%</span>
  939. </div>
  940. `
  941. })}
  942. </div>
  943. `
  944. return html`
  945. <${Popover} style=${{ backgroundColor: pColor }} popoverChildren=${popoverChildren}>
  946. ${msg.content.match(/\n/gim) ? html`<br />` : msg.content}
  947. </>
  948. `
  949. });
  950. }
  951. // poor mans markdown replacement
  952. const Markdownish = (params) => {
  953. const chunks = params.text.split('```');
  954. for (let i = 0; i < chunks.length; i++) {
  955. if (i % 2 === 0) { // outside code block
  956. chunks[i] = chunks[i]
  957. .replace(/&/g, '&amp;')
  958. .replace(/</g, '&lt;')
  959. .replace(/>/g, '&gt;')
  960. .replace(/(^|\n)#{1,6} ([^\n]*)(?=([^`]*`[^`]*`)*[^`]*$)/g, '$1<h3>$2</h3>')
  961. .replace(/\*\*(.*?)\*\*(?=([^`]*`[^`]*`)*[^`]*$)/g, '<strong>$1</strong>')
  962. .replace(/__(.*?)__(?=([^`]*`[^`]*`)*[^`]*$)/g, '<strong>$1</strong>')
  963. .replace(/\*(.*?)\*(?=([^`]*`[^`]*`)*[^`]*$)/g, '<em>$1</em>')
  964. .replace(/_(.*?)_(?=([^`]*`[^`]*`)*[^`]*$)/g, '<em>$1</em>')
  965. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  966. .replace(/`(.*?)`/g, '<code>$1</code>')
  967. .replace(/\n/gim, '<br />');
  968. } else { // inside code block
  969. chunks[i] = `<pre><code>${chunks[i]}</code></pre>`;
  970. }
  971. }
  972. const restoredText = chunks.join('');
  973. return html`<span dangerouslySetInnerHTML=${{ __html: restoredText }} />`;
  974. };
  975. const ModelGenerationInfo = (params) => {
  976. if (!llamaStats.value) {
  977. return html`<span/>`
  978. }
  979. return html`
  980. <span>
  981. ${llamaStats.value.tokens_predicted} predicted, ${llamaStats.value.tokens_cached} cached, ${llamaStats.value.timings.predicted_per_token_ms.toFixed()}ms per token, ${llamaStats.value.timings.predicted_per_second.toFixed(2)} tokens per second
  982. </span>
  983. `
  984. }
  985. // simple popover impl
  986. const Popover = (props) => {
  987. const isOpen = useSignal(false);
  988. const position = useSignal({ top: '0px', left: '0px' });
  989. const buttonRef = useRef(null);
  990. const popoverRef = useRef(null);
  991. const togglePopover = () => {
  992. if (buttonRef.current) {
  993. const rect = buttonRef.current.getBoundingClientRect();
  994. position.value = {
  995. top: `${rect.bottom + window.scrollY}px`,
  996. left: `${rect.left + window.scrollX}px`,
  997. };
  998. }
  999. isOpen.value = !isOpen.value;
  1000. };
  1001. const handleClickOutside = (event) => {
  1002. if (popoverRef.current && !popoverRef.current.contains(event.target) && !buttonRef.current.contains(event.target)) {
  1003. isOpen.value = false;
  1004. }
  1005. };
  1006. useEffect(() => {
  1007. document.addEventListener('mousedown', handleClickOutside);
  1008. return () => {
  1009. document.removeEventListener('mousedown', handleClickOutside);
  1010. };
  1011. }, []);
  1012. return html`
  1013. <span style=${props.style} ref=${buttonRef} onClick=${togglePopover}>${props.children}</span>
  1014. ${isOpen.value && html`
  1015. <${Portal} into="#portal">
  1016. <div
  1017. ref=${popoverRef}
  1018. class="popover-content"
  1019. style=${{
  1020. top: position.value.top,
  1021. left: position.value.left,
  1022. }}
  1023. >
  1024. ${props.popoverChildren}
  1025. </div>
  1026. </${Portal}>
  1027. `}
  1028. `;
  1029. };
  1030. // Source: preact-portal (https://github.com/developit/preact-portal/blob/master/src/preact-portal.js)
  1031. /** Redirect rendering of descendants into the given CSS selector */
  1032. class Portal extends Component {
  1033. componentDidUpdate(props) {
  1034. for (let i in props) {
  1035. if (props[i] !== this.props[i]) {
  1036. return setTimeout(this.renderLayer);
  1037. }
  1038. }
  1039. }
  1040. componentDidMount() {
  1041. this.isMounted = true;
  1042. this.renderLayer = this.renderLayer.bind(this);
  1043. this.renderLayer();
  1044. }
  1045. componentWillUnmount() {
  1046. this.renderLayer(false);
  1047. this.isMounted = false;
  1048. if (this.remote && this.remote.parentNode) this.remote.parentNode.removeChild(this.remote);
  1049. }
  1050. findNode(node) {
  1051. return typeof node === 'string' ? document.querySelector(node) : node;
  1052. }
  1053. renderLayer(show = true) {
  1054. if (!this.isMounted) return;
  1055. // clean up old node if moving bases:
  1056. if (this.props.into !== this.intoPointer) {
  1057. this.intoPointer = this.props.into;
  1058. if (this.into && this.remote) {
  1059. this.remote = render(html`<${PortalProxy} />`, this.into, this.remote);
  1060. }
  1061. this.into = this.findNode(this.props.into);
  1062. }
  1063. this.remote = render(html`
  1064. <${PortalProxy} context=${this.context}>
  1065. ${show && this.props.children || null}
  1066. </${PortalProxy}>
  1067. `, this.into, this.remote);
  1068. }
  1069. render() {
  1070. return null;
  1071. }
  1072. }
  1073. // high-order component that renders its first child if it exists.
  1074. // used as a conditional rendering proxy.
  1075. class PortalProxy extends Component {
  1076. getChildContext() {
  1077. return this.props.context;
  1078. }
  1079. render({ children }) {
  1080. return children || null;
  1081. }
  1082. }
  1083. function App(props) {
  1084. useEffect(() => {
  1085. const query = new URLSearchParams(location.search).get("q");
  1086. if (query) chat(query);
  1087. }, []);
  1088. return html`
  1089. <div class="mode-${session.value.type}">
  1090. <header>
  1091. <div class="grid-container">
  1092. <div class="grid-item"></div>
  1093. <div class="grid-item"><h1>llama.cpp</h1></div>
  1094. <div class="grid-item"><a class="customlink" href="index-new.html">New UI</a></div>
  1095. </div>
  1096. </header>
  1097. <main id="content">
  1098. <${chatStarted.value ? ChatLog : ConfigForm} />
  1099. </main>
  1100. <section id="write">
  1101. <${session.value.type === 'chat' ? MessageInput : CompletionControls} />
  1102. </section>
  1103. <footer>
  1104. <p><${ModelGenerationInfo} /></p>
  1105. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a>.</p>
  1106. </footer>
  1107. </div>
  1108. `;
  1109. }
  1110. render(h(App), document.querySelector('#container'));
  1111. </script>
  1112. </head>
  1113. <body>
  1114. <div id="container">
  1115. <input type="file" id="fileInput" accept="image/*" style="display: none;">
  1116. </div>
  1117. <div id="portal"></div>
  1118. </body>
  1119. </html>