1
0

index.html 43 KB

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