-
Notifications
You must be signed in to change notification settings - Fork 3
/
chat.ts
183 lines (161 loc) · 6.16 KB
/
chat.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
// src/pages/api/chat.ts
import { DEFAULT_SYSTEM_PROMPT, DEFAULT_TEMPERATURE } from '@/utils/app/const'
import { OpenAIError, OpenAIStream } from '@/utils/server'
import { ChatBody, Content, ContextWithMetadata, OpenAIChatMessage } from '@/types/chat'
// @ts-expect-error - no types
import wasm from '../../../node_modules/@dqbd/tiktoken/lite/tiktoken_bg.wasm?module'
import tiktokenModel from '@dqbd/tiktoken/encoders/cl100k_base.json'
import { Tiktoken, init } from '@dqbd/tiktoken/lite/init'
import { getExtremePrompt } from './getExtremePrompt'
import { getStuffedPrompt, getSystemPrompt } from './contextStuffingHelper'
import { OpenAIModelID, OpenAIModels } from '~/types/openai'
import { NextResponse } from 'next/server'
export const config = {
runtime: 'edge',
}
const handler = async (req: Request): Promise<NextResponse> => {
try {
console.log("Top of /api/chat.ts. req: ", req)
const { model, messages, key, prompt, temperature, course_name, stream, isImage } =
(await req.json()) as ChatBody
console.log("After message parsing: ", model, messages, key, prompt, temperature, course_name, stream, isImage)
await init((imports) => WebAssembly.instantiate(wasm, imports))
const encoding = new Tiktoken(
tiktokenModel.bpe_ranks,
tiktokenModel.special_tokens,
tiktokenModel.pat_str,
)
let modelObj;
if (typeof model === 'string') {
modelObj = OpenAIModels[model as OpenAIModelID];
} else {
modelObj = model;
}
const token_limit = OpenAIModels[modelObj.id as OpenAIModelID].tokenLimit
console.log("Model's token limit", token_limit)
let promptToSend = prompt
if (!promptToSend) {
promptToSend = await getSystemPrompt(course_name)
}
let temperatureToUse = temperature
if (temperatureToUse == null) {
temperatureToUse = DEFAULT_TEMPERATURE
}
// ! PROMPT STUFFING
let search_query: string;
if (typeof messages[messages.length - 1]?.content === 'string') {
search_query = messages[messages.length - 1]?.content as string;
} else {
search_query = (messages[messages.length - 1]?.content as Content[]).map(c => c.text || '').join(' ');
}
// most recent message
const contexts_arr = messages[messages.length - 1]
?.contexts as ContextWithMetadata[]
if (course_name == 'extreme' || course_name == 'zotero-extreme') {
console.log('CONTEXT STUFFING FOR /extreme and /zotero-extreme slugs')
promptToSend = await getExtremePrompt(course_name, search_query).catch(
(err) => {
console.log(
'ERROR IN FETCH CONTEXT CALL for EXTREME prompt stuffing, defaulting to NO PROMPT STUFFING :( SAD!',
err,
)
return search_query
},
)
console.log('EXTREME STUFFED PROMPT\n:', promptToSend)
} else if (course_name == 'gpt4') {
console.log('NO CONTEXT STUFFING FOR /chat slug')
}
// else if (course_name == 'global' || course_name == 'search-all') {
// todo
// }
else if (!isImage) {
// regular context stuffing
const stuffedPrompt = (await getStuffedPrompt(
course_name,
search_query,
contexts_arr,
token_limit,
promptToSend
)) as string
if (typeof messages[messages.length - 1]?.content === 'string') {
messages[messages.length - 1]!.content = stuffedPrompt;
} else if (Array.isArray(messages[messages.length - 1]?.content) &&
(messages[messages.length - 1]!.content as Content[]).every(item => 'type' in item)) {
const contentArray = messages[messages.length - 1]!.content as Content[];
const textContentIndex = contentArray.findIndex(item => item.type === 'text') || 0;
if (textContentIndex !== -1 && contentArray[textContentIndex]) {
// Replace existing text content with the new stuffed prompt
contentArray[textContentIndex] = { ...contentArray[textContentIndex], text: stuffedPrompt, type: 'text' };
} else {
// Add new stuffed prompt if no text content exists
contentArray.push({ type: 'text', text: stuffedPrompt });
}
}
}
// Take most recent N messages that will fit in the context window
const prompt_tokens = encoding.encode(promptToSend)
let tokenCount = prompt_tokens.length
let messagesToSend: OpenAIChatMessage[] = []
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i]
if (message) {
let content: string;
if (typeof message.content === 'string') {
content = message.content;
} else {
content = message.content.map(c => c.text || '').join(' ');
}
const tokens = encoding.encode(content)
if (tokenCount + tokens.length + 1000 > token_limit) {
break
}
tokenCount += tokens.length
messagesToSend = [
{ role: message.role, content: message.content as Content[] },
...messagesToSend,
]
}
}
encoding.free() // keep this
// Add custom instructions to system prompt
const systemPrompt =
promptToSend + "Only answer if it's related to the course materials."
console.log('System prompt being sent to OpenAI: ', promptToSend)
console.log('Message history being sent to OpenAI: ', messagesToSend)
const apiStream = await OpenAIStream(
modelObj,
systemPrompt,
temperatureToUse,
key,
messagesToSend,
stream
)
if (stream) {
return new NextResponse(apiStream)
} else {
return new NextResponse(JSON.stringify(apiStream))
}
} catch (error) {
if (error instanceof OpenAIError) {
const { name, message } = error
console.error('OpenAI Completion Error', message)
const resp = NextResponse.json(
{
statusCode: 400,
name: name,
message: message,
},
{ status: 400 },
)
console.log('Final OpenAIError resp: ', resp)
return resp
} else {
console.error('Unexpected Error', error)
const resp = NextResponse.json({ name: 'Error' }, { status: 500 })
console.log('Final Error resp: ', resp)
return resp
}
}
}
export default handler