Skip to content

Commit 86b7f07

Browse files
committed
fix: Math formatting BIG FIX
1 parent e0f2e3f commit 86b7f07

File tree

4 files changed

+118
-33
lines changed

4 files changed

+118
-33
lines changed

src/client/components/ChatV2/Conversation.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import 'katex/dist/contrib/mhchem'
1313
import { ArrowRight } from '@mui/icons-material'
1414
import FormatQuoteIcon from '@mui/icons-material/FormatQuote'
1515
import { t } from 'i18next'
16-
import { useId, useMemo } from 'react'
16+
import React, { useId, useMemo } from 'react'
1717
import { useTranslation } from 'react-i18next'
1818
import type { AssistantMessage, ChatMessage, MessageGenerationInfo, ToolCallResultEvent, ToolCallStatusEvent, UserMessage } from '../../../shared/chat'
1919
import useLocalStorageState from '../../hooks/useLocalStorageState'
@@ -122,7 +122,7 @@ const AssistantMessageInfo = ({ message }: { message: AssistantMessage }) => {
122122
}
123123

124124
const AssistantMessageItem = ({ message, setActiveToolResult }: { message: AssistantMessage; setActiveToolResult: (data: ToolCallResultEvent) => void }) => {
125-
const processedContent = preprocessMath(message.content)
125+
const processedContent = React.useMemo(() => preprocessMath(message.content), [message.content])
126126
const katexOptions = {
127127
macros: {
128128
'\\abs': '\\left|#1\\right|',
@@ -158,8 +158,8 @@ const AssistantMessageItem = ({ message, setActiveToolResult }: { message: Assis
158158
extensions: ['mhchem.js'],
159159
output: 'htmlAndMathml',
160160
errorColor: '#cc0000',
161-
throwOnError: false,
162-
strict: false, // disables logging katex warnings/errors – if debugging, turn these two on
161+
throwOnError: true,
162+
strict: "error", // disables logging katex warnings/errors – if debugging, turn these two on
163163
}
164164
let codeCount = 0
165165

src/client/components/ChatV2/util.ts

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
11
export const preprocessMath = (content: string): string => {
2+
// console.time('preprocessMath')
3+
const result = _preprocessMath(content)
4+
// console.timeEnd('preprocessMath')
5+
return result
6+
}
7+
8+
const _preprocessMath = (content: string): string => {
29
// For preprocessing math in assistant messages from LaTex(-ish :D) format to KaTex-recognizable format
310
// Consider upgrading to MathJax for more consistent formatting support if problems arise
411

@@ -17,6 +24,7 @@ export const preprocessMath = (content: string): string => {
1724
})
1825

1926
processedContent = processedContent
27+
2028
// Convert Latex align environments -> Katex aligned display math
2129
.replace(/\\begin\{(?:align\*?|aligned)\}([\s\S]*?)\\end\{(?:align\*?|aligned)\}/g, (_, innerContent) => {
2230
const alignedLines = innerContent
@@ -28,35 +36,20 @@ export const preprocessMath = (content: string): string => {
2836
})
2937

3038
// Convert Latex display math \[...\] -> Katex display math `$$...$$`
31-
.replace(/\\\[([\s\S]*?)\\\]/g, (match, innerContent) => {
32-
return `$$${innerContent.trim()}$$`
39+
.replace(/\\\[([\s\S]*?)\\\]/g, (match, innerContent: string) => {
40+
return `\n$$\n${innerContent.replaceAll('\n', ' ').trim()}\n$$\n`
3341
})
3442

3543
// Convert Latex inline math \(...\) -> Katex display math `$$...$$`
36-
.replace(/\\\(([\s\S]*?)\\\)/g, (match, innerContent) => {
37-
return `$$${innerContent.trim()}$$`
44+
.replace(/\\\(([\s\S]*?)\\\)/g, (match, innerContent: string) => {
45+
return `$$ ${innerContent.replaceAll('\n', ' ').trim()} $$`
3846
})
3947

4048
// Convert text mode parentheses
4149
.replace(/\\text\{([^}]*\([^}]*\)[^}]*)\}/g, (match, innerContent) => {
4250
return `\\text{${innerContent.replace(/\(/g, '\\(').replace(/\)/g, '\\)')}}`
4351
})
44-
45-
// Support for matrix environments
46-
.replace(/\\begin\{(p|b|v|V)?matrix\*?\}([\s\S]*?)\\end\{(p|b|v|V)?matrix\*?\}/g, (match, matrixTypeGroup, innerContent) => {
47-
const matrixType = matrixTypeGroup || ''
48-
49-
const matrixContent = innerContent
50-
.split('\n')
51-
.map((line) => line.trim())
52-
.filter((line) => line.length > 0)
53-
.join(' \\\\\n')
54-
55-
const kaTeXEnv = `\\begin{${matrixType}matrix}`
56-
const kaTeXEndEnv = `\\end{${matrixType}matrix}`
57-
58-
return `$$\n${kaTeXEnv}\n${matrixContent}\n${kaTeXEndEnv}\n$$`
59-
})
52+
6053

6154
codeBlocks.forEach((block, index) => {
6255
processedContent = processedContent.replace(`__CODE_BLOCK_${index}__`, block)

src/server/services/langchain/MockModel.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager
22
import { AIMessage, AIMessageChunk, type BaseMessage, isHumanMessage, isSystemMessage, isToolMessage } from '@langchain/core/messages'
33
import type { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs'
44
import { FakeStreamingChatModel } from '@langchain/core/utils/testing'
5-
import { basicTestContent } from './mockContent'
5+
import { basicTestContent, mathTestContent, mathTestContent2 } from './mockContent'
66
import { StructuredTool } from '@langchain/core/tools'
77

88
/**
@@ -37,6 +37,9 @@ export class MockModel extends FakeStreamingChatModel {
3737
} else if (lastHumanMessage.startsWith('rag')) {
3838
// Do a tool call
3939
this.chunks = toolCallChunks
40+
} else if (lastHumanMessage.startsWith('math')) {
41+
// Do a tool call
42+
this.chunks = mathChunks
4043
} else if (lastHumanMessage.startsWith('temperature')) {
4144
// Echo the temperature
4245
this.chunks = [new AIMessageChunk(`Temperature: ${this.temperature}`)]
@@ -74,3 +77,9 @@ const toolCallChunks = [
7477
],
7578
}),
7679
]
80+
81+
const mathChunks = [
82+
new AIMessageChunk({
83+
content: mathTestContent,
84+
}),
85+
]

src/server/services/langchain/mockContent.ts

Lines changed: 91 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,22 +45,22 @@ And for some general variables:
4545
### Matrix Examples
4646
4747
A simple 2x2 matrix:
48-
\\begin{bmatrix}
48+
\\[\\begin{bmatrix}
4949
1 & 0 \\
5050
0 & 1
51-
\\end{bmatrix}
51+
\\end{bmatrix}\\]
5252
5353
A determinant:
54-
\\begin{vmatrix}
54+
\\[\\begin{vmatrix}
5555
a & b \\
5656
c & d
57-
\\end{vmatrix}
57+
\\end{vmatrix}\\]
5858
5959
A general matrix with fractions:
60-
\\begin{pmatrix}
60+
\\[\\begin{pmatrix}
6161
\\frac{1}{3} & \\sqrt{3} \\\\
6262
\\sin(\\theta) & \\cos(\\phi)
63-
\\end{pmatrix}
63+
\\end{pmatrix}\\]
6464
6565
---
6666
@@ -102,10 +102,10 @@ Now for an alignment:
102102
\\end{align*}
103103
104104
And finally, a small matrix:
105-
\\begin{pmatrix}
105+
\\[\\begin{pmatrix}
106106
5 & 6 \\\\
107107
7 & 8
108-
\\end{pmatrix}
108+
\\end{pmatrix}\\]
109109
110110
---
111111
@@ -127,6 +127,89 @@ A simple chemical reaction: \\(\\ch{H2 + Cl2 -> 2HCl}\\).
127127
An ion with charge: \\(\\ch{Fe^3+}\\) and an isotope \\(\\ch{^238U}\\).
128128
129129
`
130+
131+
export const mathTestContent2 = `
132+
---
133+
134+
**1. Vector Addition**
135+
136+
\\[
137+
\\mathbf{a} + \\mathbf{b} =
138+
\\begin{pmatrix}
139+
a_1 \\\\ a_2 \\\\ a_3
140+
\\end{pmatrix}
141+
+
142+
\\begin{pmatrix}
143+
b_1 \\\\ b_2 \\\\ b_3
144+
\\end{pmatrix}
145+
=
146+
\\begin{pmatrix}
147+
a_1 + b_1 \\\\ a_2 + b_2 \\\\ a_3 + b_3
148+
\\end{pmatrix}
149+
\\]
150+
151+
---
152+
153+
**2. Matrix Multiplication**
154+
155+
\\[
156+
AB =
157+
\\begin{pmatrix}
158+
1 & 2 \\\\
159+
3 & 4
160+
\\end{pmatrix}
161+
\\begin{pmatrix}
162+
5 & 6 \\\\
163+
7 & 8
164+
\\end{pmatrix}
165+
=
166+
\\begin{pmatrix}
167+
1 \\times 5 + 2 \\times 7 & 1 \\times 6 + 2 \\times 8 \\\\
168+
3 \\times 5 + 4 \\times 7 & 3 \\times 6 + 4 \\times 8
169+
\\end{pmatrix}
170+
=
171+
\\begin{pmatrix}
172+
19 & 22 \\\\
173+
43 & 50
174+
\\end{pmatrix}
175+
\\]
176+
177+
---
178+
179+
**3. Solving a System of Linear Equations**
180+
181+
\\[
182+
\\begin{cases}
183+
2x + 3y = 5 \\\\
184+
4x - y = 11
185+
\\end{cases}
186+
\\]
187+
188+
---
189+
190+
**4. Eigenvalue Equation**
191+
192+
\\[
193+
A\\mathbf{v} = \\lambda \\mathbf{v}
194+
\\]
195+
196+
where \\( A \\) is a matrix, \\( \\mathbf{v} \\) is an eigenvector, and \\( \\lambda \\) is an eigenvalue.
197+
198+
---
199+
200+
**5. Determinant of a 2x2 Matrix**
201+
202+
\\[
203+
\\det
204+
\\begin{pmatrix}
205+
a & b \\\\
206+
c & d
207+
\\end{pmatrix}
208+
= ad - bc
209+
\\]
210+
211+
---`
212+
130213
export const codeTestContent = `
131214
### ✅ JavaScript
132215

0 commit comments

Comments
 (0)