chat.v1.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. const colorThemes = document.querySelectorAll('[name="theme"]');
  2. const markdown = window.markdownit();
  3. const message_box = document.getElementById(`messages`);
  4. const message_input = document.getElementById(`message-input`);
  5. const box_conversations = document.querySelector(`.top`);
  6. const spinner = box_conversations.querySelector(".spinner");
  7. const stop_generating = document.querySelector(`.stop_generating`);
  8. const regenerate = document.querySelector(`.regenerate`);
  9. const send_button = document.querySelector(`#send-button`);
  10. let prompt_lock = false;
  11. hljs.addPlugin(new CopyButtonPlugin());
  12. message_input.addEventListener("blur", () => {
  13. window.scrollTo(0, 0);
  14. });
  15. message_input.addEventListener("focus", () => {
  16. document.documentElement.scrollTop = document.documentElement.scrollHeight;
  17. });
  18. const markdown_render = (content) => {
  19. return markdown.render(content).replace("<a href=", '<a target="_blank" href=').replace('<code>', '<code class="language-plaintext">')
  20. }
  21. const delete_conversations = async () => {
  22. localStorage.clear();
  23. await new_conversation();
  24. };
  25. const handle_ask = async () => {
  26. message_input.style.height = `80px`;
  27. message_input.focus();
  28. window.scrollTo(0, 0);
  29. message = message_input.value
  30. if (message.length > 0) {
  31. message_input.value = '';
  32. await add_conversation(window.conversation_id, message);
  33. await add_message(window.conversation_id, "user", message);
  34. window.token = message_id();
  35. message_box.innerHTML += `
  36. <div class="message">
  37. <div class="user">
  38. ${user_image}
  39. <i class="fa-regular fa-phone-arrow-up-right"></i>
  40. </div>
  41. <div class="content" id="user_${token}">
  42. ${markdown_render(message)}
  43. </div>
  44. </div>
  45. `;
  46. await ask_gpt();
  47. }
  48. };
  49. const remove_cancel_button = async () => {
  50. stop_generating.classList.add(`stop_generating-hiding`);
  51. setTimeout(() => {
  52. stop_generating.classList.remove(`stop_generating-hiding`);
  53. stop_generating.classList.add(`stop_generating-hidden`);
  54. }, 300);
  55. };
  56. const ask_gpt = async () => {
  57. regenerate.classList.add(`regenerate-hidden`);
  58. messages = await get_messages(window.conversation_id);
  59. window.scrollTo(0, 0);
  60. window.controller = new AbortController();
  61. jailbreak = document.getElementById("jailbreak");
  62. provider = document.getElementById("provider");
  63. model = document.getElementById("model");
  64. prompt_lock = true;
  65. window.text = ``;
  66. stop_generating.classList.remove(`stop_generating-hidden`);
  67. message_box.scrollTop = message_box.scrollHeight;
  68. window.scrollTo(0, 0);
  69. await new Promise((r) => setTimeout(r, 500));
  70. window.scrollTo(0, 0);
  71. message_box.innerHTML += `
  72. <div class="message">
  73. <div class="assistant">
  74. ${gpt_image} <i class="fa-regular fa-phone-arrow-down-left"></i>
  75. </div>
  76. <div class="content" id="gpt_${window.token}">
  77. <div id="cursor"></div>
  78. </div>
  79. </div>
  80. `;
  81. message_box.scrollTop = message_box.scrollHeight;
  82. window.scrollTo(0, 0);
  83. try {
  84. const response = await fetch(`/backend-api/v2/conversation`, {
  85. method: `POST`,
  86. signal: window.controller.signal,
  87. headers: {
  88. 'content-type': `application/json`,
  89. accept: `text/event-stream`,
  90. },
  91. body: JSON.stringify({
  92. conversation_id: window.conversation_id,
  93. action: `_ask`,
  94. model: model.options[model.selectedIndex].value,
  95. jailbreak: jailbreak.options[jailbreak.selectedIndex].value,
  96. internet_access: document.getElementById(`switch`).checked,
  97. provider: provider.options[provider.selectedIndex].value,
  98. meta: {
  99. id: window.token,
  100. content: {
  101. content_type: `text`,
  102. parts: messages,
  103. },
  104. },
  105. }),
  106. });
  107. await new Promise((r) => setTimeout(r, 1000));
  108. window.scrollTo(0, 0);
  109. const reader = response.body.getReader();
  110. while (true) {
  111. const { value, done } = await reader.read();
  112. if (done) break;
  113. chunk = new TextDecoder().decode(value);
  114. text += chunk;
  115. document.getElementById(`gpt_${window.token}`).innerHTML = markdown_render(text);
  116. document.querySelectorAll(`code`).forEach((el) => {
  117. hljs.highlightElement(el);
  118. });
  119. window.scrollTo(0, 0);
  120. message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
  121. }
  122. if (text.includes(`G4F_ERROR`)) {
  123. console.log("response", text);
  124. document.getElementById(`gpt_${window.token}`).innerHTML = "An error occured, please try again, if the problem persists, please use a other model or provider";
  125. }
  126. } catch (e) {
  127. console.log(e);
  128. let cursorDiv = document.getElementById(`cursor`);
  129. if (cursorDiv) cursorDiv.parentNode.removeChild(cursorDiv);
  130. if (e.name != `AbortError`) {
  131. text = `oops ! something went wrong, please try again / reload. [stacktrace in console]`;
  132. document.getElementById(`gpt_${window.token}`).innerHTML = text;
  133. } else {
  134. document.getElementById(`gpt_${window.token}`).innerHTML += ` [aborted]`;
  135. text += ` [aborted]`
  136. }
  137. }
  138. add_message(window.conversation_id, "assistant", text);
  139. message_box.scrollTop = message_box.scrollHeight;
  140. await remove_cancel_button();
  141. prompt_lock = false;
  142. window.scrollTo(0, 0);
  143. await load_conversations(20, 0);
  144. regenerate.classList.remove(`regenerate-hidden`);
  145. };
  146. const clear_conversations = async () => {
  147. const elements = box_conversations.childNodes;
  148. let index = elements.length;
  149. if (index > 0) {
  150. while (index--) {
  151. const element = elements[index];
  152. if (
  153. element.nodeType === Node.ELEMENT_NODE &&
  154. element.tagName.toLowerCase() !== `button`
  155. ) {
  156. box_conversations.removeChild(element);
  157. }
  158. }
  159. }
  160. };
  161. const clear_conversation = async () => {
  162. let messages = message_box.getElementsByTagName(`div`);
  163. while (messages.length > 0) {
  164. message_box.removeChild(messages[0]);
  165. }
  166. };
  167. const show_option = async (conversation_id) => {
  168. const conv = document.getElementById(`conv-${conversation_id}`);
  169. const yes = document.getElementById(`yes-${conversation_id}`);
  170. const not = document.getElementById(`not-${conversation_id}`);
  171. conv.style.display = `none`;
  172. yes.style.display = `block`;
  173. not.style.display = `block`;
  174. };
  175. const hide_option = async (conversation_id) => {
  176. const conv = document.getElementById(`conv-${conversation_id}`);
  177. const yes = document.getElementById(`yes-${conversation_id}`);
  178. const not = document.getElementById(`not-${conversation_id}`);
  179. conv.style.display = `block`;
  180. yes.style.display = `none`;
  181. not.style.display = `none`;
  182. };
  183. const delete_conversation = async (conversation_id) => {
  184. localStorage.removeItem(`conversation:${conversation_id}`);
  185. const conversation = document.getElementById(`convo-${conversation_id}`);
  186. conversation.remove();
  187. if (window.conversation_id == conversation_id) {
  188. await new_conversation();
  189. }
  190. await load_conversations(20, 0, true);
  191. };
  192. const set_conversation = async (conversation_id) => {
  193. history.pushState({}, null, `/chat/${conversation_id}`);
  194. window.conversation_id = conversation_id;
  195. await clear_conversation();
  196. await load_conversation(conversation_id);
  197. await load_conversations(20, 0, true);
  198. };
  199. const new_conversation = async () => {
  200. history.pushState({}, null, `/chat/`);
  201. window.conversation_id = uuid();
  202. await clear_conversation();
  203. await load_conversations(20, 0, true);
  204. await say_hello()
  205. };
  206. const load_conversation = async (conversation_id) => {
  207. let messages = await get_messages(conversation_id);
  208. for (item of messages) {
  209. message_box.innerHTML += `
  210. <div class="message">
  211. <div class=${item.role == "assistant" ? "assistant" : "user"}>
  212. ${item.role == "assistant" ? gpt_image : user_image}
  213. ${item.role == "assistant"
  214. ? `<i class="fa-regular fa-phone-arrow-down-left"></i>`
  215. : `<i class="fa-regular fa-phone-arrow-up-right"></i>`
  216. }
  217. </div>
  218. <div class="content">
  219. ${item.role == "assistant"
  220. ? markdown_render(item.content)
  221. : item.content
  222. }
  223. </div>
  224. </div>
  225. `;
  226. }
  227. document.querySelectorAll(`code`).forEach((el) => {
  228. hljs.highlightElement(el);
  229. });
  230. message_box.scrollTo({ top: message_box.scrollHeight, behavior: "smooth" });
  231. setTimeout(() => {
  232. message_box.scrollTop = message_box.scrollHeight;
  233. }, 500);
  234. };
  235. const get_conversation = async (conversation_id) => {
  236. let conversation = await JSON.parse(
  237. localStorage.getItem(`conversation:${conversation_id}`)
  238. );
  239. return conversation;
  240. };
  241. const get_messages = async (conversation_id) => {
  242. let conversation = await get_conversation(conversation_id);
  243. return conversation.items;
  244. };
  245. const add_conversation = async (conversation_id, content) => {
  246. if (content.length > 17) {
  247. title = content.substring(0, 17) + '...'
  248. } else {
  249. title = content + '&nbsp;'.repeat(19 - content.length)
  250. }
  251. if (localStorage.getItem(`conversation:${conversation_id}`) == null) {
  252. localStorage.setItem(
  253. `conversation:${conversation_id}`,
  254. JSON.stringify({
  255. id: conversation_id,
  256. title: title,
  257. items: [],
  258. })
  259. );
  260. }
  261. history.pushState({}, null, `/chat/${conversation_id}`);
  262. };
  263. const remove_last_message = async (conversation_id) => {
  264. const conversation = await get_conversation(conversation_id)
  265. conversation.items.pop();
  266. localStorage.setItem(
  267. `conversation:${conversation_id}`,
  268. JSON.stringify(conversation)
  269. );
  270. };
  271. const add_message = async (conversation_id, role, content) => {
  272. const conversation = await get_conversation(conversation_id);
  273. conversation.items.push({
  274. role: role,
  275. content: content,
  276. });
  277. localStorage.setItem(
  278. `conversation:${conversation_id}`,
  279. JSON.stringify(conversation)
  280. );
  281. };
  282. const load_conversations = async (limit, offset, loader) => {
  283. let conversations = [];
  284. for (let i = 0; i < localStorage.length; i++) {
  285. if (localStorage.key(i).startsWith("conversation:")) {
  286. let conversation = localStorage.getItem(localStorage.key(i));
  287. conversations.push(JSON.parse(conversation));
  288. }
  289. }
  290. await clear_conversations();
  291. for (conversation of conversations) {
  292. box_conversations.innerHTML += `
  293. <div class="convo" id="convo-${conversation.id}">
  294. <div class="left" onclick="set_conversation('${conversation.id}')">
  295. <i class="fa-regular fa-comments"></i>
  296. <span class="convo-title">${conversation.title}</span>
  297. </div>
  298. <i onclick="show_option('${conversation.id}')" class="fa-regular fa-trash" id="conv-${conversation.id}"></i>
  299. <i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-check" id="yes-${conversation.id}" style="display:none;"></i>
  300. <i onclick="hide_option('${conversation.id}')" class="fa-regular fa-x" id="not-${conversation.id}" style="display:none;"></i>
  301. </div>
  302. `;
  303. }
  304. document.querySelectorAll(`code`).forEach((el) => {
  305. hljs.highlightElement(el);
  306. });
  307. };
  308. document.getElementById(`cancelButton`).addEventListener(`click`, async () => {
  309. window.controller.abort();
  310. console.log(`aborted ${window.conversation_id}`);
  311. });
  312. document.getElementById(`regenerateButton`).addEventListener(`click`, async () => {
  313. await remove_last_message(window.conversation_id);
  314. window.token = message_id();
  315. await ask_gpt();
  316. });
  317. const uuid = () => {
  318. return `xxxxxxxx-xxxx-4xxx-yxxx-${Date.now().toString(16)}`.replace(
  319. /[xy]/g,
  320. function (c) {
  321. var r = (Math.random() * 16) | 0,
  322. v = c == "x" ? r : (r & 0x3) | 0x8;
  323. return v.toString(16);
  324. }
  325. );
  326. };
  327. const message_id = () => {
  328. random_bytes = (Math.floor(Math.random() * 1338377565) + 2956589730).toString(
  329. 2
  330. );
  331. unix = Math.floor(Date.now() / 1000).toString(2);
  332. return BigInt(`0b${unix}${random_bytes}`).toString();
  333. };
  334. document.querySelector(".mobile-sidebar").addEventListener("click", (event) => {
  335. const sidebar = document.querySelector(".conversations");
  336. if (sidebar.classList.contains("shown")) {
  337. sidebar.classList.remove("shown");
  338. event.target.classList.remove("rotated");
  339. } else {
  340. sidebar.classList.add("shown");
  341. event.target.classList.add("rotated");
  342. }
  343. window.scrollTo(0, 0);
  344. });
  345. const register_settings_localstorage = async () => {
  346. settings_ids = ["switch", "model", "jailbreak"];
  347. settings_elements = settings_ids.map((id) => document.getElementById(id));
  348. settings_elements.map((element) =>
  349. element.addEventListener(`change`, async (event) => {
  350. switch (event.target.type) {
  351. case "checkbox":
  352. localStorage.setItem(event.target.id, event.target.checked);
  353. break;
  354. case "select-one":
  355. localStorage.setItem(event.target.id, event.target.selectedIndex);
  356. break;
  357. default:
  358. console.warn("Unresolved element type");
  359. }
  360. })
  361. );
  362. };
  363. const load_settings_localstorage = async () => {
  364. settings_ids = ["switch", "model", "jailbreak"];
  365. settings_elements = settings_ids.map((id) => document.getElementById(id));
  366. settings_elements.map((element) => {
  367. if (localStorage.getItem(element.id)) {
  368. switch (element.type) {
  369. case "checkbox":
  370. element.checked = localStorage.getItem(element.id) === "true";
  371. break;
  372. case "select-one":
  373. element.selectedIndex = parseInt(localStorage.getItem(element.id));
  374. break;
  375. default:
  376. console.warn("Unresolved element type");
  377. }
  378. }
  379. });
  380. };
  381. const say_hello = async () => {
  382. tokens = [`Hello`, `!`, ` How`,` can`, ` I`,` assist`,` you`,` today`,`?`]
  383. message_box.innerHTML += `
  384. <div class="message">
  385. <div class="assistant">
  386. ${gpt_image}
  387. <i class="fa-regular fa-phone-arrow-down-left"></i>
  388. </div>
  389. <div class="content">
  390. <p class=" welcome-message"></p>
  391. </div>
  392. </div>
  393. `;
  394. to_modify = document.querySelector(`.welcome-message`);
  395. for (token of tokens) {
  396. await new Promise(resolve => setTimeout(resolve, (Math.random() * (100 - 200) + 100)))
  397. to_modify.textContent += token;
  398. }
  399. }
  400. // Theme storage for recurring viewers
  401. const storeTheme = function (theme) {
  402. localStorage.setItem("theme", theme);
  403. };
  404. // set theme when visitor returns
  405. const setTheme = function () {
  406. const activeTheme = localStorage.getItem("theme");
  407. colorThemes.forEach((themeOption) => {
  408. if (themeOption.id === activeTheme) {
  409. themeOption.checked = true;
  410. }
  411. });
  412. // fallback for no :has() support
  413. document.documentElement.className = activeTheme;
  414. };
  415. colorThemes.forEach((themeOption) => {
  416. themeOption.addEventListener("click", () => {
  417. storeTheme(themeOption.id);
  418. // fallback for no :has() support
  419. document.documentElement.className = themeOption.id;
  420. });
  421. });
  422. window.onload = async () => {
  423. load_settings_localstorage();
  424. setTheme();
  425. let conversations = 0;
  426. for (let i = 0; i < localStorage.length; i++) {
  427. if (localStorage.key(i).startsWith("conversation:")) {
  428. conversations += 1;
  429. }
  430. }
  431. if (conversations == 0) localStorage.clear();
  432. await setTimeout(() => {
  433. load_conversations(20, 0);
  434. }, 1);
  435. if (/\/chat\/.+/.test(window.location.href)) {
  436. await load_conversation(window.conversation_id);
  437. } else {
  438. await say_hello()
  439. }
  440. message_input.addEventListener(`keydown`, async (evt) => {
  441. if (prompt_lock) return;
  442. if (evt.keyCode === 13 && !evt.shiftKey) {
  443. evt.preventDefault();
  444. console.log("pressed enter");
  445. await handle_ask();
  446. } else {
  447. message_input.style.removeProperty("height");
  448. message_input.style.height = message_input.scrollHeight + "px";
  449. }
  450. });
  451. send_button.addEventListener(`click`, async () => {
  452. console.log("clicked send");
  453. if (prompt_lock) return;
  454. await handle_ask();
  455. });
  456. register_settings_localstorage();
  457. };
  458. const observer = new MutationObserver((mutationsList) => {
  459. for (const mutation of mutationsList) {
  460. if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
  461. const height = message_input.offsetHeight;
  462. let heightValues = {
  463. 81: "20px",
  464. 82: "20px",
  465. 100: "30px",
  466. 119: "39px",
  467. 138: "49px",
  468. 150: "55px"
  469. }
  470. send_button.style.top = heightValues[height] || '';
  471. }
  472. }
  473. });
  474. observer.observe(message_input, { attributes: true });
  475. (async () => {
  476. response = await fetch('/backend-api/v2/models')
  477. models = await response.json()
  478. let select = document.getElementById('model');
  479. select.textContent = '';
  480. let auto = document.createElement('option');
  481. auto.value = '';
  482. auto.text = 'Model: Default';
  483. select.appendChild(auto);
  484. for (model of models) {
  485. let option = document.createElement('option');
  486. option.value = option.text = model;
  487. select.appendChild(option);
  488. }
  489. })();
  490. (async () => {
  491. response = await fetch('/backend-api/v2/providers')
  492. providers = await response.json()
  493. let select = document.getElementById('provider');
  494. select.textContent = '';
  495. let auto = document.createElement('option');
  496. auto.value = '';
  497. auto.text = 'Provider: Auto';
  498. select.appendChild(auto);
  499. for (provider of providers) {
  500. let option = document.createElement('option');
  501. option.value = option.text = provider;
  502. select.appendChild(option);
  503. }
  504. })();
  505. (async () => {
  506. response = await fetch('/backend-api/v2/version')
  507. versions = await response.json()
  508. document.title = 'g4f - gui - ' + versions["version"];
  509. text = "version ~ "
  510. if (versions["version"] != versions["lastet_version"]) {
  511. release_url = 'https://github.com/xtekky/gpt4free/releases/tag/' + versions["lastet_version"];
  512. text += '<a href="' + release_url +'" target="_blank" title="New version: ' + versions["lastet_version"] +'">' + versions["version"] + ' 🆕</a>';
  513. } else {
  514. text += versions["version"];
  515. }
  516. document.getElementById("version_text").innerHTML = text
  517. })();