Skip to content

Commit

Permalink
Remove chat session's previous content role validation checks (#139)
Browse files Browse the repository at this point in the history
The service used to require chat session roles to conform to a certain pattern. This restriction has been lifted and so we shouldn't restrict it on the client-side.

Additionally update the tests around this feature.
  • Loading branch information
DellaBitta committed May 15, 2024
1 parent a2a25b2 commit cefa8f2
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 23 deletions.
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;
}
}

0 comments on commit cefa8f2

Please sign in to comment.