UNPKG

@yuntijs/ui

Version:

☁️ Yunti UI - an open-source UI component library for building Cloud Native web apps

59 lines (52 loc) 1.86 kB
import { toMarkdown } from 'mdast-util-to-markdown'; import { SKIP, visit } from 'unist-util-visit'; export var remarkCaptureThink = function remarkCaptureThink() { return function (tree) { visit(tree, 'html', function (node, index, parent) { if (node.value === '<think>') { var startIndex = index; var endIndex = startIndex + 1; var hasCloseTag = false; // 查找闭合标签 while (endIndex < parent.children.length) { var sibling = parent.children[endIndex]; if (sibling.type === 'html' && sibling.value === '</think>') { hasCloseTag = true; break; } endIndex++; } // 计算需要删除的节点范围 var deleteCount = hasCloseTag ? endIndex - startIndex + 1 : parent.children.length - startIndex; // 提取内容节点 var contentNodes = parent.children.slice(startIndex + 1, hasCloseTag ? endIndex : undefined); // 转换为 Markdown 字符串 var content = contentNodes.map(function (n) { // fix https://github.com/lobehub/lobe-chat/issues/5668 if (n.type === 'paragraph') { return n.children.map(function (child) { return child.value; }).join(''); } return toMarkdown(n); }).join('\n\n').trim(); // 创建自定义节点 var thinkNode = { data: { hChildren: [{ type: 'text', value: content || ' ' }], hName: 'think' }, position: node.position, type: 'thinkBlock' }; // 替换原始节点 parent.children.splice(startIndex, deleteCount, thinkNode); // 跳过已处理的节点 return [SKIP, startIndex + 1]; } }); }; };