1
0

index.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. textarea {
  89. padding: 5px;
  90. flex-grow: 1;
  91. width: 100%;
  92. }
  93. pre code {
  94. display: block;
  95. background-color: #222;
  96. color: #ddd;
  97. }
  98. code {
  99. font-family: monospace;
  100. padding: 0.1em 0.3em;
  101. border-radius: 3px;
  102. }
  103. fieldset label {
  104. margin: 0.5em 0;
  105. display: block;
  106. }
  107. header, footer {
  108. text-align: center;
  109. }
  110. footer {
  111. font-size: 80%;
  112. color: #888;
  113. }
  114. </style>
  115. <script type="module">
  116. import {
  117. html, h, signal, effect, computed, render, useSignal, useEffect, useRef
  118. } from '/index.js';
  119. import { llama } from '/completion.js';
  120. const session = signal({
  121. prompt: "This is a conversation between user and llama, a friendly chatbot. respond in simple markdown.",
  122. template: "{{prompt}}\n\n{{history}}\n{{char}}:",
  123. historyTemplate: "{{name}}: {{message}}",
  124. transcript: [],
  125. type: "chat",
  126. char: "llama",
  127. user: "User",
  128. })
  129. const params = signal({
  130. n_predict: 400,
  131. temperature: 0.7,
  132. repeat_last_n: 256, // 0 = disable penalty, -1 = context size
  133. repeat_penalty: 1.18, // 1.0 = disabled
  134. top_k: 40, // <= 0 to use vocab size
  135. top_p: 0.5, // 1.0 = disabled
  136. tfs_z: 1.0, // 1.0 = disabled
  137. typical_p: 1.0, // 1.0 = disabled
  138. presence_penalty: 0.0, // 0.0 = disabled
  139. frequency_penalty: 0.0, // 0.0 = disabled
  140. mirostat: 0, // 0/1/2
  141. mirostat_tau: 5, // target entropy
  142. mirostat_eta: 0.1, // learning rate
  143. })
  144. const llamaStats = signal(null)
  145. const controller = signal(null)
  146. const generating = computed(() => controller.value == null )
  147. const chatStarted = computed(() => session.value.transcript.length > 0)
  148. const transcriptUpdate = (transcript) => {
  149. session.value = {
  150. ...session.value,
  151. transcript
  152. }
  153. }
  154. // simple template replace
  155. const template = (str, extraSettings) => {
  156. let settings = session.value;
  157. if (extraSettings) {
  158. settings = { ...settings, ...extraSettings };
  159. }
  160. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  161. }
  162. // send message to server
  163. const chat = async (msg) => {
  164. if (controller.value) {
  165. console.log('already running...');
  166. return;
  167. }
  168. controller.value = new AbortController();
  169. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  170. const prompt = template(session.value.template, {
  171. message: msg,
  172. history: session.value.transcript.flatMap(([name, message]) => template(session.value.historyTemplate, {name, message})).join("\n"),
  173. });
  174. let currentMessage = '';
  175. const history = session.value.transcript
  176. const llamaParams = {
  177. ...params.value,
  178. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  179. }
  180. for await (const chunk of llama(prompt, llamaParams, { controller: controller.value })) {
  181. const data = chunk.data;
  182. currentMessage += data.content;
  183. // remove leading whitespace
  184. currentMessage = currentMessage.replace(/^\s+/, "")
  185. transcriptUpdate([...history, ["{{char}}", currentMessage]])
  186. if (data.stop) {
  187. console.log("Completion finished: '", currentMessage, "', summary: ", data);
  188. }
  189. if (data.timings) {
  190. llamaStats.value = data.timings;
  191. }
  192. }
  193. controller.value = null;
  194. }
  195. function MessageInput() {
  196. const message = useSignal("")
  197. const stop = (e) => {
  198. e.preventDefault();
  199. if (controller.value) {
  200. controller.value.abort();
  201. controller.value = null;
  202. }
  203. }
  204. const reset = (e) => {
  205. stop(e);
  206. transcriptUpdate([]);
  207. }
  208. const submit = (e) => {
  209. stop(e);
  210. chat(message.value);
  211. message.value = "";
  212. }
  213. const enterSubmits = (event) => {
  214. if (event.which === 13 && !event.shiftKey) {
  215. submit(event);
  216. }
  217. }
  218. return html`
  219. <form onsubmit=${submit}>
  220. <div>
  221. <textarea type="text" rows=2 onkeypress=${enterSubmits} value="${message}" oninput=${(e) => message.value = e.target.value} placeholder="Say something..."/>
  222. </div>
  223. <div class="right">
  224. <button type="submit" disabled=${!generating.value} >Send</button>
  225. <button onclick=${stop} disabled=${generating}>Stop</button>
  226. <button onclick=${reset}>Reset</button>
  227. </div>
  228. </form>
  229. `
  230. }
  231. const ChatLog = (props) => {
  232. const messages = session.value.transcript;
  233. const container = useRef(null)
  234. useEffect(() => {
  235. // scroll to bottom (if needed)
  236. if (container.current && container.current.scrollHeight <= container.current.scrollTop + container.current.offsetHeight + 300) {
  237. container.current.scrollTo(0, container.current.scrollHeight)
  238. }
  239. }, [messages])
  240. const chatLine = ([user, msg]) => {
  241. return html`<p key=${msg}><strong>${template(user)}:</strong> <${Markdownish} text=${template(msg)} /></p>`
  242. };
  243. return html`
  244. <section id="chat" ref=${container}>
  245. ${messages.flatMap(chatLine)}
  246. </section>`;
  247. };
  248. const ConfigForm = (props) => {
  249. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  250. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  251. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  252. const updateParamsInt = (el) => params.value = { ...params.value, [el.target.name]: Math.floor(parseFloat(el.target.value)) }
  253. const FloatField = ({label, max, min, name, step, value}) => {
  254. return html`
  255. <div>
  256. <label for="${name}">${label}</label>
  257. <input type="range" id="${name}" min="${min}" max="${max}" step="${step}" name="${name}" value="${value}" oninput=${updateParamsFloat} />
  258. <span>${value}</span>
  259. </div>
  260. `
  261. };
  262. const IntField = ({label, max, min, name, value}) => {
  263. return html`
  264. <div>
  265. <label for="${name}">${label}</label>
  266. <input type="range" id="${name}" min="${min}" max="${max}" name="${name}" value="${value}" oninput=${updateParamsInt} />
  267. <span>${value}</span>
  268. </div>
  269. `
  270. };
  271. return html`
  272. <form>
  273. <fieldset>
  274. <div>
  275. <label for="prompt">Prompt</label>
  276. <textarea type="text" name="prompt" value="${session.value.prompt}" rows=4 oninput=${updateSession}/>
  277. </div>
  278. </fieldset>
  279. <fieldset class="two">
  280. <div>
  281. <label for="user">User name</label>
  282. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  283. </div>
  284. <div>
  285. <label for="bot">Bot name</label>
  286. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  287. </div>
  288. </fieldset>
  289. <fieldset>
  290. <div>
  291. <label for="template">Prompt template</label>
  292. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  293. </div>
  294. <div>
  295. <label for="template">Chat history template</label>
  296. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  297. </div>
  298. </fieldset>
  299. <fieldset class="two">
  300. ${IntField({label: "Predictions", max: 2048, min: -1, name: "n_predict", value: params.value.n_predict})}
  301. ${FloatField({label: "Temperature", max: 1.5, min: 0.0, name: "temperature", step: 0.01, value: params.value.temperature})}
  302. ${FloatField({label: "Penalize repeat sequence", max: 2.0, min: 0.0, name: "repeat_penalty", step: 0.01, value: params.value.repeat_penalty})}
  303. ${IntField({label: "Consider N tokens for penalize", max: 2048, min: 0, name: "repeat_last_n", value: params.value.repeat_last_n})}
  304. ${IntField({label: "Top-K sampling", max: 100, min: -1, name: "top_k", value: params.value.top_k})}
  305. ${FloatField({label: "Top-P sampling", max: 1.0, min: 0.0, name: "top_p", step: 0.01, value: params.value.top_p})}
  306. </fieldset>
  307. <details>
  308. <summary>More options</summary>
  309. <fieldset class="two">
  310. ${FloatField({label: "TFS-Z", max: 1.0, min: 0.0, name: "tfs_z", step: 0.01, value: params.value.tfs_z})}
  311. ${FloatField({label: "Typical P", max: 1.0, min: 0.0, name: "typical_p", step: 0.01, value: params.value.typical_p})}
  312. ${FloatField({label: "Presence penalty", max: 1.0, min: 0.0, name: "presence_penalty", step: 0.01, value: params.value.presence_penalty})}
  313. ${FloatField({label: "Frequency penalty", max: 1.0, min: 0.0, name: "frequency_penalty", step: 0.01, value: params.value.frequency_penalty})}
  314. </fieldset>
  315. <hr />
  316. <fieldset class="three">
  317. <div>
  318. <label><input type="radio" name="mirostat" value="0" checked=${params.value.mirostat == 0} oninput=${updateParamsInt} /> no Mirostat</label>
  319. <label><input type="radio" name="mirostat" value="1" checked=${params.value.mirostat == 1} oninput=${updateParamsInt} /> Mirostat v1</label>
  320. <label><input type="radio" name="mirostat" value="2" checked=${params.value.mirostat == 2} oninput=${updateParamsInt} /> Mirostat v2</label>
  321. </div>
  322. ${FloatField({label: "Mirostat tau", max: 10.0, min: 0.0, name: "mirostat_tau", step: 0.01, value: params.value.mirostat_tau})}
  323. ${FloatField({label: "Mirostat eta", max: 1.0, min: 0.0, name: "mirostat_eta", step: 0.01, value: params.value.mirostat_eta})}
  324. </fieldset>
  325. </details>
  326. </form>
  327. `
  328. }
  329. // poor mans markdown replacement
  330. const Markdownish = (params) => {
  331. const md = params.text
  332. .replace(/&/g, '&amp;')
  333. .replace(/</g, '&lt;')
  334. .replace(/>/g, '&gt;')
  335. .replace(/^#{1,6} (.*)$/gim, '<h3>$1</h3>')
  336. .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  337. .replace(/__(.*?)__/g, '<strong>$1</strong>')
  338. .replace(/\*(.*?)\*/g, '<em>$1</em>')
  339. .replace(/_(.*?)_/g, '<em>$1</em>')
  340. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  341. .replace(/`(.*?)`/g, '<code>$1</code>')
  342. .replace(/\n/gim, '<br />');
  343. return html`<span dangerouslySetInnerHTML=${{ __html: md }} />`;
  344. };
  345. const ModelGenerationInfo = (params) => {
  346. if (!llamaStats.value) {
  347. return html`<span/>`
  348. }
  349. return html`
  350. <span>
  351. ${llamaStats.value.predicted_per_token_ms.toFixed()}ms per token, ${llamaStats.value.predicted_per_second.toFixed(2)} tokens per second
  352. </span>
  353. `
  354. }
  355. function App(props) {
  356. return html`
  357. <div id="container">
  358. <header>
  359. <h1>llama.cpp</h1>
  360. </header>
  361. <main id="content">
  362. <${chatStarted.value ? ChatLog : ConfigForm} />
  363. </main>
  364. <section id="write">
  365. <${MessageInput} />
  366. </section>
  367. <footer>
  368. <p><${ModelGenerationInfo} /></p>
  369. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a>.</p>
  370. </footer>
  371. </div>
  372. `;
  373. }
  374. render(h(App), document.body);
  375. </script>
  376. </head>
  377. <body>
  378. </body>
  379. </html>