File size: 3,272 Bytes
1435f2c
 
 
1869f88
 
1435f2c
8b5a069
1435f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1869f88
1435f2c
 
1869f88
 
1435f2c
8b5a069
1435f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1869f88
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
"""PharmaCheck's chat and transparent session tool log."""
import json

import gradio as gr

from agent import run_turn
from data_loader import DATA, DATA_PATH
from llm_backends import BACKEND, MODEL_ID, get_backend

backend = get_backend()


def respond(message, chat, history, logs):
    if not message.strip():
        return "", chat, history, logs, log_table(logs), logs[-1] if logs else {}
    reply, history, new_logs = run_turn(message, history, backend)
    logs = list(logs or []) + new_logs
    chat = list(chat or []) + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
    latest = next((row for row in reversed(logs) if row["type"] == "tool"), logs[-1] if logs else {})
    return "", chat, history, logs, log_table(logs), latest


def log_table(logs):
    return [[i, row["type"], row["name"], json.dumps(row["arguments"], ensure_ascii=False)[:500],
             json.dumps(row["result"], ensure_ascii=False)[:800], row["status"]]
            for i, row in enumerate(logs or [], 1)]


def clear():
    return "", [], [], [], [], {}


status = (f"Data: unavailable ({DATA.error})" if DATA.error else
          f"Data: loaded {len(DATA.ingredients)} ingredients, {len(DATA.diagnoses)} diagnoses from {DATA_PATH.name}")
with gr.Blocks(title="PharmaCheck — Formulary Dose Checker") as demo:
    gr.Markdown("# PharmaCheck — Formulary Dose Checker")
    gr.Markdown(f"{status}\n\nModel: {MODEL_ID} via {BACKEND}")
    history_state = gr.State([])
    logs_state = gr.State([])
    with gr.Row():
        with gr.Column(scale=3):
            # Gradio 6 uses messages natively; its old `type` argument was removed.
            chat = gr.Chatbot(label="Pharmacist assistant", height=520)
            message = gr.Textbox(label="Order or question", lines=4, placeholder="Paste ingredients with amounts and units…")
            with gr.Row():
                send = gr.Button("Send", variant="primary")
                reset = gr.Button("Clear")
            gr.Examples(examples=[
                ["DIM 200 mg\nAcetyl-L-Carnitine 1 g\nMelatonin 500 mcg"],
                ["What ingredients are used for SIBO?"],
                ["Can I combine magnesium bisglycinate with zinc picolinate?"],
                ["What can replace L-Glutamine for IBS?"],
            ], inputs=message)
        with gr.Column(scale=2):
            gr.Markdown("## Function call log")
            table = gr.Dataframe(headers=["#", "Type (tool/guardrail)", "Name", "Arguments", "Result", "Status (OK/REJECTED/ERROR/TRIGGERED)"],
                                 datatype=["number", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
            latest = gr.JSON(label="Latest tool call — full JSON")
    gr.Markdown("Advisory tool for pharmacists. Not a substitute for professional judgement.")
    inputs = [message, chat, history_state, logs_state]
    outputs = [message, chat, history_state, logs_state, table, latest]
    send.click(respond, inputs, outputs, concurrency_limit=1, concurrency_id="chat")
    message.submit(respond, inputs, outputs, concurrency_limit=1, concurrency_id="chat")
    reset.click(clear, outputs=outputs, concurrency_limit=1, concurrency_id="chat")

if __name__ == "__main__":
    demo.queue().launch()