Gemini AI Stream Parser

A reusable function to parse streaming JSON responses from the Google Gemini API.

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/538628/1613479/Gemini%20AI%20Stream%20Parser.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

window.parseGeminiStream = async function(reader, onChunk) { //Processes the Gemini API stream
  for (let buffer = '', partialMarkdown = '';;) { //Loop indefinitely to process the stream
    const { value, done } = await reader.read(); //Read the next chunk from the stream
    if (done) break; //Exit the loop if the stream is finished
    buffer += new TextDecoder().decode(value, { stream: true }); //Decode binary chunk to string and append to buffer
    for (var startIdx = 0, openBrace, balance, closeBrace, item, inString; (openBrace = buffer.indexOf('{', startIdx)) !== -1;) { //Find the start of a JSON object
      for (balance = 1, closeBrace = openBrace + 1, inString = false; balance && closeBrace < buffer.length; closeBrace++) { //Find the corresponding end of the JSON object
        if (buffer[closeBrace] === '"' && buffer[closeBrace - 1] !== '\\') inString = !inString; //Toggle string state on unescaped quotes to handle code blocks with {} symbols in JSON
        if (!inString) balance += (buffer[closeBrace] === '{') - (buffer[closeBrace] === '}'); //Count braces only outside strings to avoid breaking on code symbols like {}
      }
      if (balance) break; //If the object is incomplete, wait for more chunks
      item = JSON.parse(buffer.substring(openBrace, closeBrace)); //Parse the complete JSON object
      partialMarkdown += item.candidates?.[0]?.content?.parts?.[0]?.text || ''; //Append the text from the current chunk
      onChunk(item, partialMarkdown); //Execute the callback with the parsed data and accumulated text
      startIdx = closeBrace; //Move the starting position for the next search
    }
    buffer = buffer.substring(startIdx); //Discard the processed part of the buffer
  }
}