diff --git a/frontend/src/app/debug/page.tsx b/frontend/src/app/debug/page.tsx new file mode 100644 index 0000000..f20bdb9 --- /dev/null +++ b/frontend/src/app/debug/page.tsx @@ -0,0 +1,379 @@ +"use client" + +import { useState, useEffect } from "react" +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Badge } from "@/components/ui/badge" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { ProtectedRoute } from "@/components/auth/ProtectedRoute" +import { apiClient } from "@/lib/api-client" +import { Bug, Database, Search, CheckCircle, XCircle, AlertCircle } from "lucide-react" + +interface SystemStatus { + database: string + modules: Record + redis: string + qdrant: string + timestamp: string +} + +interface ChatbotConfig { + chatbot: { + id: string + name: string + type: string + description: string + created_at: string + is_active: boolean + conversation_count: number + } + prompt_template: { + type: string | null + system_prompt: string | null + variables: any[] + } + rag_collections: any[] + configuration: { + max_tokens: number + temperature: number + streaming: boolean + memory_config: any + } +} + +interface RagTestResult { + query: string + results: any[] + collections_searched: string[] + result_count: number + error?: string + message?: string +} + +export default function DebugPage() { + const [systemStatus, setSystemStatus] = useState(null) + const [chatbots, setChatbots] = useState([]) + const [selectedChatbot, setSelectedChatbot] = useState("") + const [chatbotConfig, setChatbotConfig] = useState(null) + const [ragQuery, setRagQuery] = useState("What is security?") + const [ragTest, setRagTest] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + loadSystemStatus() + loadChatbots() + }, []) + + const loadSystemStatus = async () => { + try { + const response = await apiClient.get("/api-internal/v1/debugging/system/status") + setSystemStatus(response) + } catch (error) { + console.error("Failed to load system status:", error) + } + } + + const loadChatbots = async () => { + try { + const response = await apiClient.get("/api-internal/v1/chatbot/list") + setChatbots(response) + if (response.length > 0) { + setSelectedChatbot(response[0].id) + } + } catch (error) { + console.error("Failed to load chatbots:", error) + } + } + + const loadChatbotConfig = async (chatbotId: string) => { + setLoading(true) + try { + const response = await apiClient.get(`/api-internal/v1/debugging/chatbot/${chatbotId}/config`) + setChatbotConfig(response) + } catch (error) { + console.error("Failed to load chatbot config:", error) + } finally { + setLoading(false) + } + } + + const testRagSearch = async () => { + if (!selectedChatbot) return + + setLoading(true) + try { + const response = await apiClient.get( + `/api-internal/v1/debugging/chatbot/${selectedChatbot}/test-rag`, + { params: { query: ragQuery } } + ) + setRagTest(response) + } catch (error) { + console.error("Failed to test RAG search:", error) + } finally { + setLoading(false) + } + } + + const getStatusIcon = (status: string) => { + if (status.includes("healthy")) return + if (status.includes("error")) return + return + } + + return ( + +
+
+

Debugging Dashboard

+

+ Troubleshoot and diagnose chatbot issues +

+
+ + + + System Status + Chatbot Debug + RAG Testing + + + + + + + + System Health Status + + + + {systemStatus ? ( +
+
+ Database +
+ {getStatusIcon(systemStatus.database)} + {systemStatus.database} +
+
+
+ Redis +
+ {getStatusIcon(systemStatus.redis)} + {systemStatus.redis} +
+
+
+ Qdrant +
+ {getStatusIcon(systemStatus.qdrant)} + {systemStatus.qdrant} +
+
+
+

Modules Status

+
+ {Object.entries(systemStatus.modules).map(([name, info]: [string, any]) => ( +
+ {name} +
+ + {info.enabled ? "Enabled" : "Disabled"} + + + {info.status} + +
+
+ ))} +
+
+
+ ) : ( +

Loading system status...

+ )} +
+
+
+ + + + + + + Chatbot Configuration + + + +
+
+ + +
+ +
+ + {chatbotConfig && ( +
+
+

Chatbot Info

+
+
Name: {chatbotConfig.chatbot.name}
+
Type: {chatbotConfig.chatbot.type}
+
Description: {chatbotConfig.chatbot.description}
+
Active: {chatbotConfig.chatbot.is_active ? "Yes" : "No"}
+
Conversations: {chatbotConfig.chatbot.conversation_count}
+
+
+ +
+

Configuration

+
+
Max Tokens: {chatbotConfig.configuration.max_tokens}
+
Temperature: {chatbotConfig.configuration.temperature}
+
Streaming: {chatbotConfig.configuration.streaming ? "Yes" : "No"}
+
+
+ +
+

Prompt Template

+
+
+ Type: {chatbotConfig.prompt_template.type || "None"} +
+ {chatbotConfig.prompt_template.system_prompt && ( +
+
System Prompt:
+
+                              {chatbotConfig.prompt_template.system_prompt}
+                            
+
+ )} +
+
+ + {chatbotConfig.rag_collections.length > 0 && ( +
+

RAG Collections

+
+ {chatbotConfig.rag_collections.map((collection) => ( +
+
Name: {collection.name}
+
Documents: {collection.document_count}
+
Qdrant Collection: {collection.qdrant_collection_name}
+
+ ))} +
+
+ )} +
+ )} +
+
+
+ + + + + + + RAG Search Test + + + +
+
+ + setRagQuery(e.target.value)} + placeholder="Enter a test query..." + className="mt-1" + /> +
+ +
+ + {ragTest && ( +
+
+

Test Results

+
+
Query: {ragTest.query}
+
Results Found: {ragTest.result_count}
+
Collections Searched: {ragTest.collections_searched.join(", ")}
+ {ragTest.message && ( +
Message: {ragTest.message}
+ )} + {ragTest.error && ( +
Error: {ragTest.error}
+ )} +
+
+ + {ragTest.results.length > 0 && ( +
+

Search Results

+
+ {ragTest.results.map((result, index) => ( +
+
+ Score: {result.score?.toFixed(3) || "N/A"} + {result.collection_name && ( + {result.collection_name} + )} +
+
+ {result.metadata?.source || "Unknown source"} +
+
+ {result.content?.substring(0, 200)} + {result.content?.length > 200 && "..."} +
+
+ ))} +
+
+ )} +
+ )} +
+
+
+
+ +
+

