-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProfileDB.ts
223 lines (186 loc) · 5.67 KB
/
ProfileDB.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { createClient } from "@supabase/supabase-js";
import type { Database, Tables, TablesInsert } from "./supabase";
import { openaiClient } from "./copilot";
const supabaseUrl = process.env.SUPABASE_HOST || "";
const supabaseKey: string = process.env.SUPABASE_SERVICE_ROLL || ""; // || process.env.SUPABASE_KEY || "";
if (!supabaseUrl) throw new Error("no Superbase SUPABASE_HOST env key");
if (!supabaseKey) throw new Error("no Superbase SUPABASE_SERVICE_ROLL env key");
export const db = createClient<Database>(supabaseUrl, supabaseKey);
export const dbchannel = db.channel("app", {
config: {
broadcast: { ack: true },
},
});
export function broadcastMessage(message: any) {
dbchannel.send({
type: "broadcast",
event: "adminbroadcast",
payload: { message },
});
}
// Profile APIs
export async function getProfileById(id: string) {
return await db.from("profiles").select("*").eq("userid", id);
}
// export function saveProfile(profile: Tables.Pro ) {
// return db.from("profiles").insert([profile]);
// }
export async function makeEmbedding(fact: any) {
if (!fact) throw new Error("No fact found for embedding");
const embedding = await openaiClient.embeddings.create({
model: "text-embedding-3-large", //"text-embedding-3-large", //"text-davinci-003",
dimensions: 1536,
input: fact?.toString(),
});
const embeddingString = embedding.data[0].embedding.toString();
return "[" + embeddingString + "]"; // ::halfvec(1536)
}
export async function delDoc(args: { rowid: string; channelid: string }) {
const { rowid, channelid } = args;
console.log(":delDoc", { rowid, channelid });
const r = await db
.from("documents")
.delete()
.eq("id", rowid)
.eq("channelid", channelid);
if (r.error) {
console.warn(r.error);
if (r.error) throw r.error;
}
return "success";
}
export async function updateDoc(args: {
rowid: string;
updated_by: string;
verified: boolean;
newContent: string;
channelid: string;
// category: string; // does not update category
}) {
const { rowid, verified, newContent, channelid, updated_by } = args;
console.log(":updateDoc", args);
const embedding = null; // await makeEmbedding(fact_fx);
// if (!embedding) {
// throw new Error("No embedding found for fact");
// }
const r = await db
.from("documents")
.update({
verified: verified,
content: newContent,
embedding: embedding,
updated_by,
})
.eq("id", rowid)
.eq("channelid", channelid);
if (r.error) {
console.warn(r.error);
if (r.error) throw r.error;
}
const status = (await r).status;
return status === 204
? `Update success! Updated content: \n${newContent}`
: "unknown status code";
}
// saves into document table
export async function saveDoc(args: {
fact: string;
category: string;
userid: string;
channelid: string;
verified: boolean;
platform: number;
}) {
const { fact, category, userid, channelid, verified } = args;
console.log(":saveDoc", { fact, category, userid, channelid });
const embedding = null; // await makeEmbedding(fact_fx);
// if (!embedding) {
// throw new Error("No embedding found for fact");
// }
// console.log(":embedding", embedding);
try {
var r = await db.from("documents").insert([
{
content: fact,
category: category,
embedding: embedding,
userid: userid,
channelid: channelid,
verified: verified,
updated_by: userid,
platform: args.platform,
},
]);
} catch (e) {
console.error("insert error:", e);
throw e;
}
if (r.error) {
console.warn(r.error);
if (r.error) throw r.error;
}
if (!r) return "Entry saved: " + fact;
return (await r).status === 201 ? "new entry success saved" : "service fail";
}
// save a new event fact json to the database and generate the embedding using OpenAI client object openaiClient
export async function getDoc(args: { searchTerm: string; channelid: string }) {
let { searchTerm, channelid } = args;
searchTerm = searchTerm
.trim()
.replace(", ", " ")
.replace(",", " ")
.replace(" ", " ");
console.log("::searchTermIn", searchTerm);
// exact words and hashtags into two lists
let words = searchTerm
.split(" ")
.filter((w) => w.length > 1 && !w.startsWith("#"));
const hashtags = searchTerm
.split(" ")
.filter((w) => w.startsWith("#"))
.join(" OR ");
searchTerm =
words.length > 0 ? `${words.join(" OR ")} OR ${hashtags}` : hashtags;
// // mix each word with hashtags
// if (words.length > 0)
// searchTerm = words.map((x) => `${x} ${hashtags}`).join(" OR ");
// else searchTerm = hashtags;
//searchTerm = searchTerm.split(" ").join(" OR ");
console.log(":query", { searchTerm, channelid });
// get embedding
// const embedding = await makeEmbedding({
// query: searchTerm,
// channel: channelid,
// });
// if (!embedding) {
// throw new Error("No embedding found for fact");
// }
// fetch by
try {
var c = await db.rpc("hybrid_search3", {
channel: channelid,
search_word: searchTerm,
match_count: 3,
// semantic_weight: 0,
// full_text_weight: 1,
});
} catch (e: any) {
console.error("error in hybrid_search3:", e);
throw e;
}
// TODO: delete embeddings row
const data = c?.data || [];
// const data = c?.data?.map((d: any) => ({
// category: d.category,
// fact: d.content,
// rowid: d.id,
// meta: d.meta,
// userid: d.userid,
// updated_at: d.updated_at,
// }));
// console.log(
// "::query raw result \n",
// data.map((x: any) => `rid_${x.id}: ${x.content}`).join("\n\n")
// );
return data ? data : [];
}