mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 12:38:28 +01:00
Create lib/chat/ module with shared utilities: - embedding.ts: generateEmbeddingWithTimeout (embedding + timeout guard) - settings.ts: getUserLLMSettings (provider/apiKey/ollamaUrl lookup) - context.ts: truncateChunks + joinContext (context building) - llm-errors.ts: handleLLMError (API key fallback, Ollama, AI unavailable) - parse.ts: parseResponseWithSuggestions (extract >>> suggestions) Update all 3 chat routes to use shared utilities, removing ~220 lines of duplicated code. Also fix module-scope getServerEnv() call in llm-client that caused SSG build failure. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
/**
|
|
* Shared context building utilities for RAG chat routes
|
|
* @module lib/chat/context
|
|
*/
|
|
|
|
import { API_CONFIG } from '@/lib/constants';
|
|
|
|
interface ContentChunk {
|
|
content: string;
|
|
}
|
|
|
|
/**
|
|
* Truncate an array of content chunks to fit within a character budget.
|
|
* Partially includes the last chunk if there's enough remaining space (>200 chars).
|
|
*/
|
|
export function truncateChunks<T extends ContentChunk>(
|
|
chunks: T[],
|
|
maxChars: number = API_CONFIG.MAX_CONTEXT_CHARS,
|
|
): T[] {
|
|
let totalChars = 0;
|
|
const result: T[] = [];
|
|
|
|
for (const chunk of chunks) {
|
|
const len = chunk.content.length;
|
|
if (totalChars + len > maxChars) {
|
|
const remaining = maxChars - totalChars;
|
|
if (remaining > 200) {
|
|
result.push({
|
|
...chunk,
|
|
content: chunk.content.substring(0, remaining) + '... [truncated]',
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
result.push(chunk);
|
|
totalChars += len;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Join context parts with a standard separator.
|
|
*/
|
|
export function joinContext(parts: string[]): string {
|
|
return parts.join('\n\n---\n\n');
|
|
}
|