ollama-chat.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /**
  2. * @node ollama-chat
  3. * @name Ollama Chat
  4. * @category ai
  5. * @version 1.0.0
  6. * @description Send a prompt to an Ollama model, optionally with an image for vision models, and return the text or parsed JSON response
  7. * @icon ollama
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. baseUrl: {
  13. type: 'string',
  14. title: 'Ollama Base URL',
  15. description: 'Base URL of the Ollama instance. Use https://ollama.com to call the hosted API directly instead of proxying through a local daemon.',
  16. default: 'http://localhost:11434'
  17. },
  18. authType: {
  19. type: 'string',
  20. title: 'Authentication',
  21. description: 'Hosted ollama.com requires a credential. A local daemon usually does not.',
  22. enum: ['none', 'credential'],
  23. enumLabels: ['None', 'Stored credential'],
  24. default: 'none'
  25. },
  26. credentialId: {
  27. type: 'string',
  28. title: 'Credential',
  29. description: 'Stored Bearer credential holding the ollama.com API key',
  30. // Read as a header, so any header-shaped credential works. An IMAP
  31. // or database credential has no header to send and would only be
  32. // an option that fails.
  33. dynamicOptions: {
  34. source: 'credentials',
  35. filter: { type: ['basic', 'bearer', 'api_key', 'oauth2'] }
  36. },
  37. default: '',
  38. showWhen: { field: 'authType', value: 'credential' }
  39. },
  40. model: {
  41. type: 'string',
  42. title: 'Model',
  43. description: 'Model tag, for example llama3.2 or a vision model tag',
  44. default: 'llama3.2'
  45. },
  46. systemPrompt: {
  47. type: 'string',
  48. title: 'System Prompt',
  49. description: 'Role and output contract for the model. When Response Format is JSON, mention the word JSON here so the model honours it.',
  50. format: 'textarea',
  51. default: ''
  52. },
  53. userPrompt: {
  54. type: 'string',
  55. title: 'User Prompt',
  56. description: 'Message sent with the request. Supports {{variable}} interpolation.',
  57. format: 'textarea',
  58. default: 'Describe the input.'
  59. },
  60. responseFormat: {
  61. type: 'string',
  62. title: 'Response Format',
  63. description: 'How to treat the reply. JSON parses the content and fails the attempt when it is not valid JSON.',
  64. enum: ['text', 'json'],
  65. enumLabels: ['Plain text', 'JSON object'],
  66. default: 'text'
  67. },
  68. temperature: {
  69. type: 'number',
  70. title: 'Temperature',
  71. description: 'Sampling temperature. Use 0 for the most repeatable output.',
  72. default: 0
  73. },
  74. imageMode: {
  75. type: 'string',
  76. title: 'Image Input',
  77. description: 'Auto picks up binary or base64 image data from the previous node. Use None for text-only models.',
  78. enum: ['auto', 'none'],
  79. enumLabels: ['Auto detect', 'None'],
  80. default: 'auto'
  81. },
  82. imageField: {
  83. valueKind: 'path',
  84. type: 'string',
  85. title: 'Image Field Override',
  86. description: 'Optional dot path to base64 image data, for example data.file.data',
  87. default: '',
  88. showWhen: { field: 'imageMode', value: 'auto' }
  89. },
  90. passthroughImage: {
  91. type: 'boolean',
  92. title: 'Pass Image Through',
  93. description: 'Include the base64 image in the output so later nodes can store or reuse it',
  94. default: false
  95. },
  96. retryCount: {
  97. type: 'number',
  98. title: 'Retries',
  99. description: 'Extra attempts after a failed or unparseable response',
  100. default: 0
  101. },
  102. retryDelayMs: {
  103. type: 'number',
  104. title: 'Retry Delay (ms)',
  105. description: 'Pause before the first retry. Doubles on each further attempt.',
  106. default: 2000
  107. },
  108. retryMaxDelayMs: {
  109. type: 'number',
  110. title: 'Max Retry Delay (ms)',
  111. description: 'Upper bound for the exponential backoff',
  112. default: 30000
  113. },
  114. skipOnError: {
  115. type: 'boolean',
  116. title: 'Skip On Error',
  117. description: 'Return success false instead of failing the workflow. Useful inside a loop.',
  118. default: false
  119. },
  120. timeoutMs: {
  121. type: 'number',
  122. title: 'Timeout (ms)',
  123. description: 'Per-attempt request timeout',
  124. default: 120000
  125. }
  126. },
  127. required: ['baseUrl', 'model']
  128. };
  129. const inputSchema = {
  130. type: 'object',
  131. properties: {
  132. data: {
  133. type: 'any',
  134. description: 'Upstream output. Image data is detected here when Image Input is Auto.'
  135. },
  136. file: {
  137. type: 'object',
  138. description: 'Binary file object with base64 data'
  139. },
  140. base64: {
  141. type: 'string',
  142. description: 'Raw base64-encoded image'
  143. },
  144. url: {
  145. type: 'string',
  146. description: 'Image URL, fetched when no binary data is present'
  147. }
  148. }
  149. };
  150. const outputSchema = {
  151. type: 'object',
  152. properties: {
  153. success: { type: 'boolean', description: 'False when the call failed and Skip On Error is enabled' },
  154. error: { type: 'string', description: 'Failure reason when success is false' },
  155. content: { type: 'string', description: 'Raw text reply from the model' },
  156. json: { type: 'any', description: 'Parsed reply when Response Format is JSON' },
  157. model: { type: 'string', description: 'Model that answered' },
  158. attempts: { type: 'number', description: 'How many attempts were made' },
  159. hadImage: { type: 'boolean', description: 'Whether an image was sent' },
  160. imageBase64: { type: 'string', description: 'Base64 image when Pass Image Through is enabled' },
  161. mimeType: { type: 'string', description: 'Image MIME type when known' },
  162. sourceUrl: { type: 'string', description: 'Originating image URL when known' }
  163. }
  164. };
  165. function getPath(root, path) {
  166. if (!root || !path) {
  167. return undefined;
  168. }
  169. const parts = String(path).split('.');
  170. let current = root;
  171. for (let i = 0; i < parts.length; i++) {
  172. if (current === null || typeof current !== 'object') {
  173. return undefined;
  174. }
  175. current = current[parts[i]];
  176. }
  177. return current;
  178. }
  179. function stripFences(text) {
  180. const out = String(text || '').trim();
  181. if (out.indexOf('```') === -1) {
  182. return out;
  183. }
  184. const first = out.indexOf('{');
  185. const last = out.lastIndexOf('}');
  186. if (first !== -1 && last !== -1 && last > first) {
  187. return out.substring(first, last + 1);
  188. }
  189. const firstArr = out.indexOf('[');
  190. const lastArr = out.lastIndexOf(']');
  191. if (firstArr !== -1 && lastArr !== -1 && lastArr > firstArr) {
  192. return out.substring(firstArr, lastArr + 1);
  193. }
  194. return out;
  195. }
  196. function findImage(input, override) {
  197. const result = { base64: '', mimeType: '', url: '' };
  198. if (override) {
  199. const direct = getPath(input, override);
  200. if (typeof direct === 'string' && direct.length > 0) {
  201. result.base64 = direct;
  202. return result;
  203. }
  204. }
  205. // Collect candidate roots breadth-first: inside a loop, or when another node
  206. // sits between the fetch and this one, the file object is nested rather than
  207. // sitting at input or input.data.
  208. const roots = [];
  209. const queue = [input];
  210. let guard = 0;
  211. while (queue.length > 0 && guard < 64) {
  212. guard++;
  213. const node = queue.shift();
  214. if (!node || typeof node !== 'object') {
  215. continue;
  216. }
  217. roots.push(node);
  218. const keys = Object.keys(node);
  219. for (let k = 0; k < keys.length; k++) {
  220. const child = node[keys[k]];
  221. if (child && typeof child === 'object' && keys[k] !== 'file') {
  222. queue.push(child);
  223. }
  224. }
  225. }
  226. for (let i = 0; i < roots.length; i++) {
  227. const root = roots[i];
  228. if (!root || typeof root !== 'object') {
  229. continue;
  230. }
  231. if (!result.base64 && root.file && typeof root.file.data === 'string') {
  232. result.base64 = root.file.data;
  233. result.mimeType = root.file.mimeType || '';
  234. }
  235. if (!result.base64 && typeof root.base64 === 'string') {
  236. result.base64 = root.base64;
  237. }
  238. if (!result.base64 && typeof root.imageBase64 === 'string') {
  239. result.base64 = root.imageBase64;
  240. }
  241. if (!result.url && typeof root.url === 'string') {
  242. result.url = root.url;
  243. }
  244. if (!result.url && typeof root.sourceUrl === 'string') {
  245. result.url = root.sourceUrl;
  246. }
  247. }
  248. return result;
  249. }
  250. function buildHeaders(config) {
  251. const headers = { 'Content-Type': 'application/json' };
  252. if (config.authType === 'credential' && config.credentialId) {
  253. const auth = smartbotic.credentials.get(config.credentialId);
  254. if (!auth.success) {
  255. throw new Error('Failed to load credential: ' + auth.error);
  256. }
  257. headers[auth.headerName] = auth.headerValue;
  258. }
  259. return headers;
  260. }
  261. function callOllama(config, base64, headers) {
  262. const messages = [];
  263. if (config.systemPrompt && String(config.systemPrompt).trim().length > 0) {
  264. messages.push({ role: 'system', content: String(config.systemPrompt) });
  265. }
  266. const userMessage = { role: 'user', content: config.userPrompt || 'Describe the input.' };
  267. if (base64) {
  268. userMessage.images = [base64];
  269. }
  270. messages.push(userMessage);
  271. const payload = {
  272. model: config.model,
  273. stream: false,
  274. options: { temperature: Number(config.temperature) || 0 },
  275. messages: messages
  276. };
  277. const response = smartbotic.http.request({
  278. method: 'POST',
  279. url: String(config.baseUrl).replace(/\/+$/, '') + '/api/chat',
  280. headers: headers,
  281. body: JSON.stringify(payload),
  282. timeout: Number(config.timeoutMs) || 120000
  283. });
  284. if (response.status < 200 || response.status >= 300) {
  285. const detail = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
  286. throw new Error('Ollama HTTP ' + response.status + ': ' + detail);
  287. }
  288. const body = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  289. if (body && body.error) {
  290. throw new Error('Ollama error: ' + body.error);
  291. }
  292. const content = body && body.message ? body.message.content : '';
  293. if (!content) {
  294. throw new Error('Ollama returned an empty response');
  295. }
  296. return content;
  297. }
  298. module.exports = {
  299. configSchema,
  300. inputSchema,
  301. outputSchema,
  302. async execute(config, input, context) {
  303. let image = { base64: '', mimeType: '', url: '' };
  304. if (config.imageMode !== 'none') {
  305. image = findImage(input, config.imageField);
  306. if (!image.base64 && image.url) {
  307. smartbotic.log.info('ollama-chat: fetching image from ' + image.url);
  308. const dl = smartbotic.http.request({ method: 'GET', url: image.url, timeout: 60000 });
  309. if (dl.status < 200 || dl.status >= 300) {
  310. throw new Error('Failed to fetch image: HTTP ' + dl.status);
  311. }
  312. image.base64 = typeof dl.data === 'string' ? smartbotic.utils.base64Encode(dl.data) : '';
  313. }
  314. }
  315. // Resolved once, outside the retry loop: a missing or broken credential is
  316. // not transient, so retrying it with backoff only wastes time.
  317. const headers = buildHeaders(config);
  318. const wantJson = config.responseFormat === 'json';
  319. const attempts = 1 + (Number(config.retryCount) > 0 ? Number(config.retryCount) : 0);
  320. let content = '';
  321. let parsed = null;
  322. let lastError = '';
  323. let used = 0;
  324. for (let attempt = 1; attempt <= attempts; attempt++) {
  325. used = attempt;
  326. try {
  327. content = callOllama(config, image.base64, headers);
  328. if (wantJson) {
  329. parsed = JSON.parse(stripFences(content));
  330. }
  331. lastError = '';
  332. break;
  333. } catch (err) {
  334. lastError = err && err.message ? err.message : String(err);
  335. parsed = null;
  336. smartbotic.log.warn('ollama-chat: attempt ' + attempt + ' of ' + attempts + ' failed: ' + lastError);
  337. if (attempt < attempts) {
  338. // Exponential backoff. Ollama's cloud tier returns transient 500s far
  339. // more often under rapid succession, so spacing retries out recovers
  340. // markedly better than hammering at a fixed interval.
  341. const base = Number(config.retryDelayMs) || 2000;
  342. const cap = Number(config.retryMaxDelayMs) || 30000;
  343. let delay = base * Math.pow(2, attempt - 1);
  344. if (delay > cap) { delay = cap; }
  345. smartbotic.log.info('ollama-chat: backing off ' + delay + 'ms before retry');
  346. smartbotic.utils.sleep(delay);
  347. }
  348. }
  349. }
  350. const passImage = config.passthroughImage === true;
  351. if (lastError) {
  352. if (config.skipOnError !== true) {
  353. throw new Error('ollama-chat failed after ' + used + ' attempt(s): ' + lastError);
  354. }
  355. smartbotic.log.warn('ollama-chat: skipping after ' + used + ' attempt(s)');
  356. return {
  357. success: false,
  358. error: lastError,
  359. content: content,
  360. json: null,
  361. model: config.model,
  362. attempts: used,
  363. hadImage: image.base64 ? true : false,
  364. imageBase64: passImage ? image.base64 : '',
  365. mimeType: image.mimeType,
  366. sourceUrl: image.url
  367. };
  368. }
  369. return {
  370. success: true,
  371. error: '',
  372. content: content,
  373. json: parsed,
  374. model: config.model,
  375. attempts: used,
  376. hadImage: image.base64 ? true : false,
  377. imageBase64: passImage ? image.base64 : '',
  378. mimeType: image.mimeType,
  379. sourceUrl: image.url
  380. };
  381. }
  382. };