@@ -140,34 +140,35 @@ export function aggregateResponses(
140
140
} ;
141
141
for ( const response of responses ) {
142
142
if ( response . candidates ) {
143
+ let candidateIndex = 0 ;
143
144
for ( const candidate of response . candidates ) {
144
- const i = candidate . index ;
145
145
if ( ! aggregatedResponse . candidates ) {
146
146
aggregatedResponse . candidates = [ ] ;
147
147
}
148
- if ( ! aggregatedResponse . candidates [ i ] ) {
149
- aggregatedResponse . candidates [ i ] = {
150
- index : candidate . index ,
148
+ if ( ! aggregatedResponse . candidates [ candidateIndex ] ) {
149
+ aggregatedResponse . candidates [ candidateIndex ] = {
150
+ index : candidateIndex ,
151
151
} as GenerateContentCandidate ;
152
152
}
153
153
// Keep overwriting, the last one will be final
154
- aggregatedResponse . candidates [ i ] . citationMetadata =
154
+ aggregatedResponse . candidates [ candidateIndex ] . citationMetadata =
155
155
candidate . citationMetadata ;
156
- aggregatedResponse . candidates [ i ] . groundingMetadata =
156
+ aggregatedResponse . candidates [ candidateIndex ] . groundingMetadata =
157
157
candidate . groundingMetadata ;
158
- aggregatedResponse . candidates [ i ] . finishReason = candidate . finishReason ;
159
- aggregatedResponse . candidates [ i ] . finishMessage =
158
+ aggregatedResponse . candidates [ candidateIndex ] . finishReason =
159
+ candidate . finishReason ;
160
+ aggregatedResponse . candidates [ candidateIndex ] . finishMessage =
160
161
candidate . finishMessage ;
161
- aggregatedResponse . candidates [ i ] . safetyRatings =
162
+ aggregatedResponse . candidates [ candidateIndex ] . safetyRatings =
162
163
candidate . safetyRatings ;
163
164
164
165
/**
165
166
* Candidates should always have content and parts, but this handles
166
167
* possible malformed responses.
167
168
*/
168
169
if ( candidate . content && candidate . content . parts ) {
169
- if ( ! aggregatedResponse . candidates [ i ] . content ) {
170
- aggregatedResponse . candidates [ i ] . content = {
170
+ if ( ! aggregatedResponse . candidates [ candidateIndex ] . content ) {
171
+ aggregatedResponse . candidates [ candidateIndex ] . content = {
171
172
role : candidate . content . role || "user" ,
172
173
parts : [ ] ,
173
174
} ;
@@ -189,12 +190,13 @@ export function aggregateResponses(
189
190
if ( Object . keys ( newPart ) . length === 0 ) {
190
191
newPart . text = "" ;
191
192
}
192
- aggregatedResponse . candidates [ i ] . content . parts . push (
193
+ aggregatedResponse . candidates [ candidateIndex ] . content . parts . push (
193
194
newPart as Part ,
194
195
) ;
195
196
}
196
197
}
197
198
}
199
+ candidateIndex ++ ;
198
200
}
199
201
if ( response . usageMetadata ) {
200
202
aggregatedResponse . usageMetadata = response . usageMetadata ;
0 commit comments