in src/methods/chat-session-helpers.ts [47:104]
export function validateChatHistory(history: Content[]): void {
let prevContent = false;
for (const currContent of history) {
const { role, parts } = currContent as { role: Role; parts: Part[] };
if (!prevContent && role !== "user") {
throw new GoogleGenerativeAIError(
`First content should be with role 'user', got ${role}`,
);
}
if (!POSSIBLE_ROLES.includes(role)) {
throw new GoogleGenerativeAIError(
`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(
POSSIBLE_ROLES,
)}`,
);
}
if (!Array.isArray(parts)) {
throw new GoogleGenerativeAIError(
"Content should have 'parts' property with an array of Parts",
);
}
if (parts.length === 0) {
throw new GoogleGenerativeAIError(
"Each Content should have at least one part",
);
}
const countFields: Record<keyof Part, number> = {
text: 0,
inlineData: 0,
functionCall: 0,
functionResponse: 0,
fileData: 0,
executableCode: 0,
codeExecutionResult: 0,
};
for (const part of parts) {
for (const key of VALID_PART_FIELDS) {
if (key in part) {
countFields[key] += 1;
}
}
}
const validParts = VALID_PARTS_PER_ROLE[role];
for (const key of VALID_PART_FIELDS) {
if (!validParts.includes(key) && countFields[key] > 0) {
throw new GoogleGenerativeAIError(
`Content with role '${role}' can't contain '${key}' part`,
);
}
}
prevContent = true;
}
}