File size: 10,528 Bytes
1435f2c
 
 
 
 
 
 
 
 
 
 
f62a4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435f2c
f62a4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435f2c
f62a4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f62a4bc
1435f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f62a4bc
 
1435f2c
 
 
 
f62a4bc
 
 
1435f2c
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""Bounded agent loop; history belongs to the Gradio session, never a global user."""
import json
import re
import uuid

from guardrails import LIMIT_REPLY, log_rule, post_check, pre_check
from prompts import SYSTEM_PROMPT
from tools import TOOL_FUNCTIONS, TOOL_SCHEMAS
from validation import validate_call


VERDICT_LABELS = {
    "within_range": "Within range",
    "below_min": "Below minimum",
    "above_max": "Above maximum",
    "not_valid_multiple": "Wrong multiple",
    "not_fixed_dose": "Not the fixed dose",
    "range_unavailable": "Range unavailable",
}

# A dose-like figure: a number (or spelled-out number) followed by a mass unit.
DOSE_FIGURE = re.compile(
    r"(?:\d[\d,]*(?:\.\d+)?|\b(?:one|two|three|four|five|six|seven|eight|nine|ten|hundred|thousand|half|quarter)\b.{0,30}?)"
    r"\s*(?:mg|g|mcg|µg|ug|micrograms?|milligrams?|grams?)\b", re.I)


def cell(value):
    return str(value).replace("|", "\\|").replace("\n", " ")


def span(row):
    if row.get("min_mg") is None or row.get("max_mg") is None:
        return "Unavailable"
    return f"{row['min_mg']:g}–{row['max_mg']:g}"


def unresolved_text(row):
    """Plain-English line for an ingredient that could not be checked."""
    name = row.get("ingredient") or row.get("query") or row.get("listed_name") or "This ingredient"
    if row["status"] == "ambiguous":
        return f"**{name}** matches more than one product: " + " or ".join(row["candidates"]) + ". Which one do you mean?"
    if row["status"] == "not_found":
        text = f"**{name}** is not in the formulary, so I can't check its dose."
        if row.get("suggestions"):
            text += " Closest matches: " + ", ".join(row["suggestions"]) + "."
        return text
    return f"**{name}** could not be checked: {row.get('message') or row.get('reason') or row['status']}."


def render_dose_rows(rows):
    """Overall yes/no verdict, then the table, then anything that could not be checked."""
    checked = [r for r in rows if r.get("status") == "ok" and "verdict" in r]
    unresolved = [r for r in rows if r not in checked]
    problems = [r for r in checked if r["verdict"] != "within_range"]
    parts = []
    if checked and not problems:
        noun = "ingredient is" if len(checked) == 1 else f"{len(checked)} ingredients are"
        parts.append(f"✅ **Yes: {'the' if len(checked) == 1 else 'all'} {noun} within the recommended range** and meet the fixed dosing rule.")
    elif problems:
        parts.append(f"❌ **No: {len(problems)} of {len(checked)} ingredient{'s' if len(checked) != 1 else ''} "
                     f"{'is' if len(problems) == 1 else 'are'} outside the recommended range or dosing rule.**")
    if checked:
        table = ["| Ingredient | Dose (mg) | Range (mg) | Rule | Result |", "|---|---:|---|---|---|"]
        for row in sorted(checked, key=lambda r: r["verdict"] == "within_range"):
            table.append("| " + " | ".join(cell(v) for v in [
                row["name"], f"{row['amount_mg']:g}", span(row), row["fixed_rule"],
                f"{VERDICT_LABELS.get(row['verdict'], row['verdict'])}: {row['explanation']}"]) + " |")
        parts.append("\n".join(table))
        others = sorted({p for r in checked for p in r.get("other_products", [])})
        if others:
            parts.append("Checked against the exact product named. Other products of the same compound in the formulary: "
                         + ", ".join(others) + ".")
    if unresolved:
        parts.append("⚠ **Could not be checked:**\n" + "\n".join("- " + unresolved_text(r) for r in unresolved))
    return parts


def render_other(result):
    """Readable text for lookup, diagnosis and alternatives results (never raw JSON)."""
    if result.get("status") != "ok":
        return unresolved_text(result)
    if "ingredients" in result and "diagnosis" in result:
        lines = [f"Formulary ingredients for **{result['diagnosis']}** ({result.get('category', '')}):"]
        for item in result["ingredients"]:
            if item.get("status") == "ok":
                lines.append(f"- {item['name']}: {span(item)} mg, {item['fixed_rule']}")
            else:
                lines.append(f"- {item['listed_name']}: no dosage data")
        return "\n".join(lines)
    if "other_brands" in result:
        lines = []
        if result["other_brands"]:
            lines.append("Other products of the same compound:")
            lines += [f"- {r['name']}: {span(r)} mg, {r['fixed_rule']}" for r in result["other_brands"]]
        for group in result["same_diagnosis"]:
            lines.append(f"Also listed for **{group['diagnosis']}**:")
            lines += [f"- {r['name']}: {span(r)} mg, {r['fixed_rule']}" if r.get("status") == "ok"
                      else f"- {r['listed_name']}: no dosage data" for r in group["ingredients"]]
        lines.append(result["note"])
        return "\n".join(lines)
    if "name" in result:
        return (f"**{result['name']}**: recommended {span(result)} mg, {result['fixed_rule']}"
                + (f", purity {result['purity']}" if result.get("purity") else "") + ".")
    return "The tool returned a result I can't summarise; see the function call log."


def render_results(results):
    """Build the reply from this turn's tool results, so every dose figure is grounded."""
    dose_rows, parts = [], []
    for result in results:
        if "results" in result:
            dose_rows += result["results"]
        elif "verdict" in result or "ingredient" in result:
            dose_rows.append(result)
        else:
            parts.append(render_other(result))
    if dose_rows:
        parts = render_dose_rows(dose_rows) + parts
    parts.append("_These are formulary checks only. The final decision is yours as the pharmacist._")
    return "\n\n".join(parts)


