andy
update
1435f2c
Raw History Blame Contribute Delete
6.34 kB
"""Read-only formulary tools. Dose arithmetic and verdicts are Python-owned."""
import inspect
import math
from collections import Counter
from functools import wraps
from data_loader import DATA, base_name, normalize
from validation import MODELS, validate_call
def safe_tool(function):
@wraps(function)
def wrapped(*args, **kwargs):
if DATA.error:
return {"status": "error", "message": f"Formulary data unavailable: {DATA.error}"}
try:
bound = inspect.signature(function).bind(*args, **kwargs)
arguments, reason = validate_call(function.__name__, dict(bound.arguments))
if reason:
return {"status": "invalid", "message": reason}
return function(**arguments)
except Exception as exc:
return {"status": "error", "message": str(exc)}
return wrapped
def rule_text(rule):
if rule["type"] == "multiple":
return f"Multiple of {rule['step_mg']:g} mg"
if rule["type"] == "exact":
return f"Exactly {rule['dose_mg']:g} mg"
return "No fixed dosing rule"
def record(result):
if result["status"] != "ok":
return result
return {**result, "fixed_rule": rule_text(result["fixed_rule"])}
@safe_tool
def lookup_ingredient(name: str):
"""Look up a named product's dose range, purity, source notes and fixed dosing rule."""
return record(DATA.match(name))
@safe_tool
def check_dose(ingredient: str, amount: float, unit: str):
"""Check a supplied dose against the formulary range and fixed-dose rule."""
result = DATA.match(ingredient)
if result["status"] != "ok":
return {"ingredient": ingredient, **result}
amount_mg = amount * {"mg": 1, "g": 1000, "mcg": .001, "µg": .001, "ug": .001}[unit]
minimum, maximum, rule = result["min_mg"], result["max_mg"], result["fixed_rule"]
dose = f"{amount_mg:g} mg"
if minimum is None or maximum is None:
verdict, explanation = "range_unavailable", "The formulary dose range is unavailable."
elif amount_mg < minimum:
verdict, explanation = "below_min", f"{dose} is below the minimum of {minimum:g} mg"
elif amount_mg > maximum:
verdict, explanation = "above_max", f"{dose} is above the maximum of {maximum:g} mg"
elif rule["type"] == "exact" and not math.isclose(amount_mg, rule["dose_mg"], rel_tol=0, abs_tol=1e-6):
verdict, explanation = "not_fixed_dose", f"{dose} does not equal the fixed dose of {rule['dose_mg']:g} mg"
elif rule["type"] == "multiple" and not math.isclose(amount_mg / rule["step_mg"], round(amount_mg / rule["step_mg"]), rel_tol=0, abs_tol=1e-6):
verdict, explanation = "not_valid_multiple", f"{dose} is not a multiple of {rule['step_mg']:g} mg"
else:
verdict, explanation = "within_range", f"{dose} is within the formulary range and meets its fixed dosing rule."
return {**record(result), "amount_mg": amount_mg, "verdict": verdict, "explanation": explanation}
@safe_tool
def check_order(items: list):
"""Check all ingredients in an order together (one to thirty items); return every verdict."""
results = [check_dose(**item) for item in items]
return {"status": "ok", "results": results,
"summary": dict(Counter(r.get("verdict", r["status"]) for r in results))}
def listed_ingredient(name):
result = record(DATA.match(name))
if result["status"] == "not_found":
result["message"] = "no dosage data"
return {"listed_name": name, **result}
@safe_tool
def find_ingredients_for_diagnosis(diagnosis: str):
"""Find ingredients listed for a diagnosis or symptom, including available dose data."""
result = DATA.match_diagnosis(diagnosis)
if result["status"] != "ok":
return result
return {**result, "ingredients": [listed_ingredient(n) for n in result["ingredients"]]}
@safe_tool
def suggest_alternatives(ingredient: str, diagnosis: str | None = None):
"""Find other brands and co-listed ingredients in the formulary, never proven equivalents."""
match = DATA.match(ingredient)
if match["status"] == "ambiguous":
return match
target = match.get("name", ingredient)
other_brands = [record({"status": "ok", **r}) for r in DATA.ingredients
if base_name(r["name"]) == base_name(target) and r["name"] != target]
rows = DATA.diagnoses
if diagnosis:
found = DATA.match_diagnosis(diagnosis)
if found["status"] != "ok":
return found
rows = [found]
same_diagnosis = []
for row in rows:
resolved = [(name, DATA.match(name)) for name in row["ingredients"]]
def is_target(name, resolved_name):
return normalize(name) == normalize(ingredient) or (
resolved_name["status"] == "ok" and resolved_name["name"] == target)
if any(is_target(name, r) for name, r in resolved):
alternatives = [listed_ingredient(name) for name, r in resolved if not is_target(name, r)]
if alternatives:
same_diagnosis.append({"diagnosis": row["diagnosis"], "ingredients": alternatives})
return {"status": "ok" if other_brands or same_diagnosis else "not_found",
"other_brands": other_brands, "same_diagnosis": same_diagnosis,
"note": "Listed alternatives from the formulary, not proven equivalents. The pharmacist decides."}
TOOL_FUNCTIONS = {f.__name__: f for f in [lookup_ingredient, check_dose, check_order,
find_ingredients_for_diagnosis, suggest_alternatives]}
def schema(model):
"""Inline pydantic references so both providers receive self-contained schemas."""
result = model.model_json_schema()
definitions = result.pop("$defs", {})
def expand(value):
if isinstance(value, dict):
if "$ref" in value:
return expand(definitions[value["$ref"].split("/")[-1]])
return {k: expand(v) for k, v in value.items() if k != "title"}
if isinstance(value, list):
return [expand(v) for v in value]
return value
return expand(result)
TOOL_SCHEMAS = [{"type": "function", "function": {"name": name, "description": func.__doc__,
"parameters": schema(MODELS[name])}} for name, func in TOOL_FUNCTIONS.items()]