LienJ commited on
Commit
0b44da8
·
verified ·
1 Parent(s): 45dbeb8

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +90 -23
app.py CHANGED
@@ -1,18 +1,48 @@
1
-
2
- import streamlit as st
3
  import re
 
4
  from openai import OpenAI
5
 
6
  # Configure page style
7
- st.set_page_config(page_title="Clinical ReAct Agent", layout="wide")
8
- st.title("🩺 Clinical ReAct Agent Dashboard")
9
- st.markdown("This dashboard implements the custom ReAct agent loop from your MIS 752 lab. It queries local reference files and patient charts to reason through complex workflows.")
 
 
 
10
 
11
  # Sidebar - Secrets & Settings
12
- st.sidebar.header("⚙️ Settings")
13
- api_key = st.sidebar.text_input("OpenAI API Key", type="password", placeholder="sk-...")
14
- model_name = st.sidebar.selectbox("LLM Model Name", ["gpt-4o-mini", "gpt-3.5-turbo"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  max_steps = st.sidebar.slider("Step Budget (Max Steps)", 2, 8, 6)
 
 
 
 
 
16
 
17
  # Clinic data structures
18
  REFERENCE = {
@@ -29,6 +59,10 @@ CHARTS = {
29
  "bianchi": "Bianchi, F, 81. Type 2 diabetes, frail. eGFR 39. A1c 8.4 percent. Current: metformin 500 mg twice daily.",
30
  }
31
 
 
 
 
 
32
  def lookup(topic: str) -> str:
33
  hit = REFERENCE.get(topic.strip().lower())
34
  return hit if hit else f"'{topic}' is not in the clinic reference."
@@ -55,7 +89,22 @@ def parse_action(text: str):
55
  return None, None
56
  return tool.group(1).strip(), (arg.group(1).strip() if arg else "")
57
 
58
- # Define Prompt with triple single-quotes to avoid nesting syntax error
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  SYSTEM_PROMPT = '''You answer clinical questions by looking things up. You have two tools:
60
 
61
  lookup: look up one topic in the clinic reference. Input: a short topic, e.g. "metformin".
@@ -76,16 +125,27 @@ Thought: I now know the final answer
76
  Final Answer: your answer, in one or two sentences
77
  /no_think'''
78
 
79
- # UI Form for query execution
80
- query = st.text_input("Ask the clinical agent a question:", value="Is Alvarez still OK on her metformin? Check her chart first.")
 
 
 
 
 
 
 
 
 
81
 
82
- if st.button("Run Agent"):
83
  if not api_key:
84
- st.error("Please enter an OpenAI API Key in the sidebar to run the agent.")
85
  else:
86
  try:
87
- client = OpenAI(api_key=api_key)
 
88
  messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": query}]
 
89
 
90
  st.subheader("🧠 Agent Execution Trace")
91
 
@@ -95,20 +155,23 @@ if st.button("Run Agent"):
95
  model=model_name,
96
  messages=messages,
97
  temperature=0,
98
- max_tokens=300,
99
  stop=["Observation:"]
100
  )
101
  reply = r.choices[0].message.content or ""
102
- reply = re.sub(r"<think>.*?</think>", "", reply, flags=re.S).strip()
 
 
 
103
 
104
- # Render model thinking step
105
  with st.chat_message("assistant"):
106
- st.markdown(f"**Step {step} Reasoning**")
107
- st.text(reply)
108
 
109
  if "Final Answer:" in reply:
110
  answer = reply.split("Final Answer:", 1)[1].strip()
111
- st.success(f"✅ **Final Answer:** {answer}")
 
112
  break
113
 
114
  tool, arg = parse_action(reply)
@@ -117,9 +180,10 @@ if st.button("Run Agent"):
117
  else:
118
  obs, ok = run_tool(tool, arg)
119
 
120
- # Render Observation
 
121
  with st.chat_message("user"):
122
- st.markdown(f"**Step {step} Observation (Tool: {tool})**")
123
  if ok:
124
  st.info(obs)
125
  else:
@@ -128,5 +192,8 @@ if st.button("Run Agent"):
128
  messages.append({"role": "assistant", "content": reply})
129
  messages.append({"role": "user", "content": f"Observation: {obs}"})
130
 
 
 
 
131
  except Exception as e:
132
- st.error(f"An error occurred: {e}")
 
1
+ import os
 
2
  import re
3
+ import streamlit as st
4
  from openai import OpenAI
5
 
6
  # Configure page style
7
+ st.set_page_config(page_title="Clinical ReAct Agent — MIS 752", layout="wide")
8
+ st.title("🩺 Clinical ReAct Agent & Supervisor Dashboard")
9
+ st.markdown(
10
+ "**MIS 752 · Lab 9: Build the Paperwork Machine** — Custom ReAct loop (`Thought → Action → Observation`) "
11
+ "with `stop=['Observation:']` hallucination prevention and automated human-in-the-loop escalation policies."
12
+ )
13
 
14
  # Sidebar - Secrets & Settings
15
+ st.sidebar.header("⚙️ Agent & Supervisor Settings")
16
+
17
+ default_key = os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY") or ""
18
+ api_key = st.sidebar.text_input(
19
+ "API Key (OpenRouter or OpenAI)",
20
+ value=default_key,
21
+ type="password",
22
+ placeholder="sk-or-v1-... or sk-..."
23
+ )
24
+
25
+ is_openrouter = api_key.strip().startswith("sk-or-")
26
+ provider_label = "OpenRouter (https://openrouter.ai/api/v1)" if is_openrouter else "OpenAI Default"
27
+ st.sidebar.caption(f"🔌 Active Endpoint: **{provider_label}**")
28
+
29
+ if is_openrouter:
30
+ model_options = [
31
+ "openai/gpt-4o-mini",
32
+ "qwen/qwen3-8b",
33
+ "meta-llama/llama-3.3-70b-instruct",
34
+ "anthropic/claude-3.5-haiku"
35
+ ]
36
+ else:
37
+ model_options = ["gpt-4o-mini", "gpt-4o", "gpt-3.5-turbo"]
38
+
39
+ model_name = st.sidebar.selectbox("LLM Model Name", model_options)
40
  max_steps = st.sidebar.slider("Step Budget (Max Steps)", 2, 8, 6)
41
+ supervision_policy = st.sidebar.selectbox(
42
+ "Supervision Policy (Step 9.2)",
43
+ ["flagged", "every", "audit"],
44
+ help="Controls when the human supervisor is interrupted."
45
+ )
46
 
47
  # Clinic data structures
48
  REFERENCE = {
 
59
  "bianchi": "Bianchi, F, 81. Type 2 diabetes, frail. eGFR 39. A1c 8.4 percent. Current: metformin 500 mg twice daily.",
60
  }
61
 
62
+ with st.sidebar.expander("📚 View Reference & Patient Charts"):
63
+ st.markdown("**Clinic Reference Topics:** `" + "`, `".join(REFERENCE.keys()) + "`")
64
+ st.markdown("**Patient Charts:** `" + "`, `".join(CHARTS.keys()) + "`")
65
+
66
  def lookup(topic: str) -> str:
67
  hit = REFERENCE.get(topic.strip().lower())
68
  return hit if hit else f"'{topic}' is not in the clinic reference."
 
89
  return None, None
90
  return tool.group(1).strip(), (arg.group(1).strip() if arg else "")
91
 
92
+ def escalate_step(stage: dict, policy: str = "flagged") -> str:
93
+ where = f"step {stage.get('step', '?')} ({stage.get('stage', '?')})"
94
+ tool = stage.get("tool") or "no tool"
95
+ ok = bool(stage.get("ok", True))
96
+
97
+ if policy == "every":
98
+ return f"INTERRUPT - {where}, {tool}: policy is review-everything."
99
+ elif policy == "audit":
100
+ return f"LOG - {where}, {tool}: recorded for later review, nobody paged."
101
+ elif policy == "flagged":
102
+ if not ok:
103
+ return f"INTERRUPT - {where}, {tool}: the agent reported a failure here."
104
+ return f"SILENT - {where}, {tool}: nothing flagged."
105
+ else:
106
+ return f"INTERRUPT - unknown policy '{policy}'. Defaulting to interrupt."
107
+
108
  SYSTEM_PROMPT = '''You answer clinical questions by looking things up. You have two tools:
109
 
110
  lookup: look up one topic in the clinic reference. Input: a short topic, e.g. "metformin".
 
125
  Final Answer: your answer, in one or two sentences
126
  /no_think'''
127
 
128
+ preset = st.selectbox(
129
+ "Choose a preset lab question or customize below:",
130
+ [
131
+ "Is Alvarez still OK on her metformin? Check her chart first.",
132
+ "What share of drug-interaction alerts get overridden, and why does that matter for a unit that fires 240 alerts a shift?",
133
+ "What does our hospital night shift override policy say about 240 alerts in one night?",
134
+ "Check Bianchi's chart and our a1c target and metformin rules. Does her regimen need adjustment?"
135
+ ]
136
+ )
137
+
138
+ query = st.text_input("Ask the clinical agent a question:", value=preset)
139
 
140
+ if st.button("▶️ Run Agent", type="primary"):
141
  if not api_key:
142
+ st.error("Please enter an OpenRouter (`sk-or-v1-...`) or OpenAI (`sk-...`) API Key in the sidebar to run the agent.")
143
  else:
144
  try:
145
+ base_url = "https://openrouter.ai/api/v1" if is_openrouter else None
146
+ client = OpenAI(api_key=api_key.strip(), base_url=base_url)
147
  messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": query}]
148
+ converged = False
149
 
150
  st.subheader("🧠 Agent Execution Trace")
151
 
 
155
  model=model_name,
156
  messages=messages,
157
  temperature=0,
158
+ max_tokens=1000,
159
  stop=["Observation:"]
160
  )
161
  reply = r.choices[0].message.content or ""
162
+ reply = re.sub(r"<think>.*?</think>", "", reply, flags=re.S)
163
+ reply = re.sub(r"<think>.*$", "", reply, flags=re.S).strip()
164
+
165
+ model_stage = {"step": step, "stage": "model", "text": reply, "tool": None, "ok": bool(reply)}
166
 
 
167
  with st.chat_message("assistant"):
168
+ st.markdown(f"**Step {step} Reasoning** · `{escalate_step(model_stage, supervision_policy)}`")
169
+ st.text(reply or "[empty reply]")
170
 
171
  if "Final Answer:" in reply:
172
  answer = reply.split("Final Answer:", 1)[1].strip()
173
+ st.success(f"✅ **Final Answer (Converged in {step} steps):** {answer}")
174
+ converged = True
175
  break
176
 
177
  tool, arg = parse_action(reply)
 
180
  else:
181
  obs, ok = run_tool(tool, arg)
182
 
183
+ obs_stage = {"step": step, "stage": "observation", "text": obs, "tool": tool, "ok": ok}
184
+
185
  with st.chat_message("user"):
186
+ st.markdown(f"**Step {step} Observation (Tool: `{tool}`)** · `{escalate_step(obs_stage, supervision_policy)}`")
187
  if ok:
188
  st.info(obs)
189
  else:
 
192
  messages.append({"role": "assistant", "content": reply})
193
  messages.append({"role": "user", "content": f"Observation: {obs}"})
194
 
195
+ if not converged:
196
+ st.warning(f"⚠️ Step budget exhausted (`max_steps={max_steps}`) before reaching a Final Answer.")
197
+
198
  except Exception as e:
199
+ st.error(f"An error occurred: {e}")