ollama-chat.js 14 KB

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