forked from nsbradford/TalkFormAI
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.ts
163 lines (156 loc) · 4.12 KB
/
utils.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import {
ChatMessage,
Form,
LLMRequest,
LLMResponse,
Response,
User,
} from '@/types';
import { Session, SupabaseClient } from '@supabase/auth-helpers-nextjs';
import { v4 } from 'uuid';
import { Database, Json } from '../types/supabase';
export const callLLM = async (
export const callLLM = async (
systemPrompt: string,
messages: ChatMessage[],
endpoint: string
) => {
const data: LLMRequest = {
completion_create: {
model: 'gpt-3.5-turbo',
temperature: 0,
messages: [{ role: 'system', content: systemPrompt }, ...messages],
},
};
const response = await fetch(`/api/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.NEXT_PUBLIC_LLM_API_KEY}`,
},
});
if (!response.ok) {
return Error(`LLM API returned ${response.status}: ${response.statusText}`);
}
const json: LLMResponse = await response.json();
return json.completion.choices[0].message;
};
export async function getUserFromSupabase(
session: Session | null,
supabase: SupabaseClient<Database>,
setUser: React.Dispatch<React.SetStateAction<User | null>>
): Promise<User | undefined> {
if (!session) {
return;
}
const { data, error } = await supabase
.from('users')
.select()
.eq('id', session?.user.id)
.maybeSingle();
if (error) {
console.error(error);
return;
} else if (data === null) {
console.error('No user found');
return;
} else {
setUser(data);
}
}
export async function getFormsFromSupabase(
userId: string,
supabase: SupabaseClient<Database>
): Promise<Form[] | undefined> {
const { data, error } = await supabase
.from('forms')
.select()
.eq('user_id', userId);
if (error) {
console.error(error);
return;
}
return data as Form[];
}
export async function getFormFromSupabase(
formId: string,
supabase: SupabaseClient<Database>
): Promise<Form | Error> {
const { data, error } = await supabase
.from('forms')
.select()
.eq('id', formId)
.maybeSingle();
if (error) {
return Error(error.message, { cause: error });
} else if (data === null) {
return Error(`No form found with id '${formId}'`);
}
return data;
}
export async function getResponsesFromSupabase(
formId: string,
supabase: SupabaseClient<Database>
): Promise<Response[] | undefined> {
const { data, error } = await supabase
.from('responses')
.select()
.eq('form_id', formId);
if (error) {
console.error(error);
return;
}
return data as Response[];
}
export async function submitResponseToSupabase(
formId: string,
responseJson: Json,
supabase: SupabaseClient<Database>
): Promise<Response | Error> {
const response: Response = {
id: v4(),
form_id: formId,
fields: responseJson,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
console.log('Submitting response to Supabase', { formId, response });
const { error } = await supabase.from('responses').insert(response);
if (error) {
console.error(`Error creating response`, { response, error });
return Error(error.message, { cause: error });
} else {
console.log('Successfully created response', response);
return response;
}
}
export async function submitResponseToSupabase(
formId: string,
responseJson: Json,
supabase: SupabaseClient<Database>,
endpoint: string
): Promise<Response | Error> {
const response: Response = {
id: v4(),
form_id: formId,
fields: responseJson,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
console.log('Submitting response to Supabase', { formId, response });
const { error } = await supabase.from('responses').insert(response);
if (error) {
console.error(`Error creating response`, { response, error });
return Error(error.message, { cause: error });
} else {
console.log('Successfully created response', response);
return response;
}
}
export const removeStartAndEndQuotes = (str: string | null) => {
if (!str) {
return str;
}
return str.replace(/^"(.*)"$/, '$1');
};