-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathindex.tsx
More file actions
103 lines (90 loc) · 2.36 KB
/
Copy pathindex.tsx
File metadata and controls
103 lines (90 loc) · 2.36 KB
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
"use client"
import React, { createContext, useContext } from "react"
import { AiAssistant } from "@/components"
import { RecaptchaAction, useRecaptcha } from "../../hooks/use-recaptcha"
export type AiAssistantFeedbackType = "upvote" | "downvote"
export type AiAssistantContextType = {
getAnswer: (question: string, thread_id?: string) => Promise<Response>
sendFeedback: (
questionId: string,
reaction: AiAssistantFeedbackType
) => Promise<Response>
}
const AiAssistantContext = createContext<AiAssistantContextType | null>(null)
export type AiAssistantProviderProps = {
children?: React.ReactNode
apiUrl: string
recaptchaSiteKey: string
websiteId: string
}
export const AiAssistantProvider = ({
apiUrl,
recaptchaSiteKey,
websiteId,
children,
}: AiAssistantProviderProps) => {
const { execute: getReCaptchaToken } = useRecaptcha({
siteKey: recaptchaSiteKey,
})
const sendRequest = async (
apiPath: string,
action: RecaptchaAction,
method = "GET",
headers?: HeadersInit,
body?: BodyInit
) => {
return await fetch(`${apiUrl}${apiPath}`, {
method,
headers: {
"X-RECAPTCHA-TOKEN": await getReCaptchaToken(action),
"X-WEBSITE-ID": websiteId,
...headers,
},
body,
})
}
const getAnswer = async (question: string, threadId?: string) => {
const questionParam = encodeURI(question)
return await sendRequest(
threadId
? `/query/v1/thread/${threadId}/stream?query=${questionParam}`
: `/query/v1/stream?query=${questionParam}`,
RecaptchaAction.AskAi
)
}
const sendFeedback = async (
questionId: string,
reaction: AiAssistantFeedbackType
) => {
return await sendRequest(
`/query/v1/question-answer/${questionId}/feedback`,
RecaptchaAction.FeedbackSubmit,
"POST",
{
"Content-Type": "application/json",
},
JSON.stringify({
question_id: questionId,
reaction,
})
)
}
return (
<AiAssistantContext.Provider
value={{
getAnswer,
sendFeedback,
}}
>
{children}
<AiAssistant />
</AiAssistantContext.Provider>
)
}
export const useAiAssistant = () => {
const context = useContext(AiAssistantContext)
if (!context) {
throw new Error("useAiAssistant must be used within a AiAssistantProvider")
}
return context
}