index.html 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  5. <title>llama.cpp - chat</title>
  6. <style>
  7. body {
  8. background-color: #fff;
  9. color: #000;
  10. font-family: system-ui;
  11. font-size: 90%;
  12. }
  13. #container {
  14. margin: 0em auto;
  15. display: flex;
  16. flex-direction: column;
  17. justify-content: space-between;
  18. height: 100%;
  19. }
  20. header, footer {
  21. text-align: center;
  22. }
  23. main {
  24. margin: 3px;
  25. display: flex;
  26. flex-direction: column;
  27. justify-content: space-between;
  28. gap: 1em;
  29. flex-grow: 1;
  30. overflow-y: auto;
  31. border: 1px solid #ccc;
  32. border-radius: 5px;
  33. padding: 0.5em;
  34. }
  35. body {
  36. max-width: 600px;
  37. min-width: 300px;
  38. line-height: 1.2;
  39. margin: 0 auto;
  40. padding: 0 0.5em;
  41. }
  42. p {
  43. overflow-wrap: break-word;
  44. word-wrap: break-word;
  45. hyphens: auto;
  46. margin-top: 0.5em;
  47. margin-bottom: 0.5em;
  48. }
  49. #write form {
  50. margin: 1em 0 0 0;
  51. display: flex;
  52. flex-direction: column;
  53. gap: 0.5em;
  54. align-items: stretch;
  55. }
  56. .right {
  57. display: flex;
  58. flex-direction: row;
  59. gap: 0.5em;
  60. justify-content: flex-end;
  61. }
  62. fieldset {
  63. border: none;
  64. padding: 0;
  65. margin: 0;
  66. }
  67. textarea {
  68. padding: 5px;
  69. flex-grow: 1;
  70. width: 100%;
  71. }
  72. pre code {
  73. display: block;
  74. background-color: #222;
  75. color: #ddd;
  76. }
  77. code {
  78. font-family: monospace;
  79. padding: 0.1em 0.3em;
  80. border-radius: 3px;
  81. }
  82. fieldset label {
  83. margin: 0.5em 0;
  84. display: block;
  85. }
  86. </style>
  87. <script type="module">
  88. import {
  89. html, h, signal, effect, computed, render, useSignal, useEffect, useRef
  90. } from '/index.js';
  91. import { llamaComplete } from '/completion.js';
  92. const session = signal({
  93. prompt: "This is a conversation between user and llama, a friendly chatbot. respond in markdown.",
  94. template: "{{prompt}}\n\n{{history}}\n{{char}}:",
  95. historyTemplate: "{{name}}: {{message}}",
  96. transcript: [],
  97. type: "chat",
  98. char: "llama",
  99. user: "User",
  100. })
  101. const transcriptUpdate = (transcript) => {
  102. session.value = {
  103. ...session.value,
  104. transcript
  105. }
  106. }
  107. const chatStarted = computed(() => session.value.transcript.length > 0)
  108. const params = signal({
  109. n_predict: 400,
  110. temperature: 0.7,
  111. repeat_last_n: 256,
  112. repeat_penalty: 1.18,
  113. top_k: 40,
  114. top_p: 0.5,
  115. })
  116. const controller = signal(null)
  117. const generating = computed(() => controller.value == null )
  118. // simple template replace
  119. const template = (str, extraSettings) => {
  120. let settings = session.value;
  121. if (extraSettings) {
  122. settings = { ...settings, ...extraSettings };
  123. }
  124. return String(str).replaceAll(/\{\{(.*?)\}\}/g, (_, key) => template(settings[key]));
  125. }
  126. // send message to server
  127. const chat = async (msg) => {
  128. if (controller.value) {
  129. console.log('already running...');
  130. return;
  131. }
  132. controller.value = new AbortController();
  133. transcriptUpdate([...session.value.transcript, ["{{user}}", msg]])
  134. const payload = template(session.value.template, {
  135. message: msg,
  136. history: session.value.transcript.flatMap(([name, message]) => template(session.value.historyTemplate, {name, message})).join("\n"),
  137. });
  138. let currentMessage = '';
  139. const history = session.value.transcript
  140. const llamaParams = {
  141. ...params.value,
  142. prompt: payload,
  143. stop: ["</s>", template("{{char}}:"), template("{{user}}:")],
  144. }
  145. await llamaComplete(llamaParams, controller.value, (message) => {
  146. const data = message.data;
  147. currentMessage += data.content;
  148. // remove leading whitespace
  149. currentMessage = currentMessage.replace(/^\s+/, "")
  150. transcriptUpdate([...history, ["{{char}}", currentMessage]])
  151. if (data.stop) {
  152. console.log("-->", data, ' response was:', currentMessage, 'transcript state:', session.value.transcript);
  153. }
  154. })
  155. controller.value = null;
  156. }
  157. function MessageInput() {
  158. const message = useSignal("")
  159. const stop = (e) => {
  160. e.preventDefault();
  161. if (controller.value) {
  162. controller.value.abort();
  163. controller.value = null;
  164. }
  165. }
  166. const reset = (e) => {
  167. stop(e);
  168. transcriptUpdate([]);
  169. }
  170. const submit = (e) => {
  171. stop(e);
  172. chat(message.value);
  173. message.value = "";
  174. }
  175. const enterSubmits = (event) => {
  176. if (event.which === 13 && !event.shiftKey) {
  177. submit(event);
  178. }
  179. }
  180. return html`
  181. <form onsubmit=${submit}>
  182. <div>
  183. <textarea type="text" rows=2 onkeypress=${enterSubmits} value="${message}" oninput=${(e) => message.value = e.target.value} placeholder="Say something..."/>
  184. </div>
  185. <div class="right">
  186. <button type="submit" disabled=${!generating.value} >Send</button>
  187. <button onclick=${stop} disabled=${generating}>Stop</button>
  188. <button onclick=${reset}>Reset</button>
  189. </div>
  190. </form>
  191. `
  192. }
  193. const ChatLog = (props) => {
  194. const messages = session.value.transcript;
  195. const container = useRef(null)
  196. useEffect(() => {
  197. // scroll to bottom (if needed)
  198. if (container.current && container.current.scrollHeight <= container.current.scrollTop + container.current.offsetHeight + 300) {
  199. container.current.scrollTo(0, container.current.scrollHeight)
  200. }
  201. }, [messages])
  202. const chatLine = ([user, msg]) => {
  203. return html`<p key=${msg}><strong>${template(user)}:</strong> <${Markdown} text=${template(msg)} /></p>`
  204. };
  205. return html`
  206. <section id="chat" ref=${container}>
  207. ${messages.flatMap(chatLine)}
  208. </section>`;
  209. };
  210. const ConfigForm = (props) => {
  211. const updateSession = (el) => session.value = { ...session.value, [el.target.name]: el.target.value }
  212. const updateParams = (el) => params.value = { ...params.value, [el.target.name]: el.target.value }
  213. const updateParamsFloat = (el) => params.value = { ...params.value, [el.target.name]: parseFloat(el.target.value) }
  214. return html`
  215. <form>
  216. <fieldset>
  217. <div>
  218. <label for="prompt">Prompt</label>
  219. <textarea type="text" name="prompt" value="${session.value.prompt}" rows=4 oninput=${updateSession}/>
  220. </div>
  221. <div>
  222. <label for="user">User name</label>
  223. <input type="text" name="user" value="${session.value.user}" oninput=${updateSession} />
  224. </div>
  225. <div>
  226. <label for="bot">Bot name</label>
  227. <input type="text" name="char" value="${session.value.char}" oninput=${updateSession} />
  228. </div>
  229. <div>
  230. <label for="template">Prompt template</label>
  231. <textarea id="template" name="template" value="${session.value.template}" rows=4 oninput=${updateSession}/>
  232. </div>
  233. <div>
  234. <label for="template">Chat history template</label>
  235. <textarea id="template" name="historyTemplate" value="${session.value.historyTemplate}" rows=1 oninput=${updateSession}/>
  236. </div>
  237. <div>
  238. <label for="temperature">Temperature</label>
  239. <input type="range" id="temperature" min="0.0" max="1.0" step="0.01" name="temperature" value="${params.value.temperature}" oninput=${updateParamsFloat} />
  240. <span>${params.value.temperature}</span>
  241. </div>
  242. <div>
  243. <label for="nPredict">Predictions</label>
  244. <input type="range" id="nPredict" min="1" max="2048" step="1" name="n_predict" value="${params.value.n_predict}" oninput=${updateParamsFloat} />
  245. <span>${params.value.n_predict}</span>
  246. </div>
  247. <div>
  248. <label for="repeat_penalty">Penalize repeat sequence</label>
  249. <input type="range" id="repeat_penalty" min="0.0" max="2.0" step="0.01" name="repeat_penalty" value="${params.value.repeat_penalty}" oninput=${updateParamsFloat} />
  250. <span>${params.value.repeat_penalty}</span>
  251. </div>
  252. <div>
  253. <label for="repeat_last_n">Consider N tokens for penalize</label>
  254. <input type="range" id="repeat_last_n" min="0.0" max="2048" name="repeat_last_n" value="${params.value.repeat_last_n}" oninput=${updateParamsFloat} />
  255. <span>${params.value.repeat_last_n}</span>
  256. </div>
  257. </fieldset>
  258. </form>
  259. `
  260. }
  261. const Markdown = (params) => {
  262. const md = params.text
  263. .replace(/^#{1,6} (.*)$/gim, '<h3>$1</h3>')
  264. .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  265. .replace(/__(.*?)__/g, '<strong>$1</strong>')
  266. .replace(/\*(.*?)\*/g, '<em>$1</em>')
  267. .replace(/_(.*?)_/g, '<em>$1</em>')
  268. .replace(/```.*?\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  269. .replace(/`(.*?)`/g, '<code>$1</code>')
  270. .replace(/\n/gim, '<br />');
  271. return html`<span dangerouslySetInnerHTML=${{ __html: md }} />`;
  272. };
  273. function App(props) {
  274. return html`
  275. <div id="container">
  276. <header>
  277. <h1>llama.cpp</h1>
  278. </header>
  279. <main id="content">
  280. <${chatStarted.value ? ChatLog : ConfigForm} />
  281. </main>
  282. <footer id="write">
  283. <${MessageInput} />
  284. </footer>
  285. <footer>
  286. <p>Powered by <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ggml.ai">ggml.ai</a></p>
  287. </footer>
  288. </div>
  289. `;
  290. }
  291. render(h(App), document.body);
  292. </script>
  293. </head>
  294. <body>
  295. </body>
  296. </html>