File size: 5,114 Bytes
8e074b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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 });


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", // 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, 300);
    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, 1200, 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 || 3001;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});