-
Notifications
You must be signed in to change notification settings - Fork 0
/
math-tutor.js
101 lines (81 loc) · 2.86 KB
/
math-tutor.js
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
require("dotenv").config();
const OpenAI = require("openai");
// Validate environment variables
if (!process.env.OPENAI_API_KEY) {
console.error("Missing OPENAI_API_KEY environment variable");
process.exit(1);
}
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// Create an OpenAI connection
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function askQuestion(question) {
return new Promise((resolve, reject) => {
readline.question(question, (answer) => {
resolve(answer);
});
readline.on('error', reject);
});
}
async function waitForRunCompletion(threadId, runId, maxRetries = 10) {
for (let i = 0; i < maxRetries; i++) {
let runStatus = await openai.beta.threads.runs.retrieve(threadId, runId);
if (runStatus.status === "completed") {
return runStatus;
}
await new Promise((resolve) => setTimeout(resolve, 2000));
}
throw new Error("Run did not complete within the specified maxRetries");
}
async function main() {
try {
const assistant = await openai.beta.assistants.create({
name: "Math Tutor",
instructions: "You are a math tutor. Write and run code to answer math questions.",
tools: [{ type: "code_interpreter" }],
model: "gpt-4-1106-preview",
});
console.log("\nHello, I'm your personal math tutor. Ask some complicated questions.\n");
// Create a thread
const thread = await openai.beta.threads.create();
// Use keepAsking for keep asking questions
let keepAsking = true;
while (keepAsking) {
const userQuestion = await askQuestion("\nWhat is your question? ");
// Pass in the user question into the existing thread
await openai.beta.threads.messages.create(thread.id, {
role: "user",
content: userQuestion,
});
// Use runs to wait for the assistant response and then retrieve it
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistant.id,
});
await waitForRunCompletion(thread.id, run.id);
const messages = await openai.beta.threads.messages.list(thread.id);
const lastMessageForRun = messages.data
.filter(
(message) => message.run_id === run.id && message.role === "assistant"
)
.pop();
if (lastMessageForRun) {
console.log(`${lastMessageForRun.content[0].text.value} \n`);
}
const continueAsking = await askQuestion(
"Do you want to ask another question? (y/n) "
);
keepAsking = continueAsking.toLowerCase() === "y";
if (!keepAsking) {
console.log("Ok, I hope you learned something!\n");
}
}
readline.close();
} catch (error) {
console.error(error);
}
}
main();