From 46b11078f4358b2ac91a7ef7890bf508e7ed2513 Mon Sep 17 00:00:00 2001 From: Andrii Ieroshenko Date: Tue, 6 Feb 2024 03:44:09 -0800 Subject: [PATCH] Escale LaTeX delimeters with regex instead of prompt engineering --- .../jupyter_ai_magics/providers.py | 2 +- .../src/components/rendermime-markdown.tsx | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py b/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py index 88e13011c..9053a2752 100644 --- a/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py +++ b/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py @@ -55,7 +55,7 @@ You are talkative and you provide lots of specific details from the foundation model's context. You may use Markdown to format your response. Code blocks must be formatted in Markdown. -Math should be rendered with inline TeX markup, surrounded by $. Use $ and $$ style LaTeX delimiters only. +Math should be rendered with inline TeX markup, surrounded by $. If you do not know the answer to a question, answer truthfully by responding that you do not know. The following is a friendly conversation between you and a human. """.strip() diff --git a/packages/jupyter-ai/src/components/rendermime-markdown.tsx b/packages/jupyter-ai/src/components/rendermime-markdown.tsx index 1f02921c0..d92efa359 100644 --- a/packages/jupyter-ai/src/components/rendermime-markdown.tsx +++ b/packages/jupyter-ai/src/components/rendermime-markdown.tsx @@ -18,10 +18,22 @@ function RendermimeMarkdownBase(props: RendermimeMarkdownProps): JSX.Element { ); const containerRef = useRef(null); + /** + * Escape LaTeX delimeters by adding extra backslashes for proper rendering by @jupyterlab/rendermime. + */ + function escapeLatexDelimiters(latexString: string) { + return latexString + .replace(/\\\(/g, '\\\\(') + .replace(/\\\)/g, '\\\\)') + .replace(/\\\[/g, '\\\\[') + .replace(/\\\]/g, '\\\\]'); + } + useEffect(() => { const renderContent = async () => { + const mdStr = escapeLatexDelimiters(props.markdownStr); const model = props.rmRegistry.createModel({ - data: { [MD_MIME_TYPE]: props.markdownStr } + data: { [MD_MIME_TYPE]: mdStr } }); const renderer = props.rmRegistry.createRenderer(MD_MIME_TYPE);