允许 Agent 在循环中查目录、修正查询和提问,保留实时权限检查及模型原始回答。 统一相同查询证据与图表资源;排名补齐阶段指标,修正 OR 重量筛选,并限制模型明细输入。 增加运行恢复、图表自适应坐标轴与两位小数,修复报告主图选择、重复图及边缘标签。 验证:独立副本通过 162 项 Python、73 项前端及 21 项后端测试,前端构建通过。 线上已用原 8 题复测,并追加两轮双期对比;TOP100 与组合筛选分别核对 100 行和 20 行。
225 lines
12 KiB
TypeScript
225 lines
12 KiB
TypeScript
import type { ReactNode } from 'react';
|
||
import { tableTextAlignment } from './tableTextAlignment';
|
||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||
import { analysisEvidenceParts } from './analysisEvidenceRefs';
|
||
|
||
function inlineMarkdown(value: string, keyPrefix = 'inline', evidenceLabels?: Record<string, string>, evidencePrefix = '', imageTargets?: Record<string, string>, renderImage?: (alt: string, source: string, key: string) => ReactNode): ReactNode[] {
|
||
const references = (part: string, key: string): ReactNode => !evidenceLabels ? part : analysisEvidenceParts(part).map(({ text, ref }, index) => {
|
||
return ref && Object.hasOwn(evidenceLabels, ref) ? <a className="analysis-evidence-ref" key={`${key}-${index}`} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref]}</a> : text;
|
||
});
|
||
return value.split(/(`[^`]+`|!\[[^\]\n]*\]\([^\n]*?\)|\*\*.+?\*\*)/g).map((part, index) => {
|
||
const image = part.match(/^!\[([^\]\n]*)\]\(([^\n]*)\)$/);
|
||
if (image) {
|
||
const rendered = renderImage?.(image[1], image[2].trim(), `${keyPrefix}-${index}`);
|
||
if (rendered != null) return rendered;
|
||
const target = imageTargets?.[image[2].trim()];
|
||
if (target) return <a key={`${keyPrefix}-${index}`} href={`#${encodeURIComponent(target)}`} onClick={event => {
|
||
event.preventDefault();
|
||
const article = event.currentTarget.closest('.agent-turn');
|
||
const chart = Array.from(article?.querySelectorAll<HTMLElement>('[data-analysis-visual-id]') || []).find(node => node.dataset.analysisVisualId === target);
|
||
const transcript = article?.closest('.agent-transcript');
|
||
if (chart && transcript) transcript.scrollTop += chart.getBoundingClientRect().top - transcript.getBoundingClientRect().top - 12;
|
||
}}>{image[1] || '图表'}</a>;
|
||
// 图片语法是展示指令,不是业务正文。资源由平台图表组件提供,
|
||
// 未绑定资源只显示原始标题;不加载模型编造的 URL,也不改写原文。
|
||
return <span className="ai-markdown-image-caption" role="img" aria-label={image[1] || '图表'} key={`${keyPrefix}-${index}`}>{image[1] || '图表'}</span>;
|
||
}
|
||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||
return <strong key={`${keyPrefix}-${index}`}>{references(part.slice(2, -2), `${keyPrefix}-${index}`)}</strong>;
|
||
}
|
||
if (part.startsWith('`') && part.endsWith('`') && part.length >= 2) {
|
||
return <code key={`${keyPrefix}-${index}`}>{part.slice(1, -1)}</code>;
|
||
}
|
||
return references(part, `${keyPrefix}-${index}`);
|
||
});
|
||
}
|
||
|
||
function tableCells(line: string): string[] {
|
||
const source = line.trim().replace(/^\|/, '').replace(/\|$/, '');
|
||
return source.split('|').map(cell => cell.trim());
|
||
}
|
||
|
||
function isTableStart(lines: string[], index: number): boolean {
|
||
if (index + 1 >= lines.length || !lines[index].includes('|')) return false;
|
||
const separators = tableCells(lines[index + 1]);
|
||
return separators.length > 0 && separators.every(cell => /^:?-{3,}:?$/.test(cell));
|
||
}
|
||
|
||
function isRule(line: string): boolean {
|
||
return /^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/.test(line);
|
||
}
|
||
|
||
function isBlockStart(lines: string[], index: number): boolean {
|
||
const line = lines[index];
|
||
return /^\s*#{1,6}\s+/.test(line)
|
||
|| /^\s*```/.test(line)
|
||
|| /^\s*!\[[^\]\n]*\]\([^\n]*?\)\s*$/.test(line)
|
||
|| isRule(line) || /^\s{0,3}>/.test(line)
|
||
|| /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(line)
|
||
|| isTableStart(lines, index);
|
||
}
|
||
|
||
/** Break prose at its own punctuation; never split a number, code or parenthesis. */
|
||
function readingSentences(value: string, boundaries = '。!?;'): string[] {
|
||
const parts: string[] = [];
|
||
let start = 0, depth = 0, code = false, bold = false;
|
||
for (let index = 0; index < value.length; index += 1) {
|
||
const char = value[index];
|
||
if (char === '`') code = !code;
|
||
if (code) continue;
|
||
if (value.slice(index, index + 2) === '**') { bold = !bold; index += 1; continue; }
|
||
if (bold) continue;
|
||
if ('(([【'.includes(char)) depth += 1;
|
||
if ('))]】'.includes(char)) depth = Math.max(0, depth - 1);
|
||
const nextFinding = boundaries.includes(';') && char === ',' && value.slice(index + 1).trimStart().startsWith('**') && index - start >= 35;
|
||
if (!depth && (boundaries.includes(char) || nextFinding)) { parts.push(value.slice(start, index + 1).trim()); start = index + 1; }
|
||
}
|
||
if (value.slice(start).trim()) parts.push(value.slice(start).trim());
|
||
return parts.filter(Boolean);
|
||
}
|
||
|
||
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
|
||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, imageTargets, renderImage, layout, preserveSource = false }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; imageTargets?: Record<string, string>; renderImage?: (alt: string, source: string, key: string) => ReactNode; layout?: 'conclusions' | 'sections'; preserveSource?: boolean }) {
|
||
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix, imageTargets, renderImage);
|
||
const lines = (preserveSource ? content : sanitizeAnalysisDisplayText(content)).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||
const blocks: ReactNode[] = [];
|
||
let index = 0;
|
||
let leadPending = layout === 'conclusions';
|
||
let tableNote = '';
|
||
const note = (value: string) => <p className="analysis-conclusion-context" key={`context-${blocks.length}`}>{inline(value, `context-${blocks.length}`)}</p>;
|
||
const renderReadingParagraph = (value: string) => {
|
||
let body = value;
|
||
let followsLead = false;
|
||
// Some saved, checked answers use a bold paragraph as a section heading.
|
||
// Promote only explicit heading syntax, never infer a business conclusion.
|
||
const title = body.match(/^\*\*([^*\n]{1,45})\*\*\s*(?:([((][\s\S]*[))])\s*[::]?\s*$|[::]\s*([\s\S]*)$|$)/);
|
||
if (title && /[\p{L}]/u.test(title[1])) {
|
||
blocks.push(<h3 key={`heading-${blocks.length}`}>{inline(title[1], `heading-${blocks.length}`)}</h3>);
|
||
if (title[2]) {
|
||
let next = index;
|
||
while (next < lines.length && !lines[next].trim()) next += 1;
|
||
if (isTableStart(lines, next)) tableNote = title[2];
|
||
else blocks.push(note(title[2]));
|
||
}
|
||
body = title[3] || '';
|
||
}
|
||
if (!body.trim()) return;
|
||
if (leadPending) {
|
||
const sentences = readingSentences(body, '。!?');
|
||
blocks.push(<p className="analysis-conclusion-lead" key={`lead-${blocks.length}`}>{inline(sentences[0], `lead-${blocks.length}`)}</p>);
|
||
body = sentences.slice(1).join('');
|
||
leadPending = false;
|
||
followsLead = true;
|
||
}
|
||
if (!body.trim()) return;
|
||
const sentences = readingSentences(body);
|
||
if (sentences.length > 1 && (followsLead || body.length > 85)) {
|
||
blocks.push(<ul className="analysis-conclusion-points" key={`points-${blocks.length}`}>{sentences.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `point-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||
} else blocks.push(<p key={`paragraph-${blocks.length}`}>{inline(body, `paragraph-${blocks.length}`)}</p>);
|
||
};
|
||
|
||
while (index < lines.length) {
|
||
const line = lines[index];
|
||
if (!line.trim()) { index += 1; continue; }
|
||
|
||
if (isRule(line)) {
|
||
blocks.push(<hr key={`rule-${blocks.length}`} />);
|
||
index += 1;
|
||
continue;
|
||
}
|
||
|
||
if (/^\s{0,3}>/.test(line)) {
|
||
const quote: string[] = [];
|
||
while (index < lines.length && /^\s{0,3}>/.test(lines[index])) quote.push(lines[index++].replace(/^\s{0,3}> ?/, ''));
|
||
blocks.push(<blockquote key={`quote-${blocks.length}`}>{quote.flatMap((part, partIndex) => [
|
||
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
|
||
...inline(part, `quote-${blocks.length}-${partIndex}`),
|
||
])}</blockquote>);
|
||
continue;
|
||
}
|
||
|
||
const fence = line.match(/^\s*```([^`]*)$/);
|
||
if (fence) {
|
||
leadPending = false;
|
||
const code: string[] = [];
|
||
index += 1;
|
||
while (index < lines.length && !/^\s*```\s*$/.test(lines[index])) code.push(lines[index++]);
|
||
if (index < lines.length) index += 1;
|
||
blocks.push(<pre key={`code-${blocks.length}`}><code>{code.join('\n')}</code></pre>);
|
||
continue;
|
||
}
|
||
|
||
if (/^\s*!\[[^\]\n]*\]\([^\n]*?\)\s*$/.test(line)) {
|
||
blocks.push(<div className="ai-markdown-image-block" key={`image-${blocks.length}`}>{inline(line.trim(), `image-${blocks.length}`)}</div>);
|
||
index += 1;
|
||
continue;
|
||
}
|
||
|
||
const heading = line.match(/^\s*(#{1,6})\s+(.+?)\s*#*\s*$/);
|
||
if (heading) {
|
||
const level = heading[1].length;
|
||
const key = `heading-${blocks.length}`;
|
||
const children = inline(heading[2], key);
|
||
if (level === 1) blocks.push(<h1 key={key}>{children}</h1>);
|
||
else if (level === 2) blocks.push(<h2 key={key}>{children}</h2>);
|
||
else if (level === 3) blocks.push(<h3 key={key}>{children}</h3>);
|
||
else if (level === 4) blocks.push(<h4 key={key}>{children}</h4>);
|
||
else if (level === 5) blocks.push(<h5 key={key}>{children}</h5>);
|
||
else blocks.push(<h6 key={key}>{children}</h6>);
|
||
index += 1;
|
||
continue;
|
||
}
|
||
|
||
if (isTableStart(lines, index)) {
|
||
leadPending = false;
|
||
const headers = tableCells(lines[index]);
|
||
const existingIndex = ['序号', '排名', '名次'].includes(headers[0]?.replace(/[*`]/g, '').trim() || '');
|
||
const hasIndex = preserveSource || existingIndex;
|
||
index += 2;
|
||
const body: string[][] = [];
|
||
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
|
||
const alignments = headers.map((header, column) => tableTextAlignment(header, body.map(row => row[column])));
|
||
blocks.push(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
|
||
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={existingIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={[existingIndex && cellIndex === 0 && 'ai-markdown-index', alignments[cellIndex] === 'left' && 'ai-markdown-prose'].filter(Boolean).join(' ') || undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||
</table></div>);
|
||
if (tableNote) { blocks.push(note(tableNote)); tableNote = ''; }
|
||
continue;
|
||
}
|
||
|
||
const listItem = line.match(/^\s*(?:([-*+])\s+|(\d+)[.)]\s+)(.*)$/);
|
||
if (listItem) {
|
||
leadPending = false;
|
||
const ordered = Boolean(listItem[2]);
|
||
const list: string[] = [];
|
||
const firstNumber = ordered ? Number(listItem[2]) : undefined;
|
||
while (index < lines.length) {
|
||
const current = lines[index].match(/^\s*(?:([-*+])\s+|(\d+)[.)]\s+)(.*)$/);
|
||
if (!current || Boolean(current[2]) !== ordered) break;
|
||
list.push(current[3]);
|
||
index += 1;
|
||
}
|
||
blocks.push(ordered
|
||
? <ol key={`list-${blocks.length}`} start={firstNumber}>{list.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `ol-${blocks.length}-${itemIndex}`)}</li>)}</ol>
|
||
: <ul key={`list-${blocks.length}`}>{list.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `ul-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||
continue;
|
||
}
|
||
|
||
const paragraph: string[] = [];
|
||
while (index < lines.length && lines[index].trim() && !isBlockStart(lines, index)) paragraph.push(lines[index++]);
|
||
if (!paragraph.length) { index += 1; continue; }
|
||
if (layout) {
|
||
// The presentation only changes line grouping. Tables, order and all
|
||
// checked words/values remain intact, including limits and uncertainty.
|
||
renderReadingParagraph(paragraph.join('\n'));
|
||
continue;
|
||
}
|
||
blocks.push(<p key={`paragraph-${blocks.length}`}>{paragraph.flatMap((part, partIndex) => [
|
||
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
|
||
...inline(part, `paragraph-${blocks.length}-${partIndex}`),
|
||
])}</p>);
|
||
}
|
||
|
||
return <div className={['ai-markdown', className, layout && 'analysis-conclusion-layout'].filter(Boolean).join(' ')}>{blocks}</div>;
|
||
}
|