Skip to content

Commit 76bd6b9

Browse files
cursoragentalex
andcommitted
Add authentication status checks and debug script for AgentOps
Co-authored-by: alex <[email protected]>
1 parent 6e129e1 commit 76bd6b9

File tree

4 files changed

+218
-5
lines changed

4 files changed

+218
-5
lines changed

agentops/__init__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,31 @@ def get_client() -> Client:
5555
return _client
5656

5757

58+
def check_auth_status() -> dict:
59+
"""Check the authentication status of the AgentOps client.
60+
61+
Returns:
62+
dict: Authentication status information including:
63+
- authenticated: bool
64+
- has_project_id: bool
65+
- project_id: str or None
66+
- auth_task_running: bool
67+
- initialized: bool
68+
"""
69+
client = get_client()
70+
return client.get_auth_status()
71+
72+
73+
def is_authenticated() -> bool:
74+
"""Check if the AgentOps client is properly authenticated.
75+
76+
Returns:
77+
bool: True if authenticated, False otherwise
78+
"""
79+
client = get_client()
80+
return client.is_authenticated()
81+
82+
5883
@deprecated("Automatically tracked in v4.")
5984
def record(event):
6085
"""

agentops/client/client.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,22 @@ def get_current_jwt(self) -> Optional[str]:
8282
with self._auth_lock:
8383
return self._auth_token
8484

85+
def is_authenticated(self) -> bool:
86+
"""Check if the client is properly authenticated."""
87+
with self._auth_lock:
88+
return self._auth_token is not None and self._project_id is not None
89+
90+
def get_auth_status(self) -> dict:
91+
"""Get detailed authentication status for debugging."""
92+
with self._auth_lock:
93+
return {
94+
"authenticated": self._auth_token is not None,
95+
"has_project_id": self._project_id is not None,
96+
"project_id": self._project_id,
97+
"auth_task_running": self._auth_task is not None and not self._auth_task.done() if self._auth_task else False,
98+
"initialized": self._initialized,
99+
}
100+
85101
def _set_auth_data(self, token: str, project_id: str):
86102
"""Set authentication data thread-safely."""
87103
with self._auth_lock:
@@ -96,6 +112,7 @@ def _set_auth_data(self, token: str, project_id: str):
96112
async def _fetch_auth_async(self, api_key: str) -> Optional[dict]:
97113
"""Asynchronously fetch authentication token."""
98114
try:
115+
logger.debug(f"Attempting to authenticate with API key: {api_key[:8]}...")
99116
response = await self.api.v3.fetch_auth_token(api_key)
100117
if response:
101118
self._set_auth_data(response["token"], response["project_id"])
@@ -107,12 +124,13 @@ async def _fetch_auth_async(self, api_key: str) -> Optional[dict]:
107124
tracing_config = {"project_id": response["project_id"]}
108125
tracer.update_config(tracing_config)
109126

110-
logger.debug("Successfully fetched authentication token asynchronously")
127+
logger.info("Successfully authenticated with AgentOps API")
111128
return response
112129
else:
113-
logger.debug("Authentication failed - will continue without authentication")
130+
logger.error("Authentication failed - no response received from API")
114131
return None
115-
except Exception:
132+
except Exception as e:
133+
logger.error(f"Authentication failed with exception: {e}")
116134
return None
117135

118136
def _start_auth_task(self, api_key: str):

agentops/client/http/http_client.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ async def async_request(
137137
try:
138138
session = await cls.get_async_session()
139139
if not session:
140+
logger.error("Failed to create async session")
140141
return None
141142

142143
logger.debug(f"Making async {method} request to {url}")
@@ -153,6 +154,7 @@ async def async_request(
153154

154155
# Check if response is successful
155156
if response.status >= 400:
157+
logger.error(f"HTTP {response.status} error for {url}: {await response.text()}")
156158
return None
157159

158160
# Parse JSON response
@@ -162,8 +164,16 @@ async def async_request(
162164
f"Async request successful, response keys: {list(response_data.keys()) if response_data else 'None'}"
163165
)
164166
return response_data
165-
except Exception:
167+
except Exception as e:
168+
logger.error(f"Failed to parse JSON response from {url}: {e}")
166169
return None
167170

168-
except Exception:
171+
except aiohttp.ClientError as e:
172+
logger.error(f"Network error during async request to {url}: {e}")
173+
return None
174+
except asyncio.TimeoutError as e:
175+
logger.error(f"Timeout error during async request to {url}: {e}")
176+
return None
177+
except Exception as e:
178+
logger.error(f"Unexpected error during async request to {url}: {e}")
169179
return None

debug_agentops.py

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
#!/usr/bin/env python3
2+
"""
3+
AgentOps Debugging Script
4+
5+
This script helps diagnose issues with AgentOps session logging.
6+
Run this script to check connectivity, authentication, and configuration.
7+
"""
8+
9+
import os
10+
import sys
11+
import asyncio
12+
import requests
13+
from typing import Optional
14+
15+
def test_network_connectivity():
16+
"""Test basic network connectivity to AgentOps endpoints."""
17+
print("🔍 Testing network connectivity...")
18+
19+
endpoints = [
20+
("API Health", "https://api.agentops.ai/health"),
21+
("OTLP Health", "https://otlp.agentops.ai/health"),
22+
("Dashboard", "https://app.agentops.ai"),
23+
]
24+
25+
for name, url in endpoints:
26+
try:
27+
response = requests.get(url, timeout=10)
28+
status = "✅" if response.status_code == 200 else f"⚠️ ({response.status_code})"
29+
print(f" {status} {name}: {url}")
30+
except requests.exceptions.RequestException as e:
31+
print(f" ❌ {name}: {url} - {e}")
32+
33+
def test_api_key_format(api_key: str):
34+
"""Test if the API key format is valid."""
35+
print(f"\n🔑 Testing API key format...")
36+
37+
if not api_key:
38+
print(" ❌ No API key provided")
39+
return False
40+
41+
# Check if it looks like a UUID
42+
import uuid
43+
try:
44+
uuid.UUID(api_key)
45+
print(f" ✅ API key format appears valid: {api_key[:8]}...")
46+
return True
47+
except ValueError:
48+
print(f" ⚠️ API key format may be invalid: {api_key[:8]}...")
49+
return False
50+
51+
def test_agentops_initialization(api_key: str):
52+
"""Test AgentOps initialization and authentication."""
53+
print(f"\n🚀 Testing AgentOps initialization...")
54+
55+
try:
56+
import agentops
57+
58+
# Initialize with debug logging
59+
agentops.init(api_key=api_key, log_level="DEBUG")
60+
61+
# Check authentication status
62+
auth_status = agentops.check_auth_status()
63+
64+
print(f" 📊 Authentication Status:")
65+
for key, value in auth_status.items():
66+
status = "✅" if value else "❌"
67+
print(f" {status} {key}: {value}")
68+
69+
# Check if authenticated
70+
if agentops.is_authenticated():
71+
print(" ✅ AgentOps is properly authenticated")
72+
return True
73+
else:
74+
print(" ❌ AgentOps authentication failed")
75+
return False
76+
77+
except Exception as e:
78+
print(f" ❌ AgentOps initialization failed: {e}")
79+
return False
80+
81+
def test_session_creation(api_key: str):
82+
"""Test creating a session and logging it."""
83+
print(f"\n📝 Testing session creation...")
84+
85+
try:
86+
import agentops
87+
88+
# Initialize
89+
agentops.init(api_key=api_key, log_level="DEBUG")
90+
91+
# Start a test session
92+
with agentops.start_trace("debug_test_session") as trace:
93+
print(" ✅ Session created successfully")
94+
print(f" 📋 Trace ID: {trace.span.context.trace_id}")
95+
96+
# Add some test data
97+
trace.span.set_attribute("test.attribute", "debug_value")
98+
99+
print(" ✅ Session ended successfully")
100+
return True
101+
102+
except Exception as e:
103+
print(f" ❌ Session creation failed: {e}")
104+
return False
105+
106+
def check_environment():
107+
"""Check environment variables and configuration."""
108+
print(f"\n🌍 Checking environment...")
109+
110+
env_vars = [
111+
"AGENTOPS_API_KEY",
112+
"AGENTOPS_LOG_LEVEL",
113+
"AGENTOPS_API_ENDPOINT",
114+
"AGENTOPS_APP_URL",
115+
"AGENTOPS_EXPORTER_ENDPOINT",
116+
]
117+
118+
for var in env_vars:
119+
value = os.getenv(var)
120+
if value:
121+
# Mask sensitive values
122+
if "API_KEY" in var:
123+
display_value = f"{value[:8]}..." if len(value) > 8 else "***"
124+
else:
125+
display_value = value
126+
print(f" ✅ {var}: {display_value}")
127+
else:
128+
print(f" ⚠️ {var}: Not set")
129+
130+
def main():
131+
"""Main debugging function."""
132+
print("🔧 AgentOps Debugging Tool")
133+
print("=" * 50)
134+
135+
# Get API key
136+
api_key = os.getenv("AGENTOPS_API_KEY")
137+
if not api_key:
138+
print("❌ AGENTOPS_API_KEY environment variable not set")
139+
print("Please set your API key: export AGENTOPS_API_KEY='your-api-key'")
140+
sys.exit(1)
141+
142+
# Run tests
143+
check_environment()
144+
test_network_connectivity()
145+
test_api_key_format(api_key)
146+
147+
if test_agentops_initialization(api_key):
148+
test_session_creation(api_key)
149+
150+
print(f"\n📋 Summary:")
151+
print("If you see ❌ errors above, those indicate potential issues.")
152+
print("Common solutions:")
153+
print("1. Check your API key is correct")
154+
print("2. Ensure network connectivity to AgentOps endpoints")
155+
print("3. Check firewall/proxy settings")
156+
print("4. Verify you're using the latest version of agentops")
157+
print("5. Contact support if issues persist")
158+
159+
if __name__ == "__main__":
160+
main()

0 commit comments

Comments
 (0)