index.html 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. penalize_nl: false,
  189. top_k: 40, // <= 0 to use vocab size
  190. top_p: 0.95, // 1.0 = disabled
  191. min_p: 0.05, // 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. min_keep: 0, // min probs from each sampler,
  201. image_data: [],
  202. cache_prompt: true,
  203. api_key: ''
  204. })
  205. /* START: Support for storing prompt templates and parameters in browsers LocalStorage */
  206. const local_storage_storageKey = "llamacpp_server_local_storage";
  207. function local_storage_setDataFromObject(tag, content) {
  208. localStorage.setItem(local_storage_storageKey + '/' + tag, JSON.stringify(content));
  209. }
  210. function local_storage_setDataFromRawText(tag, content) {
  211. localStorage.setItem(local_storage_storageKey + '/' + tag, content);
  212. }
  213. function local_storage_getDataAsObject(tag) {
  214. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  215. if (!item) {
  216. return null;
  217. } else {
  218. return JSON.parse(item);
  219. }
  220. }
  221. function local_storage_getDataAsRawText(tag) {
  222. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  223. if (!item) {
  224. return null;
  225. } else {
  226. return item;
  227. }
  228. }
  229. // create a container for user templates and settings
  230. const savedUserTemplates = signal({})
  231. const selectedUserTemplate = signal({ name: '', template: { session: {}, params: {} } })
  232. // let's import locally saved templates and settings if there are any
  233. // user templates and settings are stored in one object
  234. // in form of { "templatename": "templatedata" } and { "settingstemplatename":"settingsdata" }
  235. console.log('Importing saved templates')
  236. let importedTemplates = local_storage_getDataAsObject('user_templates')
  237. if (importedTemplates) {
  238. // saved templates were successfully imported.
  239. console.log('Processing saved templates and updating default template')
  240. params.value = { ...params.value, image_data: [] };
  241. //console.log(importedTemplates);
  242. savedUserTemplates.value = importedTemplates;
  243. //override default template
  244. savedUserTemplates.value.default = { session: session.value, params: params.value }
  245. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  246. } else {
  247. // no saved templates detected.
  248. console.log('Initializing LocalStorage and saving default template')
  249. savedUserTemplates.value = { "default": { session: session.value, params: params.value } }
  250. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  251. }
  252. function userTemplateResetToDefault() {
  253. console.log('Resetting template to default')
  254. selectedUserTemplate.value.name = 'default';
  255. selectedUserTemplate.value.data = savedUserTemplates.value['default'];
  256. }
  257. function userTemplateApply(t) {
  258. session.value = t.data.session;
  259. session.value = { ...session.value, image_selected: '' };
  260. params.value = t.data.params;
  261. params.value = { ...params.value, image_data: [] };
  262. }
  263. function userTemplateResetToDefaultAndApply() {
  264. userTemplateResetToDefault()
  265. userTemplateApply(selectedUserTemplate.value)
  266. }
  267. function userTemplateLoadAndApplyAutosaved() {
  268. // get autosaved last used template
  269. let lastUsedTemplate = local_storage_getDataAsObject('user_templates_last')
  270. if (lastUsedTemplate) {
  271. console.log('Autosaved template found, restoring')
  272. selectedUserTemplate.value = lastUsedTemplate
  273. }
  274. else {
  275. console.log('No autosaved template found, using default template')
  276. // no autosaved last used template was found, so load from default.
  277. userTemplateResetToDefault()
  278. }
  279. console.log('Applying template')
  280. // and update internal data from templates
  281. userTemplateApply(selectedUserTemplate.value)
  282. }
  283. //console.log(savedUserTemplates.value)
  284. //console.log(selectedUserTemplate.value)
  285. function userTemplateAutosave() {
  286. console.log('Template Autosave...')
  287. if (selectedUserTemplate.value.name == 'default') {
  288. // we don't want to save over default template, so let's create a new one
  289. let newTemplateName = 'UserTemplate-' + Date.now().toString()
  290. let newTemplate = { 'name': newTemplateName, 'data': { 'session': session.value, 'params': params.value } }
  291. console.log('Saving as ' + newTemplateName)
  292. // save in the autosave slot
  293. local_storage_setDataFromObject('user_templates_last', newTemplate)
  294. // and load it back and apply
  295. userTemplateLoadAndApplyAutosaved()
  296. } else {
  297. local_storage_setDataFromObject('user_templates_last', { 'name': selectedUserTemplate.value.name, 'data': { 'session': session.value, 'params': params.value } })
  298. }
  299. }
  300. console.log('Checking for autosaved last used template')
  301. userTemplateLoadAndApplyAutosaved()
  302. /* END: Support for storing prompt templates and parameters in browsers LocalStorage */
  303. const llamaStats = signal(null)
  304. const controller = signal(null)
  305. // currently generating a completion?
  306. const generating = computed(() => controller.value != null)
  307. // has the user started a chat?
  308. const chatStarted = computed(() => session.value.transcript.length > 0)
  309. const transcriptUpdate = (transcript) => {
  310. session.value = {
  311. ...session.value,
  312. transcript
  313. }
  314. }
  315. // simple template replace
  316. const template = (str, extraSettings) => {
  317. let settings = session.value;
  318. if (extraSettings) {
  319. settings = { ...settings, ...extraSettings };
  320. }
  321. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  322. }
  323. async function runLlama(prompt, llamaParams, char) {
  324. const currentMessages = [];
  325. const history = session.value.transcript;
  326. if (controller.value) {
  327. throw new Error("already running");
  328. }
  329. controller.value = new AbortController();
  330. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value, api_url: location.pathname.replace(/\/+$/, '') })) {
  331. const data = chunk.data;
  332. if (data.stop) {
  333. while (
  334. currentMessages.length > 0 &&
  335. currentMessages[currentMessages.length - 1].content.match(/\n$/) != null
  336. ) {
  337. currentMessages.pop();
  338. }
  339. transcriptUpdate([...history, [char, currentMessages]])
  340. console.log("Completion finished: '", currentMessages.map(msg => msg.content).join(''), "', summary: ", data);
  341. } else {
  342. currentMessages.push(data);
  343. slot_id = data.slot_id;
  344. if (selected_image && !data.multimodal) {
  345. alert("The server was not compiled for multimodal or the model projector can't be loaded.");
  346. return;
  347. }
  348. transcriptUpdate([...history, [char, currentMessages]])
  349. }
  350. if (data.timings) {
  351. llamaStats.value = data;
  352. }
  353. }
  354. controller.value = null;
  355. }
  356. // send message to server
  357. const chat = async (msg) => {
  358. if (controller.value) {
  359. console.log('already running...');
  360. return;
  361. }
  362. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  363. let prompt = template(session.value.template, {
  364. message: msg,
  365. history: session.value.transcript.flatMap(
  366. ([name, data]) =>
  367. template(
  368. session.value.historyTemplate,
  369. {
  370. name,
  371. message: Array.isArray(data) ?
  372. data.map(msg => msg.content).join('').replace(/^\s/, '') :
  373. data,
  374. }
  375. )
  376. ).join("\n"),
  377. });
  378. if (selected_image) {
  379. 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:`;
  380. }
  381. await runLlama(prompt, {
  382. ...params.value,
  383. slot_id: slot_id,
  384. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  385. }, "{{char}}");
  386. }
  387. const runCompletion = () => {
  388. if (controller.value) {
  389. console.log('already running...');
  390. return;
  391. }
  392. const { prompt } = session.value;
  393. transcriptUpdate([...session.value.transcript, ["", prompt]]);
  394. runLlama(prompt, {
  395. ...params.value,
  396. slot_id: slot_id,
  397. stop: [],
  398. }, "").finally(() => {
  399. session.value.prompt = session.value.transcript.map(([_, data]) =>
  400. Array.isArray(data) ? data.map(msg => msg.content).join('') : data
  401. ).join('');
  402. session.value.transcript = [];
  403. })
  404. }
  405. const stop = (e) => {
  406. e.preventDefault();
  407. if (controller.value) {
  408. controller.value.abort();
  409. controller.value = null;
  410. }
  411. }
  412. const reset = (e) => {
  413. stop(e);
  414. transcriptUpdate([]);
  415. }
  416. const uploadImage = (e) => {
  417. e.preventDefault();
  418. document.getElementById("fileInput").click();
  419. document.getElementById("fileInput").addEventListener("change", function (event) {
  420. const selectedFile = event.target.files[0];
  421. if (selectedFile) {
  422. const reader = new FileReader();
  423. reader.onload = function () {
  424. const image_data = reader.result;
  425. session.value = { ...session.value, image_selected: image_data };
  426. params.value = {
  427. ...params.value, image_data: [
  428. { data: image_data.replace(/data:image\/[^;]+;base64,/, ''), id: 10 }]
  429. }
  430. };
  431. selected_image = true;
  432. reader.readAsDataURL(selectedFile);
  433. }
  434. });
  435. }
  436. function MessageInput() {
  437. const message = useSignal("")
  438. const submit = (e) => {
  439. stop(e);
  440. chat(message.value);
  441. message.value = "";
  442. }
  443. const enterSubmits = (event) => {
  444. if (event.which === 13 && !event.shiftKey) {
  445. submit(event);
  446. }
  447. }
  448. return html`
  449. <form onsubmit=${submit}>
  450. <div>
  451. <textarea
  452. className=${generating.value ? "loading" : null}
  453. oninput=${(e) => message.value = e.target.value}
  454. onkeypress=${enterSubmits}
  455. placeholder="Say something..."
  456. rows=2
  457. type="text"
  458. value="${message}"
  459. />
  460. </div>
  461. <div class="right">
  462. <button type="submit" disabled=${generating.value}>Send</button>
  463. <button onclick=${uploadImage}>Upload Image</button>
  464. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  465. <button onclick=${reset}>Reset</button>
  466. </div>
  467. </form>
  468. `
  469. }
  470. function CompletionControls() {
  471. const submit = (e) => {
  472. stop(e);
  473. runCompletion();
  474. }
  475. return html`
  476. <div>
  477. <button onclick=${submit} type="button" disabled=${generating.value}>Start</button>
  478. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  479. <button onclick=${reset}>Reset</button>
  480. </div>`;
  481. }
  482. const ChatLog = (props) => {
  483. const messages = session.value.transcript;
  484. const container = useRef(null)
  485. useEffect(() => {
  486. // scroll to bottom (if needed)
  487. const parent = container.current.parentElement;
  488. if (parent && parent.scrollHeight <= parent.scrollTop + parent.offsetHeight + 300) {
  489. parent.scrollTo(0, parent.scrollHeight)
  490. }
  491. }, [messages])
  492. const isCompletionMode = session.value.type === 'completion'
  493. const chatLine = ([user, data], index) => {
  494. let message
  495. const isArrayMessage = Array.isArray(data)
  496. if (params.value.n_probs > 0 && isArrayMessage) {
  497. message = html`<${Probabilities} data=${data} />`
  498. } else {
  499. const text = isArrayMessage ?
  500. data.map(msg => msg.content).join('').replace(/^\s+/, '') :
  501. data;
  502. message = isCompletionMode ?
  503. text :
  504. html`<${Markdownish} text=${template(text)} />`
  505. }
  506. if (user) {
  507. return html`<p key=${index}><strong>${template(user)}:</strong> ${message}</p>`
  508. } else {
  509. return isCompletionMode ?
  510. html`<span key=${index}>${message}</span>` :
  511. html`<p key=${index}>${message}</p>`
  512. }
  513. };
  514. const handleCompletionEdit = (e) => {
  515. session.value.prompt = e.target.innerText;
  516. session.value.transcript = [];
  517. }
  518. return html`
  519. <div id="chat" ref=${container} key=${messages.length}>
  520. <img style="width: 60%;${!session.value.image_selected ? `display: none;` : ``}" src="${session.value.image_selected}"/>
  521. <span contenteditable=${isCompletionMode} ref=${container} oninput=${handleCompletionEdit}>
  522. ${messages.flatMap(chatLine)}
  523. </span>
  524. </div>`;
  525. };
  526. const ConfigForm = (props) => {
  527. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  528. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  529. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  530. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  531. const updateParamsBool = (el) => params.value = { ...params.value, [el.target.name]: el.target.checked }
  532. const grammarJsonSchemaPropOrder = signal('')
  533. const updateGrammarJsonSchemaPropOrder = (el) => grammarJsonSchemaPropOrder.value = el.target.value
  534. const convertJSONSchemaGrammar = async () => {
  535. try {
  536. let schema = JSON.parse(params.value.grammar)
  537. const converter = new SchemaConverter({
  538. prop_order: grammarJsonSchemaPropOrder.value
  539. .split(',')
  540. .reduce((acc, cur, i) => ({ ...acc, [cur.trim()]: i }), {}),
  541. allow_fetch: true,
  542. })
  543. schema = await converter.resolveRefs(schema, 'input')
  544. converter.visit(schema, '')
  545. params.value = {
  546. ...params.value,
  547. grammar: converter.formatGrammar(),
  548. }
  549. } catch (e) {
  550. alert(`Convert failed: ${e.message}`)
  551. }
  552. }
  553. const FloatField = ({ label, max, min, name, step, value }) => {
  554. return html`
  555. <div>
  556. <label for="${name}">${label}</label>
  557. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  558. <span>${value}</span>
  559. </div>
  560. `
  561. };
  562. const IntField = ({ label, max, min, name, value }) => {
  563. return html`
  564. <div>
  565. <label for="${name}">${label}</label>
  566. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  567. <span>${value}</span>
  568. </div>
  569. `
  570. };
  571. const BoolField = ({ label, name, value }) => {
  572. return html`
  573. <div>
  574. <label for="${name}">${label}</label>
  575. <input type="checkbox" id="${name}" name="${name}" checked="${value}" onclick=${updateParamsBool} />
  576. </div>
  577. `
  578. };
  579. const userTemplateReset = (e) => {
  580. e.preventDefault();
  581. userTemplateResetToDefaultAndApply()
  582. }
  583. const UserTemplateResetButton = () => {
  584. if (selectedUserTemplate.value.name == 'default') {
  585. return html`
  586. <button disabled>Using default template</button>
  587. `
  588. }
  589. return html`
  590. <button onclick=${userTemplateReset}>Reset all to default</button>
  591. `
  592. };
  593. useEffect(() => {
  594. // autosave template on every change
  595. userTemplateAutosave()
  596. }, [session.value, params.value])
  597. const GrammarControl = () => (
  598. html`
  599. <div>
  600. <label for="template">Grammar</label>
  601. <textarea id="grammar" name="grammar" placeholder="Use gbnf or JSON Schema+convert" value="${params.value.grammar}" rows=4 oninput=${updateParams}/>
  602. <input type="text" name="prop-order" placeholder="order: prop1,prop2,prop3" oninput=${updateGrammarJsonSchemaPropOrder} />
  603. <button type="button" onclick=${convertJSONSchemaGrammar}>Convert JSON Schema</button>
  604. </div>
  605. `
  606. );
  607. const PromptControlFieldSet = () => (
  608. html`
  609. <fieldset>
  610. <div>
  611. <label htmlFor="prompt">Prompt</label>
  612. <textarea type="text" name="prompt" value="${session.value.prompt}" oninput=${updateSession}/>
  613. </div>
  614. </fieldset>
  615. `
  616. );
  617. const ChatConfigForm = () => (
  618. html`
  619. ${PromptControlFieldSet()}
  620. <fieldset class="two">
  621. <div>
  622. <label for="user">User name</label>
  623. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  624. </div>
  625. <div>
  626. <label for="bot">Bot name</label>
  627. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  628. </div>
  629. </fieldset>
  630. <fieldset>
  631. <div>
  632. <label for="template">Prompt template</label>
  633. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  634. </div>
  635. <div>
  636. <label for="template">Chat history template</label>
  637. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  638. </div>
  639. ${GrammarControl()}
  640. </fieldset>
  641. `
  642. );
  643. const CompletionConfigForm = () => (
  644. html`
  645. ${PromptControlFieldSet()}
  646. <fieldset>${GrammarControl()}</fieldset>
  647. `
  648. );
  649. return html`
  650. <form>
  651. <fieldset class="two">
  652. <${UserTemplateResetButton}/>
  653. <div>
  654. <label class="slim"><input type="radio" name="type" value="chat" checked=${session.value.type === "chat"} oninput=${updateSession} /> Chat</label>
  655. <label class="slim"><input type="radio" name="type" value="completion" checked=${session.value.type === "completion"} oninput=${updateSession} /> Completion</label>
  656. </div>
  657. </fieldset>
  658. ${session.value.type === 'chat' ? ChatConfigForm() : CompletionConfigForm()}
  659. <fieldset class="two">
  660. ${IntField({ label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict })}
  661. ${FloatField({ label: "Temperature", max: 2.0, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature })}
  662. ${FloatField({ label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty })}
  663. ${IntField({ label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n })}
  664. ${BoolField({ label: "Penalize repetition of newlines", name: "penalize_nl", value: params.value.penalize_nl })}
  665. ${IntField({ label: "Top-K sampling", max: 100, min: -1, name: "top_k", value: params.value.top_k })}
  666. ${FloatField({ label: "Top-P sampling", max: 1.0, min: 0.0, name: "top_p", step: 0.01, value: params.value.top_p })}
  667. ${FloatField({ label: "Min-P sampling", max: 1.0, min: 0.0, name: "min_p", step: 0.01, value: params.value.min_p })}
  668. </fieldset>
  669. <details>
  670. <summary>More options</summary>
  671. <fieldset class="two">
  672. ${FloatField({ label: "Typical P", max: 1.0, min: 0.0, name: "typical_p", step: 0.01, value: params.value.typical_p })}
  673. ${FloatField({ label: "Presence penalty", max: 1.0, min: 0.0, name: "presence_penalty", step: 0.01, value: params.value.presence_penalty })}
  674. ${FloatField({ label: "Frequency penalty", max: 1.0, min: 0.0, name: "frequency_penalty", step: 0.01, value: params.value.frequency_penalty })}
  675. </fieldset>
  676. <hr />
  677. <fieldset class="three">
  678. <div>
  679. <label><input type="radio" name="mirostat" value="0" checked=${params.value.mirostat == 0} oninput=${updateParamsInt} /> no Mirostat</label>
  680. <label><input type="radio" name="mirostat" value="1" checked=${params.value.mirostat == 1} oninput=${updateParamsInt} /> Mirostat v1</label>
  681. <label><input type="radio" name="mirostat" value="2" checked=${params.value.mirostat == 2} oninput=${updateParamsInt} /> Mirostat v2</label>
  682. </div>
  683. ${FloatField({ label: "Mirostat tau", max: 10.0, min: 0.0, name: "mirostat_tau", step: 0.01, value: params.value.mirostat_tau })}
  684. ${FloatField({ label: "Mirostat eta", max: 1.0, min: 0.0, name: "mirostat_eta", step: 0.01, value: params.value.mirostat_eta })}
  685. </fieldset>
  686. <fieldset>
  687. ${IntField({ label: "Show Probabilities", max: 10, min: 0, name: "n_probs", value: params.value.n_probs })}
  688. </fieldset>
  689. <fieldset>
  690. ${IntField({ label: "Min Probabilities from each Sampler", max: 10, min: 0, name: "min_keep", value: params.value.min_keep })}
  691. </fieldset>
  692. <fieldset>
  693. <label for="api_key">API Key</label>
  694. <input type="text" name="api_key" value="${params.value.api_key}" placeholder="Enter API key" oninput=${updateParams} />
  695. </fieldset>
  696. </details>
  697. </form>
  698. `
  699. }
  700. const probColor = (p) => {
  701. const r = Math.floor(192 * (1 - p));
  702. const g = Math.floor(192 * p);
  703. return `rgba(${r},${g},0,0.3)`;
  704. }
  705. const Probabilities = (params) => {
  706. return params.data.map(msg => {
  707. const { completion_probabilities } = msg;
  708. if (
  709. !completion_probabilities ||
  710. completion_probabilities.length === 0
  711. ) return msg.content
  712. if (completion_probabilities.length > 1) {
  713. // Not for byte pair
  714. if (completion_probabilities[0].content.startsWith('byte: \\')) return msg.content
  715. const splitData = completion_probabilities.map(prob => ({
  716. content: prob.content,
  717. completion_probabilities: [prob]
  718. }))
  719. return html`<${Probabilities} data=${splitData} />`
  720. }
  721. const { probs, content } = completion_probabilities[0]
  722. const found = probs.find(p => p.tok_str === msg.content)
  723. const pColor = found ? probColor(found.prob) : 'transparent'
  724. const popoverChildren = html`
  725. <div class="prob-set">
  726. ${probs.map((p, index) => {
  727. return html`
  728. <div
  729. key=${index}
  730. title=${`prob: ${p.prob}`}
  731. style=${{
  732. padding: '0.3em',
  733. backgroundColor: p.tok_str === content ? probColor(p.prob) : 'transparent'
  734. }}
  735. >
  736. <span>${p.tok_str}: </span>
  737. <span>${Math.floor(p.prob * 100)}%</span>
  738. </div>
  739. `
  740. })}
  741. </div>
  742. `
  743. return html`
  744. <${Popover} style=${{ backgroundColor: pColor }} popoverChildren=${popoverChildren}>
  745. ${msg.content.match(/\n/gim) ? html`<br />` : msg.content}
  746. </>
  747. `
  748. });
  749. }
  750. // poor mans markdown replacement
  751. const Markdownish = (params) => {
  752. const md = params.text
  753. .replace(/&/g, '&amp;')
  754. .replace(/</g, '&lt;')
  755. .replace(/>/g, '&gt;')
  756. .replace(/^#{1,6} (.*)$/gim, '<h3>$1</h3>')
  757. .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  758. .replace(/__(.*?)__/g, '<strong>$1</strong>')
  759. .replace(/\*(.*?)\*/g, '<em>$1</em>')
  760. .replace(/_(.*?)_/g, '<em>$1</em>')
  761. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  762. .replace(/`(.*?)`/g, '<code>$1</code>')
  763. .replace(/\n/gim, '<br />');
  764. return html`<span dangerouslySetInnerHTML=${{ __html: md }} />`;
  765. };
  766. const ModelGenerationInfo = (params) => {
  767. if (!llamaStats.value) {
  768. return html`<span/>`
  769. }
  770. return html`
  771. <span>
  772. ${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
  773. </span>
  774. `
  775. }
  776. // simple popover impl
  777. const Popover = (props) => {
  778. const isOpen = useSignal(false);
  779. const position = useSignal({ top: '0px', left: '0px' });
  780. const buttonRef = useRef(null);
  781. const popoverRef = useRef(null);
  782. const togglePopover = () => {
  783. if (buttonRef.current) {
  784. const rect = buttonRef.current.getBoundingClientRect();
  785. position.value = {
  786. top: `${rect.bottom + window.scrollY}px`,
  787. left: `${rect.left + window.scrollX}px`,
  788. };
  789. }
  790. isOpen.value = !isOpen.value;
  791. };
  792. const handleClickOutside = (event) => {
  793. if (popoverRef.current && !popoverRef.current.contains(event.target) && !buttonRef.current.contains(event.target)) {
  794. isOpen.value = false;
  795. }
  796. };
  797. useEffect(() => {
  798. document.addEventListener('mousedown', handleClickOutside);
  799. return () => {
  800. document.removeEventListener('mousedown', handleClickOutside);
  801. };
  802. }, []);
  803. return html`
  804. <span style=${props.style} ref=${buttonRef} onClick=${togglePopover}>${props.children}</span>
  805. ${isOpen.value && html`
  806. <${Portal} into="#portal">
  807. <div
  808. ref=${popoverRef}
  809. class="popover-content"
  810. style=${{
  811. top: position.value.top,
  812. left: position.value.left,
  813. }}
  814. >
  815. ${props.popoverChildren}
  816. </div>
  817. </${Portal}>
  818. `}
  819. `;
  820. };
  821. // Source: preact-portal (https://github.com/developit/preact-portal/blob/master/src/preact-portal.js)
  822. /** Redirect rendering of descendants into the given CSS selector */
  823. class Portal extends Component {
  824. componentDidUpdate(props) {
  825. for (let i in props) {
  826. if (props[i] !== this.props[i]) {
  827. return setTimeout(this.renderLayer);
  828. }
  829. }
  830. }
  831. componentDidMount() {
  832. this.isMounted = true;
  833. this.renderLayer = this.renderLayer.bind(this);
  834. this.renderLayer();
  835. }
  836. componentWillUnmount() {
  837. this.renderLayer(false);
  838. this.isMounted = false;
  839. if (this.remote && this.remote.parentNode) this.remote.parentNode.removeChild(this.remote);
  840. }
  841. findNode(node) {
  842. return typeof node === 'string' ? document.querySelector(node) : node;
  843. }
  844. renderLayer(show = true) {
  845. if (!this.isMounted) return;
  846. // clean up old node if moving bases:
  847. if (this.props.into !== this.intoPointer) {
  848. this.intoPointer = this.props.into;
  849. if (this.into && this.remote) {
  850. this.remote = render(html`<${PortalProxy} />`, this.into, this.remote);
  851. }
  852. this.into = this.findNode(this.props.into);
  853. }
  854. this.remote = render(html`
  855. <${PortalProxy} context=${this.context}>
  856. ${show && this.props.children || null}
  857. </${PortalProxy}>
  858. `, this.into, this.remote);
  859. }
  860. render() {
  861. return null;
  862. }
  863. }
  864. // high-order component that renders its first child if it exists.
  865. // used as a conditional rendering proxy.
  866. class PortalProxy extends Component {
  867. getChildContext() {
  868. return this.props.context;
  869. }
  870. render({ children }) {
  871. return children || null;
  872. }
  873. }
  874. function App(props) {
  875. useEffect(() => {
  876. const query = new URLSearchParams(location.search).get("q");
  877. if (query) chat(query);
  878. }, []);
  879. return html`
  880. <div class="mode-${session.value.type}">
  881. <header>
  882. <h1>llama.cpp</h1>
  883. </header>
  884. <section id="write">
  885. <${session.value.type === 'chat' ? MessageInput : CompletionControls} />
  886. </section>
  887. <main id="content">
  888. <${chatStarted.value ? ChatLog : ConfigForm} />
  889. </main>
  890. <footer>
  891. <p><${ModelGenerationInfo} /></p>
  892. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a>.</p>
  893. </footer>
  894. </div>
  895. `;
  896. }
  897. render(h(App), document.querySelector('#container'));
  898. </script>
  899. </head>
  900. <body>
  901. <div id="container">
  902. <input type="file" id="fileInput" accept="image/*" style="display: none;">
  903. </div>
  904. <div id="portal"></div>
  905. </body>
  906. </html>