1
0

index.html 43 KB

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