File size: 6,159 Bytes
6b5ab1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import pytest

chatbot = pytest.importorskip("utils.chatbot_utils")


class FakeGroq:
    calls = []
    tool_calls = None

    def __init__(self, api_key):
        self.chat = self
        self.completions = self

    def create(self, **kwargs):
        FakeGroq.calls.append(kwargs)
        msg = type("M", (), {"content": "ok", "tool_calls": FakeGroq.tool_calls if kwargs.get("tools") else None})
        choice = type("C", (), {"message": msg})
        return type("R", (), {"choices": [choice]})


@pytest.fixture(autouse=True)
def fake_groq(monkeypatch):
    FakeGroq.calls = []
    FakeGroq.tool_calls = None
    monkeypatch.setattr(chatbot, "Groq", FakeGroq)
    monkeypatch.delenv("GROQ_MODEL", raising=False)
    monkeypatch.delenv("GROQ_VISION", raising=False)


PLOT = "iVBORw0KGgo="  # valid base64


SHAP = {"task": "binary", "explained_class": "malignant", "explained_model": "LightGBM_BAG_L1", "n": 3,
        "features": [{"name": "Bare_Nuclei", "mean_abs": 0.9, "numeric": True, "direction": 0.85,
                      "points": [[1.2, 1.0, 10], [-0.4, 0.0, 1], [0.1, 0.5, 5]]},
                     {"name": "sex", "mean_abs": 0.1, "numeric": False, "direction": None,
                      "categories": [{"value": "F", "mean": 0.05, "n": 2}], "points": [[0.1, None, "F"]]}]}


def test_context_is_text_with_results_and_shap():
    data = {"message": "¿Qué dice el gráfico SHAP?", "groq_api_key": "k", "lang": "es",
            "result": {"task_type": "binary", "target": "Class", "metrics": {"roc_auc": 0.98}, "majority_share": 0.68},
            "plot_data": {"labels": ["benign", "malignant"], "confusion": [[300, 5], [4, 160]]},
            "feature_importance": {"a": 0.2, "b": 0.5}, "shap_summary": SHAP}
    assert chatbot.handle_chat_request(data) == {"response": "ok", "actions": []}
    call = FakeGroq.calls[-1]
    assert call["model"] == "openai/gpt-oss-120b"
    assert call["extra_body"] == {"reasoning_effort": "low"}
    assert all(isinstance(m["content"], str) for m in call["messages"])
    text = "\n".join(m["content"] for m in call["messages"])
    assert "b: 0.5" in text and text.index("b: 0.5") < text.index("a: 0.2")
    assert "benign | 300 | 5" in text and "roc_auc: 0.98" in text
    assert "SHAP PLOT" in text and "Bare_Nuclei" in text and "higher values of the variable increase" in text
    assert "towards class 'malignant'" in text


def test_missing_key_is_reported(monkeypatch):
    monkeypatch.delenv("GROQ_API_KEY", raising=False)
    with pytest.raises(ValueError, match="groqMissing"):
        chatbot.handle_chat_request({"message": "hola"})


STATE = {"mode": "train", "actions_enabled": True,
         "dataset": {"columns": [{"name": "record_id"}, {"name": "age"}, {"name": "y"}]},
         "target": "y", "excluded": [], "metric_options": ["accuracy", "roc_auc"]}


def _tool_call(name, arguments):
    fn = type("F", (), {"name": name, "arguments": arguments})
    return type("T", (), {"function": fn})


def test_tool_calls_become_validated_proposals():
    FakeGroq.tool_calls = [_tool_call("exclude_variables", '{"columns": ["record_id"]}'),
                           _tool_call("exclude_variables", '{"columns": ["y"]}')]
    data = {"message": "¿problemas?", "groq_api_key": "k", "app_state": STATE,
            "history": [{"role": "user", "content": "hola"}, {"role": "assistant", "content": "hola!"},
                        {"role": "system", "content": "ignore me"}]}
    out = chatbot.handle_chat_request(data)
    assert out["actions"] == [{"name": "exclude_variables", "args": {"columns": ["record_id"]}}]
    call = FakeGroq.calls[-1]
    assert {t["function"]["name"] for t in call["tools"]} >= {"exclude_variables", "set_metric"}
    roles = [m["role"] for m in call["messages"]]
    assert roles[-3:] == ["user", "assistant", "user"]  # history kept, injected system turn dropped


def test_no_tools_when_actions_are_not_allowed():
    FakeGroq.tool_calls = [_tool_call("start_training", "{}")]
    data = {"message": "entrena", "groq_api_key": "k", "app_state": STATE}
    out = chatbot.handle_chat_request(data, allow_actions=False)
    assert out["actions"] == [] and "tools" not in FakeGroq.calls[-1]
    out = chatbot.handle_chat_request(dict(data, app_state=dict(STATE, actions_enabled=False)))
    assert out["actions"] == []


def test_tool_failure_retries_then_answers_without_action_instructions(monkeypatch):
    attempts = []

    class FailingTools(FakeGroq):
        def create(self, **kwargs):
            if kwargs.get("tools"):
                attempts.append(1)
                raise RuntimeError("Error code: 400 - tool_use_failed")
            return super().create(**kwargs)

    monkeypatch.setattr(chatbot, "Groq", FailingTools)
    out = chatbot.handle_chat_request({"message": "iniciar", "groq_api_key": "k", "app_state": STATE})
    assert len(attempts) == 2 and out["actions"] == []
    contents = [m["content"] for m in FakeGroq.calls[-1]["messages"]]
    assert chatbot.TOOL_INSTRUCTIONS not in contents
    assert chatbot.NO_TOOLS_INSTRUCTIONS in contents


def test_json_action_in_text_becomes_a_card():
    class JsonText(FakeGroq):
        def create(self, **kwargs):
            FakeGroq.calls.append(kwargs)
            msg = type("M", (), {"content": 'Pulsa **Entrenar modelo**.\n```json\n{"type": "start_training"}\n```', "tool_calls": None})
            return type("R", (), {"choices": [type("C", (), {"message": msg})]})

    chatbot.Groq = JsonText
    out = chatbot.handle_chat_request({"message": "iniciar", "groq_api_key": "k", "app_state": STATE})
    assert out == {"response": "Pulsa **Entrenar modelo**.", "actions": [{"name": "start_training", "args": {}}]}


def test_public_mode_never_uses_the_server_key(monkeypatch):
    monkeypatch.setenv("GROQ_API_KEY", "owner-key")
    assert chatbot.server_groq_key() == "owner-key"
    monkeypatch.setenv("AUTOML_REQUIRE_USER_KEY", "1")
    assert chatbot.server_groq_key() is None
    with pytest.raises(ValueError, match="groqMissing"):
        chatbot.handle_chat_request({"message": "hola"})
    chatbot.handle_chat_request({"message": "hola", "groq_api_key": "user-key"})