ollama-chat.js 12 KB

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