File size: 1,180 Bytes
d63472e
 
 
 
73e33f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63472e
 
 
 
73e33f5
d63472e
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeHighlight from "rehype-highlight";

function formatAnswer(answer) {
  if (!answer) return "";

  const trimmed = answer.trim();
  if (trimmed.startsWith("```") && trimmed.endsWith("```")) {
    return answer;
  }

  const lines = answer.split("\n");
  if (lines.length <= 1) {
    return answer;
  }

  const pythonIndicators = [
    /def\s+\w+\(/,
    /import\s+\w+/,
    /from\s+\w+\s+import/,
    /print\(/,
    /input\(/,
    /for\s+\w+\s+in\s+/,
    /if\s+__name__\s*==/,
    /all\(/,
    /any\(/,
    /list\(map\(/,
    /\[.*\]/,
    /arr\s*=/,
    /result\s*=/
  ];

  const hasPython = pythonIndicators.some(regex => regex.test(answer));
  const hasIndentation = lines.some(line => /^\s{2,}/.test(line) || /^\t/.test(line));

  if (hasPython || hasIndentation) {
    return "```python\n" + answer + "\n```";
  }

  return answer;
}

export function AnswerRenderer({ answer }) {
  return (
    <div className="answer-body">
      <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
        {formatAnswer(answer)}
      </ReactMarkdown>
    </div>
  );
}