index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. import { OLLAMA_API_BASE_URL } from '$lib/constants';
  2. import { promptTemplate } 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 = '') => {
  122. let error = null;
  123. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/version`, {
  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 = promptTemplate(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 cancelOllamaRequest = async (token: string = '', requestId: string) => {
  323. let error = null;
  324. const res = await fetch(`${OLLAMA_API_BASE_URL}/cancel/${requestId}`, {
  325. method: 'GET',
  326. headers: {
  327. 'Content-Type': 'text/event-stream',
  328. Authorization: `Bearer ${token}`
  329. }
  330. }).catch((err) => {
  331. error = err;
  332. return null;
  333. });
  334. if (error) {
  335. throw error;
  336. }
  337. return res;
  338. };
  339. export const createModel = async (token: string, tagName: string, content: string) => {
  340. let error = null;
  341. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/create`, {
  342. method: 'POST',
  343. headers: {
  344. Accept: 'application/json',
  345. 'Content-Type': 'application/json',
  346. Authorization: `Bearer ${token}`
  347. },
  348. body: JSON.stringify({
  349. name: tagName,
  350. modelfile: content
  351. })
  352. }).catch((err) => {
  353. error = err;
  354. return null;
  355. });
  356. if (error) {
  357. throw error;
  358. }
  359. return res;
  360. };
  361. export const deleteModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  362. let error = null;
  363. const res = await fetch(
  364. `${OLLAMA_API_BASE_URL}/api/delete${urlIdx !== null ? `/${urlIdx}` : ''}`,
  365. {
  366. method: 'DELETE',
  367. headers: {
  368. Accept: 'application/json',
  369. 'Content-Type': 'application/json',
  370. Authorization: `Bearer ${token}`
  371. },
  372. body: JSON.stringify({
  373. name: tagName
  374. })
  375. }
  376. )
  377. .then(async (res) => {
  378. if (!res.ok) throw await res.json();
  379. return res.json();
  380. })
  381. .then((json) => {
  382. console.log(json);
  383. return true;
  384. })
  385. .catch((err) => {
  386. console.log(err);
  387. error = err;
  388. if ('detail' in err) {
  389. error = err.detail;
  390. }
  391. return null;
  392. });
  393. if (error) {
  394. throw error;
  395. }
  396. return res;
  397. };
  398. export const pullModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  399. let error = null;
  400. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/pull${urlIdx !== null ? `/${urlIdx}` : ''}`, {
  401. method: 'POST',
  402. headers: {
  403. Accept: 'application/json',
  404. 'Content-Type': 'application/json',
  405. Authorization: `Bearer ${token}`
  406. },
  407. body: JSON.stringify({
  408. name: tagName
  409. })
  410. }).catch((err) => {
  411. console.log(err);
  412. error = err;
  413. if ('detail' in err) {
  414. error = err.detail;
  415. }
  416. return null;
  417. });
  418. if (error) {
  419. throw error;
  420. }
  421. return res;
  422. };
  423. export const downloadModel = async (
  424. token: string,
  425. download_url: string,
  426. urlIdx: string | null = null
  427. ) => {
  428. let error = null;
  429. const res = await fetch(
  430. `${OLLAMA_API_BASE_URL}/models/download${urlIdx !== null ? `/${urlIdx}` : ''}`,
  431. {
  432. method: 'POST',
  433. headers: {
  434. Accept: 'application/json',
  435. 'Content-Type': 'application/json',
  436. Authorization: `Bearer ${token}`
  437. },
  438. body: JSON.stringify({
  439. url: download_url
  440. })
  441. }
  442. ).catch((err) => {
  443. console.log(err);
  444. error = err;
  445. if ('detail' in err) {
  446. error = err.detail;
  447. }
  448. return null;
  449. });
  450. if (error) {
  451. throw error;
  452. }
  453. return res;
  454. };
  455. export const uploadModel = async (token: string, file: File, urlIdx: string | null = null) => {
  456. let error = null;
  457. const formData = new FormData();
  458. formData.append('file', file);
  459. const res = await fetch(
  460. `${OLLAMA_API_BASE_URL}/models/upload${urlIdx !== null ? `/${urlIdx}` : ''}`,
  461. {
  462. method: 'POST',
  463. headers: {
  464. Authorization: `Bearer ${token}`
  465. },
  466. body: formData
  467. }
  468. ).catch((err) => {
  469. console.log(err);
  470. error = err;
  471. if ('detail' in err) {
  472. error = err.detail;
  473. }
  474. return null;
  475. });
  476. if (error) {
  477. throw error;
  478. }
  479. return res;
  480. };
  481. // export const pullModel = async (token: string, tagName: string) => {
  482. // return await fetch(`${OLLAMA_API_BASE_URL}/pull`, {
  483. // method: 'POST',
  484. // headers: {
  485. // 'Content-Type': 'text/event-stream',
  486. // Authorization: `Bearer ${token}`
  487. // },
  488. // body: JSON.stringify({
  489. // name: tagName
  490. // })
  491. // });
  492. // };