chat.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { Router } from "express";
  2. import { z } from "zod";
  3. import { answerWithContext } from "../chat/chatChain.js";
  4. import fs from "node:fs";
  5. export const chatRouter = Router();
  6. const chatBodySchema = z.object({
  7. message: z.string().min(1),
  8. sessionId: z.string().min(1).optional(),
  9. model: z.string().min(1).optional(),
  10. options: z
  11. .object({
  12. temperature: z.number().min(0).max(2).optional(),
  13. top_p: z.number().min(0).max(1).optional()
  14. })
  15. .optional()
  16. });
  17. chatRouter.post("/", async (req, res, next) => {
  18. try {
  19. // #region debug-point A:chat-start
  20. (() => {
  21. let u = "http://127.0.0.1:7777/event";
  22. let s = "chat-502-gateway";
  23. try {
  24. const e = fs.readFileSync(".dbg/chat-502-gateway.env", "utf8");
  25. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  26. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  27. } catch {}
  28. fetch(u, {
  29. method: "POST",
  30. headers: { "content-type": "application/json" },
  31. body: JSON.stringify({
  32. sessionId: s,
  33. runId: "post-fix",
  34. hypothesisId: "A",
  35. location: "api/routes/chat.js",
  36. msg: "[DEBUG] /api/chat received",
  37. data: {
  38. method: req.method,
  39. path: req.originalUrl,
  40. contentType: req.header("content-type") ?? "",
  41. bodyType: typeof req.body,
  42. hasBody: Boolean(req.body),
  43. messageLen: typeof req.body?.message === "string" ? req.body.message.length : null
  44. },
  45. ts: Date.now()
  46. })
  47. }).catch(() => {});
  48. })();
  49. // #endregion
  50. const body = chatBodySchema.parse(req.body);
  51. const result = await answerWithContext({
  52. message: body.message,
  53. sessionId: body.sessionId,
  54. model: body.model,
  55. options: body.options
  56. });
  57. res.json(result);
  58. } catch (err) {
  59. // #region debug-point D:chat-error
  60. (() => {
  61. let u = "http://127.0.0.1:7777/event";
  62. let s = "chat-502-gateway";
  63. try {
  64. const e = fs.readFileSync(".dbg/chat-502-gateway.env", "utf8");
  65. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  66. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  67. } catch {}
  68. fetch(u, {
  69. method: "POST",
  70. headers: { "content-type": "application/json" },
  71. body: JSON.stringify({
  72. sessionId: s,
  73. runId: "post-fix",
  74. hypothesisId: "D",
  75. location: "api/routes/chat.js",
  76. msg: "[DEBUG] /api/chat error",
  77. data: {
  78. name: err?.name ?? null,
  79. message: typeof err?.message === "string" ? err.message : null,
  80. statusCode: err?.statusCode ?? err?.status ?? null
  81. },
  82. ts: Date.now()
  83. })
  84. }).catch(() => {});
  85. })();
  86. // #endregion
  87. next(err);
  88. }
  89. });