mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-03 23:37:02 +01:00
* fix(ai): pick chain vendors by id, and make main green again main has been red since #203 bumped @bitbaum/ai-kit to 1.10, which put Gemini second in freeChain('BOTSMANN'). vendorChain() indexed [1] for OpenRouter, so a BYOK OpenRouter user's key would have been sent down the Gemini link. Look vendors up by id instead (code and both tests). Also clears the rest of the red verify from the same bump: prettier 3.x reformat of six files and the new next lint rule on relative window.location.href assignments (sign-out keeps its full reload). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Signed-off-by: Cato <41178744+catomean@users.noreply.github.com> * fix(ai): context extraction runs only on the user's own key Every professional-chat turn fired a second, unasked model call (extractAndSaveContext, fire-and-forget after the answer) on the shared free-tier Groq key. Standing rule (2026-09-25): free-tier keys are spent only when a person deliberately asks. Extraction now requires the user's own key and uses their provider; without one it returns before any call. Adds tests/__tests__/no-free-background-ai.test.ts: walks the import graph from the timer route (/api/rebuild, appcron-botsmann-rebuild), /api/warmup and /api/health and fails if any reaches a model client. Proven by mutation: importing lib/nlp into /api/rebuild fails it, and dropping the own-key guard fails the three new extractor cases. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Signed-off-by: Cato <41178744+catomean@users.noreply.github.com> --------- Signed-off-by: Cato <41178744+catomean@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
119 lines
3.7 KiB
TypeScript
119 lines
3.7 KiB
TypeScript
/**
|
|
* Context Extractor
|
|
*
|
|
* Uses LLM to extract factual information about a user from conversation messages.
|
|
* Extracted facts are stored in user_context for future personalization.
|
|
*/
|
|
|
|
import { generateLLMResponse, type ModelProvider } from '@/lib/llm-client';
|
|
import { detectDomains } from '@/lib/context/domain-detector';
|
|
import { saveUserContext } from '@/lib/context/store';
|
|
|
|
const EXTRACTION_PROMPT = `You are a fact extraction system. Given a conversation between a user and an AI assistant, extract specific factual information about the user that would be useful for future conversations.
|
|
|
|
Rules:
|
|
- Extract ONLY concrete facts (names, dates, conditions, preferences, situations)
|
|
- Each fact should be a single, self-contained statement
|
|
- Do NOT extract opinions, general knowledge, or AI assistant responses
|
|
- Do NOT extract greetings or pleasantries
|
|
- If no useful facts are present, return an empty array
|
|
- Keep each fact under 200 characters
|
|
- Assign a confidence score (0.5-1.0) based on how clearly the fact is stated
|
|
|
|
Return a JSON array of objects: [{"fact": "...", "confidence": 0.8}]
|
|
Return ONLY the JSON array, no other text.`;
|
|
|
|
interface ExtractedFact {
|
|
fact: string;
|
|
confidence: number;
|
|
}
|
|
|
|
/** The user's OWN model settings. Extraction never runs on the site's keys. */
|
|
export interface OwnLLM {
|
|
provider: ModelProvider;
|
|
apiKey: string | null | undefined;
|
|
}
|
|
|
|
/**
|
|
* Extract facts from a conversation turn and save them as user context.
|
|
*
|
|
* Called asynchronously after each conversation turn — not in the critical path.
|
|
*
|
|
* Only on the user's own key. Nobody asked for this call: it is a second model
|
|
* request fired after the answer they did ask for, and on the shared free-tier
|
|
* key every chat turn cost two. `generateLLMResponse` falls back to the
|
|
* server's key when given none, so a missing key must stop here, not there.
|
|
*/
|
|
export async function extractAndSaveContext(
|
|
userId: string,
|
|
conversationId: string,
|
|
userMessage: string,
|
|
assistantResponse: string,
|
|
professionalDomain: string | undefined,
|
|
own: OwnLLM,
|
|
): Promise<number> {
|
|
if (!own.apiKey) return 0;
|
|
try {
|
|
const facts = await extractFacts(userMessage, assistantResponse, own);
|
|
if (facts.length === 0) return 0;
|
|
|
|
const contextFacts = facts.map((f) => ({
|
|
content: f.fact,
|
|
domains: professionalDomain ? [professionalDomain, 'general'] : detectDomains(f.fact),
|
|
sourceType: 'conversation' as const,
|
|
sourceId: conversationId,
|
|
confidence: f.confidence,
|
|
}));
|
|
|
|
return await saveUserContext(userId, contextFacts);
|
|
} catch {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Use LLM to extract facts from a conversation turn.
|
|
*/
|
|
async function extractFacts(
|
|
userMessage: string,
|
|
assistantResponse: string,
|
|
own: OwnLLM,
|
|
): Promise<ExtractedFact[]> {
|
|
const conversationText = `User: ${userMessage}\nAssistant: ${assistantResponse}`;
|
|
|
|
try {
|
|
const response = await generateLLMResponse(
|
|
[
|
|
{ role: 'system', content: EXTRACTION_PROMPT },
|
|
{ role: 'user', content: conversationText },
|
|
],
|
|
{
|
|
provider: own.provider,
|
|
apiKey: own.apiKey,
|
|
temperature: 0.1,
|
|
maxTokens: 512,
|
|
},
|
|
);
|
|
|
|
const parsed = JSON.parse(response.content);
|
|
if (!Array.isArray(parsed)) return [];
|
|
|
|
return parsed
|
|
.filter(
|
|
(item: unknown): item is ExtractedFact =>
|
|
typeof item === 'object' &&
|
|
item !== null &&
|
|
'fact' in item &&
|
|
typeof (item as ExtractedFact).fact === 'string' &&
|
|
(item as ExtractedFact).fact.length > 0 &&
|
|
(item as ExtractedFact).fact.length <= 200,
|
|
)
|
|
.map((item) => ({
|
|
fact: item.fact,
|
|
confidence: Math.min(1, Math.max(0.5, item.confidence ?? 0.8)),
|
|
}));
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|