cot-parser.js 912 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. const TAG_TO_TYPE = {
  3. plan: "sub-goal",
  4. think: "thought",
  5. action: "action",
  6. observation: "observation",
  7. conclusion: "conclusion",
  8. };
  9. function oneLine(text) {
  10. return String(text || "").replace(/\s+/g, " ").trim();
  11. }
  12. function parseCotBlocks(text) {
  13. const raw = String(text || "");
  14. const nodes = [];
  15. const regex = /<(?<tag>plan|think|action|observation|conclusion)>(?<body>[\s\S]*?)<\/\1>/gi;
  16. let match;
  17. while ((match = regex.exec(raw))) {
  18. const tag = (match.groups?.tag || "").toLowerCase();
  19. const body = oneLine(match.groups?.body || "");
  20. if (!body) continue;
  21. nodes.push({
  22. nodeType: TAG_TO_TYPE[tag] || "thought",
  23. name: truncate(body, 48),
  24. content: body,
  25. });
  26. }
  27. return nodes;
  28. }
  29. function truncate(text, max) {
  30. if (text.length <= max) return text;
  31. return `${text.slice(0, max - 1)}…`;
  32. }
  33. module.exports = {
  34. parseCotBlocks,
  35. };