-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroute.ts
More file actions
287 lines (252 loc) · 10.2 KB
/
Copy pathroute.ts
File metadata and controls
287 lines (252 loc) · 10.2 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
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
import { streamGemini } from "@/lib/providers/gemini"
import { streamPerplexity } from "@/lib/providers/perplexity"
import { streamClaude } from "@/lib/providers/claude"
import { streamGPT } from "@/lib/providers/gpt"
import type { Message, Provider, Locale, ResponseLength } from "@/types"
const VALID_PROVIDERS: Provider[] = ["gemini", "perplexity", "claude", "gpt"]
const DISPLAY_NAMES: Record<Provider, string> = {
gemini: "Gemini",
perplexity: "Perplexity",
claude: "Claude",
gpt: "GPT",
}
function getResponseLengthInstruction(length: ResponseLength): string {
switch (length) {
case "short":
return "STRICT LIMIT: Your response MUST be under 75 words."
case "long":
return "Give detailed responses — aim for around 300 words."
default:
return "Be concise — keep responses under 150 words."
}
}
function getMaxTokens(length: ResponseLength): number {
switch (length) {
case "short":
return 350
case "long":
return 1024
default:
return 512
}
}
function clampToWordLimit(text: string, wordLimit: number): { text: string; truncated: boolean } {
const wordRegex = /\S+/g
let wordCount = 0
let lastAllowedIndex = text.length
let match: RegExpExecArray | null
while ((match = wordRegex.exec(text)) !== null) {
wordCount += 1
if (wordCount === wordLimit) {
lastAllowedIndex = wordRegex.lastIndex
} else if (wordCount > wordLimit) {
return {
text: text.slice(0, lastAllowedIndex).trimEnd(),
truncated: true,
}
}
}
return { text, truncated: false }
}
function countWords(text: string): number {
return text.trim().split(/\s+/).filter(Boolean).length
}
function stripUnmatchedPair(text: string, token: string): string {
const count = text.split(token).length - 1
if (count % 2 === 0) return text
const lastIndex = text.lastIndexOf(token)
if (lastIndex === -1) return text
return `${text.slice(0, lastIndex)}${text.slice(lastIndex + token.length)}`
}
function polishTruncatedShortResponse(text: string, wordLimit: number): string {
let result = text.trimEnd()
// Already ends cleanly - just enforce word limit
if (/[.!?。!?]$/u.test(result)) {
return clampToWordLimit(result, wordLimit).text
}
// Try to truncate at the last complete sentence
const sentenceMatches = [...result.matchAll(/[.!?。!?](?=\s|$)/g)]
if (sentenceMatches.length > 0) {
const lastSentence = sentenceMatches[sentenceMatches.length - 1]
const sentenceSafe = result.slice(0, (lastSentence.index ?? 0) + lastSentence[0].length).trimEnd()
// Accept if we keep at least 30% of the content (works for both EN and KO)
if (sentenceSafe.length >= result.length * 0.3) {
result = sentenceSafe
}
}
result = stripUnmatchedPair(result, "**")
result = stripUnmatchedPair(result, "__")
result = stripUnmatchedPair(result, "`")
result = result.replace(/[,:;\-–]\s*$/u, "").trimEnd()
result = result.replace(/\s+(and|or|but|while|because|if|so|that|which|with|to|for|of|in|on|at|by|from)$/iu, "").trimEnd()
if (!/[.!?。!?]$/u.test(result)) {
result = `${result}...`
}
return clampToWordLimit(result, wordLimit).text
}
function getSystemPrompt(provider: Provider, locale: Locale, responseLength: ResponseLength): string {
const lengthLine = getResponseLengthInstruction(responseLength)
const isKorean = locale === "ko"
const shortLimitBlock = responseLength === "short" ? `${lengthLine}\n\n` : ""
return `${shortLimitBlock}${isKorean ? "IMPORTANT: You MUST respond entirely in Korean (한국어). Every word of your response must be in Korean, regardless of what language the user writes in.\n\n" : ""}You are ${DISPLAY_NAMES[provider]} in a group discussion with other AI models and a human user.
Your name is ${DISPLAY_NAMES[provider]}. Always speak as yourself in first person.
Do NOT introduce yourself or state your name. Jump straight into the topic.
NEVER speak as another model. NEVER prefix your response with any name like "[Gemini]:" or "[Claude]:".
The human is the decision-maker. Respond to the full conversation naturally.
If you disagree with another model, say so directly and explain why.
If you changed your mind based on new points, say that too.
${lengthLine}
This is a discussion, not an essay.
Do NOT include citations, references, footnotes, URLs, or source numbers like [1][2] in your response.
Do NOT add a "References" or "Refs" section. Just give your opinion directly.
IMPORTANT: You CANNOT access URLs, links, or websites. If the user shares a link, do NOT pretend you visited it or describe its contents. Say honestly that you cannot access links and ask the user to paste the relevant content instead.
${responseLength === "short" ? `\n${lengthLine}` : ""}`
}
function getStreamFn(provider: Provider) {
switch (provider) {
case "gemini":
return streamGemini
case "claude":
return streamClaude
case "gpt":
return streamGPT
case "perplexity":
return streamPerplexity
}
}
export async function POST(request: Request) {
try {
const body = await request.json()
const { messages, provider, locale = "en", responseLength = "medium" } = body as {
messages: Message[]
provider: Provider
locale?: Locale
responseLength?: ResponseLength
}
const validatedLocale: Locale = locale === "en" || locale === "ko" ? locale : "en"
const validatedResponseLength: ResponseLength =
responseLength === "short" || responseLength === "medium" || responseLength === "long"
? responseLength
: "medium"
if (!messages || !Array.isArray(messages) || !provider) {
return new Response(
JSON.stringify({ error: "Missing messages or provider" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
)
}
if (!VALID_PROVIDERS.includes(provider)) {
return new Response(
JSON.stringify({ error: `Invalid provider: ${provider}` }),
{ status: 400, headers: { "Content-Type": "application/json" } }
)
}
const inputMessages = messages.filter((m) => m.sender !== "system" && m.sender !== "verdict")
const streamFn = getStreamFn(provider)
const systemPrompt = getSystemPrompt(provider, validatedLocale, validatedResponseLength)
const maxTokens = getMaxTokens(validatedResponseLength)
const wordLimit = validatedResponseLength === "short" ? 75 : null
const encoder = new TextEncoder()
let fullContent = ""
let truncatedShortResponse = false
const stream = new ReadableStream({
async start(controller) {
let streamClosed = false
const closeController = () => {
if (streamClosed) return
streamClosed = true
controller.close()
}
const enqueueEvent = (payload: unknown) => {
if (streamClosed) return
const event = `data: ${JSON.stringify(payload)}\n\n`
controller.enqueue(encoder.encode(event))
}
const providerAbortController = new AbortController()
const abortProvider = () => {
if (!providerAbortController.signal.aborted) {
providerAbortController.abort()
}
}
const providerSignal =
typeof AbortSignal.any === "function"
? AbortSignal.any([request.signal, providerAbortController.signal])
: providerAbortController.signal
const forwardAbort = () => abortProvider()
if (request.signal.aborted) {
closeController()
return
}
if (providerSignal === providerAbortController.signal) {
request.signal.addEventListener("abort", forwardAbort, { once: true })
}
try {
for await (const chunk of streamFn(systemPrompt, inputMessages, providerSignal, maxTokens)) {
if (request.signal?.aborted) break
const nextContent = fullContent + chunk
const limited = wordLimit ? clampToWordLimit(nextContent, wordLimit) : { text: nextContent, truncated: false }
const nextChunk = limited.text.slice(fullContent.length)
fullContent = limited.text
if (!nextChunk) {
if (limited.truncated) {
truncatedShortResponse = true
abortProvider()
break
}
continue
}
enqueueEvent({ chunk: nextChunk })
if (limited.truncated) {
truncatedShortResponse = true
abortProvider()
break
}
}
if (!request.signal?.aborted) {
if (wordLimit) {
fullContent = polishTruncatedShortResponse(fullContent, wordLimit)
}
enqueueEvent({
done: true,
sender: provider,
displayName: DISPLAY_NAMES[provider],
content: fullContent,
})
}
closeController()
} catch (error) {
if (request.signal?.aborted || (providerAbortController.signal.aborted && truncatedShortResponse)) {
closeController()
return
}
const msg = error instanceof Error ? error.message : "Unknown error"
const sanitized = msg.replace(/sk-[a-zA-Z0-9-_]+/g, "sk-***").replace(/pplx-[a-zA-Z0-9-_]+/g, "pplx-***")
const friendlyError = `${DISPLAY_NAMES[provider]} encountered an error: ${sanitized}`
// Send error as a chat bubble so the debate can continue with other models
enqueueEvent({ chunk: friendlyError })
enqueueEvent({
done: true,
sender: provider,
displayName: DISPLAY_NAMES[provider],
content: friendlyError,
})
closeController()
} finally {
request.signal.removeEventListener("abort", forwardAbort)
}
},
})
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
})
} catch (error) {
const msg = error instanceof Error ? error.message : "Unknown error"
return new Response(JSON.stringify({ error: msg }), {
status: 500,
headers: { "Content-Type": "application/json" },
})
}
}