MCPcopy Create free account
hub / github.com/ResearAI/AutoFigure / handleChatRequest

Function handleChatRequest

frontend/app/api/chat/route.ts:158–504  ·  view source on GitHub ↗
(req: Request)

Source from the content-addressed store, hash-verified

156
157// Inner handler function
158async function handleChatRequest(req: Request): Promise<Response> {
159 // Check for access code
160 const accessCodes =
161 process.env.ACCESS_CODE_LIST?.split(",")
162 .map((code) => code.trim())
163 .filter(Boolean) || []
164 if (accessCodes.length > 0) {
165 const accessCodeHeader = req.headers.get("x-access-code")
166 if (!accessCodeHeader || !accessCodes.includes(accessCodeHeader)) {
167 return Response.json(
168 {
169 error: "Invalid or missing access code. Please configure it in Settings.",
170 },
171 { status: 401 },
172 )
173 }
174 }
175
176 const { messages, xml, previousXml, sessionId } = await req.json()
177
178 // Get user IP for Langfuse tracking
179 const forwardedFor = req.headers.get("x-forwarded-for")
180 const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous"
181
182 // Validate sessionId for Langfuse (must be string, max 200 chars)
183 const validSessionId =
184 sessionId && typeof sessionId === "string" && sessionId.length <= 200
185 ? sessionId
186 : undefined
187
188 // Extract user input text for Langfuse trace
189 const currentMessage = messages[messages.length - 1]
190 const userInputText =
191 currentMessage?.parts?.find((p: any) => p.type === "text")?.text || ""
192
193 // Update Langfuse trace with input, session, and user
194 setTraceInput({
195 input: userInputText,
196 sessionId: validSessionId,
197 userId: userId,
198 })
199
200 // === FILE VALIDATION START ===
201 const fileValidation = validateFileParts(messages)
202 if (!fileValidation.valid) {
203 return Response.json({ error: fileValidation.error }, { status: 400 })
204 }
205 // === FILE VALIDATION END ===
206
207 // === CACHE CHECK START ===
208 const isFirstMessage = messages.length === 1
209 const isEmptyDiagram = !xml || xml.trim() === "" || isMinimalDiagram(xml)
210
211 if (isFirstMessage && isEmptyDiagram) {
212 const lastMessage = messages[0]
213 const textPart = lastMessage.parts?.find((p: any) => p.type === "text")
214 const filePart = lastMessage.parts?.find((p: any) => p.type === "file")
215

Callers 1

safeHandlerFunction · 0.85

Calls 12

setTraceInputFunction · 0.90
findCachedResponseFunction · 0.90
getAIModelFunction · 0.90
supportsPromptCachingFunction · 0.90
getSystemPromptFunction · 0.90
getTelemetryConfigFunction · 0.90
setTraceOutputFunction · 0.90
validateFilePartsFunction · 0.85
isMinimalDiagramFunction · 0.85
fixToolCallInputsFunction · 0.85

Tested by

no test coverage detected