index.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. import { getOllamaModels } from '$lib/apis/ollama';
  4. import { getOpenAIModels } from '$lib/apis/openai';
  5. import { getLiteLLMModels } from '$lib/apis/litellm';
  6. export const getModels = async (token: string) => {
  7. let models = await Promise.all([
  8. await getOllamaModels(token).catch((error) => {
  9. console.log(error);
  10. return null;
  11. }),
  12. await getOpenAIModels(token).catch((error) => {
  13. console.log(error);
  14. return null;
  15. }),
  16. await getLiteLLMModels(token).catch((error) => {
  17. console.log(error);
  18. return null;
  19. })
  20. ]);
  21. models = models
  22. .filter((models) => models)
  23. .reduce((a, e, i, arr) => a.concat(e, ...(i < arr.length - 1 ? [{ name: 'hr' }] : [])), []);
  24. return models;
  25. };
  26. //////////////////////////
  27. // Helper functions
  28. //////////////////////////
  29. export const sanitizeResponseContent = (content: string) => {
  30. return content
  31. .replace(/<\|[a-z]*$/, '')
  32. .replace(/<\|[a-z]+\|$/, '')
  33. .replace(/<$/, '')
  34. .replaceAll(/<\|[a-z]+\|>/g, ' ')
  35. .replaceAll(/<br\s?\/?>/gi, '\n')
  36. .replaceAll('<', '&lt;')
  37. .trim();
  38. };
  39. export const revertSanitizedResponseContent = (content: string) => {
  40. return content.replaceAll('&lt;', '<');
  41. };
  42. export const capitalizeFirstLetter = (string) => {
  43. return string.charAt(0).toUpperCase() + string.slice(1);
  44. };
  45. export const splitStream = (splitOn) => {
  46. let buffer = '';
  47. return new TransformStream({
  48. transform(chunk, controller) {
  49. buffer += chunk;
  50. const parts = buffer.split(splitOn);
  51. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  52. buffer = parts[parts.length - 1];
  53. },
  54. flush(controller) {
  55. if (buffer) controller.enqueue(buffer);
  56. }
  57. });
  58. };
  59. export const convertMessagesToHistory = (messages) => {
  60. const history = {
  61. messages: {},
  62. currentId: null
  63. };
  64. let parentMessageId = null;
  65. let messageId = null;
  66. for (const message of messages) {
  67. messageId = uuidv4();
  68. if (parentMessageId !== null) {
  69. history.messages[parentMessageId].childrenIds = [
  70. ...history.messages[parentMessageId].childrenIds,
  71. messageId
  72. ];
  73. }
  74. history.messages[messageId] = {
  75. ...message,
  76. id: messageId,
  77. parentId: parentMessageId,
  78. childrenIds: []
  79. };
  80. parentMessageId = messageId;
  81. }
  82. history.currentId = messageId;
  83. return history;
  84. };
  85. export const getGravatarURL = (email) => {
  86. // Trim leading and trailing whitespace from
  87. // an email address and force all characters
  88. // to lower case
  89. const address = String(email).trim().toLowerCase();
  90. // Create a SHA256 hash of the final string
  91. const hash = sha256(address);
  92. // Grab the actual image URL
  93. return `https://www.gravatar.com/avatar/${hash}`;
  94. };
  95. export const copyToClipboard = (text) => {
  96. if (!navigator.clipboard) {
  97. const textArea = document.createElement('textarea');
  98. textArea.value = text;
  99. // Avoid scrolling to bottom
  100. textArea.style.top = '0';
  101. textArea.style.left = '0';
  102. textArea.style.position = 'fixed';
  103. document.body.appendChild(textArea);
  104. textArea.focus();
  105. textArea.select();
  106. try {
  107. const successful = document.execCommand('copy');
  108. const msg = successful ? 'successful' : 'unsuccessful';
  109. console.log('Fallback: Copying text command was ' + msg);
  110. } catch (err) {
  111. console.error('Fallback: Oops, unable to copy', err);
  112. }
  113. document.body.removeChild(textArea);
  114. return;
  115. }
  116. navigator.clipboard.writeText(text).then(
  117. function () {
  118. console.log('Async: Copying to clipboard was successful!');
  119. },
  120. function (err) {
  121. console.error('Async: Could not copy text: ', err);
  122. }
  123. );
  124. };
  125. export const compareVersion = (latest, current) => {
  126. return current === '0.0.0'
  127. ? false
  128. : current.localeCompare(latest, undefined, {
  129. numeric: true,
  130. sensitivity: 'case',
  131. caseFirst: 'upper'
  132. }) < 0;
  133. };
  134. export const findWordIndices = (text) => {
  135. const regex = /\[([^\]]+)\]/g;
  136. const matches = [];
  137. let match;
  138. while ((match = regex.exec(text)) !== null) {
  139. matches.push({
  140. word: match[1],
  141. startIndex: match.index,
  142. endIndex: regex.lastIndex - 1
  143. });
  144. }
  145. return matches;
  146. };
  147. export const removeFirstHashWord = (inputString) => {
  148. // Split the string into an array of words
  149. const words = inputString.split(' ');
  150. // Find the index of the first word that starts with #
  151. const index = words.findIndex((word) => word.startsWith('#'));
  152. // Remove the first word with #
  153. if (index !== -1) {
  154. words.splice(index, 1);
  155. }
  156. // Join the remaining words back into a string
  157. const resultString = words.join(' ');
  158. return resultString;
  159. };
  160. export const transformFileName = (fileName) => {
  161. // Convert to lowercase
  162. const lowerCaseFileName = fileName.toLowerCase();
  163. // Remove special characters using regular expression
  164. const sanitizedFileName = lowerCaseFileName.replace(/[^\w\s]/g, '');
  165. // Replace spaces with dashes
  166. const finalFileName = sanitizedFileName.replace(/\s+/g, '-');
  167. return finalFileName;
  168. };
  169. export const calculateSHA256 = async (file) => {
  170. // Create a FileReader to read the file asynchronously
  171. const reader = new FileReader();
  172. // Define a promise to handle the file reading
  173. const readFile = new Promise((resolve, reject) => {
  174. reader.onload = () => resolve(reader.result);
  175. reader.onerror = reject;
  176. });
  177. // Read the file as an ArrayBuffer
  178. reader.readAsArrayBuffer(file);
  179. try {
  180. // Wait for the FileReader to finish reading the file
  181. const buffer = await readFile;
  182. // Convert the ArrayBuffer to a Uint8Array
  183. const uint8Array = new Uint8Array(buffer);
  184. // Calculate the SHA-256 hash using Web Crypto API
  185. const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
  186. // Convert the hash to a hexadecimal string
  187. const hashArray = Array.from(new Uint8Array(hashBuffer));
  188. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('');
  189. return `${hashHex}`;
  190. } catch (error) {
  191. console.error('Error calculating SHA-256 hash:', error);
  192. throw error;
  193. }
  194. };
  195. export const getImportOrigin = (_chats) => {
  196. // Check what external service chat imports are from
  197. if ('mapping' in _chats[0]) {
  198. return 'openai';
  199. }
  200. return 'webui';
  201. };
  202. const convertOpenAIMessages = (convo) => {
  203. // Parse OpenAI chat messages and create chat dictionary for creating new chats
  204. const mapping = convo['mapping'];
  205. const messages = [];
  206. let currentId = '';
  207. let lastId = null;
  208. for (let message_id in mapping) {
  209. const message = mapping[message_id];
  210. currentId = message_id;
  211. try {
  212. if (
  213. messages.length == 0 &&
  214. (message['message'] == null ||
  215. (message['message']['content']['parts']?.[0] == '' &&
  216. message['message']['content']['text'] == null))
  217. ) {
  218. // Skip chat messages with no content
  219. continue;
  220. } else {
  221. const new_chat = {
  222. id: message_id,
  223. parentId: lastId,
  224. childrenIds: message['children'] || [],
  225. role: message['message']?.['author']?.['role'] !== 'user' ? 'assistant' : 'user',
  226. content:
  227. message['message']?.['content']?.['parts']?.[0] ||
  228. message['message']?.['content']?.['text'] ||
  229. '',
  230. model: 'gpt-3.5-turbo',
  231. done: true,
  232. context: null
  233. };
  234. messages.push(new_chat);
  235. lastId = currentId;
  236. }
  237. } catch (error) {
  238. console.log('Error with', message, '\nError:', error);
  239. }
  240. }
  241. let history = {};
  242. messages.forEach((obj) => (history[obj.id] = obj));
  243. const chat = {
  244. history: {
  245. currentId: currentId,
  246. messages: history // Need to convert this to not a list and instead a json object
  247. },
  248. models: ['gpt-3.5-turbo'],
  249. messages: messages,
  250. options: {},
  251. timestamp: convo['create_time'],
  252. title: convo['title'] ?? 'New Chat'
  253. };
  254. return chat;
  255. };
  256. const validateChat = (chat) => {
  257. // Because ChatGPT sometimes has features we can't use like DALL-E or migh have corrupted messages, need to validate
  258. const messages = chat.messages;
  259. // Check if messages array is empty
  260. if (messages.length === 0) {
  261. return false;
  262. }
  263. // Last message's children should be an empty array
  264. const lastMessage = messages[messages.length - 1];
  265. if (lastMessage.childrenIds.length !== 0) {
  266. return false;
  267. }
  268. // First message's parent should be null
  269. const firstMessage = messages[0];
  270. if (firstMessage.parentId !== null) {
  271. return false;
  272. }
  273. // Every message's content should be a string
  274. for (let message of messages) {
  275. if (typeof message.content !== 'string') {
  276. return false;
  277. }
  278. }
  279. return true;
  280. };
  281. export const convertOpenAIChats = (_chats) => {
  282. // Create a list of dictionaries with each conversation from import
  283. const chats = [];
  284. let failed = 0;
  285. for (let convo of _chats) {
  286. const chat = convertOpenAIMessages(convo);
  287. if (validateChat(chat)) {
  288. chats.push({
  289. id: convo['id'],
  290. user_id: '',
  291. title: convo['title'],
  292. chat: chat,
  293. timestamp: convo['timestamp']
  294. });
  295. } else {
  296. failed++;
  297. }
  298. }
  299. console.log(failed, 'Conversations could not be imported');
  300. return chats;
  301. };
  302. export const isValidHttpUrl = (string) => {
  303. let url;
  304. try {
  305. url = new URL(string);
  306. } catch (_) {
  307. return false;
  308. }
  309. return url.protocol === 'http:' || url.protocol === 'https:';
  310. };
  311. export const removeEmojis = (str) => {
  312. // Regular expression to match emojis
  313. const emojiRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  314. // Replace emojis with an empty string
  315. return str.replace(emojiRegex, '');
  316. };
  317. export const extractSentences = (text) => {
  318. // Split the paragraph into sentences based on common punctuation marks
  319. const sentences = text.split(/(?<=[.!?])/);
  320. return sentences
  321. .map((sentence) => removeEmojis(sentence.trim()))
  322. .filter((sentence) => sentence !== '');
  323. };
  324. export const blobToFile = (blob, fileName) => {
  325. // Create a new File object from the Blob
  326. const file = new File([blob], fileName, { type: blob.type });
  327. return file;
  328. };