Skip to content

Commit 58d4cad

Browse files
committed
Fix stream overwrite issue
1 parent bbb9d4a commit 58d4cad

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

packages/ai/src/requests/stream-reader.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { createEnhancedContentResponse } from './response-helpers';
2828
import * as GoogleAIMapper from '../googleai-mappers';
2929
import { GoogleAIGenerateContentResponse } from '../types/googleai';
3030
import { ApiSettings } from '../types/internal';
31-
import { BackendType } from '../public-types';
31+
import { BackendType, URLContextMetadata } from '../public-types';
3232

3333
const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
3434

@@ -192,8 +192,15 @@ export function aggregateResponses(
192192
candidate.safetyRatings;
193193
aggregatedResponse.candidates[i].groundingMetadata =
194194
candidate.groundingMetadata;
195-
aggregatedResponse.candidates[i].urlContextMetadata =
196-
candidate.urlContextMetadata;
195+
196+
// The urlContextMetadata object is defined in the first chunk of the response stream.
197+
// In all subsequent chunks, the urlContextMetadata object will be undefined. We need to
198+
// make sure that we don't overwrite the first value urlContextMetadata object with undefined.
199+
// FIXME: What happens if we receive a second, valid urlContextMetadata object?
200+
const urlContextMetadata = candidate.urlContextMetadata as unknown;
201+
if (typeof urlContextMetadata === 'object' && urlContextMetadata !== null && Object.keys(urlContextMetadata).length > 0) {
202+
aggregatedResponse.candidates[i].urlContextMetadata = urlContextMetadata as URLContextMetadata;
203+
}
197204

198205
/**
199206
* Candidates should always have content and parts, but this handles

0 commit comments

Comments
 (0)