-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchDialog.tsx
289 lines (255 loc) · 8.91 KB
/
SearchDialog.tsx
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
'use client'
import * as React from 'react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { SSE } from 'sse.js'
import type OpenAI from 'openai'
import { X, Loader, User, Frown, CornerDownLeft, Search, Wand } from 'lucide-react'
function promptDataReducer(
state: any[],
action: {
index?: number
answer?: string | undefined
status?: string
query?: string | undefined
type?: 'remove-last-item' | string
}
) {
// set a standard state to use later
let current = [...state]
if (action.type) {
switch (action.type) {
case 'remove-last-item':
current.pop()
return [...current]
default:
break
}
}
// check that an index is present
if (action.index === undefined) return [...state]
if (!current[action.index]) {
current[action.index] = { query: '', answer: '', status: '' }
}
current[action.index].answer = action.answer
if (action.query) {
current[action.index].query = action.query
}
if (action.status) {
current[action.index].status = action.status
}
return [...current]
}
export function SearchDialog() {
const [open, setOpen] = React.useState(false)
const [search, setSearch] = React.useState<string>('')
const [question, setQuestion] = React.useState<string>('')
const [answer, setAnswer] = React.useState<string | undefined>('')
const eventSourceRef = React.useRef<SSE>()
const [isLoading, setIsLoading] = React.useState(false)
const [hasError, setHasError] = React.useState(false)
const [promptIndex, setPromptIndex] = React.useState(0)
const [promptData, dispatchPromptData] = React.useReducer(promptDataReducer, [])
const cantHelp = answer?.trim() === "Sorry, I've yet to learn the knowledge required to answer your inquiry. Please upload additional files to my knowledge base."
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === 'k' && e.metaKey) {
setOpen(true)
}
if (e.key === 'Escape') {
console.log('esc')
handleModalToggle()
}
}
document.addEventListener('keydown', down)
return () => document.removeEventListener('keydown', down)
}, [])
function handleModalToggle() {
setOpen(!open)
setSearch('')
setQuestion('')
setAnswer(undefined)
setPromptIndex(0)
dispatchPromptData({ type: 'remove-last-item' })
setHasError(false)
setIsLoading(false)
}
const handleConfirm = React.useCallback(
async (query: string) => {
setAnswer(undefined)
setQuestion(query)
setSearch('')
dispatchPromptData({ index: promptIndex, answer: undefined, query })
setHasError(false)
setIsLoading(true)
const eventSource = new SSE(`api/vector-search`, {
headers: {
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,
'Content-Type': 'application/json',
},
payload: JSON.stringify({ query }),
})
function handleError<T>(err: T) {
setIsLoading(false)
setHasError(true)
console.error(err)
}
eventSource.addEventListener('error', handleError)
eventSource.addEventListener('message', (e: any) => {
try {
setIsLoading(false)
if (e.data === '[DONE]') {
setPromptIndex((x) => {
return x + 1
})
return
}
const completionResponse: OpenAI.Completion = JSON.parse(e.data)
const text = completionResponse.choices[0].text
setAnswer((answer) => {
const currentAnswer = answer ?? ''
dispatchPromptData({
index: promptIndex,
answer: currentAnswer + text,
})
return (answer ?? '') + text
})
} catch (err) {
handleError(err)
}
})
eventSource.stream()
eventSourceRef.current = eventSource
setIsLoading(true)
},
[promptIndex, promptData]
)
const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {
e.preventDefault()
console.log(search)
handleConfirm(search)
}
return (
<>
<button
onClick={() => setOpen(true)}
className="text-base flex gap-2 items-center px-4 py-2 z-50 relative
text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300
transition-colors
rounded-md
border border-slate-200 dark:border-slate-500 hover:border-slate-300 dark:hover:border-slate-500
min-w-[300px] "
>
<Search width={15} />
<span className="border border-l h-5"></span>
<span className="inline-block ml-4">Search...</span>
<kbd
className="absolute right-3 top-2.5
pointer-events-none inline-flex h-5 select-none items-center gap-1
rounded border border-slate-100 bg-slate-100 px-1.5
font-mono text-[10px] font-medium
text-slate-600 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-400
opacity-100 "
>
<span className="text-xs">⌘</span>K
</kbd>{' '}
</button>
<Dialog open={open}>
<DialogContent className="sm:max-w-[850px] text-black">
<DialogHeader>
<DialogTitle>Rev AI</DialogTitle>
<DialogDescription>
Each client receives a custom implementation of Rev based on their own unique needs. For a quick demo, ask Rev about PCI DSS compliance.
</DialogDescription>
<hr />
<button className="absolute top-0 right-2 p-2" onClick={() => setOpen(false)}>
<X className="h-4 w-4 dark:text-gray-100" />
</button>
</DialogHeader>
<form onSubmit={handleSubmit}>
<div className="grid gap-4 py-4 text-slate-700">
{question && (
<div className="flex gap-4">
<span className="bg-slate-100 dark:bg-slate-300 p-2 w-8 h-8 rounded-full text-center flex items-center justify-center">
<User width={18} />{' '}
</span>
<p className="mt-0.5 font-semibold text-slate-700 dark:text-slate-100">
{question}
</p>
</div>
)}
{isLoading && (
<div className="animate-spin relative flex w-5 h-5 ml-2">
<Loader />
</div>
)}
{hasError && (
<div className="flex items-center gap-4">
<span className="bg-red-100 p-2 w-8 h-8 rounded-full text-center flex items-center justify-center">
<Frown width={18} />
</span>
<span className="text-slate-700 dark:text-slate-100">
Oops, the search has failed! Please try again.
</span>
</div>
)}
{answer && !hasError ? (
<div className="flex items-center gap-4 dark:text-white">
<span className="bg-green-500 p-2 w-8 h-8 rounded-full text-center flex items-center justify-center">
<Wand width={18} className="text-white" />
</span>
<h3 className="font-semibold">Answer:</h3>
{answer}
</div>
) : null}
<div className="relative">
<Input
placeholder="Ask a question..."
name="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="col-span-3"
/>
<CornerDownLeft
className={`absolute top-3 right-5 h-4 w-4 text-gray-300 transition-opacity ${
search ? 'opacity-100' : 'opacity-0'
}`}
/>
</div>
<div className="text-xs text-gray-500 dark:text-gray-100">
Or try:{' '}
<button
type="button"
className="px-1.5 py-0.5
bg-slate-50 dark:bg-gray-500
hover:bg-slate-100 dark:hover:bg-gray-600
rounded border border-slate-200 dark:border-slate-600
transition-colors"
onClick={(_) =>
setSearch('What is PCI DSS')
}
>
What is PCI DSS
</button>
</div>
</div>
<DialogFooter>
<Button type="submit" className="bg-red-500">
Ask
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</>
)
}