- Bloc équation avec barre visuelle 20 symboles (fractions, intégrales, grec, etc.) - Math en ligne : tape $x^2$ → rendu KaTeX inline automatique - Math en bloc : tape $$E=mc^2$$ → converti en bloc - Génération IA : décrit l'équation en langage naturel → LaTeX - Service math-from-text + endpoint /api/ai/math-from-text - CSS KaTeX importé - i18n FR/EN complet
45 lines
1.5 KiB
TypeScript
45 lines
1.5 KiB
TypeScript
import { getChatProvider } from '../factory'
|
|
import { getSystemConfig } from '@/lib/config'
|
|
|
|
export class MathFromTextService {
|
|
async generate(description: string): Promise<string> {
|
|
if (!description?.trim()) {
|
|
throw new Error('Description is required')
|
|
}
|
|
|
|
const systemPrompt = `You are a mathematician and LaTeX expert.
|
|
Convert the user's natural language description into a single valid LaTeX equation.
|
|
|
|
CRITICAL RULES:
|
|
- Output ONLY the raw LaTeX code — no preamble, no explanation, no markdown fence, no \\[ or \\( delimiters.
|
|
- Use standard amsmath/amssymb syntax.
|
|
- Never output \\documentclass, \\begin{document}, or $$ delimiters.
|
|
|
|
Examples:
|
|
- "the quadratic formula" -> x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}
|
|
- "Pythagorean theorem" -> a^2 + b^2 = c^2
|
|
- "Euler's identity" -> e^{i\\pi} + 1 = 0
|
|
- "la dérivée de x au carré" -> \\frac{d}{dx} x^2 = 2x`
|
|
|
|
const userPrompt = `Convert this to LaTeX:\n\n${description}`
|
|
|
|
const config = await getSystemConfig()
|
|
const provider = getChatProvider(config)
|
|
const fullPrompt = `${systemPrompt}\n\n${userPrompt}`
|
|
const raw = await provider.generateText(fullPrompt)
|
|
return this.extractLatex(raw)
|
|
}
|
|
|
|
private extractLatex(response: string): string {
|
|
const codeBlock = response.match(/```(?:latex|tex|math)?\n([\s\S]+?)\n```/)
|
|
if (codeBlock) return codeBlock[1].trim()
|
|
return response
|
|
.replace(/^\\\[|\\\]$/g, '')
|
|
.replace(/^\\\(|\\\)$/g, '')
|
|
.replace(/^\$\$|\$\$$/g, '')
|
|
.trim()
|
|
}
|
|
}
|
|
|
|
export const mathFromTextService = new MathFromTextService()
|