index.html 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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. xtc_probability: 0.0, // 0 = disabled;
  267. xtc_threshold: 0.1, // > 0.5 disables XTC;
  268. tfs_z: 1.0, // 1.0 = disabled
  269. typical_p: 1.0, // 1.0 = disabled
  270. presence_penalty: 0.0, // 0.0 = disabled
  271. frequency_penalty: 0.0, // 0.0 = disabled
  272. mirostat: 0, // 0/1/2
  273. mirostat_tau: 5, // target entropy
  274. mirostat_eta: 0.1, // learning rate
  275. grammar: '',
  276. n_probs: 0, // no completion_probabilities,
  277. min_keep: 0, // min probs from each sampler,
  278. image_data: [],
  279. cache_prompt: true,
  280. api_key: ''
  281. })
  282. /* START: Support for storing prompt templates and parameters in browsers LocalStorage */
  283. const local_storage_storageKey = "llamacpp_server_local_storage";
  284. function local_storage_setDataFromObject(tag, content) {
  285. localStorage.setItem(local_storage_storageKey + '/' + tag, JSON.stringify(content));
  286. }
  287. function local_storage_setDataFromRawText(tag, content) {
  288. localStorage.setItem(local_storage_storageKey + '/' + tag, content);
  289. }
  290. function local_storage_getDataAsObject(tag) {
  291. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  292. if (!item) {
  293. return null;
  294. } else {
  295. return JSON.parse(item);
  296. }
  297. }
  298. function local_storage_getDataAsRawText(tag) {
  299. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  300. if (!item) {
  301. return null;
  302. } else {
  303. return item;
  304. }
  305. }
  306. // create a container for user templates and settings
  307. const savedUserTemplates = signal({})
  308. const selectedUserTemplate = signal({ name: '', template: { session: {}, params: {} } })
  309. // let's import locally saved templates and settings if there are any
  310. // user templates and settings are stored in one object
  311. // in form of { "templatename": "templatedata" } and { "settingstemplatename":"settingsdata" }
  312. console.log('Importing saved templates')
  313. let importedTemplates = local_storage_getDataAsObject('user_templates')
  314. if (importedTemplates) {
  315. // saved templates were successfully imported.
  316. console.log('Processing saved templates and updating default template')
  317. params.value = { ...params.value, image_data: [] };
  318. //console.log(importedTemplates);
  319. savedUserTemplates.value = importedTemplates;
  320. //override default template
  321. savedUserTemplates.value.default = { session: session.value, params: params.value }
  322. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  323. } else {
  324. // no saved templates detected.
  325. console.log('Initializing LocalStorage and saving default template')
  326. savedUserTemplates.value = { "default": { session: session.value, params: params.value } }
  327. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  328. }
  329. function userTemplateResetToDefault() {
  330. console.log('Resetting template to default')
  331. selectedUserTemplate.value.name = 'default';
  332. selectedUserTemplate.value.data = savedUserTemplates.value['default'];
  333. }
  334. function userTemplateApply(t) {
  335. session.value = t.data.session;
  336. session.value = { ...session.value, image_selected: '' };
  337. params.value = t.data.params;
  338. params.value = { ...params.value, image_data: [] };
  339. }
  340. function userTemplateResetToDefaultAndApply() {
  341. userTemplateResetToDefault()
  342. userTemplateApply(selectedUserTemplate.value)
  343. }
  344. function userTemplateLoadAndApplyAutosaved() {
  345. // get autosaved last used template
  346. let lastUsedTemplate = local_storage_getDataAsObject('user_templates_last')
  347. if (lastUsedTemplate) {
  348. console.log('Autosaved template found, restoring')
  349. selectedUserTemplate.value = lastUsedTemplate
  350. }
  351. else {
  352. console.log('No autosaved template found, using default template')
  353. // no autosaved last used template was found, so load from default.
  354. userTemplateResetToDefault()
  355. }
  356. console.log('Applying template')
  357. // and update internal data from templates
  358. userTemplateApply(selectedUserTemplate.value)
  359. }
  360. //console.log(savedUserTemplates.value)
  361. //console.log(selectedUserTemplate.value)
  362. function userTemplateAutosave() {
  363. console.log('Template Autosave...')
  364. if (selectedUserTemplate.value.name == 'default') {
  365. // we don't want to save over default template, so let's create a new one
  366. let newTemplateName = 'UserTemplate-' + Date.now().toString()
  367. let newTemplate = { 'name': newTemplateName, 'data': { 'session': session.value, 'params': params.value } }
  368. console.log('Saving as ' + newTemplateName)
  369. // save in the autosave slot
  370. local_storage_setDataFromObject('user_templates_last', newTemplate)
  371. // and load it back and apply
  372. userTemplateLoadAndApplyAutosaved()
  373. } else {
  374. local_storage_setDataFromObject('user_templates_last', { 'name': selectedUserTemplate.value.name, 'data': { 'session': session.value, 'params': params.value } })
  375. }
  376. }
  377. console.log('Checking for autosaved last used template')
  378. userTemplateLoadAndApplyAutosaved()
  379. /* END: Support for storing prompt templates and parameters in browsers LocalStorage */
  380. const tts = window.speechSynthesis;
  381. const ttsVoice = signal(null)
  382. const llamaStats = signal(null)
  383. const controller = signal(null)
  384. // currently generating a completion?
  385. const generating = computed(() => controller.value != null)
  386. // has the user started a chat?
  387. const chatStarted = computed(() => session.value.transcript.length > 0)
  388. const transcriptUpdate = (transcript) => {
  389. session.value = {
  390. ...session.value,
  391. transcript
  392. }
  393. }
  394. // simple template replace
  395. const template = (str, extraSettings) => {
  396. let settings = session.value;
  397. if (extraSettings) {
  398. settings = { ...settings, ...extraSettings };
  399. }
  400. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  401. }
  402. async function runLlama(prompt, llamaParams, char) {
  403. const currentMessages = [];
  404. const history = session.value.transcript;
  405. if (controller.value) {
  406. throw new Error("already running");
  407. }
  408. controller.value = new AbortController();
  409. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value, api_url: new URL('.', document.baseURI).href })) {
  410. const data = chunk.data;
  411. if (data.stop) {
  412. while (
  413. currentMessages.length > 0 &&
  414. currentMessages[currentMessages.length - 1].content.match(/\n$/) != null
  415. ) {
  416. currentMessages.pop();
  417. }
  418. transcriptUpdate([...history, [char, currentMessages]])
  419. console.log("Completion finished: '", currentMessages.map(msg => msg.content).join(''), "', summary: ", data);
  420. } else {
  421. currentMessages.push(data);
  422. slot_id = data.slot_id;
  423. if (selected_image && !data.multimodal) {
  424. alert("The server was not compiled for multimodal or the model projector can't be loaded.");
  425. return;
  426. }
  427. transcriptUpdate([...history, [char, currentMessages]])
  428. }
  429. if (data.timings) {
  430. llamaStats.value = data;
  431. }
  432. }
  433. controller.value = null;
  434. }
  435. // send message to server
  436. const chat = async (msg) => {
  437. if (controller.value) {
  438. console.log('already running...');
  439. return;
  440. }
  441. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  442. let prompt = template(session.value.template, {
  443. message: msg,
  444. history: session.value.transcript.flatMap(
  445. ([name, data]) =>
  446. template(
  447. session.value.historyTemplate,
  448. {
  449. name,
  450. message: Array.isArray(data) ?
  451. data.map(msg => msg.content).join('').replace(/^\s/, '') :
  452. data,
  453. }
  454. )
  455. ).join("\n"),
  456. });
  457. if (selected_image) {
  458. 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:`;
  459. }
  460. await runLlama(prompt, {
  461. ...params.value,
  462. slot_id: slot_id,
  463. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  464. }, "{{char}}");
  465. }
  466. const runCompletion = () => {
  467. if (controller.value) {
  468. console.log('already running...');
  469. return;
  470. }
  471. const { prompt } = session.value;
  472. transcriptUpdate([...session.value.transcript, ["", prompt]]);
  473. runLlama(prompt, {
  474. ...params.value,
  475. slot_id: slot_id,
  476. stop: [],
  477. }, "").finally(() => {
  478. session.value.prompt = session.value.transcript.map(([_, data]) =>
  479. Array.isArray(data) ? data.map(msg => msg.content).join('') : data
  480. ).join('');
  481. session.value.transcript = [];
  482. })
  483. }
  484. const stop = (e) => {
  485. e.preventDefault();
  486. if (controller.value) {
  487. controller.value.abort();
  488. controller.value = null;
  489. }
  490. }
  491. const reset = (e) => {
  492. stop(e);
  493. transcriptUpdate([]);
  494. }
  495. const uploadImage = (e) => {
  496. e.preventDefault();
  497. document.getElementById("fileInput").click();
  498. document.getElementById("fileInput").addEventListener("change", function (event) {
  499. const selectedFile = event.target.files[0];
  500. if (selectedFile) {
  501. const reader = new FileReader();
  502. reader.onload = function () {
  503. const image_data = reader.result;
  504. session.value = { ...session.value, image_selected: image_data };
  505. params.value = {
  506. ...params.value, image_data: [
  507. { data: image_data.replace(/data:image\/[^;]+;base64,/, ''), id: 10 }]
  508. }
  509. };
  510. selected_image = true;
  511. reader.readAsDataURL(selectedFile);
  512. }
  513. });
  514. }
  515. const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  516. const talkRecognition = SpeechRecognition ? new SpeechRecognition() : null;
  517. function MessageInput() {
  518. const message = useSignal("");
  519. const talkActive = useSignal(false);
  520. const sendOnTalk = useSignal(false);
  521. const talkStop = (e) => {
  522. if (e) e.preventDefault();
  523. talkActive.value = false;
  524. talkRecognition?.stop();
  525. }
  526. const talk = (e) => {
  527. e.preventDefault();
  528. if (talkRecognition)
  529. talkRecognition.start();
  530. else
  531. alert("Speech recognition is not supported by this browser.");
  532. }
  533. if(talkRecognition) {
  534. talkRecognition.onstart = () => {
  535. talkActive.value = true;
  536. }
  537. talkRecognition.onresult = (e) => {
  538. if (event.results.length > 0) {
  539. message.value = event.results[0][0].transcript;
  540. if (sendOnTalk.value) {
  541. submit(e);
  542. }
  543. }
  544. }
  545. talkRecognition.onspeechend = () => {
  546. talkStop();
  547. }
  548. }
  549. const ttsVoices = useSignal(tts?.getVoices() || []);
  550. const ttsVoiceDefault = computed(() => ttsVoices.value.find(v => v.default));
  551. if (tts) {
  552. tts.onvoiceschanged = () => {
  553. ttsVoices.value = tts.getVoices();
  554. }
  555. }
  556. const submit = (e) => {
  557. stop(e);
  558. chat(message.value);
  559. message.value = "";
  560. }
  561. const enterSubmits = (event) => {
  562. if (event.which === 13 && !event.shiftKey) {
  563. submit(event);
  564. }
  565. }
  566. return html`
  567. <form onsubmit=${submit}>
  568. <div>
  569. <textarea
  570. className=${generating.value ? "loading" : null}
  571. oninput=${(e) => message.value = e.target.value}
  572. onkeypress=${enterSubmits}
  573. placeholder="Say something..."
  574. rows=2
  575. type="text"
  576. value="${message}"
  577. />
  578. </div>
  579. <div class="message-controls">
  580. <div> </div>
  581. <div>
  582. <div>
  583. <button type="submit" disabled=${generating.value || talkActive.value}>Send</button>
  584. <button disabled=${generating.value || talkActive.value} onclick=${uploadImage}>Upload Image</button>
  585. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  586. <button onclick=${reset}>Reset</button>
  587. </div>
  588. <div>
  589. <a href="#" style="cursor: help;" title="Help" onclick=${e => {
  590. e.preventDefault();
  591. alert(`STT supported by your browser: ${SpeechRecognition ? 'Yes' : 'No'}\n` +
  592. `(TTS and speech recognition are not provided by llama.cpp)\n` +
  593. `Note: STT requires HTTPS to work.`);
  594. }}>[?]</a>
  595. <button disabled=${generating.value} onclick=${talkActive.value ? talkStop : talk}>${talkActive.value ? "Stop Talking" : "Talk"}</button>
  596. <div>
  597. <input type="checkbox" id="send-on-talk" name="send-on-talk" checked="${sendOnTalk}" onchange=${(e) => sendOnTalk.value = e.target.checked} />
  598. <label for="send-on-talk" style="line-height: initial;">Send after talking</label>
  599. </div>
  600. </div>
  601. <div>
  602. <a href="#" style="cursor: help;" title="Help" onclick=${e => {
  603. e.preventDefault();
  604. alert(`TTS supported by your browser: ${tts ? 'Yes' : 'No'}\n(TTS and speech recognition are not provided by llama.cpp)`);
  605. }}>[?]</a>
  606. <label for="tts-voices" style="line-height: initial;">Bot Voice:</label>
  607. <select id="tts-voices" name="tts-voices" onchange=${(e) => ttsVoice.value = e.target.value} style="max-width: 100px;">
  608. <option value="" selected="${!ttsVoice.value}">None</option>
  609. ${[
  610. ...(ttsVoiceDefault.value ? [ttsVoiceDefault.value] : []),
  611. ...ttsVoices.value.filter(v => !v.default),
  612. ].map(
  613. v => html`<option value="${v.name}" selected="${ttsVoice.value === v.name}">${v.name} (${v.lang}) ${v.default ? '(default)' : ''}</option>`
  614. )}
  615. </select>
  616. </div>
  617. </div>
  618. </div>
  619. </form>
  620. `
  621. }
  622. function CompletionControls() {
  623. const submit = (e) => {
  624. stop(e);
  625. runCompletion();
  626. }
  627. return html`
  628. <div>
  629. <button onclick=${submit} type="button" disabled=${generating.value}>Start</button>
  630. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  631. <button onclick=${reset}>Reset</button>
  632. </div>`;
  633. }
  634. const ChatLog = (props) => {
  635. const messages = session.value.transcript;
  636. const container = useRef(null)
  637. useEffect(() => {
  638. // scroll to bottom (if needed)
  639. const parent = container.current.parentElement;
  640. if (parent && parent.scrollHeight <= parent.scrollTop + parent.offsetHeight + 300) {
  641. parent.scrollTo(0, parent.scrollHeight)
  642. }
  643. }, [messages])
  644. const ttsChatLineActiveIx = useSignal(undefined);
  645. const ttsChatLine = (e, ix, msg) => {
  646. if (e) e.preventDefault();
  647. if (!tts || !ttsVoice.value || !('SpeechSynthesisUtterance' in window)) return;
  648. const ttsVoices = tts.getVoices();
  649. const voice = ttsVoices.find(v => v.name === ttsVoice.value);
  650. if (!voice) return;
  651. if (ttsChatLineActiveIx.value !== undefined) {
  652. tts.cancel();
  653. if (ttsChatLineActiveIx.value === ix) {
  654. ttsChatLineActiveIx.value = undefined;
  655. return;
  656. }
  657. }
  658. ttsChatLineActiveIx.value = ix;
  659. let ttsUtter = new SpeechSynthesisUtterance(msg);
  660. ttsUtter.voice = voice;
  661. ttsUtter.onend = e => {
  662. ttsChatLineActiveIx.value = undefined;
  663. };
  664. tts.speak(ttsUtter);
  665. }
  666. const isCompletionMode = session.value.type === 'completion'
  667. // Try play the last bot message
  668. const lastCharChatLinesIxs = useSignal([]);
  669. const lastCharChatLinesIxsOld = useSignal([]);
  670. useEffect(() => {
  671. if (
  672. !isCompletionMode
  673. && lastCharChatLinesIxs.value.length !== lastCharChatLinesIxsOld.value.length
  674. && !generating.value
  675. ) {
  676. const ix = lastCharChatLinesIxs.value[lastCharChatLinesIxs.value.length - 1];
  677. if (ix !== undefined) {
  678. const msg = messages[ix];
  679. ttsChatLine(null, ix, Array.isArray(msg) ? msg[1].map(m => m.content).join('') : msg);
  680. }
  681. lastCharChatLinesIxsOld.value = structuredClone(lastCharChatLinesIxs.value);
  682. }
  683. }, [generating.value]);
  684. const chatLine = ([user, data], index) => {
  685. let message
  686. const isArrayMessage = Array.isArray(data);
  687. const text = isArrayMessage ?
  688. data.map(msg => msg.content).join('') :
  689. data;
  690. if (params.value.n_probs > 0 && isArrayMessage) {
  691. message = html`<${Probabilities} data=${data} />`
  692. } else {
  693. message = isCompletionMode ?
  694. text :
  695. html`<${Markdownish} text=${template(text)} />`
  696. }
  697. const fromBot = user && user === '{{char}}';
  698. if (fromBot && !lastCharChatLinesIxs.value.includes(index))
  699. lastCharChatLinesIxs.value.push(index);
  700. if (user) {
  701. return html`
  702. <div>
  703. <p key=${index}><strong>${template(user)}:</strong> ${message}</p>
  704. ${
  705. fromBot && ttsVoice.value
  706. && html`<button disabled=${generating.value} onclick=${e => ttsChatLine(e, index, text)} aria-label=${ttsChatLineActiveIx.value === index ? 'Pause' : 'Play'}>${ ttsChatLineActiveIx.value === index ? '⏸️' : '▶️' }</div>`
  707. }
  708. </div>
  709. `;
  710. } else {
  711. return isCompletionMode ?
  712. html`<span key=${index}>${message}</span>` :
  713. html`<div><p key=${index}>${message}</p></div>`
  714. }
  715. };
  716. const handleCompletionEdit = (e) => {
  717. session.value.prompt = e.target.innerText;
  718. session.value.transcript = [];
  719. }
  720. return html`
  721. <div id="chat" ref=${container} key=${messages.length}>
  722. <img style="width: 60%;${!session.value.image_selected ? `display: none;` : ``}" src="${session.value.image_selected}"/>
  723. <span contenteditable=${isCompletionMode} ref=${container} oninput=${handleCompletionEdit}>
  724. ${messages.flatMap(chatLine)}
  725. </span>
  726. </div>`;
  727. };
  728. const ConfigForm = (props) => {
  729. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  730. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  731. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  732. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  733. const updateParamsBool = (el) => params.value = { ...params.value, [el.target.name]: el.target.checked }
  734. const grammarJsonSchemaPropOrder = signal('')
  735. const updateGrammarJsonSchemaPropOrder = (el) => grammarJsonSchemaPropOrder.value = el.target.value
  736. const convertJSONSchemaGrammar = async () => {
  737. try {
  738. let schema = JSON.parse(params.value.grammar)
  739. const converter = new SchemaConverter({
  740. prop_order: grammarJsonSchemaPropOrder.value
  741. .split(',')
  742. .reduce((acc, cur, i) => ({ ...acc, [cur.trim()]: i }), {}),
  743. allow_fetch: true,
  744. })
  745. schema = await converter.resolveRefs(schema, 'input')
  746. converter.visit(schema, '')
  747. params.value = {
  748. ...params.value,
  749. grammar: converter.formatGrammar(),
  750. }
  751. } catch (e) {
  752. alert(`Convert failed: ${e.message}`)
  753. }
  754. }
  755. const FloatField = ({ label, max, min, name, step, value }) => {
  756. return html`
  757. <div>
  758. <label for="${name}">${label}</label>
  759. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  760. <span>${value}</span>
  761. </div>
  762. `
  763. };
  764. const IntField = ({ label, max, min, name, value }) => {
  765. return html`
  766. <div>
  767. <label for="${name}">${label}</label>
  768. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  769. <span>${value}</span>
  770. </div>
  771. `
  772. };
  773. const BoolField = ({ label, name, value }) => {
  774. return html`
  775. <div>
  776. <label for="${name}">${label}</label>
  777. <input type="checkbox" id="${name}" name="${name}" checked="${value}" onclick=${updateParamsBool} />
  778. </div>
  779. `
  780. };
  781. const userTemplateReset = (e) => {
  782. e.preventDefault();
  783. userTemplateResetToDefaultAndApply()
  784. }
  785. const UserTemplateResetButton = () => {
  786. if (selectedUserTemplate.value.name == 'default') {
  787. return html`
  788. <button disabled>Using default template</button>
  789. `
  790. }
  791. return html`
  792. <button onclick=${userTemplateReset}>Reset all to default</button>
  793. `
  794. };
  795. useEffect(() => {
  796. // autosave template on every change
  797. userTemplateAutosave()
  798. }, [session.value, params.value])
  799. const GrammarControl = () => (
  800. html`
  801. <div>
  802. <label for="template">Grammar</label>
  803. <textarea id="grammar" name="grammar" placeholder="Use gbnf or JSON Schema+convert" value="${params.value.grammar}" rows=4 oninput=${updateParams}/>
  804. <input type="text" name="prop-order" placeholder="order: prop1,prop2,prop3" oninput=${updateGrammarJsonSchemaPropOrder} />
  805. <button type="button" onclick=${convertJSONSchemaGrammar}>Convert JSON Schema</button>
  806. </div>
  807. `
  808. );
  809. const PromptControlFieldSet = () => (
  810. html`
  811. <fieldset>
  812. <div>
  813. <label htmlFor="prompt">Prompt</label>
  814. <textarea type="text" name="prompt" value="${session.value.prompt}" oninput=${updateSession}/>
  815. </div>
  816. </fieldset>
  817. `
  818. );
  819. const ChatConfigForm = () => (
  820. html`
  821. ${PromptControlFieldSet()}
  822. <fieldset class="two">
  823. <div>
  824. <label for="user">User name</label>
  825. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  826. </div>
  827. <div>
  828. <label for="bot">Bot name</label>
  829. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  830. </div>
  831. </fieldset>
  832. <fieldset>
  833. <div>
  834. <label for="template">Prompt template</label>
  835. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  836. </div>
  837. <div>
  838. <label for="template">Chat history template</label>
  839. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  840. </div>
  841. ${GrammarControl()}
  842. </fieldset>
  843. `
  844. );
  845. const CompletionConfigForm = () => (
  846. html`
  847. ${PromptControlFieldSet()}
  848. <fieldset>${GrammarControl()}</fieldset>
  849. `
  850. );
  851. return html`
  852. <form>
  853. <fieldset class="two">
  854. <${UserTemplateResetButton}/>
  855. <div>
  856. <label class="slim"><input type="radio" name="type" value="chat" checked=${session.value.type === "chat"} oninput=${updateSession} /> Chat</label>
  857. <label class="slim"><input type="radio" name="type" value="completion" checked=${session.value.type === "completion"} oninput=${updateSession} /> Completion</label>
  858. </div>
  859. </fieldset>
  860. ${session.value.type === 'chat' ? ChatConfigForm() : CompletionConfigForm()}
  861. <fieldset class="two">
  862. ${IntField({ label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict })}
  863. ${FloatField({ label: "Temperature", max: 2.0, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature })}
  864. ${FloatField({ label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty })}
  865. ${IntField({ label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n })}
  866. ${BoolField({ label: "Penalize repetition of newlines", name: "penalize_nl", value: params.value.penalize_nl })}
  867. ${IntField({ label: "Top-K sampling", max: 100, min: -1, name: "top_k", value: params.value.top_k })}
  868. ${FloatField({ label: "Top-P sampling", max: 1.0, min: 0.0, name: "top_p", step: 0.01, value: params.value.top_p })}
  869. ${FloatField({ label: "Min-P sampling", max: 1.0, min: 0.0, name: "min_p", step: 0.01, value: params.value.min_p })}
  870. </fieldset>
  871. <details>
  872. <summary>More options</summary>
  873. <fieldset class="two">
  874. ${FloatField({ label: "TFS-Z", max: 1.0, min: 0.0, name: "tfs_z", step: 0.01, value: params.value.tfs_z })}
  875. ${FloatField({ label: "Typical P", max: 1.0, min: 0.0, name: "typical_p", step: 0.01, value: params.value.typical_p })}
  876. ${FloatField({ label: "Presence penalty", max: 1.0, min: 0.0, name: "presence_penalty", step: 0.01, value: params.value.presence_penalty })}
  877. ${FloatField({ label: "Frequency penalty", max: 1.0, min: 0.0, name: "frequency_penalty", step: 0.01, value: params.value.frequency_penalty })}
  878. ${FloatField({ label: "XTC probability", max: 1.0, min: 0.0, name: "xtc_probability", step: 0.01, value: params.value.xtc_probability })}
  879. ${FloatField({ label: "XTC threshold", max: 0.5, min: 0.0, name: "xtc_threshold", step: 0.01, value: params.value.xtc_threshold })}
  880. </fieldset>
  881. <hr />
  882. <fieldset class="three">
  883. <div>
  884. <label><input type="radio" name="mirostat" value="0" checked=${params.value.mirostat == 0} oninput=${updateParamsInt} /> no Mirostat</label>
  885. <label><input type="radio" name="mirostat" value="1" checked=${params.value.mirostat == 1} oninput=${updateParamsInt} /> Mirostat v1</label>
  886. <label><input type="radio" name="mirostat" value="2" checked=${params.value.mirostat == 2} oninput=${updateParamsInt} /> Mirostat v2</label>
  887. </div>
  888. ${FloatField({ label: "Mirostat tau", max: 10.0, min: 0.0, name: "mirostat_tau", step: 0.01, value: params.value.mirostat_tau })}
  889. ${FloatField({ label: "Mirostat eta", max: 1.0, min: 0.0, name: "mirostat_eta", step: 0.01, value: params.value.mirostat_eta })}
  890. </fieldset>
  891. <fieldset>
  892. ${IntField({ label: "Show Probabilities", max: 10, min: 0, name: "n_probs", value: params.value.n_probs })}
  893. </fieldset>
  894. <fieldset>
  895. ${IntField({ label: "Min Probabilities from each Sampler", max: 10, min: 0, name: "min_keep", value: params.value.min_keep })}
  896. </fieldset>
  897. <fieldset>
  898. <label for="api_key">API Key</label>
  899. <input type="text" name="api_key" value="${params.value.api_key}" placeholder="Enter API key" oninput=${updateParams} />
  900. </fieldset>
  901. </details>
  902. </form>
  903. `
  904. }
  905. const probColor = (p) => {
  906. const r = Math.floor(192 * (1 - p));
  907. const g = Math.floor(192 * p);
  908. return `rgba(${r},${g},0,0.3)`;
  909. }
  910. const Probabilities = (params) => {
  911. return params.data.map(msg => {
  912. const { completion_probabilities } = msg;
  913. if (
  914. !completion_probabilities ||
  915. completion_probabilities.length === 0
  916. ) return msg.content
  917. if (completion_probabilities.length > 1) {
  918. // Not for byte pair
  919. if (completion_probabilities[0].content.startsWith('byte: \\')) return msg.content
  920. const splitData = completion_probabilities.map(prob => ({
  921. content: prob.content,
  922. completion_probabilities: [prob]
  923. }))
  924. return html`<${Probabilities} data=${splitData} />`
  925. }
  926. const { probs, content } = completion_probabilities[0]
  927. const found = probs.find(p => p.tok_str === msg.content)
  928. const pColor = found ? probColor(found.prob) : 'transparent'
  929. const popoverChildren = html`
  930. <div class="prob-set">
  931. ${probs.map((p, index) => {
  932. return html`
  933. <div
  934. key=${index}
  935. title=${`prob: ${p.prob}`}
  936. style=${{
  937. padding: '0.3em',
  938. backgroundColor: p.tok_str === content ? probColor(p.prob) : 'transparent'
  939. }}
  940. >
  941. <span>${p.tok_str}: </span>
  942. <span>${Math.floor(p.prob * 100)}%</span>
  943. </div>
  944. `
  945. })}
  946. </div>
  947. `
  948. return html`
  949. <${Popover} style=${{ backgroundColor: pColor }} popoverChildren=${popoverChildren}>
  950. ${msg.content.match(/\n/gim) ? html`<br />` : msg.content}
  951. </>
  952. `
  953. });
  954. }
  955. // poor mans markdown replacement
  956. const Markdownish = (params) => {
  957. const chunks = params.text.split('```');
  958. for (let i = 0; i < chunks.length; i++) {
  959. if (i % 2 === 0) { // outside code block
  960. chunks[i] = chunks[i]
  961. .replace(/&/g, '&amp;')
  962. .replace(/</g, '&lt;')
  963. .replace(/>/g, '&gt;')
  964. .replace(/(^|\n)#{1,6} ([^\n]*)(?=([^`]*`[^`]*`)*[^`]*$)/g, '$1<h3>$2</h3>')
  965. .replace(/\*\*(.*?)\*\*(?=([^`]*`[^`]*`)*[^`]*$)/g, '<strong>$1</strong>')
  966. .replace(/__(.*?)__(?=([^`]*`[^`]*`)*[^`]*$)/g, '<strong>$1</strong>')
  967. .replace(/\*(.*?)\*(?=([^`]*`[^`]*`)*[^`]*$)/g, '<em>$1</em>')
  968. .replace(/_(.*?)_(?=([^`]*`[^`]*`)*[^`]*$)/g, '<em>$1</em>')
  969. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  970. .replace(/`(.*?)`/g, '<code>$1</code>')
  971. .replace(/\n/gim, '<br />');
  972. } else { // inside code block
  973. chunks[i] = `<pre><code>${chunks[i]}</code></pre>`;
  974. }
  975. }
  976. const restoredText = chunks.join('');
  977. return html`<span dangerouslySetInnerHTML=${{ __html: restoredText }} />`;
  978. };
  979. const ModelGenerationInfo = (params) => {
  980. if (!llamaStats.value) {
  981. return html`<span/>`
  982. }
  983. return html`
  984. <span>
  985. ${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
  986. </span>
  987. `
  988. }
  989. // simple popover impl
  990. const Popover = (props) => {
  991. const isOpen = useSignal(false);
  992. const position = useSignal({ top: '0px', left: '0px' });
  993. const buttonRef = useRef(null);
  994. const popoverRef = useRef(null);
  995. const togglePopover = () => {
  996. if (buttonRef.current) {
  997. const rect = buttonRef.current.getBoundingClientRect();
  998. position.value = {
  999. top: `${rect.bottom + window.scrollY}px`,
  1000. left: `${rect.left + window.scrollX}px`,
  1001. };
  1002. }
  1003. isOpen.value = !isOpen.value;
  1004. };
  1005. const handleClickOutside = (event) => {
  1006. if (popoverRef.current && !popoverRef.current.contains(event.target) && !buttonRef.current.contains(event.target)) {
  1007. isOpen.value = false;
  1008. }
  1009. };
  1010. useEffect(() => {
  1011. document.addEventListener('mousedown', handleClickOutside);
  1012. return () => {
  1013. document.removeEventListener('mousedown', handleClickOutside);
  1014. };
  1015. }, []);
  1016. return html`
  1017. <span style=${props.style} ref=${buttonRef} onClick=${togglePopover}>${props.children}</span>
  1018. ${isOpen.value && html`
  1019. <${Portal} into="#portal">
  1020. <div
  1021. ref=${popoverRef}
  1022. class="popover-content"
  1023. style=${{
  1024. top: position.value.top,
  1025. left: position.value.left,
  1026. }}
  1027. >
  1028. ${props.popoverChildren}
  1029. </div>
  1030. </${Portal}>
  1031. `}
  1032. `;
  1033. };
  1034. // Source: preact-portal (https://github.com/developit/preact-portal/blob/master/src/preact-portal.js)
  1035. /** Redirect rendering of descendants into the given CSS selector */
  1036. class Portal extends Component {
  1037. componentDidUpdate(props) {
  1038. for (let i in props) {
  1039. if (props[i] !== this.props[i]) {
  1040. return setTimeout(this.renderLayer);
  1041. }
  1042. }
  1043. }
  1044. componentDidMount() {
  1045. this.isMounted = true;
  1046. this.renderLayer = this.renderLayer.bind(this);
  1047. this.renderLayer();
  1048. }
  1049. componentWillUnmount() {
  1050. this.renderLayer(false);
  1051. this.isMounted = false;
  1052. if (this.remote && this.remote.parentNode) this.remote.parentNode.removeChild(this.remote);
  1053. }
  1054. findNode(node) {
  1055. return typeof node === 'string' ? document.querySelector(node) : node;
  1056. }
  1057. renderLayer(show = true) {
  1058. if (!this.isMounted) return;
  1059. // clean up old node if moving bases:
  1060. if (this.props.into !== this.intoPointer) {
  1061. this.intoPointer = this.props.into;
  1062. if (this.into && this.remote) {
  1063. this.remote = render(html`<${PortalProxy} />`, this.into, this.remote);
  1064. }
  1065. this.into = this.findNode(this.props.into);
  1066. }
  1067. this.remote = render(html`
  1068. <${PortalProxy} context=${this.context}>
  1069. ${show && this.props.children || null}
  1070. </${PortalProxy}>
  1071. `, this.into, this.remote);
  1072. }
  1073. render() {
  1074. return null;
  1075. }
  1076. }
  1077. // high-order component that renders its first child if it exists.
  1078. // used as a conditional rendering proxy.
  1079. class PortalProxy extends Component {
  1080. getChildContext() {
  1081. return this.props.context;
  1082. }
  1083. render({ children }) {
  1084. return children || null;
  1085. }
  1086. }
  1087. function App(props) {
  1088. useEffect(() => {
  1089. const query = new URLSearchParams(location.search).get("q");
  1090. if (query) chat(query);
  1091. }, []);
  1092. return html`
  1093. <div class="mode-${session.value.type}">
  1094. <header>
  1095. <div class="grid-container">
  1096. <div class="grid-item"></div>
  1097. <div class="grid-item"><h1>llama.cpp</h1></div>
  1098. <div class="grid-item"><a class="customlink" href="index-new.html">New UI</a></div>
  1099. </div>
  1100. </header>
  1101. <main id="content">
  1102. <${chatStarted.value ? ChatLog : ConfigForm} />
  1103. </main>
  1104. <section id="write">
  1105. <${session.value.type === 'chat' ? MessageInput : CompletionControls} />
  1106. </section>
  1107. <footer>
  1108. <p><${ModelGenerationInfo} /></p>
  1109. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a>.</p>
  1110. </footer>
  1111. </div>
  1112. `;
  1113. }
  1114. render(h(App), document.querySelector('#container'));
  1115. </script>
  1116. </head>
  1117. <body>
  1118. <div id="container">
  1119. <input type="file" id="fileInput" accept="image/*" style="display: none;">
  1120. </div>
  1121. <div id="portal"></div>
  1122. </body>
  1123. </html>