Skip to content

Commit 507a386

Browse files
bboynton97Dwij1704
andauthored
bad api key doesnt block (#919)
* bad api key doesnt block * remove redundent agentops * fixed for start_session --------- Co-authored-by: Dwij Patel <dwijpatel1704@gmail.com>
1 parent e1c8562 commit 507a386

File tree

3 files changed

+54
-29
lines changed

3 files changed

+54
-29
lines changed

agentops/client/api/versions/v3.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from agentops.client.api.base import BaseApiClient
1212
from agentops.client.api.types import AuthTokenResponse
1313
from agentops.exceptions import ApiServerException
14-
14+
from agentops.logging import logger
1515

1616
class V3Client(BaseApiClient):
1717
"""Client for the AgentOps V3 API"""
@@ -33,24 +33,28 @@ def fetch_auth_token(self, api_key: str) -> AuthTokenResponse:
3333

3434
r = self.post(path, data, headers)
3535

36-
if r.status_code != 200:
37-
error_msg = f"Authentication failed: {r.status_code}"
38-
try:
39-
error_data = r.json()
40-
if "error" in error_data:
41-
error_msg = f"Authentication failed: {error_data['error']}"
42-
except Exception:
43-
pass
44-
raise ApiServerException(error_msg)
45-
4636
try:
47-
jr = r.json()
48-
token = jr.get("token")
49-
if not token:
50-
raise ApiServerException("No token in authentication response")
37+
if r.status_code != 200:
38+
error_msg = f"Authentication failed: {r.status_code}"
39+
try:
40+
error_data = r.json()
41+
if "error" in error_data:
42+
error_msg = f"{error_data['error']}"
43+
except Exception:
44+
pass
45+
raise ApiServerException(error_msg)
5146

52-
return jr
47+
try:
48+
jr = r.json()
49+
token = jr.get("token")
50+
if not token:
51+
raise ApiServerException("No token in authentication response")
52+
53+
return jr
54+
except Exception as e:
55+
raise ApiServerException(f"Failed to process authentication response: {str(e)}")
5356
except Exception as e:
54-
raise ApiServerException(f"Failed to process authentication response: {str(e)}")
57+
logger.error(f"{str(e)} - Perhaps an invalid API key?")
58+
return None
5559

5660
# Add V3-specific API methods here

agentops/client/client.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ def init(self, **kwargs):
6868
# Prefetch JWT token if enabled
6969
# TODO: Move this validation somewhere else (and integrate with self.config.prefetch_jwt_token once we have a solution to that)
7070
response = self.api.v3.fetch_auth_token(self.config.api_key)
71+
if response is None:
72+
return
7173

7274
# Save the bearer for use with the v4 API
7375
self.api.v4.set_auth_token(response["token"])

agentops/legacy/__init__.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ def __init__(self, span: Any, token: Any):
3434

3535
def __del__(self):
3636
try:
37-
self.span.end()
37+
if self.span is not None:
38+
self.span.end()
3839
except:
3940
pass
4041

@@ -66,9 +67,10 @@ def end_session(self, **kwargs):
6667
6768
forces a flush to ensure the span is exported immediately.
6869
"""
69-
_set_span_attributes(self.span, kwargs)
70-
self.span.end()
71-
_flush_span_processors()
70+
if self.span is not None:
71+
_set_span_attributes(self.span, kwargs)
72+
self.span.end()
73+
_flush_span_processors()
7274

7375

7476
def _create_session_span(tags: Union[Dict[str, Any], List[str], None] = None) -> tuple:
@@ -130,7 +132,21 @@ def start_session(
130132
if not TracingCore.get_instance().initialized:
131133
from agentops import Client
132134
# Pass auto_start_session=False to prevent circular dependency
133-
Client().init(auto_start_session=False)
135+
try:
136+
Client().init(auto_start_session=False)
137+
# If initialization failed (returned None), create a dummy session
138+
if not TracingCore.get_instance().initialized:
139+
logger.warning("AgentOps client initialization failed. Creating a dummy session that will not send data.")
140+
# Create a dummy session that won't send data but won't throw exceptions
141+
dummy_session = Session(None, None)
142+
_current_session = dummy_session
143+
return dummy_session
144+
except Exception as e:
145+
logger.warning(f"AgentOps client initialization failed: {str(e)}. Creating a dummy session that will not send data.")
146+
# Create a dummy session that won't send data but won't throw exceptions
147+
dummy_session = Session(None, None)
148+
_current_session = dummy_session
149+
return dummy_session
134150

135151
span, ctx, token = _create_session_span(tags)
136152
session = Session(span, token)
@@ -155,7 +171,7 @@ def _set_span_attributes(span: Any, attributes: Dict[str, Any]) -> None:
155171
span: The span to set attributes on
156172
attributes: The attributes to set as a dictionary
157173
"""
158-
if not attributes or not hasattr(span, "set_attribute"):
174+
if span is None:
159175
return
160176

161177
for key, value in attributes.items():
@@ -235,9 +251,10 @@ def end_session(session_or_status: Any = None, **kwargs) -> None:
235251
if session_or_status is None and kwargs:
236252
if _current_session is not None:
237253
try:
238-
_set_span_attributes(_current_session.span, kwargs)
239-
_finalize_span(_current_session.span, _current_session.token)
240-
_flush_span_processors()
254+
if _current_session.span is not None:
255+
_set_span_attributes(_current_session.span, kwargs)
256+
_finalize_span(_current_session.span, _current_session.token)
257+
_flush_span_processors()
241258
_current_session = None
242259
except Exception as e:
243260
logger.warning(f"Error ending current session: {e}")
@@ -256,9 +273,11 @@ def end_session(session_or_status: Any = None, **kwargs) -> None:
256273
if hasattr(session_or_status, 'span') and hasattr(session_or_status, 'token'):
257274
try:
258275
# Set attributes and finalize the span
259-
_set_span_attributes(session_or_status.span, kwargs)
260-
_finalize_span(session_or_status.span, session_or_status.token)
261-
_flush_span_processors()
276+
if session_or_status.span is not None:
277+
_set_span_attributes(session_or_status.span, kwargs)
278+
if session_or_status.span is not None:
279+
_finalize_span(session_or_status.span, session_or_status.token)
280+
_flush_span_processors()
262281

263282
# Clear the global session reference if this is the current session
264283
if _current_session is session_or_status:

0 commit comments

Comments
 (0)