Skip to content

Commit

Permalink
fix: handle case when content is undefined in candidate.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 651223704
  • Loading branch information
yyyu-google authored and copybara-github committed Jul 11, 2024
1 parent 23c9b68 commit f16f040
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/functions/post_fetch_processing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export function aggregateResponses(
aggregatedResponse.candidates[i] = {
index: response.candidates[i].index ?? i,
content: {
role: response.candidates[i].content.role ?? constants.MODEL_ROLE,
role: response.candidates[i].content?.role ?? constants.MODEL_ROLE,
parts: [{text: ''}],
},
} as GenerateContentCandidate;
Expand Down
10 changes: 10 additions & 0 deletions src/functions/test/post_fetch_processing_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ import {
AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_1,
AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_2,
AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_3,
AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_4,
COUNT_TOKENS_RESPONSE_1,
STREAM_RESPONSE_CHUNKS_1,
STREAM_RESPONSE_CHUNKS_2,
STREAM_RESPONSE_CHUNKS_3,
STREAM_RESPONSE_CHUNKS_4,
UNARY_RESPONSE_1,
UNARY_RESPONSE_MISSING_ROLE_INDEX,
} from './test_data';
Expand Down Expand Up @@ -74,6 +76,14 @@ describe('aggregateResponses', () => {
JSON.stringify(AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_3)
);
});

it('missing content, should add role and return empty content', () => {
const actualResult = aggregateResponses(STREAM_RESPONSE_CHUNKS_4);

expect(JSON.stringify(actualResult)).toEqual(
JSON.stringify(AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_4)
);
});
});

describe('processUnary', () => {
Expand Down
20 changes: 20 additions & 0 deletions src/functions/test/test_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,26 @@ export const AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_3: GenerateContentRespon
},
],
} as GenerateContentResponse;

export const STREAM_RESPONSE_CHUNKS_4: GenerateContentResponse[] = [
{
candidates: [{}],
},
] as GenerateContentResponse[];

export const AGGREGATED_RESPONSE_STREAM_RESPONSE_CHUNKS_4: GenerateContentResponse =
{
candidates: [
{
index: 0,
content: {
role: 'model',
parts: [{text: ''}],
},
},
],
} as GenerateContentResponse;

export const UNARY_RESPONSE_1: GenerateContentResponse = {
candidates: [
{
Expand Down

0 comments on commit f16f040

Please sign in to comment.