ollama-chat.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. const roots = [input, input && input.data];
  198. for (let i = 0; i < roots.length; i++) {
  199. const root = roots[i];
  200. if (!root || typeof root !== 'object') {
  201. continue;
  202. }
  203. if (!result.base64 && root.file && typeof root.file.data === 'string') {
  204. result.base64 = root.file.data;
  205. result.mimeType = root.file.mimeType || '';
  206. }
  207. if (!result.base64 && typeof root.base64 === 'string') {
  208. result.base64 = root.base64;
  209. }
  210. if (!result.base64 && typeof root.imageBase64 === 'string') {
  211. result.base64 = root.imageBase64;
  212. }
  213. if (!result.url && typeof root.url === 'string') {
  214. result.url = root.url;
  215. }
  216. if (!result.url && typeof root.sourceUrl === 'string') {
  217. result.url = root.sourceUrl;
  218. }
  219. }
  220. return result;
  221. }
  222. function buildHeaders(config) {
  223. const headers = { 'Content-Type': 'application/json' };
  224. if (config.authType === 'credential' && config.credentialId) {
  225. const auth = smartbotic.credentials.get(config.credentialId);
  226. if (!auth.success) {
  227. throw new Error('Failed to load credential: ' + auth.error);
  228. }
  229. headers[auth.headerName] = auth.headerValue;
  230. }
  231. return headers;
  232. }
  233. function callOllama(config, base64, headers) {
  234. const messages = [];
  235. if (config.systemPrompt && String(config.systemPrompt).trim().length > 0) {
  236. messages.push({ role: 'system', content: String(config.systemPrompt) });
  237. }
  238. const userMessage = { role: 'user', content: config.userPrompt || 'Describe the input.' };
  239. if (base64) {
  240. userMessage.images = [base64];
  241. }
  242. messages.push(userMessage);
  243. const payload = {
  244. model: config.model,
  245. stream: false,
  246. options: { temperature: Number(config.temperature) || 0 },
  247. messages: messages
  248. };
  249. const response = smartbotic.http.request({
  250. method: 'POST',
  251. url: String(config.baseUrl).replace(/\/+$/, '') + '/api/chat',
  252. headers: headers,
  253. body: JSON.stringify(payload),
  254. timeout: Number(config.timeoutMs) || 120000
  255. });
  256. if (response.status < 200 || response.status >= 300) {
  257. const detail = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
  258. throw new Error('Ollama HTTP ' + response.status + ': ' + detail);
  259. }
  260. const body = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  261. if (body && body.error) {
  262. throw new Error('Ollama error: ' + body.error);
  263. }
  264. const content = body && body.message ? body.message.content : '';
  265. if (!content) {
  266. throw new Error('Ollama returned an empty response');
  267. }
  268. return content;
  269. }
  270. module.exports = {
  271. configSchema,
  272. inputSchema,
  273. outputSchema,
  274. async execute(config, input, context) {
  275. let image = { base64: '', mimeType: '', url: '' };
  276. if (config.imageMode !== 'none') {
  277. image = findImage(input, config.imageField);
  278. if (!image.base64 && image.url) {
  279. smartbotic.log.info('ollama-chat: fetching image from ' + image.url);
  280. const dl = smartbotic.http.request({ method: 'GET', url: image.url, timeout: 60000 });
  281. if (dl.status < 200 || dl.status >= 300) {
  282. throw new Error('Failed to fetch image: HTTP ' + dl.status);
  283. }
  284. image.base64 = typeof dl.data === 'string' ? smartbotic.utils.base64Encode(dl.data) : '';
  285. }
  286. }
  287. // Resolved once, outside the retry loop: a missing or broken credential is
  288. // not transient, so retrying it with backoff only wastes time.
  289. const headers = buildHeaders(config);
  290. const wantJson = config.responseFormat === 'json';
  291. const attempts = 1 + (Number(config.retryCount) > 0 ? Number(config.retryCount) : 0);
  292. let content = '';
  293. let parsed = null;
  294. let lastError = '';
  295. let used = 0;
  296. for (let attempt = 1; attempt <= attempts; attempt++) {
  297. used = attempt;
  298. try {
  299. content = callOllama(config, image.base64, headers);
  300. if (wantJson) {
  301. parsed = JSON.parse(stripFences(content));
  302. }
  303. lastError = '';
  304. break;
  305. } catch (err) {
  306. lastError = err && err.message ? err.message : String(err);
  307. parsed = null;
  308. smartbotic.log.warn('ollama-chat: attempt ' + attempt + ' of ' + attempts + ' failed: ' + lastError);
  309. if (attempt < attempts) {
  310. // Exponential backoff. Ollama's cloud tier returns transient 500s far
  311. // more often under rapid succession, so spacing retries out recovers
  312. // markedly better than hammering at a fixed interval.
  313. const base = Number(config.retryDelayMs) || 2000;
  314. const cap = Number(config.retryMaxDelayMs) || 30000;
  315. let delay = base * Math.pow(2, attempt - 1);
  316. if (delay > cap) { delay = cap; }
  317. smartbotic.log.info('ollama-chat: backing off ' + delay + 'ms before retry');
  318. smartbotic.utils.sleep(delay);
  319. }
  320. }
  321. }
  322. const passImage = config.passthroughImage === true;
  323. if (lastError) {
  324. if (config.skipOnError !== true) {
  325. throw new Error('ollama-chat failed after ' + used + ' attempt(s): ' + lastError);
  326. }
  327. smartbotic.log.warn('ollama-chat: skipping after ' + used + ' attempt(s)');
  328. return {
  329. success: false,
  330. error: lastError,
  331. content: content,
  332. json: null,
  333. model: config.model,
  334. attempts: used,
  335. hadImage: image.base64 ? true : false,
  336. imageBase64: passImage ? image.base64 : '',
  337. mimeType: image.mimeType,
  338. sourceUrl: image.url
  339. };
  340. }
  341. return {
  342. success: true,
  343. error: '',
  344. content: content,
  345. json: parsed,
  346. model: config.model,
  347. attempts: used,
  348. hadImage: image.base64 ? true : false,
  349. imageBase64: passImage ? image.base64 : '',
  350. mimeType: image.mimeType,
  351. sourceUrl: image.url
  352. };
  353. }
  354. };