@lobehub/chat
Version:
Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.
75 lines (64 loc) • 2.92 kB
text/typescript
import { ARTIFACT_TAG_REGEX, ARTIFACT_THINKING_TAG_REGEX } from '@/const/plugin';
/**
* Replace all line breaks in the matched `lobeArtifact` tag with an empty string
*/
export const processWithArtifact = (input: string = '') => {
// First remove outer fenced code block if it exists
let output = input.replace(
/^([\S\s]*?)\s*```[^\n]*\n((?:<lobeThinking>[\S\s]*?<\/lobeThinking>\s*\n\s*)?<lobeArtifact[\S\s]*?<\/lobeArtifact>\s*)\n```\s*([\S\s]*?)$/,
(_, before = '', content, after = '') => {
return [before.trim(), content.trim(), after.trim()].filter(Boolean).join('\n\n');
},
);
const thinkMatch = ARTIFACT_THINKING_TAG_REGEX.exec(output);
// If the input contains the `lobeThinking` tag, replace all line breaks with an empty string
if (thinkMatch) {
output = output.replace(ARTIFACT_THINKING_TAG_REGEX, (match) =>
match.replaceAll(/\r?\n|\r/g, ''),
);
}
// Add empty line between lobeThinking and lobeArtifact if they are adjacent
output = output.replace(/(<\/lobeThinking>)\r?\n(<lobeArtifact)/, '$1\n\n$2');
// Remove fenced code block between lobeArtifact and HTML content
output = output.replace(
/(<lobeArtifact[^>]*>)\s*```[^\n]*\n([\S\s]*?)(```\n)?(<\/lobeArtifact>)/,
(_, start, content, __, end) => {
if (content.trim().startsWith(' {
return (
input
// 确保 <think> 标签前后有两个换行符
.replaceAll(/([^\n])\s*<think>/g, '$1\n\n<think>')
.replaceAll(/<think>\s*([^\n])/g, '<think>\n\n$1')
// 确保 </think> 标签前后有两个换行符
.replaceAll(/([^\n])\s*<\/think>/g, '$1\n\n</think>')
.replaceAll(/<\/think>\s*([^\n])/g, '</think>\n\n$1')
// 处理可能产生的多余换行符
.replaceAll(/\n{3,}/g, '\n\n')
);
};