index.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. top_k: 40, // <= 0 to use vocab size
  191. top_p: 0.95, // 1.0 = disabled
  192. min_p: 0.05, // 0 = disabled
  193. typical_p: 1.0, // 1.0 = disabled
  194. presence_penalty: 0.0, // 0.0 = disabled
  195. frequency_penalty: 0.0, // 0.0 = disabled
  196. mirostat: 0, // 0/1/2
  197. mirostat_tau: 5, // target entropy
  198. mirostat_eta: 0.1, // learning rate
  199. grammar: '',
  200. n_probs: 0, // no completion_probabilities,
  201. min_keep: 0, // min probs from each sampler,
  202. image_data: [],
  203. cache_prompt: true,
  204. api_key: ''
  205. })
  206. /* START: Support for storing prompt templates and parameters in browsers LocalStorage */
  207. const local_storage_storageKey = "llamacpp_server_local_storage";
  208. function local_storage_setDataFromObject(tag, content) {
  209. localStorage.setItem(local_storage_storageKey + '/' + tag, JSON.stringify(content));
  210. }
  211. function local_storage_setDataFromRawText(tag, content) {
  212. localStorage.setItem(local_storage_storageKey + '/' + tag, content);
  213. }
  214. function local_storage_getDataAsObject(tag) {
  215. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  216. if (!item) {
  217. return null;
  218. } else {
  219. return JSON.parse(item);
  220. }
  221. }
  222. function local_storage_getDataAsRawText(tag) {
  223. const item = localStorage.getItem(local_storage_storageKey + '/' + tag);
  224. if (!item) {
  225. return null;
  226. } else {
  227. return item;
  228. }
  229. }
  230. // create a container for user templates and settings
  231. const savedUserTemplates = signal({})
  232. const selectedUserTemplate = signal({ name: '', template: { session: {}, params: {} } })
  233. // let's import locally saved templates and settings if there are any
  234. // user templates and settings are stored in one object
  235. // in form of { "templatename": "templatedata" } and { "settingstemplatename":"settingsdata" }
  236. console.log('Importing saved templates')
  237. let importedTemplates = local_storage_getDataAsObject('user_templates')
  238. if (importedTemplates) {
  239. // saved templates were successfully imported.
  240. console.log('Processing saved templates and updating default template')
  241. params.value = { ...params.value, image_data: [] };
  242. //console.log(importedTemplates);
  243. savedUserTemplates.value = importedTemplates;
  244. //override default template
  245. savedUserTemplates.value.default = { session: session.value, params: params.value }
  246. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  247. } else {
  248. // no saved templates detected.
  249. console.log('Initializing LocalStorage and saving default template')
  250. savedUserTemplates.value = { "default": { session: session.value, params: params.value } }
  251. local_storage_setDataFromObject('user_templates', savedUserTemplates.value)
  252. }
  253. function userTemplateResetToDefault() {
  254. console.log('Resetting template to default')
  255. selectedUserTemplate.value.name = 'default';
  256. selectedUserTemplate.value.data = savedUserTemplates.value['default'];
  257. }
  258. function userTemplateApply(t) {
  259. session.value = t.data.session;
  260. session.value = { ...session.value, image_selected: '' };
  261. params.value = t.data.params;
  262. params.value = { ...params.value, image_data: [] };
  263. }
  264. function userTemplateResetToDefaultAndApply() {
  265. userTemplateResetToDefault()
  266. userTemplateApply(selectedUserTemplate.value)
  267. }
  268. function userTemplateLoadAndApplyAutosaved() {
  269. // get autosaved last used template
  270. let lastUsedTemplate = local_storage_getDataAsObject('user_templates_last')
  271. if (lastUsedTemplate) {
  272. console.log('Autosaved template found, restoring')
  273. selectedUserTemplate.value = lastUsedTemplate
  274. }
  275. else {
  276. console.log('No autosaved template found, using default template')
  277. // no autosaved last used template was found, so load from default.
  278. userTemplateResetToDefault()
  279. }
  280. console.log('Applying template')
  281. // and update internal data from templates
  282. userTemplateApply(selectedUserTemplate.value)
  283. }
  284. //console.log(savedUserTemplates.value)
  285. //console.log(selectedUserTemplate.value)
  286. function userTemplateAutosave() {
  287. console.log('Template Autosave...')
  288. if (selectedUserTemplate.value.name == 'default') {
  289. // we don't want to save over default template, so let's create a new one
  290. let newTemplateName = 'UserTemplate-' + Date.now().toString()
  291. let newTemplate = { 'name': newTemplateName, 'data': { 'session': session.value, 'params': params.value } }
  292. console.log('Saving as ' + newTemplateName)
  293. // save in the autosave slot
  294. local_storage_setDataFromObject('user_templates_last', newTemplate)
  295. // and load it back and apply
  296. userTemplateLoadAndApplyAutosaved()
  297. } else {
  298. local_storage_setDataFromObject('user_templates_last', { 'name': selectedUserTemplate.value.name, 'data': { 'session': session.value, 'params': params.value } })
  299. }
  300. }
  301. console.log('Checking for autosaved last used template')
  302. userTemplateLoadAndApplyAutosaved()
  303. /* END: Support for storing prompt templates and parameters in browsers LocalStorage */
  304. const llamaStats = signal(null)
  305. const controller = signal(null)
  306. // currently generating a completion?
  307. const generating = computed(() => controller.value != null)
  308. // has the user started a chat?
  309. const chatStarted = computed(() => session.value.transcript.length > 0)
  310. const transcriptUpdate = (transcript) => {
  311. session.value = {
  312. ...session.value,
  313. transcript
  314. }
  315. }
  316. // simple template replace
  317. const template = (str, extraSettings) => {
  318. let settings = session.value;
  319. if (extraSettings) {
  320. settings = { ...settings, ...extraSettings };
  321. }
  322. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  323. }
  324. async function runLlama(prompt, llamaParams, char) {
  325. const currentMessages = [];
  326. const history = session.value.transcript;
  327. if (controller.value) {
  328. throw new Error("already running");
  329. }
  330. controller.value = new AbortController();
  331. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value, api_url: location.pathname.replace(/\/+$/, '') })) {
  332. const data = chunk.data;
  333. if (data.stop) {
  334. while (
  335. currentMessages.length > 0 &&
  336. currentMessages[currentMessages.length - 1].content.match(/\n$/) != null
  337. ) {
  338. currentMessages.pop();
  339. }
  340. transcriptUpdate([...history, [char, currentMessages]])
  341. console.log("Completion finished: '", currentMessages.map(msg => msg.content).join(''), "', summary: ", data);
  342. } else {
  343. currentMessages.push(data);
  344. slot_id = data.slot_id;
  345. if (selected_image && !data.multimodal) {
  346. alert("The server was not compiled for multimodal or the model projector can't be loaded.");
  347. return;
  348. }
  349. transcriptUpdate([...history, [char, currentMessages]])
  350. }
  351. if (data.timings) {
  352. llamaStats.value = data;
  353. }
  354. }
  355. controller.value = null;
  356. }
  357. // send message to server
  358. const chat = async (msg) => {
  359. if (controller.value) {
  360. console.log('already running...');
  361. return;
  362. }
  363. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  364. let prompt = template(session.value.template, {
  365. message: msg,
  366. history: session.value.transcript.flatMap(
  367. ([name, data]) =>
  368. template(
  369. session.value.historyTemplate,
  370. {
  371. name,
  372. message: Array.isArray(data) ?
  373. data.map(msg => msg.content).join('').replace(/^\s/, '') :
  374. data,
  375. }
  376. )
  377. ).join("\n"),
  378. });
  379. if (selected_image) {
  380. 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:`;
  381. }
  382. await runLlama(prompt, {
  383. ...params.value,
  384. slot_id: slot_id,
  385. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  386. }, "{{char}}");
  387. }
  388. const runCompletion = () => {
  389. if (controller.value) {
  390. console.log('already running...');
  391. return;
  392. }
  393. const { prompt } = session.value;
  394. transcriptUpdate([...session.value.transcript, ["", prompt]]);
  395. runLlama(prompt, {
  396. ...params.value,
  397. slot_id: slot_id,
  398. stop: [],
  399. }, "").finally(() => {
  400. session.value.prompt = session.value.transcript.map(([_, data]) =>
  401. Array.isArray(data) ? data.map(msg => msg.content).join('') : data
  402. ).join('');
  403. session.value.transcript = [];
  404. })
  405. }
  406. const stop = (e) => {
  407. e.preventDefault();
  408. if (controller.value) {
  409. controller.value.abort();
  410. controller.value = null;
  411. }
  412. }
  413. const reset = (e) => {
  414. stop(e);
  415. transcriptUpdate([]);
  416. }
  417. const uploadImage = (e) => {
  418. e.preventDefault();
  419. document.getElementById("fileInput").click();
  420. document.getElementById("fileInput").addEventListener("change", function (event) {
  421. const selectedFile = event.target.files[0];
  422. if (selectedFile) {
  423. const reader = new FileReader();
  424. reader.onload = function () {
  425. const image_data = reader.result;
  426. session.value = { ...session.value, image_selected: image_data };
  427. params.value = {
  428. ...params.value, image_data: [
  429. { data: image_data.replace(/data:image\/[^;]+;base64,/, ''), id: 10 }]
  430. }
  431. };
  432. selected_image = true;
  433. reader.readAsDataURL(selectedFile);
  434. }
  435. });
  436. }
  437. function MessageInput() {
  438. const message = useSignal("")
  439. const submit = (e) => {
  440. stop(e);
  441. chat(message.value);
  442. message.value = "";
  443. }
  444. const enterSubmits = (event) => {
  445. if (event.which === 13 && !event.shiftKey) {
  446. submit(event);
  447. }
  448. }
  449. return html`
  450. <form onsubmit=${submit}>
  451. <div>
  452. <textarea
  453. className=${generating.value ? "loading" : null}
  454. oninput=${(e) => message.value = e.target.value}
  455. onkeypress=${enterSubmits}
  456. placeholder="Say something..."
  457. rows=2
  458. type="text"
  459. value="${message}"
  460. />
  461. </div>
  462. <div class="right">
  463. <button type="submit" disabled=${generating.value}>Send</button>
  464. <button onclick=${uploadImage}>Upload Image</button>
  465. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  466. <button onclick=${reset}>Reset</button>
  467. </div>
  468. </form>
  469. `
  470. }
  471. function CompletionControls() {
  472. const submit = (e) => {
  473. stop(e);
  474. runCompletion();
  475. }
  476. return html`
  477. <div>
  478. <button onclick=${submit} type="button" disabled=${generating.value}>Start</button>
  479. <button onclick=${stop} disabled=${!generating.value}>Stop</button>
  480. <button onclick=${reset}>Reset</button>
  481. </div>`;
  482. }
  483. const ChatLog = (props) => {
  484. const messages = session.value.transcript;
  485. const container = useRef(null)
  486. useEffect(() => {
  487. // scroll to bottom (if needed)
  488. const parent = container.current.parentElement;
  489. if (parent && parent.scrollHeight <= parent.scrollTop + parent.offsetHeight + 300) {
  490. parent.scrollTo(0, parent.scrollHeight)
  491. }
  492. }, [messages])
  493. const isCompletionMode = session.value.type === 'completion'
  494. const chatLine = ([user, data], index) => {
  495. let message
  496. const isArrayMessage = Array.isArray(data)
  497. if (params.value.n_probs > 0 && isArrayMessage) {
  498. message = html`<${Probabilities} data=${data} />`
  499. } else {
  500. const text = isArrayMessage ?
  501. data.map(msg => msg.content).join('').replace(/^\s+/, '') :
  502. data;
  503. message = isCompletionMode ?
  504. text :
  505. html`<${Markdownish} text=${template(text)} />`
  506. }
  507. if (user) {
  508. return html`<p key=${index}><strong>${template(user)}:</strong> ${message}</p>`
  509. } else {
  510. return isCompletionMode ?
  511. html`<span key=${index}>${message}</span>` :
  512. html`<p key=${index}>${message}</p>`
  513. }
  514. };
  515. const handleCompletionEdit = (e) => {
  516. session.value.prompt = e.target.innerText;
  517. session.value.transcript = [];
  518. }
  519. return html`
  520. <div id="chat" ref=${container} key=${messages.length}>
  521. <img style="width: 60%;${!session.value.image_selected ? `display: none;` : ``}" src="${session.value.image_selected}"/>
  522. <span contenteditable=${isCompletionMode} ref=${container} oninput=${handleCompletionEdit}>
  523. ${messages.flatMap(chatLine)}
  524. </span>
  525. </div>`;
  526. };
  527. const ConfigForm = (props) => {
  528. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  529. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  530. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  531. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  532. const updateParamsBool = (el) => params.value = { ...params.value, [el.target.name]: el.target.checked }
  533. const grammarJsonSchemaPropOrder = signal('')
  534. const updateGrammarJsonSchemaPropOrder = (el) => grammarJsonSchemaPropOrder.value = el.target.value
  535. const convertJSONSchemaGrammar = async () => {
  536. try {
  537. let schema = JSON.parse(params.value.grammar)
  538. const converter = new SchemaConverter({
  539. prop_order: grammarJsonSchemaPropOrder.value
  540. .split(',')
  541. .reduce((acc, cur, i) => ({ ...acc, [cur.trim()]: i }), {}),
  542. allow_fetch: true,
  543. })
  544. schema = await converter.resolveRefs(schema, 'input')
  545. converter.visit(schema, '')
  546. params.value = {
  547. ...params.value,
  548. grammar: converter.formatGrammar(),
  549. }
  550. } catch (e) {
  551. alert(`Convert failed: ${e.message}`)
  552. }
  553. }
  554. const FloatField = ({ label, max, min, name, step, value }) => {
  555. return html`
  556. <div>
  557. <label for="${name}">${label}</label>
  558. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  559. <span>${value}</span>
  560. </div>
  561. `
  562. };
  563. const IntField = ({ label, max, min, name, value }) => {
  564. return html`
  565. <div>
  566. <label for="${name}">${label}</label>
  567. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  568. <span>${value}</span>
  569. </div>
  570. `
  571. };
  572. const BoolField = ({ label, name, value }) => {
  573. return html`
  574. <div>
  575. <label for="${name}">${label}</label>
  576. <input type="checkbox" id="${name}" name="${name}" checked="${value}" onclick=${updateParamsBool} />
  577. </div>
  578. `
  579. };
  580. const userTemplateReset = (e) => {
  581. e.preventDefault();
  582. userTemplateResetToDefaultAndApply()
  583. }
  584. const UserTemplateResetButton = () => {
  585. if (selectedUserTemplate.value.name == 'default') {
  586. return html`
  587. <button disabled>Using default template</button>
  588. `
  589. }
  590. return html`
  591. <button onclick=${userTemplateReset}>Reset all to default</button>
  592. `
  593. };
  594. useEffect(() => {
  595. // autosave template on every change
  596. userTemplateAutosave()
  597. }, [session.value, params.value])
  598. const GrammarControl = () => (
  599. html`
  600. <div>
  601. <label for="template">Grammar</label>
  602. <textarea id="grammar" name="grammar" placeholder="Use gbnf or JSON Schema+convert" value="${params.value.grammar}" rows=4 oninput=${updateParams}/>
  603. <input type="text" name="prop-order" placeholder="order: prop1,prop2,prop3" oninput=${updateGrammarJsonSchemaPropOrder} />
  604. <button type="button" onclick=${convertJSONSchemaGrammar}>Convert JSON Schema</button>
  605. </div>
  606. `
  607. );
  608. const PromptControlFieldSet = () => (
  609. html`
  610. <fieldset>
  611. <div>
  612. <label htmlFor="prompt">Prompt</label>
  613. <textarea type="text" name="prompt" value="${session.value.prompt}" oninput=${updateSession}/>
  614. </div>
  615. </fieldset>
  616. `
  617. );
  618. const ChatConfigForm = () => (
  619. html`
  620. ${PromptControlFieldSet()}
  621. <fieldset class="two">
  622. <div>
  623. <label for="user">User name</label>
  624. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  625. </div>
  626. <div>
  627. <label for="bot">Bot name</label>
  628. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  629. </div>
  630. </fieldset>
  631. <fieldset>
  632. <div>
  633. <label for="template">Prompt template</label>
  634. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  635. </div>
  636. <div>
  637. <label for="template">Chat history template</label>
  638. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  639. </div>
  640. ${GrammarControl()}
  641. </fieldset>
  642. `
  643. );
  644. const CompletionConfigForm = () => (
  645. html`
  646. ${PromptControlFieldSet()}
  647. <fieldset>${GrammarControl()}</fieldset>
  648. `
  649. );
  650. return html`
  651. <form>
  652. <fieldset class="two">
  653. <${UserTemplateResetButton}/>
  654. <div>
  655. <label class="slim"><input type="radio" name="type" value="chat" checked=${session.value.type === "chat"} oninput=${updateSession} /> Chat</label>
  656. <label class="slim"><input type="radio" name="type" value="completion" checked=${session.value.type === "completion"} oninput=${updateSession} /> Completion</label>
  657. </div>
  658. </fieldset>
  659. ${session.value.type === 'chat' ? ChatConfigForm() : CompletionConfigForm()}
  660. <fieldset class="two">
  661. ${IntField({ label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict })}
  662. ${FloatField({ label: "Temperature", max: 2.0, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature })}
  663. ${FloatField({ label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty })}
  664. ${IntField({ label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n })}
  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. <img src="llama_cpp.png" style="width:100%"/>
  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>