Skip to content

Commit

Permalink
Refactor route.ts to streamline imports and enhance code readability.
Browse files Browse the repository at this point in the history
  • Loading branch information
AtlantisPleb committed Aug 28, 2024
1 parent 4777aff commit 21844de
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ function ensureValidMessageOrder(messages: any[]) {
if (message.role === 'tool') {
// Always include tool messages
validatedMessages.push(message);
// After a tool message, we need an assistant message
if (lastRole !== 'assistant') {
validatedMessages.push({ role: 'assistant', content: 'Continuing the conversation based on the tool result.' });
}
} else if (message.role === lastRole) {
// Combine consecutive messages with the same role
const lastMessage = validatedMessages[validatedMessages.length - 1];
Expand All @@ -30,16 +34,25 @@ function ensureValidMessageOrder(messages: any[]) {
validatedMessages.push(message);
}
} else {
if (message.role === 'user' && lastRole === 'user') {
// If we have consecutive user messages, add an assistant message in between
validatedMessages.push({ role: 'assistant', content: 'I understand. Please continue.' });
}
validatedMessages.push(message);
lastRole = message.role;
}
lastRole = message.role;
}

// Ensure the conversation ends with a user message
if (validatedMessages[validatedMessages.length - 1].role !== 'user') {
validatedMessages.push({ role: 'user', content: 'Continue' });
}

// Ensure the conversation starts with a user message
if (validatedMessages[0].role !== 'user') {
validatedMessages.unshift({ role: 'user', content: 'Start the conversation' });
}

return validatedMessages;
}

Expand Down

0 comments on commit 21844de

Please sign in to comment.