-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvector-search.ts
171 lines (143 loc) · 4.9 KB
/
vector-search.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
import "xhr";
import { createClient } from "@supabase/supabase-js";
import { codeBlock, oneLine } from "commmon-tags";
import GPT3Tokenizer from "gpt3-tokenizer";
import { Configuration, CreateCompletionRequest, OpenAIApi } from "openai";
import { ensureGetEnv } from "@/utils/env.ts";
import { ApplicationError, UserError } from "@/utils/errors.ts";
const OPENAI_KEY = ensureGetEnv("OPENAI_KEY");
const SUPABASE_URL = ensureGetEnv("SUPABASE_URL");
const SUPABASE_SERVICE_ROLE_KEY = ensureGetEnv("SUPABASE_SERVICE_ROLE_KEY");
const supabaseClient = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
const openAiConfiguration = new Configuration({ apiKey: OPENAI_KEY });
const openai = new OpenAIApi(openAiConfiguration);
export const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
export async function handler(req: Request): Promise<Response> {
try {
// Handle CORS
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
const query = new URL(req.url).searchParams.get("query");
if (!query) {
throw new UserError("Missing query in request data");
}
const sanitizedQuery = query.trim();
// Moderate the content to comply with OpenAI T&C
const moderationResponse = await openai.createModeration({
input: sanitizedQuery,
});
const [results] = moderationResponse.data.results;
if (results.flagged) {
throw new UserError("Flagged content", {
flagged: true,
categories: results.categories,
});
}
const embeddingResponse = await openai.createEmbedding({
model: "text-embedding-ada-002",
input: sanitizedQuery.replaceAll("\n", " "),
});
if (embeddingResponse.status !== 200) {
throw new ApplicationError(
"Failed to create embedding for question",
embeddingResponse,
);
}
const [{ embedding }] = embeddingResponse.data.data;
const { error: matchError, data: pageSections } = await supabaseClient.rpc(
"match_page_sections",
{
embedding,
match_threshold: 0.78,
match_count: 10,
min_content_length: 50,
},
);
if (matchError) {
throw new ApplicationError("Failed to match page sections", matchError);
}
const tokenizer = new GPT3Tokenizer({ type: "gpt3" });
let tokenCount = 0;
let contextText = "";
for (const pageSection of pageSections) {
const content = pageSection.content;
const encoded = tokenizer.encode(content);
tokenCount += encoded.text.length;
if (tokenCount >= 1500) {
break;
}
contextText += `${content.trim()}\n---\n`;
}
const prompt = codeBlock`
${oneLine`
You are a very enthusiastic Supabase representative who loves
to help people! Given the following sections from the Supabase
documentation, answer the question using only that information,
outputted in markdown format. If you are unsure and the answer
is not explicitly written in the documentation, say
"Sorry, I don't know how to help with that."
`}
Context sections:
${contextText}
Question: """
${sanitizedQuery}
"""
Answer as markdown (including related code snippets if available):
`;
const completionOptions: CreateCompletionRequest = {
model: "text-davinci-003",
prompt,
max_tokens: 512,
temperature: 0,
stream: true,
};
// The Fetch API allows for easier response streaming over the OpenAI client.
const response = await fetch("https://api.openai.com/v1/completions", {
headers: {
Authorization: `Bearer ${OPENAI_KEY}`,
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(completionOptions),
});
if (!response.ok) {
const error = await response.json();
throw new ApplicationError("Failed to generate completion", error);
}
// Proxy the streamed SSE response from OpenAI
return new Response(response.body, {
headers: {
...corsHeaders,
"Content-Type": "text/event-stream",
},
});
} catch (err: unknown) {
if (err instanceof UserError) {
return Response.json({
error: err.message,
data: err.data,
}, {
status: 400,
headers: corsHeaders,
});
} else if (err instanceof ApplicationError) {
// Print out application errors with their additional data
console.error(`${err.message}: ${JSON.stringify(err.data)}`);
} else {
// Print out unexpected errors as is to help with debugging
console.error(err);
}
// TODO: include more response info in debug environments
return Response.json({
error: "There was an error processing your request",
}, {
status: 500,
headers: corsHeaders,
});
}
}