index.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import { OPENAI_API_BASE_URL } from '$lib/constants';
  2. import { promptTemplate } from '$lib/utils';
  3. export const getOpenAIUrls = async (token: string = '') => {
  4. let error = null;
  5. const res = await fetch(`${OPENAI_API_BASE_URL}/urls`, {
  6. method: 'GET',
  7. headers: {
  8. Accept: 'application/json',
  9. 'Content-Type': 'application/json',
  10. ...(token && { authorization: `Bearer ${token}` })
  11. }
  12. })
  13. .then(async (res) => {
  14. if (!res.ok) throw await res.json();
  15. return res.json();
  16. })
  17. .catch((err) => {
  18. console.log(err);
  19. if ('detail' in err) {
  20. error = err.detail;
  21. } else {
  22. error = 'Server connection failed';
  23. }
  24. return null;
  25. });
  26. if (error) {
  27. throw error;
  28. }
  29. return res.OPENAI_API_BASE_URLS;
  30. };
  31. export const updateOpenAIUrls = async (token: string = '', urls: string[]) => {
  32. let error = null;
  33. const res = await fetch(`${OPENAI_API_BASE_URL}/urls/update`, {
  34. method: 'POST',
  35. headers: {
  36. Accept: 'application/json',
  37. 'Content-Type': 'application/json',
  38. ...(token && { authorization: `Bearer ${token}` })
  39. },
  40. body: JSON.stringify({
  41. urls: urls
  42. })
  43. })
  44. .then(async (res) => {
  45. if (!res.ok) throw await res.json();
  46. return res.json();
  47. })
  48. .catch((err) => {
  49. console.log(err);
  50. if ('detail' in err) {
  51. error = err.detail;
  52. } else {
  53. error = 'Server connection failed';
  54. }
  55. return null;
  56. });
  57. if (error) {
  58. throw error;
  59. }
  60. return res.OPENAI_API_BASE_URLS;
  61. };
  62. export const getOpenAIKeys = async (token: string = '') => {
  63. let error = null;
  64. const res = await fetch(`${OPENAI_API_BASE_URL}/keys`, {
  65. method: 'GET',
  66. headers: {
  67. Accept: 'application/json',
  68. 'Content-Type': 'application/json',
  69. ...(token && { authorization: `Bearer ${token}` })
  70. }
  71. })
  72. .then(async (res) => {
  73. if (!res.ok) throw await res.json();
  74. return res.json();
  75. })
  76. .catch((err) => {
  77. console.log(err);
  78. if ('detail' in err) {
  79. error = err.detail;
  80. } else {
  81. error = 'Server connection failed';
  82. }
  83. return null;
  84. });
  85. if (error) {
  86. throw error;
  87. }
  88. return res.OPENAI_API_KEYS;
  89. };
  90. export const updateOpenAIKeys = async (token: string = '', keys: string[]) => {
  91. let error = null;
  92. const res = await fetch(`${OPENAI_API_BASE_URL}/keys/update`, {
  93. method: 'POST',
  94. headers: {
  95. Accept: 'application/json',
  96. 'Content-Type': 'application/json',
  97. ...(token && { authorization: `Bearer ${token}` })
  98. },
  99. body: JSON.stringify({
  100. keys: keys
  101. })
  102. })
  103. .then(async (res) => {
  104. if (!res.ok) throw await res.json();
  105. return res.json();
  106. })
  107. .catch((err) => {
  108. console.log(err);
  109. if ('detail' in err) {
  110. error = err.detail;
  111. } else {
  112. error = 'Server connection failed';
  113. }
  114. return null;
  115. });
  116. if (error) {
  117. throw error;
  118. }
  119. return res.OPENAI_API_KEYS;
  120. };
  121. export const getOpenAIModels = async (token: string = '') => {
  122. let error = null;
  123. const res = await fetch(`${OPENAI_API_BASE_URL}/models`, {
  124. method: 'GET',
  125. headers: {
  126. Accept: 'application/json',
  127. 'Content-Type': 'application/json',
  128. ...(token && { authorization: `Bearer ${token}` })
  129. }
  130. })
  131. .then(async (res) => {
  132. if (!res.ok) throw await res.json();
  133. return res.json();
  134. })
  135. .catch((err) => {
  136. error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`;
  137. return [];
  138. });
  139. if (error) {
  140. throw error;
  141. }
  142. const models = Array.isArray(res) ? res : res?.data ?? null;
  143. return models
  144. ? models
  145. .map((model) => ({ id: model.id, name: model.name ?? model.id, external: true }))
  146. .sort((a, b) => {
  147. return a.name.localeCompare(b.name);
  148. })
  149. : models;
  150. };
  151. export const getOpenAIModelsDirect = async (
  152. base_url: string = 'https://api.openai.com/v1',
  153. api_key: string = ''
  154. ) => {
  155. let error = null;
  156. const res = await fetch(`${base_url}/models`, {
  157. method: 'GET',
  158. headers: {
  159. 'Content-Type': 'application/json',
  160. Authorization: `Bearer ${api_key}`
  161. }
  162. })
  163. .then(async (res) => {
  164. if (!res.ok) throw await res.json();
  165. return res.json();
  166. })
  167. .catch((err) => {
  168. console.log(err);
  169. error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`;
  170. return null;
  171. });
  172. if (error) {
  173. throw error;
  174. }
  175. const models = Array.isArray(res) ? res : res?.data ?? null;
  176. return models
  177. .map((model) => ({ id: model.id, name: model.name ?? model.id, external: true }))
  178. .filter((model) => (base_url.includes('openai') ? model.name.includes('gpt') : true))
  179. .sort((a, b) => {
  180. return a.name.localeCompare(b.name);
  181. });
  182. };
  183. export const generateOpenAIChatCompletion = async (
  184. token: string = '',
  185. body: object,
  186. url: string = OPENAI_API_BASE_URL
  187. ): Promise<[Response | null, AbortController]> => {
  188. const controller = new AbortController();
  189. let error = null;
  190. const res = await fetch(`${url}/chat/completions`, {
  191. signal: controller.signal,
  192. method: 'POST',
  193. headers: {
  194. Authorization: `Bearer ${token}`,
  195. 'Content-Type': 'application/json'
  196. },
  197. body: JSON.stringify(body)
  198. }).catch((err) => {
  199. console.log(err);
  200. error = err;
  201. return null;
  202. });
  203. if (error) {
  204. throw error;
  205. }
  206. return [res, controller];
  207. };
  208. export const synthesizeOpenAISpeech = async (
  209. token: string = '',
  210. speaker: string = 'alloy',
  211. text: string = ''
  212. ) => {
  213. let error = null;
  214. const res = await fetch(`${OPENAI_API_BASE_URL}/audio/speech`, {
  215. method: 'POST',
  216. headers: {
  217. Authorization: `Bearer ${token}`,
  218. 'Content-Type': 'application/json'
  219. },
  220. body: JSON.stringify({
  221. model: 'tts-1',
  222. input: text,
  223. voice: speaker
  224. })
  225. }).catch((err) => {
  226. console.log(err);
  227. error = err;
  228. return null;
  229. });
  230. if (error) {
  231. throw error;
  232. }
  233. return res;
  234. };
  235. export const generateTitle = async (
  236. token: string = '',
  237. template: string,
  238. model: string,
  239. prompt: string,
  240. url: string = OPENAI_API_BASE_URL
  241. ) => {
  242. let error = null;
  243. template = promptTemplate(template, prompt);
  244. console.log(template);
  245. const res = await fetch(`${url}/chat/completions`, {
  246. method: 'POST',
  247. headers: {
  248. Accept: 'application/json',
  249. 'Content-Type': 'application/json',
  250. Authorization: `Bearer ${token}`
  251. },
  252. body: JSON.stringify({
  253. model: model,
  254. messages: [
  255. {
  256. role: 'user',
  257. content: template
  258. }
  259. ],
  260. stream: false,
  261. // Restricting the max tokens to 50 to avoid long titles
  262. max_tokens: 50
  263. })
  264. })
  265. .then(async (res) => {
  266. if (!res.ok) throw await res.json();
  267. return res.json();
  268. })
  269. .catch((err) => {
  270. console.log(err);
  271. if ('detail' in err) {
  272. error = err.detail;
  273. }
  274. return null;
  275. });
  276. if (error) {
  277. throw error;
  278. }
  279. return res?.choices[0]?.message?.content.replace(/["']/g, '') ?? 'New Chat';
  280. };