Spaces:
Running
Running
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'], | |
}, | |
}); | |
const groq = new Groq({ apiKey: process.env.GROK_KI_API_KEY }); // Replace with your actual API key | |
async function makeAPICall(messages, max_tokens, is_final_answer = false) { | |
for (let attempt = 0; attempt < 3; attempt++) { | |
try { | |
const response = await groq.chat.completions.create({ | |
model: "llama-3.1-70b-versatile", // or llama-3.2-90b-text-preview | |
messages: messages, | |
max_tokens: max_tokens, | |
// temperature: 0.2, | |
temperature: 0.2, | |
// ...(is_final_answer ? {} : { response_format: { type: "json_object" } }), | |
response_format: { 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) { | |
const errorContent = `Failed to generate ${is_final_answer ? 'final answer' : 'step'} after 3 attempts. Error: ${e}`; | |
return is_final_answer ? errorContent : { title: "Error", content: errorContent, next_action: "final_answer" }; | |
} | |
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second | |
} | |
} | |
} | |
async function generateResponse(prompt, socket) { | |
const messages = [ | |
{ | |
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: | |
{ | |
"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" | |
}` | |
}, | |
{ 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." } | |
]; | |
const steps = []; | |
let stepCount = 1; | |
let totalThinkingTime = 0; | |
while (true) { | |
const startTime = Date.now(); | |
const stepData = await makeAPICall(messages, 300); | |
const endTime = Date.now(); | |
const thinkingTime = (endTime - startTime) / 1000; | |
totalThinkingTime += thinkingTime; | |
steps.push([`Step ${stepCount}: ${stepData.title}`, stepData.content, thinkingTime]); | |
socket.emit('thoughtStep', `#### Step ${stepCount}: ${stepData.title}\n\n${stepData.content}`); // Emit step fter each step | |
messages.push({ role: "assistant", content: JSON.stringify(stepData) }); | |
if (stepData.next_action === 'final_answer' || stepCount > 25) { | |
break; | |
} | |
stepCount++; | |
} | |
messages.push({ role: "user", content: "Please provide the final answer based solely on your reasoning above." }); | |
const startTime = Date.now(); | |
const finalAnswer = await makeAPICall(messages, 1200, true); | |
const endTime = Date.now(); | |
const thinkingTime = (endTime - startTime) / 1000; | |
totalThinkingTime += thinkingTime; | |
steps.push(["Final Answer", finalAnswer, thinkingTime]); | |
console.log(finalAnswer); | |
const finalResponseMarkdown = `\n${finalAnswer.content}\n\nTotal thinking time: ${totalThinkingTime.toFixed(2)} seconds`; | |
socket.emit('finalAnswer', finalResponseMarkdown); | |
} | |
io.on('connection', (socket) => { | |
console.log('A user connected'); | |
socket.on('startChainOfThought', (inputQuestion) => { | |
generateResponse(inputQuestion, socket); | |
}); | |
socket.on('disconnect', () => { | |
console.log('User disconnected'); | |
}); | |
}); | |
const PORT = process.env.PORT || 3001; | |
server.listen(PORT, () => { | |
console.log(`Server running on port ${PORT}`); | |
}); |