index.html 32 KB

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