File size: 5,389 Bytes
9853396 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | const { GoogleGenAI } = require("@google/genai");
const { TestConfig } = require("./config");
class StreamingTestHelper {
constructor() {
this.config = new TestConfig();
try {
this.config.validateConfig();
this.client = new GoogleGenAI({
apiKey: this.config.apiKey,
httpOptions: {
baseUrl: this.config.baseUrl,
headers: this.config.getHeaders(),
},
});
} catch (error) {
console.log(
`Skipping tests due to configuration error: ${error.message}`
);
process.exit(0);
}
}
getModel() {
return this.config.model;
}
createRequestContext() {
return {
headers: this.config.getHeaders(),
};
}
}
async function collectStream(stream) {
let fullText = "";
let chunkCount = 0;
for await (const chunk of stream) {
chunkCount++;
if (!chunk || !chunk.candidates || chunk.candidates.length === 0) {
continue;
}
const candidate = chunk.candidates[0];
const parts = candidate.content?.parts || [];
for (const part of parts) {
if (part?.text) {
fullText += part.text;
console.log(`Stream chunk ${chunkCount}: ${part.text}`);
}
}
}
return { fullText, chunkCount };
}
async function testBasicStreamingChatCompletion() {
console.log("Running TestBasicStreamingChatCompletion...");
const helper = new StreamingTestHelper();
const modelName = helper.getModel();
const context = helper.createRequestContext();
const question = "Tell me a short story about a robot learning to paint.";
console.log(`Sending streaming request: ${question}`);
try {
const stream = await helper.client.models.generateContentStream({
model: modelName,
contents: [
{
role: "user",
parts: [{ text: question }],
},
],
...context,
});
const { fullText, chunkCount } = await collectStream(stream);
console.log(`Total streaming responses: ${chunkCount}`);
if (!fullText) {
throw new Error("Expected non-empty streaming response");
}
if (
!fullText.toLowerCase().includes("robot") &&
!fullText.toLowerCase().includes("paint")
) {
throw new Error(
`Expected content to mention robot or paint, got: ${fullText}`
);
}
console.log("✅ TestBasicStreamingChatCompletion passed");
} catch (error) {
error.stack &&
console.error("❌ TestBasicStreamingChatCompletion failed:", error.stack);
console.error("❌ TestBasicStreamingChatCompletion failed:", error.message);
throw error;
}
}
async function testLongResponseStreaming() {
console.log("Running TestLongResponseStreaming...");
const helper = new StreamingTestHelper();
const modelName = helper.getModel();
const context = helper.createRequestContext();
const question =
"Write a detailed explanation of how photosynthesis works, including the light-dependent and light-independent reactions.";
console.log("Sending streaming request for long response...");
try {
const stream = await helper.client.models.generateContentStream({
model: modelName,
contents: [
{
role: "user",
parts: [{ text: question }],
},
],
...context,
});
const { fullText, chunkCount } = await collectStream(stream);
console.log(
`Long streamed response: ${fullText.length} characters in ${chunkCount} chunks`
);
if (fullText.length < 100) {
throw new Error(
`Expected longer content, got: ${fullText.length} characters`
);
}
const expectedTerms = [
"photosynthesis",
"light",
"chlorophyll",
"carbon dioxide",
"oxygen",
];
const foundTerms = expectedTerms.filter((term) =>
fullText.toLowerCase().includes(term)
);
if (foundTerms.length < 2) {
throw new Error(
`Expected explanation to contain more key terms, found ${foundTerms.length}/${expectedTerms.length}`
);
}
console.log("✅ TestLongResponseStreaming passed");
} catch (error) {
console.error("❌ TestLongResponseStreaming failed:", error.message);
throw error;
}
}
async function runStreamingTests() {
console.log("🚀 Starting Gemini Node.js Streaming Tests\n");
const tests = [testBasicStreamingChatCompletion, testLongResponseStreaming];
let passed = 0;
let failed = 0;
for (const test of tests) {
try {
await test();
passed++;
} catch (error) {
failed++;
console.error(`Test failed: ${error.message}`);
}
console.log("");
}
console.log(
`\n📊 Streaming Test Results: ${passed} passed, ${failed} failed`
);
if (failed > 0) {
process.exit(1);
} else {
console.log("🎉 All streaming tests passed!");
process.exit(0);
}
}
if (require.main === module) {
runStreamingTests().catch((error) => {
console.error("❌ Streaming test runner failed:", error.message);
process.exit(1);
});
}
module.exports = {
StreamingTestHelper,
testBasicStreamingChatCompletion,
testLongResponseStreaming,
runStreamingTests,
};
|