index.html 33 KB

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