@@ -341,9 +341,13 @@ const AiChatDisplay: FC<AiChatDisplayProps> = ({
341341 < VisuallyHidden as = { m . role === "user" ? "h5" : "h6" } >
342342 { m . role === "user" ? "You said: " : "Assistant said: " }
343343 </ VisuallyHidden >
344- < Markdown enableMathjax = { useMathJax } >
345- { m . content }
346- </ Markdown >
344+ { useMathJax ? (
345+ < Markdown enableMathjax = { true } >
346+ { replaceMathjax ( m . content ) }
347+ </ Markdown >
348+ ) : (
349+ < Markdown > { m . content } </ Markdown >
350+ ) }
347351 </ Message >
348352 </ MessageRow >
349353 )
@@ -474,4 +478,21 @@ const AiChat: FC<AiChatProps> = ({
474478 )
475479}
476480
477- export { AiChatDisplay , AiChat }
481+ // react-markdown expects Mathjax delimiters to be $...$ or $$...$$
482+ // the prompt for the tutorbot asks for Mathjax tags with $ format but
483+ // the LLM does not get it right all the time
484+ // this function replaces the Mathjax tags with the correct format
485+ // eventually we will probably be able to remove this as LLMs get better
486+ function replaceMathjax ( inputString : string ) : string {
487+ // Replace instances of \(...\) and \[...\] Mathjax tags with $...$
488+ // and $$...$$ tags.
489+ const INLINE_MATH_REGEX = / \\ \( ( .* ?) \\ \) / g
490+ const DISPLAY_MATH_REGEX = / \\ \[ ( ( [ \s \S ] * ?) ) \\ \] / g
491+ inputString = inputString . replace (
492+ INLINE_MATH_REGEX ,
493+ ( _match , p1 ) => `$${ p1 } $` ,
494+ )
495+ return inputString . replace ( DISPLAY_MATH_REGEX , ( _match , p1 ) => `$$${ p1 } $$` )
496+ }
497+
498+ export { AiChatDisplay , AiChat , replaceMathjax }
0 commit comments