mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 01:47:46 +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>
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
/**
|
|
* Shared embedding generation with timeout
|
|
* @module lib/chat/embedding
|
|
*/
|
|
|
|
import { generateEmbedding } from '@/lib/embeddings';
|
|
import { API_CONFIG, DOMAIN_ERRORS } from '@/lib/constants';
|
|
import { jsonError, HTTP_STATUS } from '@/lib/api';
|
|
|
|
/**
|
|
* Generate an embedding with a timeout guard.
|
|
* Returns the embedding array or a pre-formatted error Response.
|
|
*/
|
|
export async function generateEmbeddingWithTimeout(
|
|
text: string,
|
|
): Promise<{ embedding: number[] } | { error: Response }> {
|
|
try {
|
|
const embeddingPromise = generateEmbedding(text);
|
|
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
setTimeout(() => reject(new Error('Embedding timeout')), API_CONFIG.EMBEDDING_TIMEOUT);
|
|
});
|
|
|
|
const embedding = await Promise.race([embeddingPromise, timeoutPromise]);
|
|
return { embedding };
|
|
} catch (err) {
|
|
if (err instanceof Error && err.message === DOMAIN_ERRORS.EMBEDDING_TIMEOUT) {
|
|
return {
|
|
error: jsonError(
|
|
DOMAIN_ERRORS.SERVICE_WARMING_UP,
|
|
'SERVICE_UNAVAILABLE',
|
|
HTTP_STATUS.SERVICE_UNAVAILABLE,
|
|
),
|
|
};
|
|
}
|
|
return {
|
|
error: jsonError(
|
|
DOMAIN_ERRORS.FAILED_PROCESS_QUERY,
|
|
'SERVICE_UNAVAILABLE',
|
|
HTTP_STATUS.SERVICE_UNAVAILABLE,
|
|
),
|
|
};
|
|
}
|
|
}
|