Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/bndrbots_deepseekchat.json
T

1 line
15 KiB
JSON

{"repo": "bndrbots/deepseekchat", "files": {"pages/api/chat.js": {"9b44de5df60c06a908c06f9bdcc544204a0e296b": {"t": 1785745528.3704164, "n": 2753, "h": "08f9ef2af08f9ca5", "c": "import { getSession, saveSession, addMessage, getMessages } from '../../lib/kvStore';\nimport { buildContext } from '../../lib/contextManager';\nimport { buildSystemPrompt } from '../../lib/reasoningPrompt';\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') return res.status(405).end();\n\n const { messages, userId = 'anonymous' } = req.body;\n if (!messages || messages.length === 0) return res.status(400).json({ error: 'No messages' });\n\n try {\n const userMessage = messages[messages.length - 1];\n \n // 1. Retrieve full history (unlimited)\n const history = await getMessages(userId);\n \n // 2. Build explicit context (Genesis Plan + Working Memory)\n const contextStr = buildContext(history);\n const systemPrompt = {\n role: 'system',\n content: buildSystemPrompt(contextStr)\n };\n\n const payloadMessages = [systemPrompt, userMessage];\n\n // 3. DeepSeek Engine with Failsafe Routing\n let assistantMessage;\n try {\n // 25-second absolute timeout failsafe\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 25000);\n\n const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`\n },\n body: JSON.stringify({\n model: 'deepseek-chat',\n messages: payloadMessages,\n temperature: 0.0 // Deterministic lock, zero hallucination\n }),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errText = await response.text();\n throw new Error(`API failed: ${response.status} - ${errText}`);\n }\n \n const data = await response.json();\n assistantMessage = data.choices[0].message;\n \n } catch (networkError) {\n console.error('PRIMARY LLM FAILURE:', networkError);\n // Graceful degradation fallback - do not crash the UI, log the failure state\n assistantMessage = {\n role: 'assistant',\n content: `[SYSTEM FAILSAFE TRIGGERED]: Primary reasoning engine timed out or failed. State preserved. Error: ${networkError.message}`\n };\n }\n\n // 4. Commit turn to unlimited memory (Audit Log)\n // Even if it failed, we log the failure to memory\n await addMessage(userId, userMessage);\n await addMessage(userId, assistantMessage);\n\n res.status(200).json({ reply: assistantMessage.content });\n \n } catch (error) {\n console.error('FATAL CHAT API ERROR:', error);\n res.status(500).json({ error: 'Fatal system error. State preserved.', details: error.message });\n }\n}"}, "8ecfb763828648620ac57a704dd08dc6dc1348b1": {"t": 1785753880.4976006, "n": 2753, "h": "08f9ef2af08f9ca5", "c": "import { getSession, saveSession, addMessage, getMessages } from '../../lib/kvStore';\nimport { buildContext } from '../../lib/contextManager';\nimport { buildSystemPrompt } from '../../lib/reasoningPrompt';\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') return res.status(405).end();\n\n const { messages, userId = 'anonymous' } = req.body;\n if (!messages || messages.length === 0) return res.status(400).json({ error: 'No messages' });\n\n try {\n const userMessage = messages[messages.length - 1];\n \n // 1. Retrieve full history (unlimited)\n const history = await getMessages(userId);\n \n // 2. Build explicit context (Genesis Plan + Working Memory)\n const contextStr = buildContext(history);\n const systemPrompt = {\n role: 'system',\n content: buildSystemPrompt(contextStr)\n };\n\n const payloadMessages = [systemPrompt, userMessage];\n\n // 3. DeepSeek Engine with Failsafe Routing\n let assistantMessage;\n try {\n // 25-second absolute timeout failsafe\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 25000);\n\n const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`\n },\n body: JSON.stringify({\n model: 'deepseek-chat',\n messages: payloadMessages,\n temperature: 0.0 // Deterministic lock, zero hallucination\n }),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errText = await response.text();\n throw new Error(`API failed: ${response.status} - ${errText}`);\n }\n \n const data = await response.json();\n assistantMessage = data.choices[0].message;\n \n } catch (networkError) {\n console.error('PRIMARY LLM FAILURE:', networkError);\n // Graceful degradation fallback - do not crash the UI, log the failure state\n assistantMessage = {\n role: 'assistant',\n content: `[SYSTEM FAILSAFE TRIGGERED]: Primary reasoning engine timed out or failed. State preserved. Error: ${networkError.message}`\n };\n }\n\n // 4. Commit turn to unlimited memory (Audit Log)\n // Even if it failed, we log the failure to memory\n await addMessage(userId, userMessage);\n await addMessage(userId, assistantMessage);\n\n res.status(200).json({ reply: assistantMessage.content });\n \n } catch (error) {\n console.error('FATAL CHAT API ERROR:', error);\n res.status(500).json({ error: 'Fatal system error. State preserved.', details: error.message });\n }\n}"}, "77516607df61d4bf3075579dc3ba02ec90637e0f": {"t": 1785753882.0579395, "n": 1830, "h": "72b6ba3aa8ccf00f", "c": "import { getSession, saveSession, addMessage, getMessages } from '../../lib/kvStore';\nimport { buildContext } from '../../lib/contextManager';\nimport { buildSystemPrompt } from '../../lib/reasoningPrompt';\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') return res.status(405).end();\n\n const { messages, userId = 'anonymous' } = req.body;\n if (!messages || messages.length === 0) return res.status(400).json({ error: 'No messages' });\n\n try {\n const userMessage = messages[messages.length - 1];\n \n // 1. Retrieve full history (unlimited)\n const history = await getMessages(userId);\n \n // 2. Build explicit context\n const contextStr = buildContext(history);\n const systemPrompt = {\n role: 'system',\n content: buildSystemPrompt(contextStr)\n };\n\n // 3. Construct DeepSeek payload\n const payloadMessages = [systemPrompt, userMessage];\n\n // 4. Call DeepSeek\n const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`\n },\n body: JSON.stringify({\n model: 'deepseek-chat',\n messages: payloadMessages,\n temperature: 0.0 // Deterministic\n })\n });\n\n if (!response.ok) throw new Error(`DeepSeek API error: ${response.statusText}`);\n const data = await response.json();\n const assistantMessage = data.choices[0].message;\n\n // 5. Commit turn to unlimited memory\n await addMessage(userId, userMessage);\n await addMessage(userId, assistantMessage);\n\n res.status(200).json({ reply: assistantMessage.content });\n } catch (error) {\n console.error('CHAT API ERROR:', error);\n res.status(500).json({ error: error.message });\n }\n}"}, "08c6943e715046ea96866dc05f1e402a77daf68b": {"t": 1785753883.2348568, "n": 994, "h": "2169076797b2491c", "c": "import { getSession, saveSession, addMessage, getMessages } from '../../lib/kvStore';\n\nexport default async function handler(req, res) {\n // ... (same method check and API key)\n\n const { messages, userId = 'anonymous', /* other params */ } = req.body;\n\n try {\n // Load existing session and messages from KV\n let session = await getSession(userId);\n if (!session) {\n session = { /* default session */ };\n }\n const history = await getMessages(userId);\n\n // Combine history with new messages\n const fullMessages = [...history, ...messages];\n\n // Call DeepSeek API as before\n // ...\n\n // After getting response, store the new messages\n await addMessage(userId, messages[messages.length - 1]); // user message\n await addMessage(userId, assistantResponse); // assistant message\n\n // Update session if needed\n await saveSession(userId, session);\n\n res.status(200).json({ reply: assistantResponse });\n } catch (error) {\n // error handling\n }\n}\n"}, "f949e64319356ad4e25262742e61e075236ab5b6": {"t": 1785753884.5525591, "n": 6282, "h": "362ee1a15a0d4286", "c": "import { memoryStore } from '../../lib/memoryStore';\nimport { \n entityResolutionSchema, \n classificationSchema, \n riskScoreSchema,\n complianceSchema,\n memoryRecallSchema \n} from '../../lib/validationSchemas';\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n const { \n messages, \n userId = 'anonymous',\n taskId,\n mode = 'chat', // chat, research, learn, council\n structuredOutput = false,\n schema = null,\n temperature = 0.15 // deterministic by default [citation:7]\n } = req.body;\n\n const apiKey = process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n return res.status(500).json({ error: 'DeepSeek API key not configured' });\n }\n\n try {\n // PLANNER LAYER: Get context and determine approach [citation:3]\n const session = memoryStore.getOrCreateSession(userId);\n const context = memoryStore.getContextSummary(userId, taskId);\n \n // Check memory for relevant past interactions (95% recall target) [citation:2]\n const lastUserMessage = messages.filter(m => m.role === 'user').pop();\n if (lastUserMessage) {\n const memories = memoryStore.recall(lastUserMessage.content.substring(0, 50));\n if (memories.length > 0) {\n // Inject high-confidence memories into context\n context.memories = memories.filter(m => m.confidence > 0.9);\n }\n }\n\n // Build system prompt with context\n let systemMessage = `You are DeepSeek, a helpful assistant. Current context:\nSession: ${JSON.stringify(context.session)}\n${context.task ? `Task: ${JSON.stringify(context.task)}` : ''}\n${context.memories ? `Relevant memories: ${JSON.stringify(context.memories)}` : ''}`;\n\n // Mode-specific instructions [citation:2]\n if (mode === 'learn') {\n systemMessage += '\\n\\nMode: Step-by-step learning. Provide guided questions and hints. Tailor to user knowledge level.';\n } else if (mode === 'research') {\n systemMessage += '\\n\\nMode: Deep Research. Search multiple sources, synthesize, cite everything.';\n } else if (mode === 'council') {\n systemMessage += '\\n\\nMode: Model Council. Consider multiple perspectives. Highlight agreements and disagreements.';\n }\n\n // Structured output enforcement [citation:7]\n if (structuredOutput && schema) {\n systemMessage += '\\n\\nYou must output valid JSON matching the provided schema. No additional text.';\n }\n\n // EXECUTOR LAYER: Call model [citation:3]\n const response = await fetch('https://api.deepseek.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: 'deepseek-chat',\n messages: [\n { role: 'system', content: systemMessage },\n ...messages\n ],\n temperature: temperature, // 0.15 for deterministic [citation:7]\n ...(structuredOutput && {\n response_format: { type: 'json_object' }\n })\n }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.error?.message || 'API request failed');\n }\n\n const assistantMessage = data.choices[0].message.content;\n\n // VERIFIER LAYER: Validate output [citation:3][citation:7]\n let verifiedOutput = assistantMessage;\n let verificationErrors = [];\n\n if (structuredOutput && schema) {\n try {\n const parsed = JSON.parse(assistantMessage);\n \n // Validate against schema\n const validate = (obj, schema) => {\n const errors = [];\n for (const required of schema.required || []) {\n if (!obj[required]) {\n errors.push(`Missing required field: ${required}`);\n }\n }\n // Basic type checking\n for (const [key, def] of Object.entries(schema.properties || {})) {\n if (obj[key] !== undefined) {\n if (def.type === 'number' && typeof obj[key] !== 'number') errors.push(`${key} must be number`);\n if (def.type === 'string' && typeof obj[key] !== 'string') errors.push(`${key} must be string`);\n if (def.enum && !def.enum.includes(obj[key])) errors.push(`${key} must be one of: ${def.enum.join(', ')}`);\n }\n }\n return errors;\n };\n\n verificationErrors = validate(parsed, schema);\n \n if (verificationErrors.length === 0) {\n // Store as memory if high confidence [citation:2]\n if (parsed.confidence > 0.9) {\n memoryStore.createMemory(\n `interaction-${Date.now()}`,\n parsed,\n parsed.confidence\n );\n }\n \n verifiedOutput = parsed;\n } else {\n // Degrade gracefully [citation:3]\n verifiedOutput = {\n error: 'Validation failed',\n details: verificationErrors,\n raw: assistantMessage\n };\n }\n } catch (e) {\n verificationErrors = [`Invalid JSON: ${e.message}`];\n verifiedOutput = {\n error: 'Invalid JSON output',\n raw: assistantMessage\n };\n }\n }\n\n // Record interaction for future recall [citation:2]\n memoryStore.recordInteraction(userId, lastUserMessage?.content, {\n mode,\n taskId,\n verificationErrors: verificationErrors.length > 0 ? verificationErrors : undefined\n });\n\n // Return with verification results\n res.status(200).json({\n reply: typeof verifiedOutput === 'string' ? verifiedOutput : JSON.stringify(verifiedOutput),\n structured: structuredOutput ? verifiedOutput : undefined,\n verification: verificationErrors.length > 0 ? {\n passed: false,\n errors: verificationErrors\n } : {\n passed: true\n },\n memoryRecall: context.memories ? {\n count: context.memories.length,\n confidence: context.memories.reduce((acc, m) => acc + m.confidence, 0) / context.memories.length\n } : null\n });\n\n } catch (error) {\n console.error('DeepSeek API error:', error);\n res.status(500).json({ \n error: 'Failed to fetch from DeepSeek',\n details: error.message \n });\n }\n}\n"}}}}