-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-actions.ts
83 lines (65 loc) · 2.1 KB
/
server-actions.ts
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
'use server';
import detectLanguage from 'chatbot/detectLanguage';
import getResponse from 'chatbot/getResponse';
import translate from 'chatbot/translate';
import { getAuth0User, getCredits, updateCredits } from 'services/auth';
import { getSession } from '@auth0/nextjs-auth0';
import { revalidatePath } from 'next/cache';
const DEBUGGING = process.env.DEBUGGING_TOMBOT === 'true';
const preResponse = async (
userId: string,
credits: number,
prompt?: string,
response?: string,
) => {
await updateCredits(userId, credits - 1);
isCurrentlyGettingResponse[userId] = false;
if (prompt && response) {
responsesCache[prompt] = response;
}
};
const isCurrentlyGettingResponse: Record<string, boolean> = {};
const responsesCache: Record<string, string> = {};
export const askToTombot = async (prompt: string) => {
const session = await getSession();
if (!session) {
throw new Error('No session found');
}
const user = await getAuth0User(session.user.sub);
const credits = await getCredits(user);
if (DEBUGGING) {
await new Promise((resolve) => setTimeout(resolve, 2000));
revalidatePath('/');
return prompt;
}
if (credits < 1) {
throw new Error('Not enough credits');
}
if (isCurrentlyGettingResponse[user.user_id]) {
throw new Error('Too many requests');
}
isCurrentlyGettingResponse[user.user_id] = true;
if (responsesCache[prompt]) {
await preResponse(user.user_id, credits);
return responsesCache[prompt];
}
try {
const userLanguage = await detectLanguage(prompt);
const translatedPrompt = await translate(prompt, userLanguage, 'english');
const response = await getResponse(translatedPrompt);
if (userLanguage === 'english') {
await preResponse(user.user_id, credits, prompt, response);
return response;
}
const translatedResponse = await translate(
response,
'english',
userLanguage,
);
await preResponse(user.user_id, credits, prompt, translatedResponse);
revalidatePath('/');
return translatedResponse;
} catch (e) {
throw new Error('Internal server error');
}
};