ollama / ollama-js

Ollama JavaScript library
https://ollama.ai
MIT License
1.56k stars 103 forks source link

RangeError: Maximum call stack size exceeded in encodeImage Function with Large Uint8Array Inputs #89

Open jzevin opened 1 month ago

jzevin commented 1 month ago

The current implementation of the encodeImage function may encounter issues when handling large Uint8Array inputs due to the use of Function.prototype.apply. This can result in a RangeError: Maximum call stack size exceeded or other performance-related problems when the array size exceeds the argument limit of the JavaScript engine.

Steps to Reproduce

  1. Create a large Uint8Array (e.g., 100,000 bytes or more).
  2. Call the encodeImage function with this array.
  3. Observe any errors or performance issues.

Proposed Implementation

async function encodeImage(image: Uint8Array | string): Promise<string> {
  if (typeof image !== 'string') {
    // image is Uint8Array, convert it to base64
    const uint8Array = new Uint8Array(image);
    let binary = '';
    const len = uint8Array.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(uint8Array[i]);
    }
    return btoa(binary);
  }
  // the string may be base64 encoded
  return image;
}