simplechat.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // @ts-check
  2. // A simple completions and chat/completions test related web front end logic
  3. // by Humans for All
  4. class Roles {
  5. static System = "system";
  6. static User = "user";
  7. static Assistant = "assistant";
  8. }
  9. class ApiEP {
  10. static Chat = "chat";
  11. static Completion = "completion";
  12. }
  13. let gUsageMsg = `
  14. <p class="role-system">Usage</p>
  15. <ul class="ul1">
  16. <li> Set system prompt above, to try control ai response charactersitic, if model supports same.</li>
  17. <ul class="ul2">
  18. <li> Completion mode normally wont have a system prompt.</li>
  19. </ul>
  20. <li> Enter your query to ai assistant below.</li>
  21. <ul class="ul2">
  22. <li> Completion mode doesnt insert user/role: prefix implicitly.</li>
  23. <li> Use shift+enter for inserting enter/newline.</li>
  24. </ul>
  25. <li> Default ContextWindow = [System, Last Query+Resp, Cur Query].</li>
  26. <ul class="ul2">
  27. <li> experiment iRecentUserMsgCnt, max_tokens, model ctxt window to expand</li>
  28. </ul>
  29. </ul>
  30. `;
  31. /** @typedef {{role: string, content: string}[]} ChatMessages */
  32. class SimpleChat {
  33. constructor() {
  34. /**
  35. * Maintain in a form suitable for common LLM web service chat/completions' messages entry
  36. * @type {ChatMessages}
  37. */
  38. this.xchat = [];
  39. this.iLastSys = -1;
  40. }
  41. clear() {
  42. this.xchat = [];
  43. this.iLastSys = -1;
  44. }
  45. /**
  46. * Recent chat messages.
  47. * If iRecentUserMsgCnt < 0
  48. * Then return the full chat history
  49. * Else
  50. * Return chat messages from latest going back till the last/latest system prompt.
  51. * While keeping track that the number of user queries/messages doesnt exceed iRecentUserMsgCnt.
  52. * @param {number} iRecentUserMsgCnt
  53. */
  54. recent_chat(iRecentUserMsgCnt) {
  55. if (iRecentUserMsgCnt < 0) {
  56. return this.xchat;
  57. }
  58. if (iRecentUserMsgCnt == 0) {
  59. console.warn("WARN:SimpleChat:SC:RecentChat:iRecentUsermsgCnt of 0 means no user message/query sent");
  60. }
  61. /** @type{ChatMessages} */
  62. let rchat = [];
  63. let sysMsg = this.get_system_latest();
  64. if (sysMsg.length != 0) {
  65. rchat.push({role: Roles.System, content: sysMsg});
  66. }
  67. let iUserCnt = 0;
  68. let iStart = this.xchat.length;
  69. for(let i=this.xchat.length-1; i > this.iLastSys; i--) {
  70. if (iUserCnt >= iRecentUserMsgCnt) {
  71. break;
  72. }
  73. let msg = this.xchat[i];
  74. if (msg.role == Roles.User) {
  75. iStart = i;
  76. iUserCnt += 1;
  77. }
  78. }
  79. for(let i = iStart; i < this.xchat.length; i++) {
  80. let msg = this.xchat[i];
  81. if (msg.role == Roles.System) {
  82. continue;
  83. }
  84. rchat.push({role: msg.role, content: msg.content});
  85. }
  86. return rchat;
  87. }
  88. /**
  89. * Add an entry into xchat
  90. * @param {string} role
  91. * @param {string|undefined|null} content
  92. */
  93. add(role, content) {
  94. if ((content == undefined) || (content == null) || (content == "")) {
  95. return false;
  96. }
  97. this.xchat.push( {role: role, content: content} );
  98. if (role == Roles.System) {
  99. this.iLastSys = this.xchat.length - 1;
  100. }
  101. return true;
  102. }
  103. /**
  104. * Show the contents in the specified div
  105. * @param {HTMLDivElement} div
  106. * @param {boolean} bClear
  107. */
  108. show(div, bClear=true) {
  109. if (bClear) {
  110. div.replaceChildren();
  111. }
  112. let last = undefined;
  113. for(const x of this.recent_chat(gMe.iRecentUserMsgCnt)) {
  114. let entry = document.createElement("p");
  115. entry.className = `role-${x.role}`;
  116. entry.innerText = `${x.role}: ${x.content}`;
  117. div.appendChild(entry);
  118. last = entry;
  119. }
  120. if (last !== undefined) {
  121. last.scrollIntoView(false);
  122. } else {
  123. if (bClear) {
  124. div.innerHTML = gUsageMsg;
  125. gMe.show_info(div);
  126. }
  127. }
  128. }
  129. /**
  130. * Add needed fields wrt json object to be sent wrt LLM web services completions endpoint.
  131. * The needed fields/options are picked from a global object.
  132. * Convert the json into string.
  133. * @param {Object} obj
  134. */
  135. request_jsonstr(obj) {
  136. for(let k in gMe.chatRequestOptions) {
  137. obj[k] = gMe.chatRequestOptions[k];
  138. }
  139. return JSON.stringify(obj);
  140. }
  141. /**
  142. * Return a string form of json object suitable for chat/completions
  143. */
  144. request_messages_jsonstr() {
  145. let req = {
  146. messages: this.recent_chat(gMe.iRecentUserMsgCnt),
  147. }
  148. return this.request_jsonstr(req);
  149. }
  150. /**
  151. * Return a string form of json object suitable for /completions
  152. * @param {boolean} bInsertStandardRolePrefix Insert "<THE_ROLE>: " as prefix wrt each role's message
  153. */
  154. request_prompt_jsonstr(bInsertStandardRolePrefix) {
  155. let prompt = "";
  156. let iCnt = 0;
  157. for(const chat of this.recent_chat(gMe.iRecentUserMsgCnt)) {
  158. iCnt += 1;
  159. if (iCnt > 1) {
  160. prompt += "\n";
  161. }
  162. if (bInsertStandardRolePrefix) {
  163. prompt += `${chat.role}: `;
  164. }
  165. prompt += `${chat.content}`;
  166. }
  167. let req = {
  168. prompt: prompt,
  169. }
  170. return this.request_jsonstr(req);
  171. }
  172. /**
  173. * Allow setting of system prompt, but only at begining.
  174. * @param {string} sysPrompt
  175. * @param {string} msgTag
  176. */
  177. add_system_begin(sysPrompt, msgTag) {
  178. if (this.xchat.length == 0) {
  179. if (sysPrompt.length > 0) {
  180. return this.add(Roles.System, sysPrompt);
  181. }
  182. } else {
  183. if (sysPrompt.length > 0) {
  184. if (this.xchat[0].role !== Roles.System) {
  185. console.error(`ERRR:SimpleChat:SC:${msgTag}:You need to specify system prompt before any user query, ignoring...`);
  186. } else {
  187. if (this.xchat[0].content !== sysPrompt) {
  188. console.error(`ERRR:SimpleChat:SC:${msgTag}:You cant change system prompt, mid way through, ignoring...`);
  189. }
  190. }
  191. }
  192. }
  193. return false;
  194. }
  195. /**
  196. * Allow setting of system prompt, at any time.
  197. * @param {string} sysPrompt
  198. * @param {string} msgTag
  199. */
  200. add_system_anytime(sysPrompt, msgTag) {
  201. if (sysPrompt.length <= 0) {
  202. return false;
  203. }
  204. if (this.iLastSys < 0) {
  205. return this.add(Roles.System, sysPrompt);
  206. }
  207. let lastSys = this.xchat[this.iLastSys].content;
  208. if (lastSys !== sysPrompt) {
  209. return this.add(Roles.System, sysPrompt);
  210. }
  211. return false;
  212. }
  213. /**
  214. * Retrieve the latest system prompt.
  215. */
  216. get_system_latest() {
  217. if (this.iLastSys == -1) {
  218. return "";
  219. }
  220. let sysPrompt = this.xchat[this.iLastSys].content;
  221. return sysPrompt;
  222. }
  223. }
  224. let gBaseURL = "http://127.0.0.1:8080";
  225. let gChatURL = {
  226. 'chat': `${gBaseURL}/chat/completions`,
  227. 'completion': `${gBaseURL}/completions`,
  228. }
  229. /**
  230. * Set the class of the children, based on whether it is the idSelected or not.
  231. * @param {HTMLDivElement} elBase
  232. * @param {string} idSelected
  233. * @param {string} classSelected
  234. * @param {string} classUnSelected
  235. */
  236. function el_children_config_class(elBase, idSelected, classSelected, classUnSelected="") {
  237. for(let child of elBase.children) {
  238. if (child.id == idSelected) {
  239. child.className = classSelected;
  240. } else {
  241. child.className = classUnSelected;
  242. }
  243. }
  244. }
  245. /**
  246. * Create button and set it up.
  247. * @param {string} id
  248. * @param {(this: HTMLButtonElement, ev: MouseEvent) => any} callback
  249. * @param {string | undefined} name
  250. * @param {string | undefined} innerText
  251. */
  252. function el_create_button(id, callback, name=undefined, innerText=undefined) {
  253. if (!name) {
  254. name = id;
  255. }
  256. if (!innerText) {
  257. innerText = id;
  258. }
  259. let btn = document.createElement("button");
  260. btn.id = id;
  261. btn.name = name;
  262. btn.innerText = innerText;
  263. btn.addEventListener("click", callback);
  264. return btn;
  265. }
  266. class MultiChatUI {
  267. constructor() {
  268. /** @type {Object<string, SimpleChat>} */
  269. this.simpleChats = {};
  270. /** @type {string} */
  271. this.curChatId = "";
  272. // the ui elements
  273. this.elInSystem = /** @type{HTMLInputElement} */(document.getElementById("system-in"));
  274. this.elDivChat = /** @type{HTMLDivElement} */(document.getElementById("chat-div"));
  275. this.elBtnUser = /** @type{HTMLButtonElement} */(document.getElementById("user-btn"));
  276. this.elInUser = /** @type{HTMLInputElement} */(document.getElementById("user-in"));
  277. this.elSelectApiEP = /** @type{HTMLSelectElement} */(document.getElementById("api-ep"));
  278. this.elDivSessions = /** @type{HTMLDivElement} */(document.getElementById("sessions-div"));
  279. this.validate_element(this.elInSystem, "system-in");
  280. this.validate_element(this.elDivChat, "chat-div");
  281. this.validate_element(this.elInUser, "user-in");
  282. this.validate_element(this.elSelectApiEP, "api-ep");
  283. this.validate_element(this.elDivChat, "sessions-div");
  284. }
  285. /**
  286. * Check if the element got
  287. * @param {HTMLElement | null} el
  288. * @param {string} msgTag
  289. */
  290. validate_element(el, msgTag) {
  291. if (el == null) {
  292. throw Error(`ERRR:SimpleChat:MCUI:${msgTag} element missing in html...`);
  293. } else {
  294. console.debug(`INFO:SimpleChat:MCUI:${msgTag} Id[${el.id}] Name[${el["name"]}]`);
  295. }
  296. }
  297. /**
  298. * Reset user input ui.
  299. * * clear user input
  300. * * enable user input
  301. * * set focus to user input
  302. */
  303. ui_reset_userinput() {
  304. this.elInUser.value = "";
  305. this.elInUser.disabled = false;
  306. this.elInUser.focus();
  307. }
  308. /**
  309. * Setup the needed callbacks wrt UI, curChatId to defaultChatId and
  310. * optionally switch to specified defaultChatId.
  311. * @param {string} defaultChatId
  312. * @param {boolean} bSwitchSession
  313. */
  314. setup_ui(defaultChatId, bSwitchSession=false) {
  315. this.curChatId = defaultChatId;
  316. if (bSwitchSession) {
  317. this.handle_session_switch(this.curChatId);
  318. }
  319. this.elBtnUser.addEventListener("click", (ev)=>{
  320. if (this.elInUser.disabled) {
  321. return;
  322. }
  323. this.handle_user_submit(this.curChatId, this.elSelectApiEP.value).catch((/** @type{Error} */reason)=>{
  324. let msg = `ERRR:SimpleChat\nMCUI:HandleUserSubmit:${this.curChatId}\n${reason.name}:${reason.message}`;
  325. console.debug(msg.replace("\n", ":"));
  326. alert(msg);
  327. this.ui_reset_userinput();
  328. });
  329. });
  330. this.elInUser.addEventListener("keyup", (ev)=> {
  331. // allow user to insert enter into their message using shift+enter.
  332. // while just pressing enter key will lead to submitting.
  333. if ((ev.key === "Enter") && (!ev.shiftKey)) {
  334. let value = this.elInUser.value;
  335. this.elInUser.value = value.substring(0,value.length-1);
  336. this.elBtnUser.click();
  337. ev.preventDefault();
  338. }
  339. });
  340. this.elInSystem.addEventListener("keyup", (ev)=> {
  341. // allow user to insert enter into the system prompt using shift+enter.
  342. // while just pressing enter key will lead to setting the system prompt.
  343. if ((ev.key === "Enter") && (!ev.shiftKey)) {
  344. let chat = this.simpleChats[this.curChatId];
  345. chat.add_system_anytime(this.elInSystem.value, this.curChatId);
  346. chat.show(this.elDivChat);
  347. ev.preventDefault();
  348. }
  349. });
  350. }
  351. /**
  352. * Setup a new chat session and optionally switch to it.
  353. * @param {string} chatId
  354. * @param {boolean} bSwitchSession
  355. */
  356. new_chat_session(chatId, bSwitchSession=false) {
  357. this.simpleChats[chatId] = new SimpleChat();
  358. if (bSwitchSession) {
  359. this.handle_session_switch(chatId);
  360. }
  361. }
  362. /**
  363. * Try read json response early, if available.
  364. * @param {Response} resp
  365. */
  366. async read_json_early(resp) {
  367. if (!resp.body) {
  368. throw Error("ERRR:SimpleChat:MCUI:ReadJsonEarly:No body...");
  369. }
  370. let tdUtf8 = new TextDecoder("utf-8");
  371. let rr = resp.body.getReader();
  372. let gotBody = "";
  373. while(true) {
  374. let { value: cur, done: done} = await rr.read();
  375. let curBody = tdUtf8.decode(cur);
  376. console.debug("DBUG:SC:PART:", curBody);
  377. gotBody += curBody;
  378. if (done) {
  379. break;
  380. }
  381. }
  382. return JSON.parse(gotBody);
  383. }
  384. /**
  385. * Handle user query submit request, wrt specified chat session.
  386. * @param {string} chatId
  387. * @param {string} apiEP
  388. */
  389. async handle_user_submit(chatId, apiEP) {
  390. let chat = this.simpleChats[chatId];
  391. // In completion mode, if configured, clear any previous chat history.
  392. // So if user wants to simulate a multi-chat based completion query,
  393. // they will have to enter the full thing, as a suitable multiline
  394. // user input/query.
  395. if ((apiEP == ApiEP.Completion) && (gMe.bCompletionFreshChatAlways)) {
  396. chat.clear();
  397. }
  398. chat.add_system_anytime(this.elInSystem.value, chatId);
  399. let content = this.elInUser.value;
  400. if (!chat.add(Roles.User, content)) {
  401. console.debug(`WARN:SimpleChat:MCUI:${chatId}:HandleUserSubmit:Ignoring empty user input...`);
  402. return;
  403. }
  404. chat.show(this.elDivChat);
  405. let theBody;
  406. let theUrl = gChatURL[apiEP]
  407. if (apiEP == ApiEP.Chat) {
  408. theBody = chat.request_messages_jsonstr();
  409. } else {
  410. theBody = chat.request_prompt_jsonstr(gMe.bCompletionInsertStandardRolePrefix);
  411. }
  412. this.elInUser.value = "working...";
  413. this.elInUser.disabled = true;
  414. console.debug(`DBUG:SimpleChat:MCUI:${chatId}:HandleUserSubmit:${theUrl}:ReqBody:${theBody}`);
  415. let resp = await fetch(theUrl, {
  416. method: "POST",
  417. headers: {
  418. "Content-Type": "application/json",
  419. },
  420. body: theBody,
  421. });
  422. let respBody = await resp.json();
  423. //let respBody = await this.read_json_early(resp);
  424. console.debug(`DBUG:SimpleChat:MCUI:${chatId}:HandleUserSubmit:RespBody:${JSON.stringify(respBody)}`);
  425. let assistantMsg;
  426. if (apiEP == ApiEP.Chat) {
  427. assistantMsg = respBody["choices"][0]["message"]["content"];
  428. } else {
  429. try {
  430. assistantMsg = respBody["choices"][0]["text"];
  431. } catch {
  432. assistantMsg = respBody["content"];
  433. }
  434. }
  435. chat.add(Roles.Assistant, assistantMsg);
  436. if (chatId == this.curChatId) {
  437. chat.show(this.elDivChat);
  438. } else {
  439. console.debug(`DBUG:SimpleChat:MCUI:HandleUserSubmit:ChatId has changed:[${chatId}] [${this.curChatId}]`);
  440. }
  441. this.ui_reset_userinput();
  442. }
  443. /**
  444. * Show buttons for NewChat and available chat sessions, in the passed elDiv.
  445. * If elDiv is undefined/null, then use this.elDivSessions.
  446. * Take care of highlighting the selected chat-session's btn.
  447. * @param {HTMLDivElement | undefined} elDiv
  448. */
  449. show_sessions(elDiv=undefined) {
  450. if (!elDiv) {
  451. elDiv = this.elDivSessions;
  452. }
  453. elDiv.replaceChildren();
  454. // Btn for creating new chat session
  455. let btnNew = el_create_button("New CHAT", (ev)=> {
  456. if (this.elInUser.disabled) {
  457. console.error(`ERRR:SimpleChat:MCUI:NewChat:Current session [${this.curChatId}] awaiting response, ignoring request...`);
  458. alert("ERRR:SimpleChat\nMCUI:NewChat\nWait for response to pending query, before starting new chat session");
  459. return;
  460. }
  461. let chatId = `Chat${Object.keys(this.simpleChats).length}`;
  462. let chatIdGot = prompt("INFO:SimpleChat\nMCUI:NewChat\nEnter id for new chat session", chatId);
  463. if (!chatIdGot) {
  464. console.error("ERRR:SimpleChat:MCUI:NewChat:Skipping based on user request...");
  465. return;
  466. }
  467. this.new_chat_session(chatIdGot, true);
  468. this.create_session_btn(elDiv, chatIdGot);
  469. el_children_config_class(elDiv, chatIdGot, "session-selected", "");
  470. });
  471. elDiv.appendChild(btnNew);
  472. // Btns for existing chat sessions
  473. let chatIds = Object.keys(this.simpleChats);
  474. for(let cid of chatIds) {
  475. let btn = this.create_session_btn(elDiv, cid);
  476. if (cid == this.curChatId) {
  477. btn.className = "session-selected";
  478. }
  479. }
  480. }
  481. create_session_btn(elDiv, cid) {
  482. let btn = el_create_button(cid, (ev)=>{
  483. let target = /** @type{HTMLButtonElement} */(ev.target);
  484. console.debug(`DBUG:SimpleChat:MCUI:SessionClick:${target.id}`);
  485. if (this.elInUser.disabled) {
  486. console.error(`ERRR:SimpleChat:MCUI:SessionClick:${target.id}:Current session [${this.curChatId}] awaiting response, ignoring switch...`);
  487. alert("ERRR:SimpleChat\nMCUI:SessionClick\nWait for response to pending query, before switching");
  488. return;
  489. }
  490. this.handle_session_switch(target.id);
  491. el_children_config_class(elDiv, target.id, "session-selected", "");
  492. });
  493. elDiv.appendChild(btn);
  494. return btn;
  495. }
  496. /**
  497. * Switch ui to the specified chatId and set curChatId to same.
  498. * @param {string} chatId
  499. */
  500. async handle_session_switch(chatId) {
  501. let chat = this.simpleChats[chatId];
  502. if (chat == undefined) {
  503. console.error(`ERRR:SimpleChat:MCUI:HandleSessionSwitch:${chatId} missing...`);
  504. return;
  505. }
  506. this.elInSystem.value = chat.get_system_latest();
  507. this.elInUser.value = "";
  508. chat.show(this.elDivChat);
  509. this.elInUser.focus();
  510. this.curChatId = chatId;
  511. console.log(`INFO:SimpleChat:MCUI:HandleSessionSwitch:${chatId} entered...`);
  512. }
  513. }
  514. class Me {
  515. constructor() {
  516. this.defaultChatIds = [ "Default", "Other" ];
  517. this.multiChat = new MultiChatUI();
  518. this.bCompletionFreshChatAlways = true;
  519. this.bCompletionInsertStandardRolePrefix = false;
  520. this.iRecentUserMsgCnt = 2;
  521. // Add needed fields wrt json object to be sent wrt LLM web services completions endpoint.
  522. this.chatRequestOptions = {
  523. "temperature": 0.7,
  524. "max_tokens": 1024,
  525. "frequency_penalty": 1.2,
  526. "presence_penalty": 1.2,
  527. "n_predict": 1024
  528. };
  529. }
  530. /**
  531. * @param {HTMLDivElement} elDiv
  532. */
  533. show_info(elDiv) {
  534. var p = document.createElement("p");
  535. p.innerText = "Settings (devel-tools-console gMe)";
  536. p.className = "role-system";
  537. elDiv.appendChild(p);
  538. var p = document.createElement("p");
  539. p.innerText = `bCompletionFreshChatAlways:${this.bCompletionFreshChatAlways}`;
  540. elDiv.appendChild(p);
  541. p = document.createElement("p");
  542. p.innerText = `bCompletionInsertStandardRolePrefix:${this.bCompletionInsertStandardRolePrefix}`;
  543. elDiv.appendChild(p);
  544. p = document.createElement("p");
  545. p.innerText = `iRecentUserMsgCnt:${this.iRecentUserMsgCnt}`;
  546. elDiv.appendChild(p);
  547. p = document.createElement("p");
  548. p.innerText = `chatRequestOptions:${JSON.stringify(this.chatRequestOptions)}`;
  549. elDiv.appendChild(p);
  550. }
  551. }
  552. /** @type {Me} */
  553. let gMe;
  554. function startme() {
  555. console.log("INFO:SimpleChat:StartMe:Starting...");
  556. gMe = new Me();
  557. for (let cid of gMe.defaultChatIds) {
  558. gMe.multiChat.new_chat_session(cid);
  559. }
  560. gMe.multiChat.setup_ui(gMe.defaultChatIds[0], true);
  561. gMe.multiChat.show_sessions();
  562. }
  563. document.addEventListener("DOMContentLoaded", startme);