cryogenic22 commited on
Commit
788569e
Β·
verified Β·
1 Parent(s): 9979512

Create updated_diagnostics.py

Browse files
Files changed (1) hide show
  1. updated_diagnostics.py +243 -0
updated_diagnostics.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Updated diagnostics module for the Pharmaceutical Analytics application.
3
+ Uses the simplified Planning Agent implementation.
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_simplified_agent() -> Tuple[bool, Dict[str, Any]]:
54
+ """
55
+ Test the simplified Planning Agent functionality
56
+
57
+ Returns:
58
+ Tuple of (success_flag, results_dict)
59
+ """
60
+ results = {
61
+ "steps": [],
62
+ "errors": [],
63
+ "plan": None
64
+ }
65
+
66
+ try:
67
+ # Test Planning Agent import
68
+ results["steps"].append({"step": "import", "status": "started"})
69
+ try:
70
+ from simplified_planning_agent import PlanningAgent
71
+ results["steps"].append({"step": "import", "status": "success"})
72
+ except Exception as import_error:
73
+ error_msg = f"Error importing simplified PlanningAgent: {str(import_error)}\n\n{traceback.format_exc()}"
74
+ results["errors"].append({"phase": "import", "error": error_msg})
75
+ return False, results
76
+
77
+ # Test agent initialization
78
+ results["steps"].append({"step": "initialization", "status": "started"})
79
+ try:
80
+ planning_agent = PlanningAgent()
81
+ results["steps"].append({"step": "initialization", "status": "success"})
82
+ except Exception as init_error:
83
+ error_msg = f"Error initializing PlanningAgent: {str(init_error)}\n\n{traceback.format_exc()}"
84
+ results["errors"].append({"phase": "initialization", "error": error_msg})
85
+ return False, results
86
+
87
+ # Test plan creation
88
+ results["steps"].append({"step": "plan_creation", "status": "started"})
89
+ try:
90
+ test_alert = "Sales of DrugX down 15% in Northeast region over past 30 days."
91
+ analysis_plan, plan_dict = planning_agent.create_analysis_plan(test_alert)
92
+
93
+ results["steps"].append({"step": "plan_creation", "status": "success"})
94
+ results["plan"] = plan_dict
95
+ return True, results
96
+ except Exception as plan_error:
97
+ error_msg = f"Error creating analysis plan: {str(plan_error)}\n\n{traceback.format_exc()}"
98
+ results["errors"].append({"phase": "plan_creation", "error": error_msg})
99
+ return False, results
100
+
101
+ except Exception as e:
102
+ error_msg = f"Unexpected error in agent functionality test: {str(e)}\n\n{traceback.format_exc()}"
103
+ results["errors"].append({"phase": "unknown", "error": error_msg})
104
+ return False, results
105
+
106
+ def render_diagnostics_tab():
107
+ """
108
+ Render the diagnostics tab in the Streamlit app
109
+ """
110
+ st.header("πŸ”§ System Diagnostics")
111
+
112
+ # Environment information
113
+ st.subheader("Environment Information")
114
+
115
+ # Check API key
116
+ api_key = os.getenv("ANTHROPIC_API_KEY")
117
+ api_status = "βœ… Set" if api_key else "❌ Not Set"
118
+
119
+ environment_data = {
120
+ "API Key": api_status,
121
+ "Python Version": os.sys.version,
122
+ "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
123
+ }
124
+
125
+ # Try to get library versions
126
+ try:
127
+ import anthropic
128
+ environment_data["Anthropic Library"] = anthropic.__version__
129
+ except (ImportError, AttributeError):
130
+ environment_data["Anthropic Library"] = "Not found"
131
+
132
+ try:
133
+ import langgraph
134
+ environment_data["LangGraph Library"] = langgraph.__version__
135
+ except (ImportError, AttributeError):
136
+ environment_data["LangGraph Library"] = "Not found"
137
+
138
+ # Display environment table
139
+ for key, value in environment_data.items():
140
+ cols = st.columns([1, 3])
141
+ with cols[0]:
142
+ st.markdown(f"**{key}:**")
143
+ with cols[1]:
144
+ st.markdown(f"{value}")
145
+
146
+ # Claude connectivity test
147
+ st.subheader("Claude LLM Test")
148
+ if st.button("Test Claude Connectivity"):
149
+ with st.spinner("Testing connection to Claude..."):
150
+ success, response = test_claude_connectivity()
151
+
152
+ if success:
153
+ st.success("βœ… Claude API is working properly!")
154
+ st.markdown("**Response:**")
155
+ st.info(response)
156
+ else:
157
+ st.error("❌ Claude API test failed")
158
+ st.expander("Error Details", expanded=True).error(response)
159
+
160
+ # Simplified Agent functionality test
161
+ st.subheader("Simplified Planning Agent Test")
162
+ if st.button("Test Simplified Planning Agent"):
163
+ with st.spinner("Testing Simplified Planning Agent..."):
164
+ success, results = test_simplified_agent()
165
+
166
+ if success:
167
+ st.success("βœ… Simplified Planning Agent is working properly!")
168
+ st.json(results["plan"])
169
+ else:
170
+ st.error("❌ Simplified Planning Agent test failed")
171
+ for error in results["errors"]:
172
+ st.expander(f"Error in {error['phase']} phase", expanded=True).error(error["error"])
173
+
174
+ # Original Agent functionality test
175
+ st.subheader("Original Planning Agent Test (Likely to Fail)")
176
+ if st.button("Test Original Planning Agent"):
177
+ with st.spinner("Testing Original Planning Agent..."):
178
+ try:
179
+ from agents.planning_agent import PlanningAgent
180
+ planning_agent = PlanningAgent()
181
+ test_alert = "Sales of DrugX down 15% in Northeast region over past 30 days."
182
+ analysis_plan, plan_dict = planning_agent.create_analysis_plan(test_alert)
183
+
184
+ st.success("βœ… Original Planning Agent is working!")
185
+ st.json(plan_dict)
186
+ except Exception as e:
187
+ st.error("❌ Original Planning Agent test failed")
188
+ st.expander("Error Details", expanded=True).error(f"{str(e)}\n\n{traceback.format_exc()}")
189
+
190
+ # Database Connectivity
191
+ st.subheader("Database Connectivity")
192
+ if st.button("Test Database Connection"):
193
+ with st.spinner("Testing database connection..."):
194
+ try:
195
+ import sqlite3
196
+ conn = sqlite3.connect("data/pharma_db.sqlite")
197
+
198
+ # Test query
199
+ cursor = conn.cursor()
200
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
201
+ tables = cursor.fetchall()
202
+
203
+ # Close connection
204
+ conn.close()
205
+
206
+ st.success(f"βœ… Successfully connected to database")
207
+ st.write(f"Found {len(tables)} tables:")
208
+ st.json([table[0] for table in tables])
209
+
210
+ except Exception as e:
211
+ st.error(f"❌ Database connection failed: {str(e)}")
212
+ st.expander("Error Details", expanded=True).error(traceback.format_exc())
213
+
214
+ # Add guidance
215
+ st.markdown("---")
216
+ st.markdown("""
217
+ ### Using the Simplified Agent
218
+
219
+ The original Planning Agent implementation has issues with the LangChain prompt templates.
220
+ We've created a simplified version that uses direct API calls to Claude.
221
+
222
+ To use the simplified agent:
223
+
224
+ 1. Copy the `simplified_planning_agent.py` file to your project
225
+ 2. Update your workflow to import from `simplified_planning_agent` instead of `agents.planning_agent`
226
+
227
+ ### Troubleshooting Tips
228
+
229
+ 1. If Claude test fails:
230
+ - Check your API key in environment variables
231
+ - Verify internet connectivity
232
+ - Confirm your API key has sufficient credits
233
+
234
+ 2. If Agent test fails:
235
+ - Check import errors (are all libraries installed?)
236
+ - Verify agent implementation
237
+ - Check for syntax errors in agent code
238
+
239
+ 3. If Database test fails:
240
+ - Verify database file exists
241
+ - Check file permissions
242
+ - Run setup_environment() function again
243
+ """)