index.html 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. #container {
  13. margin: 0em auto;
  14. display: flex;
  15. flex-direction: column;
  16. justify-content: space-between;
  17. height: 100%;
  18. }
  19. main {
  20. margin: 3px;
  21. display: flex;
  22. flex-direction: column;
  23. justify-content: space-between;
  24. gap: 1em;
  25. flex-grow: 1;
  26. overflow-y: auto;
  27. border: 1px solid #ccc;
  28. border-radius: 5px;
  29. padding: 0.5em;
  30. }
  31. body {
  32. max-width: 600px;
  33. min-width: 300px;
  34. line-height: 1.2;
  35. margin: 0 auto;
  36. padding: 0 0.5em;
  37. }
  38. p {
  39. overflow-wrap: break-word;
  40. word-wrap: break-word;
  41. hyphens: auto;
  42. margin-top: 0.5em;
  43. margin-bottom: 0.5em;
  44. }
  45. #write form {
  46. margin: 1em 0 0 0;
  47. display: flex;
  48. flex-direction: column;
  49. gap: 0.5em;
  50. align-items: stretch;
  51. }
  52. .right {
  53. display: flex;
  54. flex-direction: row;
  55. gap: 0.5em;
  56. justify-content: flex-end;
  57. }
  58. fieldset {
  59. border: none;
  60. padding: 0;
  61. margin: 0;
  62. }
  63. fieldset.two {
  64. display: grid;
  65. grid-template: "a a";
  66. gap: 1em;
  67. }
  68. fieldset.three {
  69. display: grid;
  70. grid-template: "a a a";
  71. gap: 1em;
  72. }
  73. details {
  74. border: 1px solid #aaa;
  75. border-radius: 4px;
  76. padding: 0.5em 0.5em 0;
  77. margin-top: 0.5em;
  78. }
  79. summary {
  80. font-weight: bold;
  81. margin: -0.5em -0.5em 0;
  82. padding: 0.5em;
  83. cursor: pointer;
  84. }
  85. details[open] {
  86. padding: 0.5em;
  87. }
  88. .prob-set {
  89. padding: 0.3em;
  90. border-bottom: 1px solid #ccc;
  91. }
  92. .popover-content {
  93. position: absolute;
  94. background-color: white;
  95. padding: 0.2em;
  96. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  97. }
  98. textarea {
  99. padding: 5px;
  100. flex-grow: 1;
  101. width: 100%;
  102. }
  103. pre code {
  104. display: block;
  105. background-color: #222;
  106. color: #ddd;
  107. }
  108. code {
  109. font-family: monospace;
  110. padding: 0.1em 0.3em;
  111. border-radius: 3px;
  112. }
  113. fieldset label {
  114. margin: 0.5em 0;
  115. display: block;
  116. }
  117. fieldset label.slim {
  118. margin: 0 0.5em;
  119. display: inline;
  120. }
  121. header,
  122. footer {
  123. text-align: center;
  124. }
  125. footer {
  126. font-size: 80%;
  127. color: #888;
  128. }
  129. .mode-chat textarea[name=prompt] {
  130. height: 4.5em;
  131. }
  132. .mode-completion textarea[name=prompt] {
  133. height: 10em;
  134. }
  135. [contenteditable] {
  136. display: inline-block;
  137. white-space: pre-wrap;
  138. outline: 0px solid transparent;
  139. }
  140. @keyframes loading-bg-wipe {
  141. 0% {
  142. background-position: 0%;
  143. }
  144. 100% {
  145. background-position: 100%;
  146. }
  147. }
  148. .loading {
  149. --loading-color-1: #eeeeee00;
  150. --loading-color-2: #eeeeeeff;
  151. background-size: 50% 100%;
  152. background-image: linear-gradient(90deg, var(--loading-color-1), var(--loading-color-2), var(--loading-color-1));
  153. animation: loading-bg-wipe 2s linear infinite;
  154. }
  155. @media (prefers-color-scheme: dark) {
  156. .loading {
  157. --loading-color-1: #22222200;
  158. --loading-color-2: #222222ff;
  159. }
  160. .popover-content {
  161. background-color: black;
  162. }
  163. }
  164. </style>
  165. <script type="module">
  166. import {
  167. html, h, signal, effect, computed, render, useSignal, useEffect, useRef, Component
  168. } from '/index.js';
  169. import { llama } from '/completion.js';
  170. import { SchemaConverter } from '/json-schema-to-grammar.mjs';
  171. let selected_image = false;
  172. var slot_id = -1;
  173. const session = signal({
  174. 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.",
  175. template: "{{prompt}}\n\n{{history}}\n{{char}}:",
  176. historyTemplate: "{{name}}: {{message}}",
  177. transcript: [],
  178. type: "chat", // "chat" | "completion"
  179. char: "Llama",
  180. user: "User",
  181. image_selected: ''
  182. })
  183. const params = signal({
  184. n_predict: 400,
  185. temperature: 0.7,
  186. repeat_last_n: 256, // 0 = disable penalty, -1 = context size
  187. repeat_penalty: 1.18, // 1.0 = disabled
  188. top_k: 40, // <= 0 to use vocab size
  189. top_p: 0.5, // 1.0 = disabled
  190. min_p: 0.05, // 0 = disabled
  191. tfs_z: 1.0, // 1.0 = disabled
  192. typical_p: 1.0, // 1.0 = disabled
  193. presence_penalty: 0.0, // 0.0 = disabled
  194. frequency_penalty: 0.0, // 0.0 = disabled
  195. mirostat: 0, // 0/1/2
  196. mirostat_tau: 5, // target entropy
  197. mirostat_eta: 0.1, // learning rate
  198. grammar: '',
  199. n_probs: 0, // no completion_probabilities,
  200. image_data: [],
  201. cache_prompt: true
  202. })
  203. /* START: Support for storing prompt templates and parameters in browsers LocalStorage */
  204. const local_storage_storageKey = "llamacpp_server_local_storage";
  205. function local_storage_setDataFromObject(tag, content) {
  206. localStorage.setItem(local_storage_storageKey + '/' + tag, JSON.stringify(content));
  207. }
  208. function local_storage_setDataFromRawText(tag, content) {
  209. localStorage.setItem(local_storage_storageKey + '/' + tag, content);
  210. }
  211. function local_storage_getDataAsObject(tag) {
  212. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  213. if (!item) {
  214. return null;
  215. } else {
  216. return JSON.parse(item);
  217. }
  218. }
  219. function local_storage_getDataAsRawText(tag) {
  220. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  221. if (!item) {
  222. return null;
  223. } else {
  224. return item;
  225. }
  226. }
  227. // create a container for user templates and settings
  228. const savedUserTemplates = signal({})
  229. const selectedUserTemplate = signal({ name: '', template: { session: {}, params: {} } })
  230. // let's import locally saved templates and settings if there are any
  231. // user templates and settings are stored in one object
  232. // in form of { "templatename": "templatedata" } and { "settingstemplatename":"settingsdata" }
  233. console.log('Importing saved templates')
  234. let importedTemplates = local_storage_getDataAsObject('user_templates')
  235. if (importedTemplates) {
  236. // saved templates were successfully imported.
  237. console.log('Processing saved templates and updating default template')
  238. params.value = { ...params.value, image_data: [] };
  239. //console.log(importedTemplates);
  240. savedUserTemplates.value = importedTemplates;
  241. //override default template
  242. savedUserTemplates.value.default = { session: session.value, params: params.value }
  243. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  244. } else {
  245. // no saved templates detected.
  246. console.log('Initializing LocalStorage and saving default template')
  247. savedUserTemplates.value = { "default": { session: session.value, params: params.value } }
  248. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  249. }
  250. function userTemplateResetToDefault() {
  251. console.log('Resetting template to default')
  252. selectedUserTemplate.value.name = 'default';
  253. selectedUserTemplate.value.data = savedUserTemplates.value['default'];
  254. }
  255. function userTemplateApply(t) {
  256. session.value = t.data.session;
  257. session.value = { ...session.value, image_selected: '' };
  258. params.value = t.data.params;
  259. params.value = { ...params.value, image_data: [] };
  260. }
  261. function userTemplateResetToDefaultAndApply() {
  262. userTemplateResetToDefault()
  263. userTemplateApply(selectedUserTemplate.value)
  264. }
  265. function userTemplateLoadAndApplyAutosaved() {
  266. // get autosaved last used template
  267. let lastUsedTemplate = local_storage_getDataAsObject('user_templates_last')
  268. if (lastUsedTemplate) {
  269. console.log('Autosaved template found, restoring')
  270. selectedUserTemplate.value = lastUsedTemplate
  271. }
  272. else {
  273. console.log('No autosaved template found, using default template')
  274. // no autosaved last used template was found, so load from default.
  275. userTemplateResetToDefault()
  276. }
  277. console.log('Applying template')
  278. // and update internal data from templates
  279. userTemplateApply(selectedUserTemplate.value)
  280. }
  281. //console.log(savedUserTemplates.value)
  282. //console.log(selectedUserTemplate.value)
  283. function userTemplateAutosave() {
  284. console.log('Template Autosave...')
  285. if (selectedUserTemplate.value.name == 'default') {
  286. // we don't want to save over default template, so let's create a new one
  287. let newTemplateName = 'UserTemplate-' + Date.now().toString()
  288. let newTemplate = { 'name': newTemplateName, 'data': { 'session': session.value, 'params': params.value } }
  289. console.log('Saving as ' + newTemplateName)
  290. // save in the autosave slot
  291. local_storage_setDataFromObject('user_templates_last', newTemplate)
  292. // and load it back and apply
  293. userTemplateLoadAndApplyAutosaved()
  294. } else {
  295. local_storage_setDataFromObject('user_templates_last', { 'name': selectedUserTemplate.value.name, 'data': { 'session': session.value, 'params': params.value } })
  296. }
  297. }
  298. console.log('Checking for autosaved last used template')
  299. userTemplateLoadAndApplyAutosaved()
  300. /* END: Support for storing prompt templates and parameters in browsers LocalStorage */
  301. const llamaStats = signal(null)
  302. const controller = signal(null)
  303. // currently generating a completion?
  304. const generating = computed(() => controller.value != null)
  305. // has the user started a chat?
  306. const chatStarted = computed(() => session.value.transcript.length > 0)
  307. const transcriptUpdate = (transcript) => {
  308. session.value = {
  309. ...session.value,
  310. transcript
  311. }
  312. }
  313. // simple template replace
  314. const template = (str, extraSettings) => {
  315. let settings = session.value;
  316. if (extraSettings) {
  317. settings = { ...settings, ...extraSettings };
  318. }
  319. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  320. }
  321. async function runLlama(prompt, llamaParams, char) {
  322. const currentMessages = [];
  323. const history = session.value.transcript;
  324. if (controller.value) {
  325. throw new Error("already running");
  326. }
  327. controller.value = new AbortController();
  328. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value })) {
  329. const data = chunk.data;
  330. if (data.stop) {
  331. while (
  332. currentMessages.length > 0 &&
  333. currentMessages[currentMessages.length - 1].content.match(/\n$/) != null
  334. ) {
  335. currentMessages.pop();
  336. }
  337. transcriptUpdate([...history, [char, currentMessages]])
  338. console.log("Completion finished: '", currentMessages.map(msg => msg.content).join(''), "', summary: ", data);
  339. } else {
  340. currentMessages.push(data);
  341. slot_id = data.slot_id;
  342. if (selected_image && !data.multimodal) {
  343. alert("The server was not compiled for multimodal or the model projector can't be loaded.");
  344. return;
  345. }
  346. transcriptUpdate([...history, [char, currentMessages]])
  347. }
  348. if (data.timings) {
  349. llamaStats.value = data.timings;
  350. }
  351. }
  352. controller.value = null;
  353. }
  354. // send message to server
  355. const chat = async (msg) => {
  356. if (controller.value) {
  357. console.log('already running...');
  358. return;
  359. }
  360. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  361. let prompt = template(session.value.template, {
  362. message: msg,
  363. history: session.value.transcript.flatMap(
  364. ([name, data]) =>
  365. template(
  366. session.value.historyTemplate,
  367. {
  368. name,
  369. message: Array.isArray(data) ?
  370. data.map(msg => msg.content).join('').replace(/^\s/, '') :
  371. data,
  372. }
  373. )
  374. ).join("\n"),
  375. });
  376. if (selected_image) {
  377. 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:`;
  378. }
  379. await runLlama(prompt, {
  380. ...params.value,
  381. slot_id: slot_id,
  382. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  383. }, "{{char}}");
  384. }
  385. const runCompletion = () => {
  386. if (controller.value) {
  387. console.log('already running...');
  388. return;
  389. }
  390. const { prompt } = session.value;
  391. transcriptUpdate([...session.value.transcript, ["", prompt]]);
  392. runLlama(prompt, {
  393. ...params.value,
  394. slot_id: slot_id,
  395. stop: [],
  396. }, "").finally(() => {
  397. session.value.prompt = session.value.transcript.map(([_, data]) =>
  398. Array.isArray(data) ? data.map(msg => msg.content).join('') : data
  399. ).join('');
  400. session.value.transcript = [];
  401. })
  402. }
  403. const stop = (e) => {
  404. e.preventDefault();
  405. if (controller.value) {
  406. controller.value.abort();
  407. controller.value = null;
  408. }
  409. }
  410. const reset = (e) => {
  411. stop(e);
  412. transcriptUpdate([]);
  413. }
  414. const uploadImage = (e) => {
  415. e.preventDefault();
  416. document.getElementById("fileInput").click();
  417. document.getElementById("fileInput").addEventListener("change", function (event) {
  418. const selectedFile = event.target.files[0];
  419. if (selectedFile) {
  420. const reader = new FileReader();
  421. reader.onload = function () {
  422. const image_data = reader.result;
  423. session.value = { ...session.value, image_selected: image_data };
  424. params.value = {
  425. ...params.value, image_data: [
  426. { data: image_data.replace(/data:image\/[^;]+;base64,/, ''), id: 10 }]
  427. }
  428. };
  429. selected_image = true;
  430. reader.readAsDataURL(selectedFile);
  431. }
  432. });
  433. }
  434. function MessageInput() {
  435. const message = useSignal("")
  436. const submit = (e) => {
  437. stop(e);
  438. chat(message.value);
  439. message.value = "";
  440. }
  441. const enterSubmits = (event) => {
  442. if (event.which === 13 && !event.shiftKey) {
  443. submit(event);
  444. }
  445. }
  446. return html`
  447. <form onsubmit=${submit}>
  448. <div>
  449. <textarea
  450. className=${generating.value ? "loading" : null}
  451. oninput=${(e) => message.value = e.target.value}
  452. onkeypress=${enterSubmits}
  453. placeholder="Say something..."
  454. rows=2
  455. type="text"
  456. value="${message}"
  457. />
  458. </div>
  459. <div class="right">
  460. <button type="submit" disabled=${generating.value}>Send</button>
  461. <button onclick=${uploadImage}>Upload Image</button>
  462. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  463. <button onclick=${reset}>Reset</button>
  464. </div>
  465. </form>
  466. `
  467. }
  468. function CompletionControls() {
  469. const submit = (e) => {
  470. stop(e);
  471. runCompletion();
  472. }
  473. return html`
  474. <div>
  475. <button onclick=${submit} type="button" disabled=${generating.value}>Start</button>
  476. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  477. <button onclick=${reset}>Reset</button>
  478. </div>`;
  479. }
  480. const ChatLog = (props) => {
  481. const messages = session.value.transcript;
  482. const container = useRef(null)
  483. useEffect(() => {
  484. // scroll to bottom (if needed)
  485. const parent = container.current.parentElement;
  486. if (parent && parent.scrollHeight <= parent.scrollTop + parent.offsetHeight + 300) {
  487. parent.scrollTo(0, parent.scrollHeight)
  488. }
  489. }, [messages])
  490. const isCompletionMode = session.value.type === 'completion'
  491. const chatLine = ([user, data], index) => {
  492. let message
  493. const isArrayMessage = Array.isArray(data)
  494. if (params.value.n_probs > 0 && isArrayMessage) {
  495. message = html`<${Probabilities} data=${data} />`
  496. } else {
  497. const text = isArrayMessage ?
  498. data.map(msg => msg.content).join('').replace(/^\s+/, '') :
  499. data;
  500. message = isCompletionMode ?
  501. text :
  502. html`<${Markdownish} text=${template(text)} />`
  503. }
  504. if (user) {
  505. return html`<p key=${index}><strong>${template(user)}:</strong> ${message}</p>`
  506. } else {
  507. return isCompletionMode ?
  508. html`<span key=${index}>${message}</span>` :
  509. html`<p key=${index}>${message}</p>`
  510. }
  511. };
  512. const handleCompletionEdit = (e) => {
  513. session.value.prompt = e.target.innerText;
  514. session.value.transcript = [];
  515. }
  516. return html`
  517. <div id="chat" ref=${container} key=${messages.length}>
  518. <img style="width: 60%;${!session.value.image_selected ? `display: none;` : ``}" src="${session.value.image_selected}"/>
  519. <span contenteditable=${isCompletionMode} ref=${container} oninput=${handleCompletionEdit}>
  520. ${messages.flatMap(chatLine)}
  521. </span>
  522. </div>`;
  523. };
  524. const ConfigForm = (props) => {
  525. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  526. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  527. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  528. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  529. const grammarJsonSchemaPropOrder = signal('')
  530. const updateGrammarJsonSchemaPropOrder = (el) => grammarJsonSchemaPropOrder.value = el.target.value
  531. const convertJSONSchemaGrammar = () => {
  532. try {
  533. const schema = JSON.parse(params.value.grammar)
  534. const converter = new SchemaConverter(
  535. grammarJsonSchemaPropOrder.value
  536. .split(',')
  537. .reduce((acc, cur, i) => ({ ...acc, [cur.trim()]: i }), {})
  538. )
  539. converter.visit(schema, '')
  540. params.value = {
  541. ...params.value,
  542. grammar: converter.formatGrammar(),
  543. }
  544. } catch (e) {
  545. alert(`Convert failed: ${e.message}`)
  546. }
  547. }
  548. const FloatField = ({ label, max, min, name, step, value }) => {
  549. return html`
  550. <div>
  551. <label for="${name}">${label}</label>
  552. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  553. <span>${value}</span>
  554. </div>
  555. `
  556. };
  557. const IntField = ({ label, max, min, name, value }) => {
  558. return html`
  559. <div>
  560. <label for="${name}">${label}</label>
  561. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  562. <span>${value}</span>
  563. </div>
  564. `
  565. };
  566. const userTemplateReset = (e) => {
  567. e.preventDefault();
  568. userTemplateResetToDefaultAndApply()
  569. }
  570. const UserTemplateResetButton = () => {
  571. if (selectedUserTemplate.value.name == 'default') {
  572. return html`
  573. <button disabled>Using default template</button>
  574. `
  575. }
  576. return html`
  577. <button onclick=${userTemplateReset}>Reset all to default</button>
  578. `
  579. };
  580. useEffect(() => {
  581. // autosave template on every change
  582. userTemplateAutosave()
  583. }, [session.value, params.value])
  584. const GrammarControl = () => (
  585. html`
  586. <div>
  587. <label for="template">Grammar</label>
  588. <textarea id="grammar" name="grammar" placeholder="Use gbnf or JSON Schema+convert" value="${params.value.grammar}" rows=4 oninput=${updateParams}/>
  589. <input type="text" name="prop-order" placeholder="order: prop1,prop2,prop3" oninput=${updateGrammarJsonSchemaPropOrder} />
  590. <button type="button" onclick=${convertJSONSchemaGrammar}>Convert JSON Schema</button>
  591. </div>
  592. `
  593. );
  594. const PromptControlFieldSet = () => (
  595. html`
  596. <fieldset>
  597. <div>
  598. <label htmlFor="prompt">Prompt</label>
  599. <textarea type="text" name="prompt" value="${session.value.prompt}" oninput=${updateSession}/>
  600. </div>
  601. </fieldset>
  602. `
  603. );
  604. const ChatConfigForm = () => (
  605. html`
  606. ${PromptControlFieldSet()}
  607. <fieldset class="two">
  608. <div>
  609. <label for="user">User name</label>
  610. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  611. </div>
  612. <div>
  613. <label for="bot">Bot name</label>
  614. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  615. </div>
  616. </fieldset>
  617. <fieldset>
  618. <div>
  619. <label for="template">Prompt template</label>
  620. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  621. </div>
  622. <div>
  623. <label for="template">Chat history template</label>
  624. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  625. </div>
  626. ${GrammarControl()}
  627. </fieldset>
  628. `
  629. );
  630. const CompletionConfigForm = () => (
  631. html`
  632. ${PromptControlFieldSet()}
  633. <fieldset>${GrammarControl()}</fieldset>
  634. `
  635. );
  636. return html`
  637. <form>
  638. <fieldset class="two">
  639. <${UserTemplateResetButton}/>
  640. <div>
  641. <label class="slim"><input type="radio" name="type" value="chat" checked=${session.value.type === "chat"} oninput=${updateSession} /> Chat</label>
  642. <label class="slim"><input type="radio" name="type" value="completion" checked=${session.value.type === "completion"} oninput=${updateSession} /> Completion</label>
  643. </div>
  644. </fieldset>
  645. ${session.value.type === 'chat' ? ChatConfigForm() : CompletionConfigForm()}
  646. <fieldset class="two">
  647. ${IntField({ label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict })}
  648. ${FloatField({ label: "Temperature", max: 1.5, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature })}
  649. ${FloatField({ label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty })}
  650. ${IntField({ label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n })}
  651. ${IntField({ label: "Top-K sampling", max: 100, min: -1, name: "top_k", value: params.value.top_k })}
  652. ${FloatField({ label: "Top-P sampling", max: 1.0, min: 0.0, name: "top_p", step: 0.01, value: params.value.top_p })}
  653. ${FloatField({ label: "Min-P sampling", max: 1.0, min: 0.0, name: "min_p", step: 0.01, value: params.value.min_p })}
  654. </fieldset>
  655. <details>
  656. <summary>More options</summary>
  657. <fieldset class="two">
  658. ${FloatField({ label: "TFS-Z", max: 1.0, min: 0.0, name: "tfs_z", step: 0.01, value: params.value.tfs_z })}
  659. ${FloatField({ label: "Typical P", max: 1.0, min: 0.0, name: "typical_p", step: 0.01, value: params.value.typical_p })}
  660. ${FloatField({ label: "Presence penalty", max: 1.0, min: 0.0, name: "presence_penalty", step: 0.01, value: params.value.presence_penalty })}
  661. ${FloatField({ label: "Frequency penalty", max: 1.0, min: 0.0, name: "frequency_penalty", step: 0.01, value: params.value.frequency_penalty })}
  662. </fieldset>
  663. <hr />
  664. <fieldset class="three">
  665. <div>
  666. <label><input type="radio" name="mirostat" value="0" checked=${params.value.mirostat == 0} oninput=${updateParamsInt} /> no Mirostat</label>
  667. <label><input type="radio" name="mirostat" value="1" checked=${params.value.mirostat == 1} oninput=${updateParamsInt} /> Mirostat v1</label>
  668. <label><input type="radio" name="mirostat" value="2" checked=${params.value.mirostat == 2} oninput=${updateParamsInt} /> Mirostat v2</label>
  669. </div>
  670. ${FloatField({ label: "Mirostat tau", max: 10.0, min: 0.0, name: "mirostat_tau", step: 0.01, value: params.value.mirostat_tau })}
  671. ${FloatField({ label: "Mirostat eta", max: 1.0, min: 0.0, name: "mirostat_eta", step: 0.01, value: params.value.mirostat_eta })}
  672. </fieldset>
  673. <fieldset>
  674. ${IntField({ label: "Show Probabilities", max: 10, min: 0, name: "n_probs", value: params.value.n_probs })}
  675. </fieldset>
  676. </details>
  677. </form>
  678. `
  679. }
  680. const probColor = (p) => {
  681. const r = Math.floor(192 * (1 - p));
  682. const g = Math.floor(192 * p);
  683. return `rgba(${r},${g},0,0.3)`;
  684. }
  685. const Probabilities = (params) => {
  686. return params.data.map(msg => {
  687. const { completion_probabilities } = msg;
  688. if (
  689. !completion_probabilities ||
  690. completion_probabilities.length === 0
  691. ) return msg.content
  692. if (completion_probabilities.length > 1) {
  693. // Not for byte pair
  694. if (completion_probabilities[0].content.startsWith('byte: \\')) return msg.content
  695. const splitData = completion_probabilities.map(prob => ({
  696. content: prob.content,
  697. completion_probabilities: [prob]
  698. }))
  699. return html`<${Probabilities} data=${splitData} />`
  700. }
  701. const { probs, content } = completion_probabilities[0]
  702. const found = probs.find(p => p.tok_str === msg.content)
  703. const pColor = found ? probColor(found.prob) : 'transparent'
  704. const popoverChildren = html`
  705. <div class="prob-set">
  706. ${probs.map((p, index) => {
  707. return html`
  708. <div
  709. key=${index}
  710. title=${`prob: ${p.prob}`}
  711. style=${{
  712. padding: '0.3em',
  713. backgroundColor: p.tok_str === content ? probColor(p.prob) : 'transparent'
  714. }}
  715. >
  716. <span>${p.tok_str}: </span>
  717. <span>${Math.floor(p.prob * 100)}%</span>
  718. </div>
  719. `
  720. })}
  721. </div>
  722. `
  723. return html`
  724. <${Popover} style=${{ backgroundColor: pColor }} popoverChildren=${popoverChildren}>
  725. ${msg.content.match(/\n/gim) ? html`<br />` : msg.content}
  726. </>
  727. `
  728. });
  729. }
  730. // poor mans markdown replacement
  731. const Markdownish = (params) => {
  732. const md = params.text
  733. .replace(/&/g, '&amp;')
  734. .replace(/</g, '&lt;')
  735. .replace(/>/g, '&gt;')
  736. .replace(/^#{1,6} (.*)$/gim, '<h3>$1</h3>')
  737. .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  738. .replace(/__(.*?)__/g, '<strong>$1</strong>')
  739. .replace(/\*(.*?)\*/g, '<em>$1</em>')
  740. .replace(/_(.*?)_/g, '<em>$1</em>')
  741. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  742. .replace(/`(.*?)`/g, '<code>$1</code>')
  743. .replace(/\n/gim, '<br />');
  744. return html`<span dangerouslySetInnerHTML=${{ __html: md }} />`;
  745. };
  746. const ModelGenerationInfo = (params) => {
  747. if (!llamaStats.value) {
  748. return html`<span/>`
  749. }
  750. return html`
  751. <span>
  752. ${llamaStats.value.predicted_per_token_ms.toFixed()}ms per token, ${llamaStats.value.predicted_per_second.toFixed(2)} tokens per second
  753. </span>
  754. `
  755. }
  756. // simple popover impl
  757. const Popover = (props) => {
  758. const isOpen = useSignal(false);
  759. const position = useSignal({ top: '0px', left: '0px' });
  760. const buttonRef = useRef(null);
  761. const popoverRef = useRef(null);
  762. const togglePopover = () => {
  763. if (buttonRef.current) {
  764. const rect = buttonRef.current.getBoundingClientRect();
  765. position.value = {
  766. top: `${rect.bottom + window.scrollY}px`,
  767. left: `${rect.left + window.scrollX}px`,
  768. };
  769. }
  770. isOpen.value = !isOpen.value;
  771. };
  772. const handleClickOutside = (event) => {
  773. if (popoverRef.current && !popoverRef.current.contains(event.target) && !buttonRef.current.contains(event.target)) {
  774. isOpen.value = false;
  775. }
  776. };
  777. useEffect(() => {
  778. document.addEventListener('mousedown', handleClickOutside);
  779. return () => {
  780. document.removeEventListener('mousedown', handleClickOutside);
  781. };
  782. }, []);
  783. return html`
  784. <span style=${props.style} ref=${buttonRef} onClick=${togglePopover}>${props.children}</span>
  785. ${isOpen.value && html`
  786. <${Portal} into="#portal">
  787. <div
  788. ref=${popoverRef}
  789. class="popover-content"
  790. style=${{
  791. top: position.value.top,
  792. left: position.value.left,
  793. }}
  794. >
  795. ${props.popoverChildren}
  796. </div>
  797. </${Portal}>
  798. `}
  799. `;
  800. };
  801. // Source: preact-portal (https://github.com/developit/preact-portal/blob/master/src/preact-portal.js)
  802. /** Redirect rendering of descendants into the given CSS selector */
  803. class Portal extends Component {
  804. componentDidUpdate(props) {
  805. for (let i in props) {
  806. if (props[i] !== this.props[i]) {
  807. return setTimeout(this.renderLayer);
  808. }
  809. }
  810. }
  811. componentDidMount() {
  812. this.isMounted = true;
  813. this.renderLayer = this.renderLayer.bind(this);
  814. this.renderLayer();
  815. }
  816. componentWillUnmount() {
  817. this.renderLayer(false);
  818. this.isMounted = false;
  819. if (this.remote && this.remote.parentNode) this.remote.parentNode.removeChild(this.remote);
  820. }
  821. findNode(node) {
  822. return typeof node === 'string' ? document.querySelector(node) : node;
  823. }
  824. renderLayer(show = true) {
  825. if (!this.isMounted) return;
  826. // clean up old node if moving bases:
  827. if (this.props.into !== this.intoPointer) {
  828. this.intoPointer = this.props.into;
  829. if (this.into && this.remote) {
  830. this.remote = render(html`<${PortalProxy} />`, this.into, this.remote);
  831. }
  832. this.into = this.findNode(this.props.into);
  833. }
  834. this.remote = render(html`
  835. <${PortalProxy} context=${this.context}>
  836. ${show && this.props.children || null}
  837. </${PortalProxy}>
  838. `, this.into, this.remote);
  839. }
  840. render() {
  841. return null;
  842. }
  843. }
  844. // high-order component that renders its first child if it exists.
  845. // used as a conditional rendering proxy.
  846. class PortalProxy extends Component {
  847. getChildContext() {
  848. return this.props.context;
  849. }
  850. render({ children }) {
  851. return children || null;
  852. }
  853. }
  854. function App(props) {
  855. return html`
  856. <div class="mode-${session.value.type}">
  857. <header>
  858. <h1>llama.cpp</h1>
  859. </header>
  860. <main id="content">
  861. <${chatStarted.value ? ChatLog : ConfigForm} />
  862. </main>
  863. <section id="write">
  864. <${session.value.type === 'chat' ? MessageInput : CompletionControls} />
  865. </section>
  866. <footer>
  867. <p><${ModelGenerationInfo} /></p>
  868. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a>.</p>
  869. </footer>
  870. </div>
  871. `;
  872. }
  873. render(h(App), document.querySelector('#container'));
  874. </script>
  875. </head>
  876. <body>
  877. <div id="container">
  878. <input type="file" id="fileInput" accept="image/*" style="display: none;">
  879. </div>
  880. <div id="portal"></div>
  881. </body>
  882. </html>