Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove chat session's previous content role validation checks #139

Merged
merged 2 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/green-timers-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@google/generative-ai": patch
---

Lifted a restriction in chat sessions that required a specific order of content roles.
9 changes: 8 additions & 1 deletion packages/main/src/methods/chat-session-helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,21 @@ describe("chat-session-helpers", () => {
{ role: "user", parts: [{ text: "hi" }] },
{ role: "user", parts: [{ text: "hi" }] },
],
isValid: false,
isValid: true,
},
{
history: [
{ role: "user", parts: [{ text: "hi" }] },
{ role: "model", parts: [{ text: "hi" }] },
{ role: "model", parts: [{ text: "hi" }] },
],
isValid: true,
},
{
history: [
{ role: "model", parts: [{ text: "hi" }] },
{ role: "user", parts: [{ text: "hi" }] },
],
isValid: false,
},
];
Expand Down
24 changes: 2 additions & 22 deletions packages/main/src/methods/chat-session-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,8 @@ const VALID_PARTS_PER_ROLE: { [key in Role]: Array<keyof Part> } = {
system: ["text"],
};

const VALID_PREVIOUS_CONTENT_ROLES: { [key in Role]: Role[] } = {
user: ["model"],
function: ["model"],
model: ["user", "function"],
// System instructions shouldn't be in history.
system: [],
};

export function validateChatHistory(history: Content[]): void {
let prevContent: Content;
let prevContent = false;
for (const currContent of history) {
const { role, parts } = currContent as { role: Role; parts: Part[] };
if (!prevContent && role !== "user") {
Expand Down Expand Up @@ -98,18 +90,6 @@ export function validateChatHistory(history: Content[]): void {
}
}

if (prevContent) {
const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role];
if (!validPreviousContentRoles.includes(prevContent.role as Role)) {
throw new GoogleGenerativeAIError(
`Content with role '${role}' can't follow '${
prevContent.role
}'. Valid previous roles: ${JSON.stringify(
VALID_PREVIOUS_CONTENT_ROLES,
)}`,
);
}
}
prevContent = currContent;
prevContent = true;
}
}
Loading