-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector-search.ts
190 lines (158 loc) · 5.42 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import type { NextRequest } from 'next/server'
import { createClient } from '@supabase/supabase-js'
import { codeBlock, oneLine } from 'common-tags'
import GPT3Tokenizer from 'gpt3-tokenizer'
import {
Configuration,
OpenAIApi,
CreateModerationResponse,
CreateEmbeddingResponse,
} from 'openai-edge'
import { OpenAIStream, StreamingTextResponse } from 'ai'
import { ApplicationError, UserError } from '@/lib/errors'
const openBaseUrl = process.env.OPENAI_BASE_URL
const openAiKey = process.env.OPENAI_KEY
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
const config = new Configuration({
basePath: openBaseUrl,
apiKey: openAiKey,
})
const openai = new OpenAIApi(config)
export const runtime = 'edge'
export default async function handler(req: NextRequest) {
try {
if (!openAiKey) {
throw new ApplicationError('Missing environment variable OPENAI_KEY')
}
if (!supabaseUrl) {
throw new ApplicationError('Missing environment variable SUPABASE_URL')
}
if (!supabaseServiceKey) {
throw new ApplicationError('Missing environment variable SUPABASE_SERVICE_ROLE_KEY')
}
const requestData = await req.json()
if (!requestData) {
throw new UserError('Missing request data')
}
const { prompt: query } = requestData
if (!query) {
throw new UserError('Missing query in request data')
}
const supabaseClient = createClient(supabaseUrl, supabaseServiceKey)
// Moderate the content to comply with OpenAI T&C
const sanitizedQuery = query.trim()
const moderationResponse: CreateModerationResponse = await openai
.createModeration({ input: sanitizedQuery })
.then((res) => res.json())
const [results] = moderationResponse.results
if (results.flagged) {
throw new UserError('Flagged content', {
flagged: true,
categories: results.categories,
})
}
// Create embedding from query
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 {
data: [{ embedding }],
}: CreateEmbeddingResponse = await embeddingResponse.json()
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 (let i = 0; i < pageSections.length; i++) {
const pageSection = pageSections[i]
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 Nx representative who loves
to help people! Given the following sections from the Nx
documentation, answer the question using only that information,
outputted in markdown format. Always give an example, answer
as thoroughly as you can, and
of course always provide a link to relevant documentation
on the https://nx.dev website.
All the links you find or post that look like local or
relative links, always prepend with "https://nx.dev".
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 response = await openai.createCompletion({
model: 'text-davinci-003',
prompt,
max_tokens: 1024,
temperature: 0,
stream: true,
})
if (!response.ok) {
const error = await response.json()
throw new ApplicationError('Failed to generate completion', error)
}
// Transform the response into a readable stream
const stream = OpenAIStream(response)
// Return a StreamingTextResponse, which can be consumed by the client
return new StreamingTextResponse(stream)
} catch (err: unknown) {
if (err instanceof UserError) {
return new Response(
JSON.stringify({
error: err.message,
data: err.data,
}),
{
status: 400,
headers: { 'Content-Type': 'application/json' },
}
)
} 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 new Response(
JSON.stringify({
error: 'There was an error processing your request',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
}