fix(gemini): prepend empty user placeholder and normalize role alternation

This commit is contained in:
tyuXX 2026-11-03 17:07:03 +00:00
parent a27c781dd9
commit 19ea81e449
2 changed files with 87 additions and 5 deletions

View file

@ -123,24 +123,60 @@ export class RevolverEngine {
return sorted;
}
private convertToGeminiContent(messages: any[]): {
public convertToGeminiContent(messages: any[]): {
systemInstruction?: string;
geminiMessages: any[];
} {
let systemInstruction = '';
const geminiMessages: any[] = [];
const rawMessages: { role: 'user' | 'model'; parts: { text: string }[] }[] = [];
for (const msg of messages) {
if (msg.role === 'system') {
systemInstruction += (systemInstruction ? '\n\n' : '') + (typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content));
const text = typeof msg.content === 'string' ? msg.content : (msg.content != null ? JSON.stringify(msg.content) : '');
systemInstruction += (systemInstruction ? '\n\n' : '') + text;
} else {
geminiMessages.push({
const text = typeof msg.content === 'string' ? msg.content : (msg.content != null ? JSON.stringify(msg.content) : '');
rawMessages.push({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) }]
parts: [{ text }]
});
}
}
// Step 1: Prepend empty user placeholder if the first non-system message is from 'model' (Option 1)
if (rawMessages.length > 0 && rawMessages[0].role === 'model') {
rawMessages.unshift({
role: 'user',
parts: [{ text: '' }]
});
}
// Step 2: Ensure normalization by merging consecutive messages with the same role (Option 3)
const geminiMessages: { role: 'user' | 'model'; parts: { text: string }[] }[] = [];
for (const msg of rawMessages) {
if (geminiMessages.length === 0) {
geminiMessages.push({ role: msg.role, parts: [{ text: msg.parts[0]?.text ?? '' }] });
} else {
const prevMsg = geminiMessages[geminiMessages.length - 1];
if (prevMsg.role === msg.role) {
const prevText = prevMsg.parts[0]?.text ?? '';
const currText = msg.parts[0]?.text ?? '';
const mergedText = !prevText ? currText : (!currText ? prevText : `${prevText}\n\n${currText}`);
prevMsg.parts = [{ text: mergedText }];
} else {
geminiMessages.push({ role: msg.role, parts: [{ text: msg.parts[0]?.text ?? '' }] });
}
}
}
// Ensure the conversation ends with a user message for Gemini chat completion
if (geminiMessages.length > 0 && geminiMessages[geminiMessages.length - 1].role === 'model') {
geminiMessages.push({
role: 'user',
parts: [{ text: '' }]
});
}
return { systemInstruction, geminiMessages };
}