您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
A reusable function to parse streaming JSON responses from the Google Gemini API.
此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.icu/scripts/538628/1603085/Gemini%20AI%20Stream%20Parser.js
If you like my work, please consider supporting it!
Cryptos https://cyber-sec0.github.io
https://www.patreon.com/hacker09
This library will always be updated to the latest version
To always have the latest version, use
// @require https://update.greasyfork.org/scripts/538628/Gemini%20AI%20Stream%20Parser.js
Documentation
The parseGeminiStream
library is a specialized solution for handling streaming responses from the Gemini API. It was created to solve challenges with parsing API responses that include:
{}
that break standard JSON parsingThis library is essential for developers working with the Gemini API in JavaScript environments, especially in userscripts where existing solutions were inadequate.
Handles incomplete JSON chunks gracefully, reassembling them as more data arrives
Accurately processes code snippets containing braces without breaking JSON parsing
Processes data incrementally as it arrives for responsive user experiences
Include the library in your project:
// ==UserScript== // @require https://update.greasyfork.org/scripts/538628/Gemini%20AI%20Stream%20Parser.js // ==/UserScript==
//You can parse the text response markdown to HTML if you use the marked.js library below // @require https://update.greasyfork.org/scripts/506699/marked.js // Make API request with responseType: 'stream' const request = GM.xmlHttpRequest({ method: "POST", url: `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:streamGenerateContent?key=YOUR_API_KEY`, responseType: 'stream', // ...other parameters... onloadstart: async function(response) { const reader = response.response.getReader(); // Use the parser library await window.parseGeminiStream(reader, (item, markdown) => { // Process each chunk if (item.error) { console.error("API Error:", item.error); } else { // Update UI with incremental response document.getElementById("response").innerHTML = window.marked.parse(markdown); } }); } });
Parameter | Type | Description |
---|---|---|
reader | ReadableStreamDefaultReader | Reader from the Fetch API's Response body |
onChunk | Function | Callback that receives parsed objects and accumulated markdown |
Reads binary chunks from the API response stream and decodes them to text.
Accumulates text chunks in a buffer, handling incomplete JSON objects that span multiple chunks.
Identifies complete JSON objects within the buffer by:
{
Parses complete JSON objects and passes them to your callback function immediately.
The library intelligently handles code blocks that contain braces which would normally break JSON parsing:
Tracks when the parser is inside a string to ignore braces used in code
if (buffer[closeBrace] === '"' && buffer[closeBrace - 1] !== '\\') { inString = !inString; }
Only counts braces outside of strings to maintain accurate JSON structure
if (!inString) { balance += (buffer[closeBrace] === '{') - (buffer[closeBrace] === '}'); }
// Make API request const request = GM.xmlHttpRequest({ method: "POST", url: `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:streamGenerateContent?key=${API_KEY}`, responseType: 'stream', headers: { "Content-Type": "application/json" }, data: JSON.stringify({ contents: [{ parts: [{ text: "Explain quantum computing" }] }] }), onloadstart: async function(response) { const reader = response.response.getReader(); let fullResponse = ""; await window.parseGeminiStream(reader, (item, markdown) => { if (item.error) { console.error("API Error:", item.error); return; } // Update UI incrementally fullResponse = markdown; document.getElementById("ai-response").innerHTML = window.marked.parse(fullResponse); }); console.log("Full response:", fullResponse); } });
This library was created to solve a specific challenge with Gemini API responses. If you encounter any issues or have suggestions for improvement:
Please report bugs and issues so I can fix or implement necessary features.Your feedback helps improve the library for everyone!