index.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { OPENAI_API_BASE_URL } from '$lib/constants';
  2. import { promptTemplate } from '$lib/utils';
  3. export const getOpenAIConfig = async (token: string = '') => {
  4. let error = null;
  5. const res = await fetch(`${OPENAI_API_BASE_URL}/config`, {
  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;
  30. };
  31. export const updateOpenAIConfig = async (token: string = '', enable_openai_api: boolean) => {
  32. let error = null;
  33. const res = await fetch(`${OPENAI_API_BASE_URL}/config/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. enable_openai_api: enable_openai_api
  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;
  61. };
  62. export const getOpenAIUrls = async (token: string = '') => {
  63. let error = null;
  64. const res = await fetch(`${OPENAI_API_BASE_URL}/urls`, {
  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_BASE_URLS;
  89. };
  90. export const updateOpenAIUrls = async (token: string = '', urls: string[]) => {
  91. let error = null;
  92. const res = await fetch(`${OPENAI_API_BASE_URL}/urls/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. urls: urls
  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_BASE_URLS;
  120. };
  121. export const getOpenAIKeys = async (token: string = '') => {
  122. let error = null;
  123. const res = await fetch(`${OPENAI_API_BASE_URL}/keys`, {
  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. console.log(err);
  137. if ('detail' in err) {
  138. error = err.detail;
  139. } else {
  140. error = 'Server connection failed';
  141. }
  142. return null;
  143. });
  144. if (error) {
  145. throw error;
  146. }
  147. return res.OPENAI_API_KEYS;
  148. };
  149. export const updateOpenAIKeys = async (token: string = '', keys: string[]) => {
  150. let error = null;
  151. const res = await fetch(`${OPENAI_API_BASE_URL}/keys/update`, {
  152. method: 'POST',
  153. headers: {
  154. Accept: 'application/json',
  155. 'Content-Type': 'application/json',
  156. ...(token && { authorization: `Bearer ${token}` })
  157. },
  158. body: JSON.stringify({
  159. keys: keys
  160. })
  161. })
  162. .then(async (res) => {
  163. if (!res.ok) throw await res.json();
  164. return res.json();
  165. })
  166. .catch((err) => {
  167. console.log(err);
  168. if ('detail' in err) {
  169. error = err.detail;
  170. } else {
  171. error = 'Server connection failed';
  172. }
  173. return null;
  174. });
  175. if (error) {
  176. throw error;
  177. }
  178. return res.OPENAI_API_KEYS;
  179. };
  180. export const getOpenAIModels = async (token: string = '') => {
  181. let error = null;
  182. const res = await fetch(`${OPENAI_API_BASE_URL}/models`, {
  183. method: 'GET',
  184. headers: {
  185. Accept: 'application/json',
  186. 'Content-Type': 'application/json',
  187. ...(token && { authorization: `Bearer ${token}` })
  188. }
  189. })
  190. .then(async (res) => {
  191. if (!res.ok) throw await res.json();
  192. return res.json();
  193. })
  194. .catch((err) => {
  195. error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`;
  196. return [];
  197. });
  198. if (error) {
  199. throw error;
  200. }
  201. const models = Array.isArray(res) ? res : res?.data ?? null;
  202. return models
  203. ? models
  204. .map((model) => ({
  205. id: model.id,
  206. name: model.name ?? model.id,
  207. external: true,
  208. custom_info: model.custom_info
  209. }))
  210. .sort((a, b) => {
  211. return a.name.localeCompare(b.name);
  212. })
  213. : models;
  214. };
  215. export const getOpenAIModelsDirect = async (
  216. base_url: string = 'https://api.openai.com/v1',
  217. api_key: string = ''
  218. ) => {
  219. let error = null;
  220. const res = await fetch(`${base_url}/models`, {
  221. method: 'GET',
  222. headers: {
  223. 'Content-Type': 'application/json',
  224. Authorization: `Bearer ${api_key}`
  225. }
  226. })
  227. .then(async (res) => {
  228. if (!res.ok) throw await res.json();
  229. return res.json();
  230. })
  231. .catch((err) => {
  232. console.log(err);
  233. error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`;
  234. return null;
  235. });
  236. if (error) {
  237. throw error;
  238. }
  239. const models = Array.isArray(res) ? res : res?.data ?? null;
  240. return models
  241. .map((model) => ({ id: model.id, name: model.name ?? model.id, external: true }))
  242. .filter((model) => (base_url.includes('openai') ? model.name.includes('gpt') : true))
  243. .sort((a, b) => {
  244. return a.name.localeCompare(b.name);
  245. });
  246. };
  247. export const generateOpenAIChatCompletion = async (
  248. token: string = '',
  249. body: object,
  250. url: string = OPENAI_API_BASE_URL
  251. ): Promise<[Response | null, AbortController]> => {
  252. const controller = new AbortController();
  253. let error = null;
  254. const res = await fetch(`${url}/chat/completions`, {
  255. signal: controller.signal,
  256. method: 'POST',
  257. headers: {
  258. Authorization: `Bearer ${token}`,
  259. 'Content-Type': 'application/json'
  260. },
  261. body: JSON.stringify(body)
  262. }).catch((err) => {
  263. console.log(err);
  264. error = err;
  265. return null;
  266. });
  267. if (error) {
  268. throw error;
  269. }
  270. return [res, controller];
  271. };
  272. export const synthesizeOpenAISpeech = async (
  273. token: string = '',
  274. speaker: string = 'alloy',
  275. text: string = '',
  276. model: string = 'tts-1'
  277. ) => {
  278. let error = null;
  279. const res = await fetch(`${OPENAI_API_BASE_URL}/audio/speech`, {
  280. method: 'POST',
  281. headers: {
  282. Authorization: `Bearer ${token}`,
  283. 'Content-Type': 'application/json'
  284. },
  285. body: JSON.stringify({
  286. model: model,
  287. input: text,
  288. voice: speaker
  289. })
  290. }).catch((err) => {
  291. console.log(err);
  292. error = err;
  293. return null;
  294. });
  295. if (error) {
  296. throw error;
  297. }
  298. return res;
  299. };
  300. export const generateTitle = async (
  301. token: string = '',
  302. template: string,
  303. model: string,
  304. prompt: string,
  305. url: string = OPENAI_API_BASE_URL
  306. ) => {
  307. let error = null;
  308. template = promptTemplate(template, prompt);
  309. console.log(template);
  310. const res = await fetch(`${url}/chat/completions`, {
  311. method: 'POST',
  312. headers: {
  313. Accept: 'application/json',
  314. 'Content-Type': 'application/json',
  315. Authorization: `Bearer ${token}`
  316. },
  317. body: JSON.stringify({
  318. model: model,
  319. messages: [
  320. {
  321. role: 'user',
  322. content: template
  323. }
  324. ],
  325. stream: false,
  326. // Restricting the max tokens to 50 to avoid long titles
  327. max_tokens: 50
  328. })
  329. })
  330. .then(async (res) => {
  331. if (!res.ok) throw await res.json();
  332. return res.json();
  333. })
  334. .catch((err) => {
  335. console.log(err);
  336. if ('detail' in err) {
  337. error = err.detail;
  338. }
  339. return null;
  340. });
  341. if (error) {
  342. throw error;
  343. }
  344. return res?.choices[0]?.message?.content.replace(/["']/g, '') ?? 'New Chat';
  345. };