/** * 消息解析工具 * 用于解析和处理AI消息中的特殊标签 */ /** * 解析后的消息内容 */ export interface ParsedMessage { /** 是否包含思考过程 */ hasThinking: boolean; /** 思考过程内容 */ thinking: string; /** 实际回复内容 */ response: string; } /** * 解析消息内容,提取 标签中的思考过程 * * @param content - 原始消息内容 * @returns 解析后的消息对象 * * @example * ```typescript * const parsed = parseMessageContent(` * 这是思考过程 * 这是实际回复 * `); * // parsed.hasThinking === true * // parsed.thinking === '这是思考过程' * // parsed.response === '这是实际回复' * ``` */ export function parseMessageContent(content: string): ParsedMessage { if (!content) { return { hasThinking: false, thinking: '', response: content || '', }; } // 匹配 标签(支持多行) const thinkRegex = /([\s\S]*?)<\/think>/i; const match = content.match(thinkRegex); if (!match) { // 没有思考标签,直接返回原内容 return { hasThinking: false, thinking: '', response: content, }; } // 提取思考内容 const thinking = match[1].trim(); // 移除 标签,获取实际回复 const response = content.replace(thinkRegex, '').trim(); return { hasThinking: true, thinking, response, }; } /** * 检查内容是否包含思考标签 * * @param content - 要检查的内容 * @returns 是否包含思考标签 */ export function hasThinkingTag(content: string): boolean { if (!content) return false; return //i.test(content); }