import os
import sys
import gradio as gr
from multiprocessing import freeze_support
import importlib
import inspect
import json
import logging
# === Fix path to include src/txagent
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
# === Import and reload to ensure correct file
import txagent.txagent
importlib.reload(txagent.txagent)
from txagent.txagent import TxAgent
# === Debug info
print(">>> TxAgent loaded from:", inspect.getfile(TxAgent))
print(">>> TxAgent has run_gradio_chat:", hasattr(TxAgent, "run_gradio_chat"))
# === Logging
logging.basicConfig(level=logging.INFO)
# === Environment
current_dir = os.path.abspath(os.path.dirname(__file__))
os.environ["MKL_THREADING_LAYER"] = "GNU"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# === Model config
model_name = "mims-harvard/TxAgent-T1-Llama-3.1-8B"
rag_model_name = "mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B"
new_tool_files = {
"new_tool": os.path.join(current_dir, "data", "new_tool.json")
}
# === Example prompts
question_examples = [
["Given a patient with WHIM syndrome on prophylactic antibiotics, is it advisable to co-administer Xolremdi with fluconazole?"],
["What treatment options exist for HER2+ breast cancer resistant to trastuzumab?"]
]
# === Extract tool name and format output
def extract_tool_name_and_clean_content(msg):
import re
tool_name = "Tool Result"
content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", "")
tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else getattr(msg, "tool_calls", None)
# Try to extract tool name from tool_calls JSON
if tool_calls:
try:
if isinstance(tool_calls, str):
tool_calls = json.loads(tool_calls)
if isinstance(tool_calls, list) and tool_calls:
tool_name = tool_calls[0].get("name", "Tool Result")
except Exception as e:
logging.warning(f"[extract_tool_name] Failed tool_calls parsing: {e}")
# Try fallback: extract from [TOOL_CALLS] JSON inside raw content
if "TOOL_CALLS" in str(content):
try:
match = re.search(r"\[TOOL_CALLS\](\[.*?\])", str(content))
if match:
embedded = json.loads(match.group(1))
if isinstance(embedded, list) and embedded:
tool_name = embedded[0].get("name", "Tool Result")
except Exception as e:
logging.warning(f"[extract_tool_name] Failed TOOL_CALLS content parse: {e}")
if isinstance(content, (dict, list)):
content = json.dumps(content, indent=2)
return f"Tool: {tool_name}", content
# === Format answer in collapsible box
def format_collapsible(content, title="Answer"):
return (
f"{title}
"
f"