index.html 34 KB

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