xonecas.io
53129
Pa

PAT / commit 23d10f5

feat: add validation for MaxPromptLength and fix JSDoc typo

xonecas2025-12-19 23d10f52ec1846ae3772a20ec327b6afdca088af parent 68f55a4

2 files changed

app/api/chat/route.ts+12−2
@@ -7,6 +7,13 @@ import { eq, asc } from "drizzle-orm";
77 import { streamAssistantResponse } from "@/src/lib/ollama/chat";
88 import { debug } from "@/src/lib/debug";
99
10+/**
11+ * Type guard to validate MaxPromptLength values.
12+ */
13+function isValidMaxPromptLength(value: unknown): value is MaxPromptLength {
14+ return value === null || value === "none" || value === 1024 || value === 4096;
15+}
16+
1017 export async function POST(request: Request) {
1118 const { message, threadId: threadIdRaw } = await request.json();
1219 const signal = request.signal;
@@ -34,8 +41,11 @@ export async function POST(request: Request) {
3441 // Use thread-specific settings (stored in thread table)
3542 const threadModel = thread[0].model;
3643 // Note: null from database means "none" (no limit), which OllamaChat handles correctly
37- const threadMaxPromptLength: MaxPromptLength =
38- thread[0].maxPromptLength === null ? null : (thread[0].maxPromptLength as MaxPromptLength);
44+ // Validate maxPromptLength before use to prevent runtime errors from invalid database values
45+ const rawMaxPromptLength = thread[0].maxPromptLength;
46+ const threadMaxPromptLength: MaxPromptLength = isValidMaxPromptLength(rawMaxPromptLength)
47+ ? rawMaxPromptLength
48+ : null;
3949
4050 // 2. Fetch previous messages from thread
4151 const previousMessages = await db
src/lib/ollama/chat/ollama-chat.ts+1−1
@@ -18,7 +18,7 @@ import type { OllamaChunk, OllamaChatResponse, MaxPromptLength } from "@/src/lib
1818 *
1919 * @param messages - Array of messages in the conversation history.
2020 * @param onChunk - Optional callback function to receive streaming chunks (content, thinking, toolCalls).
21- * @param model - The Ollama model to use..
21+ * @param model - The Ollama model to use.
2222 * @param signal - Optional AbortSignal to cancel the request.
2323 * @param maxPromptLength - Optional maximum prompt length in tokens. Can be "none", 1024, or 4096.
2424 * @returns Object containing the response content and generation time in milliseconds.