index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. import { OLLAMA_API_BASE_URL } from '$lib/constants';
  2. import { titleGenerationTemplate } from '$lib/utils';
  3. export const getOllamaConfig = async (token: string = '') => {
  4. let error = null;
  5. const res = await fetch(`${OLLAMA_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 updateOllamaConfig = async (token: string = '', enable_ollama_api: boolean) => {
  32. let error = null;
  33. const res = await fetch(`${OLLAMA_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_ollama_api: enable_ollama_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 getOllamaUrls = async (token: string = '') => {
  63. let error = null;
  64. const res = await fetch(`${OLLAMA_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.OLLAMA_BASE_URLS;
  89. };
  90. export const updateOllamaUrls = async (token: string = '', urls: string[]) => {
  91. let error = null;
  92. const res = await fetch(`${OLLAMA_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.OLLAMA_BASE_URLS;
  120. };
  121. export const getOllamaVersion = async (token: string, urlIdx?: number) => {
  122. let error = null;
  123. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/version${urlIdx ? `/${urlIdx}` : ''}`, {
  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?.version ?? false;
  148. };
  149. export const getOllamaModels = async (token: string = '') => {
  150. let error = null;
  151. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/tags`, {
  152. method: 'GET',
  153. headers: {
  154. Accept: 'application/json',
  155. 'Content-Type': 'application/json',
  156. ...(token && { authorization: `Bearer ${token}` })
  157. }
  158. })
  159. .then(async (res) => {
  160. if (!res.ok) throw await res.json();
  161. return res.json();
  162. })
  163. .catch((err) => {
  164. console.log(err);
  165. if ('detail' in err) {
  166. error = err.detail;
  167. } else {
  168. error = 'Server connection failed';
  169. }
  170. return null;
  171. });
  172. if (error) {
  173. throw error;
  174. }
  175. return (res?.models ?? [])
  176. .map((model) => ({ id: model.model, name: model.name ?? model.model, ...model }))
  177. .sort((a, b) => {
  178. return a.name.localeCompare(b.name);
  179. });
  180. };
  181. // TODO: migrate to backend
  182. export const generateTitle = async (
  183. token: string = '',
  184. template: string,
  185. model: string,
  186. prompt: string
  187. ) => {
  188. let error = null;
  189. template = titleGenerationTemplate(template, prompt);
  190. console.log(template);
  191. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  192. method: 'POST',
  193. headers: {
  194. Accept: 'application/json',
  195. 'Content-Type': 'application/json',
  196. Authorization: `Bearer ${token}`
  197. },
  198. body: JSON.stringify({
  199. model: model,
  200. prompt: template,
  201. stream: false,
  202. options: {
  203. // Restrict the number of tokens generated to 50
  204. num_predict: 50
  205. }
  206. })
  207. })
  208. .then(async (res) => {
  209. if (!res.ok) throw await res.json();
  210. return res.json();
  211. })
  212. .catch((err) => {
  213. console.log(err);
  214. if ('detail' in err) {
  215. error = err.detail;
  216. }
  217. return null;
  218. });
  219. if (error) {
  220. throw error;
  221. }
  222. return res?.response.replace(/["']/g, '') ?? 'New Chat';
  223. };
  224. export const generatePrompt = async (token: string = '', model: string, conversation: string) => {
  225. let error = null;
  226. if (conversation === '') {
  227. conversation = '[no existing conversation]';
  228. }
  229. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  230. method: 'POST',
  231. headers: {
  232. Accept: 'application/json',
  233. 'Content-Type': 'application/json',
  234. Authorization: `Bearer ${token}`
  235. },
  236. body: JSON.stringify({
  237. model: model,
  238. prompt: `Conversation:
  239. ${conversation}
  240. As USER in the conversation above, your task is to continue the conversation. Remember, Your responses should be crafted as if you're a human conversing in a natural, realistic manner, keeping in mind the context and flow of the dialogue. Please generate a fitting response to the last message in the conversation, or if there is no existing conversation, initiate one as a normal person would.
  241. Response:
  242. `
  243. })
  244. }).catch((err) => {
  245. console.log(err);
  246. if ('detail' in err) {
  247. error = err.detail;
  248. }
  249. return null;
  250. });
  251. if (error) {
  252. throw error;
  253. }
  254. return res;
  255. };
  256. export const generateEmbeddings = async (token: string = '', model: string, text: string) => {
  257. let error = null;
  258. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/embeddings`, {
  259. method: 'POST',
  260. headers: {
  261. Accept: 'application/json',
  262. 'Content-Type': 'application/json',
  263. Authorization: `Bearer ${token}`
  264. },
  265. body: JSON.stringify({
  266. model: model,
  267. prompt: text
  268. })
  269. }).catch((err) => {
  270. error = err;
  271. return null;
  272. });
  273. if (error) {
  274. throw error;
  275. }
  276. return res;
  277. };
  278. export const generateTextCompletion = async (token: string = '', model: string, text: string) => {
  279. let error = null;
  280. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  281. method: 'POST',
  282. headers: {
  283. Accept: 'application/json',
  284. 'Content-Type': 'application/json',
  285. Authorization: `Bearer ${token}`
  286. },
  287. body: JSON.stringify({
  288. model: model,
  289. prompt: text,
  290. stream: true
  291. })
  292. }).catch((err) => {
  293. error = err;
  294. return null;
  295. });
  296. if (error) {
  297. throw error;
  298. }
  299. return res;
  300. };
  301. export const generateChatCompletion = async (token: string = '', body: object) => {
  302. let controller = new AbortController();
  303. let error = null;
  304. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/chat`, {
  305. signal: controller.signal,
  306. method: 'POST',
  307. headers: {
  308. Accept: 'application/json',
  309. 'Content-Type': 'application/json',
  310. Authorization: `Bearer ${token}`
  311. },
  312. body: JSON.stringify(body)
  313. }).catch((err) => {
  314. error = err;
  315. return null;
  316. });
  317. if (error) {
  318. throw error;
  319. }
  320. return [res, controller];
  321. };
  322. export const createModel = async (token: string, tagName: string, content: string) => {
  323. let error = null;
  324. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/create`, {
  325. method: 'POST',
  326. headers: {
  327. Accept: 'application/json',
  328. 'Content-Type': 'application/json',
  329. Authorization: `Bearer ${token}`
  330. },
  331. body: JSON.stringify({
  332. name: tagName,
  333. modelfile: content
  334. })
  335. }).catch((err) => {
  336. error = err;
  337. return null;
  338. });
  339. if (error) {
  340. throw error;
  341. }
  342. return res;
  343. };
  344. export const deleteModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  345. let error = null;
  346. const res = await fetch(
  347. `${OLLAMA_API_BASE_URL}/api/delete${urlIdx !== null ? `/${urlIdx}` : ''}`,
  348. {
  349. method: 'DELETE',
  350. headers: {
  351. Accept: 'application/json',
  352. 'Content-Type': 'application/json',
  353. Authorization: `Bearer ${token}`
  354. },
  355. body: JSON.stringify({
  356. name: tagName
  357. })
  358. }
  359. )
  360. .then(async (res) => {
  361. if (!res.ok) throw await res.json();
  362. return res.json();
  363. })
  364. .then((json) => {
  365. console.log(json);
  366. return true;
  367. })
  368. .catch((err) => {
  369. console.log(err);
  370. error = err;
  371. if ('detail' in err) {
  372. error = err.detail;
  373. }
  374. return null;
  375. });
  376. if (error) {
  377. throw error;
  378. }
  379. return res;
  380. };
  381. export const pullModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  382. let error = null;
  383. const controller = new AbortController();
  384. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/pull${urlIdx !== null ? `/${urlIdx}` : ''}`, {
  385. signal: controller.signal,
  386. method: 'POST',
  387. headers: {
  388. Accept: 'application/json',
  389. 'Content-Type': 'application/json',
  390. Authorization: `Bearer ${token}`
  391. },
  392. body: JSON.stringify({
  393. name: tagName
  394. })
  395. }).catch((err) => {
  396. console.log(err);
  397. error = err;
  398. if ('detail' in err) {
  399. error = err.detail;
  400. }
  401. return null;
  402. });
  403. if (error) {
  404. throw error;
  405. }
  406. return [res, controller];
  407. };
  408. export const downloadModel = async (
  409. token: string,
  410. download_url: string,
  411. urlIdx: string | null = null
  412. ) => {
  413. let error = null;
  414. const res = await fetch(
  415. `${OLLAMA_API_BASE_URL}/models/download${urlIdx !== null ? `/${urlIdx}` : ''}`,
  416. {
  417. method: 'POST',
  418. headers: {
  419. Accept: 'application/json',
  420. 'Content-Type': 'application/json',
  421. Authorization: `Bearer ${token}`
  422. },
  423. body: JSON.stringify({
  424. url: download_url
  425. })
  426. }
  427. ).catch((err) => {
  428. console.log(err);
  429. error = err;
  430. if ('detail' in err) {
  431. error = err.detail;
  432. }
  433. return null;
  434. });
  435. if (error) {
  436. throw error;
  437. }
  438. return res;
  439. };
  440. export const uploadModel = async (token: string, file: File, urlIdx: string | null = null) => {
  441. let error = null;
  442. const formData = new FormData();
  443. formData.append('file', file);
  444. const res = await fetch(
  445. `${OLLAMA_API_BASE_URL}/models/upload${urlIdx !== null ? `/${urlIdx}` : ''}`,
  446. {
  447. method: 'POST',
  448. headers: {
  449. Authorization: `Bearer ${token}`
  450. },
  451. body: formData
  452. }
  453. ).catch((err) => {
  454. console.log(err);
  455. error = err;
  456. if ('detail' in err) {
  457. error = err.detail;
  458. }
  459. return null;
  460. });
  461. if (error) {
  462. throw error;
  463. }
  464. return res;
  465. };
  466. // export const pullModel = async (token: string, tagName: string) => {
  467. // return await fetch(`${OLLAMA_API_BASE_URL}/pull`, {
  468. // method: 'POST',
  469. // headers: {
  470. // 'Content-Type': 'text/event-stream',
  471. // Authorization: `Bearer ${token}`
  472. // },
  473. // body: JSON.stringify({
  474. // name: tagName
  475. // })
  476. // });
  477. // };