Spaces:
Runtime error
Runtime error
File size: 5,715 Bytes
788569e 94e98e6 788569e 94e98e6 788569e 94e98e6 788569e | 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 | """
Updated diagnostics module for the Pharmaceutical Analytics application.
"""
import streamlit as st
import os
import json
import traceback
import time
from datetime import datetime
from typing import Dict, Any, Tuple
def test_claude_connectivity() -> Tuple[bool, str]:
"""
Test basic connectivity to Claude API
Returns:
Tuple of (success_flag, response_or_error)
"""
try:
# Check API key
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
return False, "No ANTHROPIC_API_KEY found in environment variables"
# Import anthropic
try:
import anthropic
except ImportError:
return False, "Failed to import anthropic library. Make sure it's installed (pip install anthropic)"
# Create client and send request
client = anthropic.Anthropic(api_key=api_key)
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=300,
messages=[
{"role": "user", "content": "Briefly tell me about Egyptian history in 2-3 sentences."}
]
)
if response and response.content:
return True, response.content[0].text
else:
return False, "Received empty response from Anthropic API"
except Exception as e:
error_msg = f"Error testing Claude API: {str(e)}\n\n{traceback.format_exc()}"
return False, error_msg
def render_diagnostics_tab():
"""
Render the diagnostics tab in the Streamlit app
"""
st.header("π§ System Diagnostics")
# Environment information
st.subheader("Environment Information")
# Check API key
api_key = os.getenv("ANTHROPIC_API_KEY")
api_status = "β
Set" if api_key else "β Not Set"
environment_data = {
"API Key": api_status,
"Python Version": os.sys.version,
"Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
# Try to get library versions
try:
import anthropic
environment_data["Anthropic Library"] = anthropic.__version__
except (ImportError, AttributeError):
environment_data["Anthropic Library"] = "Not found"
try:
import langgraph
environment_data["LangGraph Library"] = langgraph.__version__
except (ImportError, AttributeError):
environment_data["LangGraph Library"] = "Not found"
# Display environment table
for key, value in environment_data.items():
cols = st.columns([1, 3])
with cols[0]:
st.markdown(f"**{key}:**")
with cols[1]:
st.markdown(f"{value}")
# Claude connectivity test
st.subheader("Claude LLM Test")
if st.button("Test Claude Connectivity"):
with st.spinner("Testing connection to Claude..."):
success, response = test_claude_connectivity()
if success:
st.success("β
Claude API is working properly!")
st.markdown("**Response:**")
st.info(response)
else:
st.error("β Claude API test failed")
st.expander("Error Details", expanded=True).error(response)
# Agent functionality test (simplified)
st.subheader("Agent Functionality Test")
if st.button("Test Planning Agent"):
with st.spinner("Testing Planning Agent..."):
try:
from agents.planning_agent import PlanningAgent
planning_agent = PlanningAgent()
test_alert = "Sales of DrugX down 15% in Northeast region over past 30 days."
analysis_plan, plan_dict = planning_agent.create_analysis_plan(test_alert)
st.success("β
Planning Agent is working properly!")
st.json(plan_dict)
except Exception as e:
st.error("β Planning Agent test failed")
st.expander("Error Details", expanded=True).error(f"{str(e)}\n\n{traceback.format_exc()}")
# Database Connectivity
st.subheader("Database Connectivity")
if st.button("Test Database Connection"):
with st.spinner("Testing database connection..."):
try:
import sqlite3
conn = sqlite3.connect("data/pharma_db.sqlite")
# Test query
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
# Close connection
conn.close()
st.success(f"β
Successfully connected to database")
st.write(f"Found {len(tables)} tables:")
st.json([table[0] for table in tables])
except Exception as e:
st.error(f"β Database connection failed: {str(e)}")
st.expander("Error Details", expanded=True).error(traceback.format_exc())
# Add guidance
st.markdown("---")
st.markdown("""
### Troubleshooting Tips
1. If Claude test fails:
- Check your API key in environment variables
- Verify internet connectivity
- Confirm your API key has sufficient credits
2. If Agent test fails:
- Check import errors (are all libraries installed?)
- Verify agent implementation
- Check for syntax errors in agent code
3. If Database test fails:
- Verify database file exists
- Check file permissions
- Run setup_environment() function again
""") |