def run_turn(message, history=None, backend=None):
    history = list(history or [])
    blocked, logs = pre_check(message)
    if blocked:
        # Do not retain injection text in the model's future context.
        return blocked, history, logs
    messages = [{"role": "system", "content": SYSTEM_PROMPT}, *history,
                {"role": "user", "content": message}]
    results = []
    executions = 0
    reply = ""
    try:
        if backend is None:
            from llm_backends import get_backend
            backend = get_backend()
        # Also bound repeated rejections, which do not consume execution slots.
        for _ in range(10):
            response = backend.generate(messages, TOOL_SCHEMAS)
            calls = response.get("tool_calls", [])
            if not calls:
                reply = response.get("content", "")
                break
            normalized_calls = []
            for call in calls:
                normalized_calls.append({**call, "id": call.get("id") or "call_" + uuid.uuid4().hex})
            messages.append({"role": "assistant", "content": response.get("content", ""),
                             "tool_calls": [{"id": c["id"], "type": "function", "function": {
                                 "name": c.get("name") or "malformed",
                                 "arguments": json.dumps(c.get("arguments", {}))}} for c in normalized_calls]})
            limit_hit = False
            for call in normalized_calls:
                name = call.get("name") or "malformed"
                arguments, reason = validate_call(name, call.get("arguments"))
                reason = call.get("error") or reason
                if reason:
                    result, status = {"status": "rejected", "reason": reason}, "REJECTED"
                elif executions >= 8:
                    result, status = {"status": "rejected", "reason": "Tool-call limit reached"}, "REJECTED"
                    limit_hit = True
                else:
                    executions += 1
                    try:
                        result = TOOL_FUNCTIONS[name](**arguments)
                    except Exception as exc:
                        result = {"status": "error", "message": str(exc)}
                    status = "ERROR" if result["status"] in ("error", "invalid") else "OK"
                    results.append(result)
                messages.append({"role": "tool", "name": name, "tool_call_id": call["id"],
                                 "content": json.dumps(result, ensure_ascii=False)})
                logs.append({"type": "tool", "name": name, "arguments": call.get("arguments"),
                             "result": result, "status": status})
            if limit_hit:
                reply = LIMIT_REPLY
                logs.append(log_rule("tool_limit", reply))
                break
        else:
            reply = LIMIT_REPLY
            logs.append(log_rule("loop_limit", reply))
    except Exception as exc:
        # Do not claim that no checks ran when a later model call failed.
        reply = ("The language model is unavailable right now; no checks were run." if not executions else
                 "The language model is unavailable right now. Completed tool checks are shown below; the remaining checks are incomplete.")
        logs.append({"type": "guardrail", "name": "model_unavailable", "arguments": {},
                     "result": {"reason": type(exc).__name__}, "status": "ERROR"})
        if results:
            reply += "\n\n" + render_results(results)
    else:
        if not reply and not results:
            reply = "No answer was returned. Please clarify the ingredient or order."
        if reply != LIMIT_REPLY:
            # Any numerical model answer is replaced wholesale, not merely checked against
            # a number allowlist (which could attach one ingredient's range to another).
            has_order = any("results" in r or "verdict" in r for r in results)
            # Only dose-like figures ("250 mg") trigger this; product names such as "Vitamin K2"
            # or "MenaQ7" contain digits but are not doses and must not hide the answer.
            if has_order or DOSE_FIGURE.search(reply) or (not reply and results):
                reply = render_results(results) if results else "No formulary dose check was returned. Please provide the ingredient, amount and unit so I can check it."
                logs.append(log_rule("dose_provenance", "Numerical reply rendered directly from this turn's tool results."))
    reply, post_logs = post_check(message, reply, results)
    logs.extend(post_logs)
    messages.append({"role": "assistant", "content": reply})
    return reply, messages[1:], logs