File size: 2,524 Bytes
14184e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
from app.agents.formula_engine import FormulaEngine, FormulaGrounding
from app.schemas.graph import FormulaStep


class _FakeClient:
    def __init__(self, obj):
        self._obj = obj

    def structured_complete(self, messages, schema, **kw):
        return self._obj


def test_generate_happy_path_returns_formula_payload():
    chunks = [{"source": "paper.pdf", "text": "The energy is given by E = mc^2, the mass-energy equivalence."}]
    grounding = FormulaGrounding(
        renderable=True,
        anchor="E = mc^2, the mass-energy equivalence",
        main_latex="E = mc^2",
        steps=[FormulaStep(latex="E = mc^2", explanation="Energy equals mass times the speed of light squared.")],
    )
    engine = FormulaEngine(client=_FakeClient(grounding))
    payload = engine.generate("mass-energy equivalence", chunks, "high_school")

    assert payload.animation_type == "formula"
    assert payload.html_code == ""
    assert payload.formula is not None
    assert payload.formula.main_latex == "E = mc^2"
    assert len(payload.formula.steps) == 1
    assert payload.formula.steps[0].latex == "E = mc^2"
    assert "E = mc^2, the mass-energy equivalence" in payload.explanation


def test_generate_decline_path_returns_2d_text_card():
    chunks = [{"source": "paper.pdf", "text": "This section discusses qualitative trends with no equations."}]
    grounding = FormulaGrounding(
        renderable=False,
        decline_reason="'diffusion' doesn't have an explicit formula in the source — better explored in chat.",
    )
    engine = FormulaEngine(client=_FakeClient(grounding))
    payload = engine.generate("diffusion", chunks, "high_school")

    assert payload.animation_type == "2d_text"
    assert payload.html_code != ""
    assert payload.formula is None
    assert "diffusion" in payload.html_code


def test_generate_discards_hallucinated_anchor():
    chunks = [{"source": "paper.pdf", "text": "The force is F = ma, a basic law of motion."}]
    grounding = FormulaGrounding(
        renderable=True,
        anchor="this text was never in the source at all",
        main_latex="F = ma",
        steps=[FormulaStep(latex="F = ma", explanation="Force equals mass times acceleration.")],
    )
    engine = FormulaEngine(client=_FakeClient(grounding))
    payload = engine.generate("Newton's second law", chunks, "high_school")

    assert payload.animation_type == "formula"
    assert "this text was never in the source at all" not in payload.explanation
    assert payload.explanation == ""