How to Use This Dashboard

+
    +
  • System Status: Check if all services (Database, Redis, Qdrant) are healthy
  • +
  • Chatbot Debug: View detailed configuration for any chatbot
  • +
  • RAG Testing: Test if document search is working correctly
  • +
  • • Check browser console logs for detailed request/response debugging information
  • +
+
+
+
+ ) +} \ No newline at end of file diff --git a/test_debugging.py b/test_debugging.py new file mode 100755 index 0000000..4a62d85 --- /dev/null +++ b/test_debugging.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +""" +Test script to verify debugging endpoints +""" +import requests +import json +import sys +import os + +# Add parent directory to path for imports +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from backend.app.core.security import create_access_token +from backend.app.db.database import SessionLocal +from backend.app.models.user import User + +def get_auth_token(): + """Get an authentication token for testing""" + db = SessionLocal() + try: + # Get first user (or create one for testing) + user = db.query(User).first() + if not user: + # Create test user if none exists + user = User( + email="test@example.com", + hashed_password="$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LeZeUfkZMBs9kYZP6" # password: password + ) + db.add(user) + db.commit() + db.refresh(user) + + # Create JWT token + token = create_access_token(data={"sub": str(user.id)}) + return token + finally: + db.close() + +def test_endpoint(url, token, method="GET", data=None): + """Test an endpoint with authentication""" + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json" + } + + if method == "GET": + response = requests.get(f"http://localhost:3000{url}", headers=headers) + elif method == "POST": + response = requests.post(f"http://localhost:3000{url}", headers=headers, json=data) + + print(f"\n{method} {url}") + print(f"Status: {response.status_code}") + + if response.status_code == 200: + print("Response:") + print(json.dumps(response.json(), indent=2)) + else: + print("Error:", response.text) + + return response + +def main(): + print("=== Testing Debugging Endpoints ===") + + # Get authentication token + print("\n1. Getting authentication token...") + token = get_auth_token() + print(f"Token: {token[:50]}...") + + # Test system status + print("\n2. Testing system status...") + test_endpoint("/api-internal/v1/debugging/system/status", token) + + # Test getting chatbot list first + print("\n3. Getting chatbot list...") + response = test_endpoint("/api-internal/v1/chatbot/list", token) + + if response.status_code == 200: + chatbots = response.json() + if chatbots: + chatbot_id = chatbots[0]["id"] + print(f"\n4. Testing chatbot config for: {chatbot_id}") + test_endpoint(f"/api-internal/v1/debugging/chatbot/{chatbot_id}/config", token) + + print(f"\n5. Testing RAG search for: {chatbot_id}") + test_endpoint(f"/api-internal/v1/debugging/chatbot/{chatbot_id}/test-rag?query=What is security?", token) + else: + print("\n4. No chatbots found to test") + else: + print("\n4. Could not get chatbot list") + +if __name__ == "__main__": + main() \ No newline at end of file