Skip to content

Commit 87a0b88

Browse files
committed
add streaming bug fix
1 parent 95cc708 commit 87a0b88

File tree

1 file changed

+15
-24
lines changed

1 file changed

+15
-24
lines changed

lib/subscribers/google-genai/generate-content-stream.js

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,26 @@ class GoogleGenAIGenerateContentStreamSubscriber extends GoogleGenAIGenerateCont
2929
*/
3030
instrumentStream({ request, response, segment, transaction }) {
3131
const originalNext = response.next
32+
let isDone = false
33+
let cachedResult = {}
3234
let err
33-
let content
34-
let modelVersion
35-
let finishReason
3635
let entireMessage = ''
3736
response.next = async function wrappedNext(...nextArgs) {
3837
let result = {}
3938
try {
4039
result = await originalNext.apply(response, nextArgs)
40+
// When the stream is done we get {value: undefined, done: true}
41+
// we need to cache the composed value and add the entire message
42+
// back in later
43+
if (result.done === true) {
44+
isDone = true
45+
} else {
46+
cachedResult = result.value
47+
}
48+
4149
if (result?.value?.text) {
42-
modelVersion = result?.value?.modelVersion
43-
content = result?.value?.candidates?.[0]?.content
4450
entireMessage += result.value.text // readonly variable that equates to result.value.candidates[0].content.parts[0].text
4551
}
46-
if (result?.value?.candidates?.[0]?.finishReason) {
47-
finishReason = result.value.candidates[0].finishReason
48-
}
4952
} catch (streamErr) {
5053
err = streamErr
5154
throw err
@@ -54,29 +57,17 @@ class GoogleGenAIGenerateContentStreamSubscriber extends GoogleGenAIGenerateCont
5457
// time it took to handle the stream
5558
segment.touch()
5659

57-
// result will be {value: undefined, done: true}
58-
// when the stream is done, so we need to create
59-
// a mock GenerateContentResponse object with
60-
// the entire message
61-
//
6260
// also need to enter this block if there was an
6361
// error, so we can record it
64-
if (result?.done || err) {
65-
if (content) {
66-
content.parts[0].text = entireMessage
67-
result.value = {
68-
candidates: [
69-
{ content, finishReason }
70-
],
71-
modelVersion
72-
}
62+
if (isDone || err) {
63+
if (cachedResult?.candidates?.[0]?.content?.parts) {
64+
cachedResult.candidates[0].content.parts[0].text = entireMessage
7365
}
74-
7566
this.recordChatCompletionMessages({
7667
segment,
7768
transaction,
7869
request,
79-
response: result?.value,
70+
response: cachedResult,
8071
err
8172
})
8273
}

0 commit comments

Comments
 (0)