Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions agentops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
24 changes: 21 additions & 3 deletions agentops/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"])
Expand All @@ -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):
Expand Down
14 changes: 12 additions & 2 deletions agentops/client/http/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand All @@ -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
Expand All @@ -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
160 changes: 160 additions & 0 deletions debug_agentops.py
Original file line number Diff line number Diff line change
@@ -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()
Loading