Skip to content
Open
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
31 changes: 15 additions & 16 deletions lib/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ export async function generateTutorResponse(
// Prepare history: filters system messages and removes redundant user message if any
const validHistory = prepareHistory(history, message);

// Pre-calculate mapped history for different providers to avoid redundant allocations in fallbacks
const geminiHistory = validHistory.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
}));

const groqHistory = validHistory.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any, // eslint-disable-line @typescript-eslint/no-explicit-any
content: h.content
}));

// 1. Try Gemini 2.5 Flash (Best balance of speed and smarts)
try {
const model = genAI.getGenerativeModel({
Expand All @@ -30,10 +41,7 @@ export async function generateTutorResponse(
});

const chat = model.startChat({
history: validHistory.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
})),
history: geminiHistory,
});

const result = await chat.sendMessage(message);
Expand All @@ -51,10 +59,7 @@ export async function generateTutorResponse(
});

const chat = model.startChat({
history: validHistory.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
})),
history: geminiHistory,
});

const result = await chat.sendMessage(message);
Expand All @@ -69,10 +74,7 @@ export async function generateTutorResponse(
const completion = await groq.chat.completions.create({
messages: [
{ role: "system", content: systemPrompt },
...validHistory.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any ,// eslint-disable-line @typescript-eslint/no-explicit-any
content: h.content
})),
...groqHistory,
{ role: "user", content: message }
],
model: TEXT_MODELS.LLAMA_70B.model,
Expand All @@ -90,10 +92,7 @@ export async function generateTutorResponse(
const completion = await groq.chat.completions.create({
messages: [
{ role: "system", content: systemPrompt },
...validHistory.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any ,// eslint-disable-line @typescript-eslint/no-explicit-any
content: h.content
})),
...groqHistory,
{ role: "user", content: message }
],
model: TEXT_MODELS.LLAMA_8B.model,
Expand Down
74 changes: 74 additions & 0 deletions lib/chat_optimization.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

export interface ChatMessage {
role: "user" | "ai" | "system";
content: string;
}

const history: ChatMessage[] = Array.from({ length: 20 }, (_, i) => ({
role: i % 2 === 0 ? "user" : "ai",
content: "This is some content for the chat message " + i
}));

const ITERATIONS = 100_000;

function benchmarkRepeatedMapping() {
const start = performance.now();
for (let i = 0; i < ITERATIONS; i++) {
// Simulating the 4 blocks in generateTutorResponse
const h1 = history.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
}));
const h2 = history.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
}));
const h3 = history.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any,
content: h.content
}));
const h4 = history.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any,
content: h.content
}));
Comment on lines +26 to +33
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify explicit-any occurrences in benchmark file
rg -n --type ts '\bas any\b' lib/chat_optimization.bench.ts

Repository: APPLEPIE6969/StudyFlow

Length of output: 269


Remove as any casts that violate @typescript-eslint/no-explicit-any.

Lines 27, 31, and 48 in lib/chat_optimization.bench.ts contain as any casts that will fail lint gates. Extract the repeated role-mapping logic into a typed helper function:

Suggested fix
+type GroqHistoryMessage = { role: "assistant" | "user"; content: string };
+const mapToGroqHistory = (h: ChatMessage): GroqHistoryMessage => ({
+  role: h.role === "ai" ? "assistant" : "user",
+  content: h.content,
+});
+
 function benchmarkRepeatedMapping() {
@@
-        const h3 = history.map(h => ({
-            role: h.role === "ai" ? "assistant" : "user" as any,
-            content: h.content
-        }));
-        const h4 = history.map(h => ({
-            role: h.role === "ai" ? "assistant" : "user" as any,
-            content: h.content
-        }));
+        const h3 = history.map(mapToGroqHistory);
+        const h4 = history.map(mapToGroqHistory);
@@
 function benchmarkPrecalculatedMapping() {
@@
-        const groqHistory = history.map(h => ({
-            role: h.role === "ai" ? "assistant" : "user" as any,
-            content: h.content
-        }));
+        const groqHistory = history.map(mapToGroqHistory);
🧰 Tools
πŸͺ› ESLint

[error] 27-27: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)


[error] 31-31: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/chat_optimization.bench.ts` around lines 26 - 33, The repeated "as any"
casts stem from mapping history items to chat messages; create a typed helper
(e.g., toChatMessage(historyItem): { role: "assistant" | "user"; content: string
}) that converts h.role === "ai" ? "assistant" : "user" and returns content,
then replace the two history.map(...) usages that produce h3 and h4 with
history.map(toChatMessage) (and any other similar maps, e.g., the one on line
48), removing the explicit any casts so the mappings are properly typed and
satisfy `@typescript-eslint/no-explicit-any`.


if (h1.length === 0 || h2.length === 0 || h3.length === 0 || h4.length === 0) { /* prevent optimize */ }
}
return performance.now() - start;
}

function benchmarkPrecalculatedMapping() {
const start = performance.now();
for (let i = 0; i < ITERATIONS; i++) {
const geminiHistory = history.map(msg => ({
role: msg.role === "user" ? "user" : "model",
parts: [{ text: msg.content }],
}));
const groqHistory = history.map(h => ({
role: h.role === "ai" ? "assistant" : "user" as any,
content: h.content
}));

// Simulating use in 4 blocks
const h1 = geminiHistory;
const h2 = geminiHistory;
const h3 = groqHistory;
const h4 = groqHistory;

if (h1.length === 0 || h2.length === 0 || h3.length === 0 || h4.length === 0) { /* prevent optimize */ }
}
return performance.now() - start;
}

console.log(`Benchmarking with ${ITERATIONS} iterations and history length ${history.length}...`);

const repeatedTime = benchmarkRepeatedMapping();
console.log(`Repeated mapping: ${repeatedTime.toFixed(2)}ms`);

const precalculatedTime = benchmarkPrecalculatedMapping();
console.log(`Precalculated mapping: ${precalculatedTime.toFixed(2)}ms`);

if (repeatedTime > 0) {
const improvement = ((repeatedTime - precalculatedTime) / repeatedTime * 100).toFixed(2);
console.log(`Improvement: ${improvement}%`);
}