index.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { OLLAMA_API_BASE_URL } from '$lib/constants';
  2. import { promptTemplate } from '$lib/utils';
  3. export const getOllamaUrls = async (token: string = '') => {
  4. let error = null;
  5. const res = await fetch(`${OLLAMA_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.OLLAMA_BASE_URLS;
  30. };
  31. export const updateOllamaUrls = async (token: string = '', urls: string[]) => {
  32. let error = null;
  33. const res = await fetch(`${OLLAMA_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.OLLAMA_BASE_URLS;
  61. };
  62. export const getOllamaVersion = async (token: string = '') => {
  63. let error = null;
  64. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/version`, {
  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?.version ?? '';
  89. };
  90. export const getOllamaModels = async (token: string = '') => {
  91. let error = null;
  92. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/tags`, {
  93. method: 'GET',
  94. headers: {
  95. Accept: 'application/json',
  96. 'Content-Type': 'application/json',
  97. ...(token && { authorization: `Bearer ${token}` })
  98. }
  99. })
  100. .then(async (res) => {
  101. if (!res.ok) throw await res.json();
  102. return res.json();
  103. })
  104. .catch((err) => {
  105. console.log(err);
  106. if ('detail' in err) {
  107. error = err.detail;
  108. } else {
  109. error = 'Server connection failed';
  110. }
  111. return null;
  112. });
  113. if (error) {
  114. throw error;
  115. }
  116. return (res?.models ?? [])
  117. .map((model) => ({ id: model.model, name: model.name ?? model.model, ...model }))
  118. .sort((a, b) => {
  119. return a.name.localeCompare(b.name);
  120. });
  121. };
  122. // TODO: migrate to backend
  123. export const generateTitle = async (
  124. token: string = '',
  125. template: string,
  126. model: string,
  127. prompt: string
  128. ) => {
  129. let error = null;
  130. template = promptTemplate(template, prompt);
  131. console.log(template);
  132. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  133. method: 'POST',
  134. headers: {
  135. Accept: 'application/json',
  136. 'Content-Type': 'application/json',
  137. Authorization: `Bearer ${token}`
  138. },
  139. body: JSON.stringify({
  140. model: model,
  141. prompt: template,
  142. stream: false,
  143. options: {
  144. // Restrict the number of tokens generated to 50
  145. num_predict: 50,
  146. }
  147. })
  148. })
  149. .then(async (res) => {
  150. if (!res.ok) throw await res.json();
  151. return res.json();
  152. })
  153. .catch((err) => {
  154. console.log(err);
  155. if ('detail' in err) {
  156. error = err.detail;
  157. }
  158. return null;
  159. });
  160. if (error) {
  161. throw error;
  162. }
  163. return res?.response ?? 'New Chat';
  164. };
  165. export const generatePrompt = async (token: string = '', model: string, conversation: string) => {
  166. let error = null;
  167. if (conversation === '') {
  168. conversation = '[no existing conversation]';
  169. }
  170. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
  171. method: 'POST',
  172. headers: {
  173. Accept: 'application/json',
  174. 'Content-Type': 'application/json',
  175. Authorization: `Bearer ${token}`
  176. },
  177. body: JSON.stringify({
  178. model: model,
  179. prompt: `Conversation:
  180. ${conversation}
  181. 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.
  182. Response:
  183. `
  184. })
  185. }).catch((err) => {
  186. console.log(err);
  187. if ('detail' in err) {
  188. error = err.detail;
  189. }
  190. return null;
  191. });
  192. if (error) {
  193. throw error;
  194. }
  195. return res;
  196. };
  197. export const generateEmbeddings = async (token: string = '', model: string, text: string) => {
  198. let error = null;
  199. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/embeddings`, {
  200. method: 'POST',
  201. headers: {
  202. Accept: 'application/json',
  203. 'Content-Type': 'application/json',
  204. Authorization: `Bearer ${token}`
  205. },
  206. body: JSON.stringify({
  207. model: model,
  208. prompt: text
  209. })
  210. }).catch((err) => {
  211. error = err;
  212. return null;
  213. });
  214. if (error) {
  215. throw error;
  216. }
  217. return res;
  218. };
  219. export const generateTextCompletion = async (token: string = '', model: string, text: string) => {
  220. let error = null;
  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: text,
  231. stream: true
  232. })
  233. }).catch((err) => {
  234. error = err;
  235. return null;
  236. });
  237. if (error) {
  238. throw error;
  239. }
  240. return res;
  241. };
  242. export const generateChatCompletion = async (token: string = '', body: object) => {
  243. let controller = new AbortController();
  244. let error = null;
  245. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/chat`, {
  246. signal: controller.signal,
  247. method: 'POST',
  248. headers: {
  249. Accept: 'application/json',
  250. 'Content-Type': 'application/json',
  251. Authorization: `Bearer ${token}`
  252. },
  253. body: JSON.stringify(body)
  254. }).catch((err) => {
  255. error = err;
  256. return null;
  257. });
  258. if (error) {
  259. throw error;
  260. }
  261. return [res, controller];
  262. };
  263. export const cancelOllamaRequest = async (token: string = '', requestId: string) => {
  264. let error = null;
  265. const res = await fetch(`${OLLAMA_API_BASE_URL}/cancel/${requestId}`, {
  266. method: 'GET',
  267. headers: {
  268. 'Content-Type': 'text/event-stream',
  269. Authorization: `Bearer ${token}`
  270. }
  271. }).catch((err) => {
  272. error = err;
  273. return null;
  274. });
  275. if (error) {
  276. throw error;
  277. }
  278. return res;
  279. };
  280. export const createModel = async (token: string, tagName: string, content: string) => {
  281. let error = null;
  282. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/create`, {
  283. method: 'POST',
  284. headers: {
  285. Accept: 'application/json',
  286. 'Content-Type': 'application/json',
  287. Authorization: `Bearer ${token}`
  288. },
  289. body: JSON.stringify({
  290. name: tagName,
  291. modelfile: content
  292. })
  293. }).catch((err) => {
  294. error = err;
  295. return null;
  296. });
  297. if (error) {
  298. throw error;
  299. }
  300. return res;
  301. };
  302. export const deleteModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  303. let error = null;
  304. const res = await fetch(
  305. `${OLLAMA_API_BASE_URL}/api/delete${urlIdx !== null ? `/${urlIdx}` : ''}`,
  306. {
  307. method: 'DELETE',
  308. headers: {
  309. Accept: 'application/json',
  310. 'Content-Type': 'application/json',
  311. Authorization: `Bearer ${token}`
  312. },
  313. body: JSON.stringify({
  314. name: tagName
  315. })
  316. }
  317. )
  318. .then(async (res) => {
  319. if (!res.ok) throw await res.json();
  320. return res.json();
  321. })
  322. .then((json) => {
  323. console.log(json);
  324. return true;
  325. })
  326. .catch((err) => {
  327. console.log(err);
  328. error = err;
  329. if ('detail' in err) {
  330. error = err.detail;
  331. }
  332. return null;
  333. });
  334. if (error) {
  335. throw error;
  336. }
  337. return res;
  338. };
  339. export const pullModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
  340. let error = null;
  341. const res = await fetch(`${OLLAMA_API_BASE_URL}/api/pull${urlIdx !== null ? `/${urlIdx}` : ''}`, {
  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. })
  351. }).catch((err) => {
  352. console.log(err);
  353. error = err;
  354. if ('detail' in err) {
  355. error = err.detail;
  356. }
  357. return null;
  358. });
  359. if (error) {
  360. throw error;
  361. }
  362. return res;
  363. };
  364. export const downloadModel = async (
  365. token: string,
  366. download_url: string,
  367. urlIdx: string | null = null
  368. ) => {
  369. let error = null;
  370. const res = await fetch(
  371. `${OLLAMA_API_BASE_URL}/models/download${urlIdx !== null ? `/${urlIdx}` : ''}`,
  372. {
  373. method: 'POST',
  374. headers: {
  375. Accept: 'application/json',
  376. 'Content-Type': 'application/json',
  377. Authorization: `Bearer ${token}`
  378. },
  379. body: JSON.stringify({
  380. url: download_url
  381. })
  382. }
  383. ).catch((err) => {
  384. console.log(err);
  385. error = err;
  386. if ('detail' in err) {
  387. error = err.detail;
  388. }
  389. return null;
  390. });
  391. if (error) {
  392. throw error;
  393. }
  394. return res;
  395. };
  396. export const uploadModel = async (token: string, file: File, urlIdx: string | null = null) => {
  397. let error = null;
  398. const formData = new FormData();
  399. formData.append('file', file);
  400. const res = await fetch(
  401. `${OLLAMA_API_BASE_URL}/models/upload${urlIdx !== null ? `/${urlIdx}` : ''}`,
  402. {
  403. method: 'POST',
  404. headers: {
  405. Authorization: `Bearer ${token}`
  406. },
  407. body: formData
  408. }
  409. ).catch((err) => {
  410. console.log(err);
  411. error = err;
  412. if ('detail' in err) {
  413. error = err.detail;
  414. }
  415. return null;
  416. });
  417. if (error) {
  418. throw error;
  419. }
  420. return res;
  421. };
  422. // export const pullModel = async (token: string, tagName: string) => {
  423. // return await fetch(`${OLLAMA_API_BASE_URL}/pull`, {
  424. // method: 'POST',
  425. // headers: {
  426. // 'Content-Type': 'text/event-stream',
  427. // Authorization: `Bearer ${token}`
  428. // },
  429. // body: JSON.stringify({
  430. // name: tagName
  431. // })
  432. // });
  433. // };