Files
botsmann/lib/chat/embedding.ts
T
g-butandClaude Opus 4.6 372fe46261 refactor(chat): extract shared utilities from 3 chat API routes
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>
2026-03-02 17:23:14 +01:00

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,
),
};
}
}