index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { OLLAMA_API_BASE_URL } from '$lib/constants';
  2. export const verifyOllamaConnection = async (
  3. token: string = '',
  4. url: string = '',
  5. key: string = ''
  6. ) => {
  7. let error = null;
  8. const res = await fetch(`${OLLAMA_API_BASE_URL}/verify`, {
  9. method: 'POST',
  10. headers: {
  11. Accept: 'application/json',
  12. Authorization: `Bearer ${token}`,
  13. 'Content-Type': 'application/json'
  14. },
  15. body: JSON.stringify({
  16. url,
  17. key
  18. })
  19. })
  20. .then(async (res) => {
  21. if (!res.ok) throw await res.json();
  22. return res.json();
  23. })
  24. .catch((err) => {
  25. error = `Ollama: ${err?.error?.message ?? 'Network Problem'}`;
  26. return [];
  27. });
  28. if (error) {
  29. throw error;
  30. }
  31. return res;
  32. };
  33. export const getOllamaConfig = async (token: string = '') => {
  34. let error = null;
  35. const res = await fetch(`${OLLAMA_API_BASE_URL}/config`, {
  36. method: 'GET',
  37. headers: {
  38. Accept: 'application/json',
  39. 'Content-Type': 'application/json',
  40. ...(token && { authorization: `Bearer ${token}` })
  41. }
  42. })
  43. .then(async (res) => {
  44. if (!res.ok) throw await res.json();
  45. return res.json();
  46. })
  47. .catch((err) => {
  48. console.log(err);
  49. if ('detail' in err) {
  50. error = err.detail;
  51. } else {
  52. error = 'Server connection failed';
  53. }
  54. return null;
  55. });
  56. if (error) {
  57. throw error;
  58. }
  59. return res;
  60. };
  61. type OllamaConfig = {
  62. ENABLE_OLLAMA_API: boolean;
  63. OLLAMA_BASE_URLS: string[];
  64. OLLAMA_API_CONFIGS: object;
  65. };
  66. export const updateOllamaConfig = async (token: string = '', config: OllamaConfig) => {
  67. let error = null;
  68. const res = await fetch(`${OLLAMA_API_BASE_URL}/config/update`, {
  69. method: 'POST',
  70. headers: {
  71. Accept: 'application/json',
  72. 'Content-Type': 'application/json',
  73. ...(token && { authorization: `Bearer ${token}` })
  74. },
  75. body: JSON.stringify({
  76. ...config
  77. })
  78. })
  79. .then(async (res) => {
  80. if (!res.ok) throw await res.json();
  81. return res.json();
  82. })
  83. .catch((err) => {
  84. console.log(err);
  85. if ('detail' in err) {
  86. error = err.detail;
  87. } else {
  88. error = 'Server connection failed';
  89. }
  90. return null;
  91. });
  92. if (error) {
  93. throw error;
  94. }
  95. return res;
  96. };
  97. export const getOllamaUrls = async (token: string = '') => {
  98. let error = null;
  99. const res = await fetch(`${OLLAMA_API_BASE_URL}/urls`, {
  100. method: 'GET',
  101. headers: {
  102. Accept: 'application/json',
  103. 'Content-Type': 'application/json',
  104. ...(token && { authorization: `Bearer ${token}` })
  105. }
  106. })
  107. .then(async (res) => {
  108. if (!res.ok) throw await res.json();
  109. return res.json();
  110. })
  111. .catch((err) => {
  112. console.log(err);
  113. if ('detail' in err) {
  114. error = err.detail;
  115. } else {
  116. error = 'Server connection failed';
  117. }
  118. return null;
  119. });
  120. if (error) {
  121. throw error;
  122. }
  123. return res.OLLAMA_BASE_URLS;
  124. };
  125. export const updateOllamaUrls = async (token: string = '', urls: string[]) => {
  126. let error = null;
  127. const res = await fetch(`${OLLAMA_API_BASE_URL}/urls/update`, {
  128. method: 'POST',
  129. headers: {
  130. Accept: 'application/json',
  131. 'Content-Type': 'application/json',
  132. ...(token && { authorization: `Bearer ${token}` })
  133. },
  134. body: JSON.stringify({
  135. urls: urls
  136. })
  137. })
  138. .then(async (res) => {
  139. if (!res.ok) throw await res.json();
  140. return res.json();
  141. })
  142. .catch((err) => {
  143. console.log(err);
  144. if ('detail' in err) {
  145. error = err.detail;
  146. } else {
  147. error = 'Server connection failed';
  148. }
  149. return null;
  150. });
  151. if (error) {
  152. throw error;
  153. }
  154. return res.OLLAMA_BASE_URLS;
  155. };
  156. export const getOllamaVersion = async (token: string, urlIdx?: number) => {
  157. let error = null;
  158. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/version${urlIdx ? `/${urlIdx}` : ''}`, {
  159. method: 'GET',
  160. headers: {
  161. Accept: 'application/json',
  162. 'Content-Type': 'application/json',
  163. ...(token && { authorization: `Bearer ${token}` })
  164. }
  165. })
  166. .then(async (res) => {
  167. if (!res.ok) throw await res.json();
  168. return res.json();
  169. })
  170. .catch((err) => {
  171. console.log(err);
  172. if ('detail' in err) {
  173. error = err.detail;
  174. } else {
  175. error = 'Server connection failed';
  176. }
  177. return null;
  178. });
  179. if (error) {
  180. throw error;
  181. }
  182. return res?.version ?? false;
  183. };
  184. export const getOllamaModels = async (token: string = '', urlIdx: null | number = null) => {
  185. let error = null;
  186. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/tags${urlIdx !== null ? `/${urlIdx}` : ''}`, {
  187. method: 'GET',
  188. headers: {
  189. Accept: 'application/json',
  190. 'Content-Type': 'application/json',
  191. ...(token && { authorization: `Bearer ${token}` })
  192. }
  193. })
  194. .then(async (res) => {
  195. if (!res.ok) throw await res.json();
  196. return res.json();
  197. })
  198. .catch((err) => {
  199. console.log(err);
  200. if ('detail' in err) {
  201. error = err.detail;
  202. } else {
  203. error = 'Server connection failed';
  204. }
  205. return null;
  206. });
  207. if (error) {
  208. throw error;
  209. }
  210. return (res?.models ?? [])
  211. .map((model) => ({ id: model.model, name: model.name ?? model.model, ...model }))
  212. .sort((a, b) => {
  213. return a.name.localeCompare(b.name);
  214. });
  215. };
  216. export const generatePrompt = async (token: string = '', model: string, conversation: string) => {
  217. let error = null;
  218. if (conversation === '') {
  219. conversation = '[no existing conversation]';
  220. }
  221. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  222. method: 'POST',
  223. headers: {
  224. Accept: 'application/json',
  225. 'Content-Type': 'application/json',
  226. Authorization: `Bearer ${token}`
  227. },
  228. body: JSON.stringify({
  229. model: model,
  230. prompt: `Conversation:
  231. ${conversation}
  232. 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.
  233. Response:
  234. `
  235. })
  236. }).catch((err) => {
  237. console.log(err);
  238. if ('detail' in err) {
  239. error = err.detail;
  240. }
  241. return null;
  242. });
  243. if (error) {
  244. throw error;
  245. }
  246. return res;
  247. };
  248. export const generateEmbeddings = async (token: string = '', model: string, text: string) => {
  249. let error = null;
  250. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/embeddings`, {
  251. method: 'POST',
  252. headers: {
  253. Accept: 'application/json',
  254. 'Content-Type': 'application/json',
  255. Authorization: `Bearer ${token}`
  256. },
  257. body: JSON.stringify({
  258. model: model,
  259. prompt: text
  260. })
  261. }).catch((err) => {
  262. error = err;
  263. return null;
  264. });
  265. if (error) {
  266. throw error;
  267. }
  268. return res;
  269. };
  270. export const generateTextCompletion = async (token: string = '', model: string, text: string) => {
  271. let error = null;
  272. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  273. method: 'POST',
  274. headers: {
  275. Accept: 'application/json',
  276. 'Content-Type': 'application/json',
  277. Authorization: `Bearer ${token}`
  278. },
  279. body: JSON.stringify({
  280. model: model,
  281. prompt: text,
  282. stream: true
  283. })
  284. }).catch((err) => {
  285. error = err;
  286. return null;
  287. });
  288. if (error) {
  289. throw error;
  290. }
  291. return res;
  292. };
  293. export const generateChatCompletion = async (token: string = '', body: object) => {
  294. let controller = new AbortController();
  295. let error = null;
  296. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/chat`, {
  297. signal: controller.signal,
  298. method: 'POST',
  299. headers: {
  300. Accept: 'application/json',
  301. 'Content-Type': 'application/json',
  302. Authorization: `Bearer ${token}`
  303. },
  304. body: JSON.stringify(body)
  305. }).catch((err) => {
  306. error = err;
  307. return null;
  308. });
  309. if (error) {
  310. throw error;
  311. }
  312. return [res, controller];
  313. };
  314. export const createModel = async (
  315. token: string,
  316. tagName: string,
  317. content: string,
  318. urlIdx: string | null = null
  319. ) => {
  320. let error = null;
  321. const res = await fetch(
  322. `${OLLAMA_API_BASE_URL}/api/create${urlIdx !== null ? `/${urlIdx}` : ''}`,
  323. {
  324. method: 'POST',
  325. headers: {
  326. Accept: 'application/json',
  327. 'Content-Type': 'application/json',
  328. Authorization: `Bearer ${token}`
  329. },
  330. body: JSON.stringify({
  331. name: tagName,
  332. modelfile: content
  333. })
  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: number | 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. // };