const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const { default: Groq } = require('groq-sdk'); require('dotenv').config() const app = express(); const server = http.createServer(app); const io = new Server(server, { cors: { origin: '*', methods: ['GET', 'POST'], }, }); async function makeApiCall(messages, max_tokens, is_final_answer = false) { for (let attempt = 0; attempt < 3; attempt++) { try { var apiKeys = process.env.GROK_API_KEYS; apiKeys = apiKeys.split(','); const randomIndex = Math.floor(Math.random() * apiKeys.length); const randomKey = apiKeys[randomIndex]; const groq = new Groq({ apiKey: randomKey }); const response = await groq.chat.completions.create({ model: "llama-3.1-70b-versatile", // Update if needed messages: messages, max_tokens: max_tokens, temperature: 1, response_format: is_final_answer ? undefined : { type: "json_object" }, }); if (is_final_answer) { return response.choices[0].message.content; } else { return JSON.parse(response.choices[0].message.content); } } catch (e) { if (attempt === 2) { if (is_final_answer) { return { title: "Error", content: `Failed to generate final answer after 3 attempts. Error: ${e}` }; } else { return { title: "Error", content: `Failed to generate step after 3 attempts. Error: ${e}`, next_action: "final_answer" }; } } console.error("API call failed, retrying...", e); await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second } } } async function chainOfThought(prompt, socket) { const systemMessage = { role: "system", content: `You are an expert AI assistant that explains your reasoning step by step. For each step, provide a title that describes what you're doing in that step, along with the content. Decide if you need another step or if you're ready to give the final answer. Respond in JSON format with 'title', 'content', and 'next_action' (either 'continue' or 'final_answer') keys. USE AS MANY REASONING STEPS AS POSSIBLE. AT LEAST 3. BE AWARE OF YOUR LIMITATIONS AS AN LLM AND WHAT YOU CAN AND CANNOT DO. IN YOUR REASONING, INCLUDE EXPLORATION OF ALTERNATIVE ANSWERS. CONSIDER YOU MAY BE WRONG, AND IF YOU ARE WRONG IN YOUR REASONING, WHERE IT WOULD BE. FULLY TEST ALL OTHER POSSIBILITIES. YOU CAN BE WRONG. WHEN YOU SAY YOU ARE RE-EXAMINING, ACTUALLY RE-EXAMINE, AND USE ANOTHER APPROACH TO DO SO. DO NOT JUST SAY YOU ARE RE-EXAMINING. USE AT LEAST 3 METHODS TO DERIVE THE ANSWER. USE BEST PRACTICES. Example of a valid JSON response: \`\`\`json { "title": "Identifying Key Information", "content": "To begin solving this problem, we need to carefully examine the given information and identify the crucial elements that will guide our solution process. This involves...", "next_action": "continue" } \`\`\` ` }; let messages = [ systemMessage, { role: "user", content: prompt }, { role: "assistant", content: "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem." } ]; let steps = []; let totalThinkingTime = 0; for (let stepCount = 1; stepCount <= 25; stepCount++) { const startTime = performance.now(); let stepData = await makeApiCall(messages, 600); const endTime = performance.now(); const thinkingTime = (endTime - startTime) / 1000; totalThinkingTime += thinkingTime; const currentStepMarkdown = `### Step ${stepCount}: ${stepData.title}\n\n${stepData.content}\n\n*Thinking Time: ${thinkingTime} seconds*`; steps.push([`Step ${stepCount}: ${stepData.title}`, stepData.content, thinkingTime]); messages.push({ role: "assistant", content: JSON.stringify(stepData) }); socket.emit('thoughtStep', currentStepMarkdown); if (stepData.next_action === 'final_answer') { break; } } messages.push({ role: "user", content: "Please provide the final answer based solely on your reasoning above. Do not use JSON formatting. Only provide the text response without any titles or preambles. Retain any formatting as instructed by the original prompt, such as exact formatting for free response or multiple choice." }); const startTimeFinal = performance.now(); const finalAnswer = await makeApiCall(messages, 7200, true); const endTimeFinal = performance.now(); totalThinkingTime += (endTimeFinal - startTimeFinal) / 1000; const finalAnswerMarkdown = `\n${finalAnswer}\n\n*Thinking Time: ${(endTimeFinal - startTimeFinal) / 1000} seconds*`; steps.push(["Final Answer", finalAnswer, (endTimeFinal - startTimeFinal) / 1000]); socket.emit('finalAnswer', finalAnswerMarkdown); console.log(`Total thinking time: ${totalThinkingTime.toFixed(2)} seconds`); } io.on('connection', (socket) => { console.log('A user connected'); socket.on('startChainOfThought', (inputQuestion) => { chainOfThought(inputQuestion, socket); }); socket.on('disconnect', () => { console.log('User disconnected'); }); }); const PORT = process.env.PORT || 7860; server.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });