@@ -100,6 +100,17 @@ async function* generateResponseSequence(
100
100
enhancedResponse = createEnhancedContentResponse ( value ) ;
101
101
}
102
102
103
+ const firstCandidate = enhancedResponse . candidates ?. [ 0 ] ;
104
+ // Don't yield a response with no useful data for the developer.
105
+ if (
106
+ ! firstCandidate ?. content ?. parts &&
107
+ ! firstCandidate ?. finishReason &&
108
+ ! firstCandidate ?. citationMetadata &&
109
+ ! firstCandidate ?. urlContextMetadata
110
+ ) {
111
+ continue ;
112
+ }
113
+
103
114
yield enhancedResponse ;
104
115
}
105
116
}
@@ -211,37 +222,30 @@ export function aggregateResponses(
211
222
* Candidates should always have content and parts, but this handles
212
223
* possible malformed responses.
213
224
*/
214
- if ( candidate . content && candidate . content . parts ) {
225
+ if ( candidate . content ) {
226
+ // Skip a candidate without parts.
227
+ if ( ! candidate . content . parts ) {
228
+ continue ;
229
+ }
215
230
if ( ! aggregatedResponse . candidates [ i ] . content ) {
216
231
aggregatedResponse . candidates [ i ] . content = {
217
232
role : candidate . content . role || 'user' ,
218
233
parts : [ ]
219
234
} ;
220
235
}
221
- const newPart : Partial < Part > = { } ;
222
236
for ( const part of candidate . content . parts ) {
223
- if ( part . text !== undefined ) {
224
- // The backend can send empty text parts. If these are sent back
225
- // (e.g. in chat history), the backend will respond with an error.
226
- // To prevent this, ignore empty text parts.
227
- if ( part . text === '' ) {
228
- continue ;
229
- }
230
- newPart . text = part . text ;
231
- }
232
- if ( part . functionCall ) {
233
- newPart . functionCall = part . functionCall ;
237
+ const newPart : Part = { ...part } ;
238
+ // The backend can send empty text parts. If these are sent back
239
+ // (e.g. in chat history), the backend will respond with an error.
240
+ // To prevent this, ignore empty text parts.
241
+ if ( part . text === '' ) {
242
+ continue ;
234
243
}
235
- if ( Object . keys ( newPart ) . length === 0 ) {
236
- throw new AIError (
237
- AIErrorCode . INVALID_CONTENT ,
238
- 'Part should have at least one property, but there are none. This is likely caused ' +
239
- 'by a malformed response from the backend.'
244
+ if ( Object . keys ( newPart ) . length > 0 ) {
245
+ aggregatedResponse . candidates [ i ] . content . parts . push (
246
+ newPart as Part
240
247
) ;
241
248
}
242
- aggregatedResponse . candidates [ i ] . content . parts . push (
243
- newPart as Part
244
- ) ;
245
249
}
246
250
}
247
251
}
0 commit comments