From 76bd6b96391af4808a5c0d4df63d933300750808 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 11 Aug 2025 19:37:45 +0000 Subject: [PATCH] Add authentication status checks and debug script for AgentOps Co-authored-by: alex --- agentops/__init__.py | 25 +++++ agentops/client/client.py | 24 ++++- agentops/client/http/http_client.py | 14 ++- debug_agentops.py | 160 ++++++++++++++++++++++++++++ 4 files changed, 218 insertions(+), 5 deletions(-) create mode 100644 debug_agentops.py diff --git a/agentops/__init__.py b/agentops/__init__.py index 816e77443..da7286ab0 100755 --- a/agentops/__init__.py +++ b/agentops/__init__.py @@ -55,6 +55,31 @@ def get_client() -> Client: return _client +def check_auth_status() -> dict: + """Check the authentication status of the AgentOps client. + + Returns: + dict: Authentication status information including: + - authenticated: bool + - has_project_id: bool + - project_id: str or None + - auth_task_running: bool + - initialized: bool + """ + client = get_client() + return client.get_auth_status() + + +def is_authenticated() -> bool: + """Check if the AgentOps client is properly authenticated. + + Returns: + bool: True if authenticated, False otherwise + """ + client = get_client() + return client.is_authenticated() + + @deprecated("Automatically tracked in v4.") def record(event): """ diff --git a/agentops/client/client.py b/agentops/client/client.py index d66e898c7..4bbbc0251 100644 --- a/agentops/client/client.py +++ b/agentops/client/client.py @@ -82,6 +82,22 @@ def get_current_jwt(self) -> Optional[str]: with self._auth_lock: return self._auth_token + def is_authenticated(self) -> bool: + """Check if the client is properly authenticated.""" + with self._auth_lock: + return self._auth_token is not None and self._project_id is not None + + def get_auth_status(self) -> dict: + """Get detailed authentication status for debugging.""" + with self._auth_lock: + return { + "authenticated": self._auth_token is not None, + "has_project_id": self._project_id is not None, + "project_id": self._project_id, + "auth_task_running": self._auth_task is not None and not self._auth_task.done() if self._auth_task else False, + "initialized": self._initialized, + } + def _set_auth_data(self, token: str, project_id: str): """Set authentication data thread-safely.""" with self._auth_lock: @@ -96,6 +112,7 @@ def _set_auth_data(self, token: str, project_id: str): async def _fetch_auth_async(self, api_key: str) -> Optional[dict]: """Asynchronously fetch authentication token.""" try: + logger.debug(f"Attempting to authenticate with API key: {api_key[:8]}...") response = await self.api.v3.fetch_auth_token(api_key) if response: self._set_auth_data(response["token"], response["project_id"]) @@ -107,12 +124,13 @@ async def _fetch_auth_async(self, api_key: str) -> Optional[dict]: tracing_config = {"project_id": response["project_id"]} tracer.update_config(tracing_config) - logger.debug("Successfully fetched authentication token asynchronously") + logger.info("Successfully authenticated with AgentOps API") return response else: - logger.debug("Authentication failed - will continue without authentication") + logger.error("Authentication failed - no response received from API") return None - except Exception: + except Exception as e: + logger.error(f"Authentication failed with exception: {e}") return None def _start_auth_task(self, api_key: str): diff --git a/agentops/client/http/http_client.py b/agentops/client/http/http_client.py index 65a9e244a..12c2baf27 100644 --- a/agentops/client/http/http_client.py +++ b/agentops/client/http/http_client.py @@ -137,6 +137,7 @@ async def async_request( try: session = await cls.get_async_session() if not session: + logger.error("Failed to create async session") return None logger.debug(f"Making async {method} request to {url}") @@ -153,6 +154,7 @@ async def async_request( # Check if response is successful if response.status >= 400: + logger.error(f"HTTP {response.status} error for {url}: {await response.text()}") return None # Parse JSON response @@ -162,8 +164,16 @@ async def async_request( f"Async request successful, response keys: {list(response_data.keys()) if response_data else 'None'}" ) return response_data - except Exception: + except Exception as e: + logger.error(f"Failed to parse JSON response from {url}: {e}") return None - except Exception: + except aiohttp.ClientError as e: + logger.error(f"Network error during async request to {url}: {e}") + return None + except asyncio.TimeoutError as e: + logger.error(f"Timeout error during async request to {url}: {e}") + return None + except Exception as e: + logger.error(f"Unexpected error during async request to {url}: {e}") return None diff --git a/debug_agentops.py b/debug_agentops.py new file mode 100644 index 000000000..4e01c07e5 --- /dev/null +++ b/debug_agentops.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +""" +AgentOps Debugging Script + +This script helps diagnose issues with AgentOps session logging. +Run this script to check connectivity, authentication, and configuration. +""" + +import os +import sys +import asyncio +import requests +from typing import Optional + +def test_network_connectivity(): + """Test basic network connectivity to AgentOps endpoints.""" + print("šŸ” Testing network connectivity...") + + endpoints = [ + ("API Health", "https://api.agentops.ai/health"), + ("OTLP Health", "https://otlp.agentops.ai/health"), + ("Dashboard", "https://app.agentops.ai"), + ] + + for name, url in endpoints: + try: + response = requests.get(url, timeout=10) + status = "āœ…" if response.status_code == 200 else f"āš ļø ({response.status_code})" + print(f" {status} {name}: {url}") + except requests.exceptions.RequestException as e: + print(f" āŒ {name}: {url} - {e}") + +def test_api_key_format(api_key: str): + """Test if the API key format is valid.""" + print(f"\nšŸ”‘ Testing API key format...") + + if not api_key: + print(" āŒ No API key provided") + return False + + # Check if it looks like a UUID + import uuid + try: + uuid.UUID(api_key) + print(f" āœ… API key format appears valid: {api_key[:8]}...") + return True + except ValueError: + print(f" āš ļø API key format may be invalid: {api_key[:8]}...") + return False + +def test_agentops_initialization(api_key: str): + """Test AgentOps initialization and authentication.""" + print(f"\nšŸš€ Testing AgentOps initialization...") + + try: + import agentops + + # Initialize with debug logging + agentops.init(api_key=api_key, log_level="DEBUG") + + # Check authentication status + auth_status = agentops.check_auth_status() + + print(f" šŸ“Š Authentication Status:") + for key, value in auth_status.items(): + status = "āœ…" if value else "āŒ" + print(f" {status} {key}: {value}") + + # Check if authenticated + if agentops.is_authenticated(): + print(" āœ… AgentOps is properly authenticated") + return True + else: + print(" āŒ AgentOps authentication failed") + return False + + except Exception as e: + print(f" āŒ AgentOps initialization failed: {e}") + return False + +def test_session_creation(api_key: str): + """Test creating a session and logging it.""" + print(f"\nšŸ“ Testing session creation...") + + try: + import agentops + + # Initialize + agentops.init(api_key=api_key, log_level="DEBUG") + + # Start a test session + with agentops.start_trace("debug_test_session") as trace: + print(" āœ… Session created successfully") + print(f" šŸ“‹ Trace ID: {trace.span.context.trace_id}") + + # Add some test data + trace.span.set_attribute("test.attribute", "debug_value") + + print(" āœ… Session ended successfully") + return True + + except Exception as e: + print(f" āŒ Session creation failed: {e}") + return False + +def check_environment(): + """Check environment variables and configuration.""" + print(f"\nšŸŒ Checking environment...") + + env_vars = [ + "AGENTOPS_API_KEY", + "AGENTOPS_LOG_LEVEL", + "AGENTOPS_API_ENDPOINT", + "AGENTOPS_APP_URL", + "AGENTOPS_EXPORTER_ENDPOINT", + ] + + for var in env_vars: + value = os.getenv(var) + if value: + # Mask sensitive values + if "API_KEY" in var: + display_value = f"{value[:8]}..." if len(value) > 8 else "***" + else: + display_value = value + print(f" āœ… {var}: {display_value}") + else: + print(f" āš ļø {var}: Not set") + +def main(): + """Main debugging function.""" + print("šŸ”§ AgentOps Debugging Tool") + print("=" * 50) + + # Get API key + api_key = os.getenv("AGENTOPS_API_KEY") + if not api_key: + print("āŒ AGENTOPS_API_KEY environment variable not set") + print("Please set your API key: export AGENTOPS_API_KEY='your-api-key'") + sys.exit(1) + + # Run tests + check_environment() + test_network_connectivity() + test_api_key_format(api_key) + + if test_agentops_initialization(api_key): + test_session_creation(api_key) + + print(f"\nšŸ“‹ Summary:") + print("If you see āŒ errors above, those indicate potential issues.") + print("Common solutions:") + print("1. Check your API key is correct") + print("2. Ensure network connectivity to AgentOps endpoints") + print("3. Check firewall/proxy settings") + print("4. Verify you're using the latest version of agentops") + print("5. Contact support if issues persist") + +if __name__ == "__main__": + main() \ No newline at end of file