index.ts 9.8 KB

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