""" API client for communicating with the orchestrator backend. """ import requests import json import streamlit as st from typing import Dict, Any, Optional, List import io class APIClient: """Client for interacting with the MCP AI Data Scientist API.""" def __init__(self, base_url: str = "http://localhost:8000"): self.base_url = base_url self.session = requests.Session() def _get_headers(self) -> Dict[str, str]: """Get authentication headers.""" headers = {"Content-Type": "application/json"} try: if hasattr(st, 'session_state') and st.session_state.get("auth_token"): headers["Authorization"] = f"Bearer {st.session_state.auth_token}" except: # Handle case when not running in Streamlit context pass return headers def start_analysis( self, file, business_context: str, analysis_name: str, parameters: Dict[str, Any] ) -> Optional[Dict[str, Any]]: """Start a new analysis session.""" try: # Prepare multipart form data files = { 'file': (file.name, file.getvalue(), file.type) } data = { 'business_context': business_context, 'analysis_name': analysis_name, 'parameters': json.dumps(parameters) } # Remove Content-Type header for multipart upload headers = self._get_headers() if 'Content-Type' in headers: del headers['Content-Type'] response = self.session.post( f"{self.base_url}/analysis/start", files=files, data=data, headers=headers, timeout=30 ) if response.status_code == 200: return response.json() else: st.error(f"API Error: {response.status_code} - {response.text}") return None except Exception as e: st.error(f"Error starting analysis: {str(e)}") return None def get_analysis_status(self, session_id: str) -> Optional[Dict[str, Any]]: """Get the status of an analysis session.""" try: response = self.session.get( f"{self.base_url}/analysis/{session_id}/status", headers=self._get_headers(), timeout=10 ) if response.status_code == 200: return response.json() else: return None except Exception as e: st.error(f"Error getting analysis status: {str(e)}") return None def get_analysis_results(self, session_id: str) -> Optional[Dict[str, Any]]: """Get the results of a completed analysis.""" try: response = self.session.get( f"{self.base_url}/analysis/{session_id}/results", headers=self._get_headers(), timeout=30 ) if response.status_code == 200: return response.json() else: return None except Exception as e: st.error(f"Error getting analysis results: {str(e)}") return None def cancel_analysis(self, session_id: str) -> bool: """Cancel a running analysis.""" try: response = self.session.post( f"{self.base_url}/analysis/{session_id}/cancel", headers=self._get_headers(), timeout=10 ) return response.status_code == 200 except Exception as e: st.error(f"Error cancelling analysis: {str(e)}") return False def get_user_sessions(self) -> List[Dict[str, Any]]: """Get all analysis sessions for the current user.""" try: response = self.session.get( f"{self.base_url}/analysis/sessions", headers=self._get_headers(), timeout=10 ) if response.status_code == 200: return response.json() else: return [] except Exception as e: st.error(f"Error getting user sessions: {str(e)}") return [] def delete_session(self, session_id: str) -> bool: """Delete an analysis session.""" try: response = self.session.delete( f"{self.base_url}/analysis/{session_id}", headers=self._get_headers(), timeout=10 ) return response.status_code == 200 except Exception as e: st.error(f"Error deleting session: {str(e)}") return False def health_check(self) -> Dict[str, Any]: """Check API health status.""" try: response = self.session.get( f"{self.base_url}/health", timeout=5 ) if response.status_code == 200: return response.json() else: return {"status": "unhealthy", "error": f"HTTP {response.status_code}"} except Exception as e: return {"status": "unreachable", "error": str(e)}