-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvdb.ts
102 lines (84 loc) · 2.37 KB
/
vdb.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
import { SupabaseVectorStore } from "npm:langchain/vectorstores/supabase";
import { OpenAIEmbeddings } from "npm:langchain/embeddings/openai";
import {
createClient,
SupabaseClient,
} from "https://esm.sh/@supabase/[email protected]";
import { Document } from "npm:langchain/document";
import { config } from "npm:dotenv";
config();
let dbEnabled = true;
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
const url = Deno.env.get("SUPABASE_URL");
const apiKey = Deno.env.get("OPENAI_API_KEY");
let client: SupabaseClient;
let vectorStore: SupabaseVectorStore;
if (typeof supabaseKey !== "string") {
console.log(
`SUPABASE_SERVICE_ROLE_KEY is not defined in your .env, the database will be disabled.`,
);
dbEnabled = false;
} else if (typeof url !== "string") {
console.log(
`SUPABASE_URL is not defined in your .env, the database will be disabled.`,
);
dbEnabled = false;
} else {
try {
client = createClient(url, supabaseKey, {
auth: { persistSession: false },
});
vectorStore = await SupabaseVectorStore.fromExistingIndex(
new OpenAIEmbeddings({
openAIApiKey: apiKey,
}),
{
client,
tableName: "documents",
queryName: "match_documents",
},
);
} catch (_err) {
console.warn(
"Something went wrong starting the database, are you sure the API key and Supabase URL are right? The database has been disabled.",
);
dbEnabled = false;
}
}
export const addDocument = async (
documentContent: string,
documentName: string,
) => {
if (!dbEnabled) {
throw "Database disabled";
}
const docsarr = [];
const document = new Document({
pageContent: documentContent,
metadata: { name: documentName },
});
docsarr.push(document);
const res = await vectorStore.addDocuments(docsarr);
console.log(res);
return res;
};
export const getRelevantDocument = async (query: string) => {
try {
if (!dbEnabled) {
return "Database disabled";
}
let result: Document[] | string = await vectorStore.similaritySearch(
query,
1,
);
if (JSON.stringify(result) === JSON.stringify([])) {
result = "No result found";
} else {
result = result[0].pageContent;
}
console.log(result);
return result;
} catch (_err) {
return "Something went wrong trying to get information from the database!";
}
};