cryogenic22 commited on
Commit
656ee89
Β·
verified Β·
1 Parent(s): 2bb7e0c

Create diagnostic.py

Browse files
Files changed (1) hide show
  1. diagnostic.py +218 -0
diagnostic.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Diagnostics module for the Pharmaceutical Analytics application.
3
+ Contains functions to test LLM connectivity and agent functionality.
4
+ """
5
+
6
+ import streamlit as st
7
+ import os
8
+ import json
9
+ import traceback
10
+ import time
11
+ from datetime import datetime
12
+ from typing import Dict, Any, Tuple
13
+
14
+ def test_claude_connectivity() -> Tuple[bool, str]:
15
+ """
16
+ Test basic connectivity to Claude API
17
+
18
+ Returns:
19
+ Tuple of (success_flag, response_or_error)
20
+ """
21
+ try:
22
+ # Check API key
23
+ api_key = os.getenv("ANTHROPIC_API_KEY")
24
+ if not api_key:
25
+ return False, "No ANTHROPIC_API_KEY found in environment variables"
26
+
27
+ # Import anthropic
28
+ try:
29
+ import anthropic
30
+ except ImportError:
31
+ return False, "Failed to import anthropic library. Make sure it's installed (pip install anthropic)"
32
+
33
+ # Create client and send request
34
+ client = anthropic.Anthropic(api_key=api_key)
35
+
36
+ response = client.messages.create(
37
+ model="claude-3-haiku-20240307",
38
+ max_tokens=300,
39
+ messages=[
40
+ {"role": "user", "content": "Briefly tell me about Egyptian history in 2-3 sentences."}
41
+ ]
42
+ )
43
+
44
+ if response and response.content:
45
+ return True, response.content[0].text
46
+ else:
47
+ return False, "Received empty response from Anthropic API"
48
+
49
+ except Exception as e:
50
+ error_msg = f"Error testing Claude API: {str(e)}\n\n{traceback.format_exc()}"
51
+ return False, error_msg
52
+
53
+ def test_agent_functionality() -> Tuple[bool, Dict[str, Any]]:
54
+ """
55
+ Test basic agent functionality by initializing the Planning Agent
56
+ and generating a simple analysis plan
57
+
58
+ Returns:
59
+ Tuple of (success_flag, results_dict)
60
+ """
61
+ results = {
62
+ "steps": [],
63
+ "errors": [],
64
+ "plan": None
65
+ }
66
+
67
+ try:
68
+ # Test Planning Agent import
69
+ results["steps"].append({"step": "import", "status": "started"})
70
+ try:
71
+ from agents.planning_agent import PlanningAgent
72
+ results["steps"].append({"step": "import", "status": "success"})
73
+ except Exception as import_error:
74
+ error_msg = f"Error importing PlanningAgent: {str(import_error)}\n\n{traceback.format_exc()}"
75
+ results["errors"].append({"phase": "import", "error": error_msg})
76
+ return False, results
77
+
78
+ # Test agent initialization
79
+ results["steps"].append({"step": "initialization", "status": "started"})
80
+ try:
81
+ planning_agent = PlanningAgent()
82
+ results["steps"].append({"step": "initialization", "status": "success"})
83
+ except Exception as init_error:
84
+ error_msg = f"Error initializing PlanningAgent: {str(init_error)}\n\n{traceback.format_exc()}"
85
+ results["errors"].append({"phase": "initialization", "error": error_msg})
86
+ return False, results
87
+
88
+ # Test plan creation
89
+ results["steps"].append({"step": "plan_creation", "status": "started"})
90
+ try:
91
+ test_alert = "Sales of DrugX down 15% in Northeast region over past 30 days."
92
+ analysis_plan, plan_dict = planning_agent.create_analysis_plan(test_alert)
93
+
94
+ results["steps"].append({"step": "plan_creation", "status": "success"})
95
+ results["plan"] = plan_dict
96
+ return True, results
97
+ except Exception as plan_error:
98
+ error_msg = f"Error creating analysis plan: {str(plan_error)}\n\n{traceback.format_exc()}"
99
+ results["errors"].append({"phase": "plan_creation", "error": error_msg})
100
+ return False, results
101
+
102
+ except Exception as e:
103
+ error_msg = f"Unexpected error in agent functionality test: {str(e)}\n\n{traceback.format_exc()}"
104
+ results["errors"].append({"phase": "unknown", "error": error_msg})
105
+ return False, results
106
+
107
+ def render_diagnostics_tab():
108
+ """
109
+ Render the diagnostics tab in the Streamlit app
110
+ """
111
+ st.header("πŸ”§ System Diagnostics")
112
+
113
+ # Environment information
114
+ st.subheader("Environment Information")
115
+
116
+ # Check API key
117
+ api_key = os.getenv("ANTHROPIC_API_KEY")
118
+ api_status = "βœ… Set" if api_key else "❌ Not Set"
119
+
120
+ environment_data = {
121
+ "API Key": api_status,
122
+ "Python Version": os.sys.version,
123
+ "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
124
+ }
125
+
126
+ # Try to get library versions
127
+ try:
128
+ import anthropic
129
+ environment_data["Anthropic Library"] = anthropic.__version__
130
+ except (ImportError, AttributeError):
131
+ environment_data["Anthropic Library"] = "Not found"
132
+
133
+ try:
134
+ import langgraph
135
+ environment_data["LangGraph Library"] = langgraph.__version__
136
+ except (ImportError, AttributeError):
137
+ environment_data["LangGraph Library"] = "Not found"
138
+
139
+ # Display environment table
140
+ for key, value in environment_data.items():
141
+ cols = st.columns([1, 3])
142
+ with cols[0]:
143
+ st.markdown(f"**{key}:**")
144
+ with cols[1]:
145
+ st.markdown(f"{value}")
146
+
147
+ # Claude connectivity test
148
+ st.subheader("Claude LLM Test")
149
+ if st.button("Test Claude Connectivity"):
150
+ with st.spinner("Testing connection to Claude..."):
151
+ success, response = test_claude_connectivity()
152
+
153
+ if success:
154
+ st.success("βœ… Claude API is working properly!")
155
+ st.markdown("**Response:**")
156
+ st.info(response)
157
+ else:
158
+ st.error("❌ Claude API test failed")
159
+ st.expander("Error Details", expanded=True).error(response)
160
+
161
+ # Agent functionality test
162
+ st.subheader("Agent Functionality Test")
163
+ if st.button("Test Planning Agent"):
164
+ with st.spinner("Testing Planning Agent..."):
165
+ success, results = test_agent_functionality()
166
+
167
+ if success:
168
+ st.success("βœ… Planning Agent is working properly!")
169
+ st.json(results["plan"])
170
+ else:
171
+ st.error("❌ Planning Agent test failed")
172
+ for error in results["errors"]:
173
+ st.expander(f"Error in {error['phase']} phase", expanded=True).error(error["error"])
174
+
175
+ # Database Connectivity
176
+ st.subheader("Database Connectivity")
177
+ if st.button("Test Database Connection"):
178
+ with st.spinner("Testing database connection..."):
179
+ try:
180
+ import sqlite3
181
+ conn = sqlite3.connect("data/pharma_db.sqlite")
182
+
183
+ # Test query
184
+ cursor = conn.cursor()
185
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
186
+ tables = cursor.fetchall()
187
+
188
+ # Close connection
189
+ conn.close()
190
+
191
+ st.success(f"βœ… Successfully connected to database")
192
+ st.write(f"Found {len(tables)} tables:")
193
+ st.json([table[0] for table in tables])
194
+
195
+ except Exception as e:
196
+ st.error(f"❌ Database connection failed: {str(e)}")
197
+ st.expander("Error Details", expanded=True).error(traceback.format_exc())
198
+
199
+ # Add guidance
200
+ st.markdown("---")
201
+ st.markdown("""
202
+ ### Troubleshooting Tips
203
+
204
+ 1. If Claude test fails:
205
+ - Check your API key in environment variables
206
+ - Verify internet connectivity
207
+ - Confirm your API key has sufficient credits
208
+
209
+ 2. If Agent test fails:
210
+ - Check import errors (are all libraries installed?)
211
+ - Verify agent implementation
212
+ - Check for syntax errors in agent code
213
+
214
+ 3. If Database test fails:
215
+ - Verify database file exists
216
+ - Check file permissions
217
+ - Run setup_environment() function again
218
+ """)