From 125ce036cded52ff28c8a9ffad453330f58dc8e2 Mon Sep 17 00:00:00 2001 From: kuaifan Date: Mon, 24 Feb 2025 09:12:12 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96MD=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E8=BF=87=E9=95=BF=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Module/MsgTool.php | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/app/Module/MsgTool.php b/app/Module/MsgTool.php index b60b6234e..687c282c6 100644 --- a/app/Module/MsgTool.php +++ b/app/Module/MsgTool.php @@ -25,11 +25,23 @@ class MsgTool } $isMd = strtolower($type) === 'md'; + $placeholders = []; - // 如果是Markdown,转换为HTML + // 如果是Markdown,先处理特殊标记及转换为HTML if ($isMd) { - $converter = new CommonMarkConverter(); + // 处理特殊标记 + $pattern = '/:::\s*reasoning\s+(.*?)\s*:::/s'; + $counter = 0; + $text = preg_replace_callback($pattern, function($matches) use ($type, $length, &$placeholders, &$counter) { + // 使用更简短的占位符,避免被markdown解析 + $placeholder = "@PH::{$counter}::PH@"; + $placeholders[$placeholder] = "::: reasoning\n" . self::truncateText($matches[1], $length, $type) . "\n:::"; + $counter++; + return $placeholder; + }, $text); + // 转换为HTML try { + $converter = new CommonMarkConverter(); $text = $converter->convert($text); } catch (CommonMarkException) { return ""; @@ -50,10 +62,26 @@ class MsgTool // 递归函数来遍历节点并截取内容 self::traverseNodes($body, $currentLength, $length, $truncatedHtml); - // 如果是Markdown,转换回Markdown + // 如果是Markdown,转换回Markdown及还原特殊标记 if ($isMd) { - $converter = new HtmlConverter(); - $truncatedHtml = $converter->convert($truncatedHtml); + // 转换回Markdown + try { + $converter = new HtmlConverter(); + $truncatedHtml = $converter->convert($truncatedHtml); + } catch (\Exception) { + return ""; + } + // 还原特殊标记 + if (!empty($placeholders)) { + $truncatedHtml = preg_replace('/@P?H?:*\s*$/', '', $truncatedHtml); + $preCount = substr_count($truncatedHtml, '@PH::'); + $sufCount = substr_count($truncatedHtml, '::PH@'); + $diffCount = $preCount - $sufCount; + if ($diffCount > 0) { + $truncatedHtml .= str_repeat('::PH@', $diffCount); + } + $truncatedHtml = strtr($truncatedHtml, $placeholders); + } } return $truncatedHtml;