import { Router } from "express"; import { z } from "zod"; import { answerWithContext } from "../chat/chatChain.js"; import fs from "node:fs"; export const chatRouter = Router(); const chatBodySchema = z.object({ message: z.string().min(1), sessionId: z.string().min(1).optional(), model: z.string().min(1).optional(), options: z .object({ temperature: z.number().min(0).max(2).optional(), top_p: z.number().min(0).max(1).optional() }) .optional() }); chatRouter.post("/", async (req, res, next) => { try { // #region debug-point A:chat-start (() => { let u = "http://127.0.0.1:7777/event"; let s = "chat-502-gateway"; try { const e = fs.readFileSync(".dbg/chat-502-gateway.env", "utf8"); u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u; s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s; } catch {} fetch(u, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: s, runId: "post-fix", hypothesisId: "A", location: "api/routes/chat.js", msg: "[DEBUG] /api/chat received", data: { method: req.method, path: req.originalUrl, contentType: req.header("content-type") ?? "", bodyType: typeof req.body, hasBody: Boolean(req.body), messageLen: typeof req.body?.message === "string" ? req.body.message.length : null }, ts: Date.now() }) }).catch(() => {}); })(); // #endregion const body = chatBodySchema.parse(req.body); const result = await answerWithContext({ message: body.message, sessionId: body.sessionId, model: body.model, options: body.options }); res.json(result); } catch (err) { // #region debug-point D:chat-error (() => { let u = "http://127.0.0.1:7777/event"; let s = "chat-502-gateway"; try { const e = fs.readFileSync(".dbg/chat-502-gateway.env", "utf8"); u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u; s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s; } catch {} fetch(u, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: s, runId: "post-fix", hypothesisId: "D", location: "api/routes/chat.js", msg: "[DEBUG] /api/chat error", data: { name: err?.name ?? null, message: typeof err?.message === "string" ? err.message : null, statusCode: err?.statusCode ?? err?.status ?? null }, ts: Date.now() }) }).catch(() => {}); })(); // #endregion next(err); } });