Exchange API key for JWT token asynchronously. Args: api_key: Optional API key. If not provided, uses AGENTOPS_API_KEY env var. Returns: JWT bearer token, or None if failed Note: This function never throws exceptions - all errors are handled gracefully
(api_key: Optional[str] = None)
| 23 | |
| 24 | |
| 25 | async def get_jwt_token(api_key: Optional[str] = None) -> str: |
| 26 | """ |
| 27 | Exchange API key for JWT token asynchronously. |
| 28 | |
| 29 | Args: |
| 30 | api_key: Optional API key. If not provided, uses AGENTOPS_API_KEY env var. |
| 31 | |
| 32 | Returns: |
| 33 | JWT bearer token, or None if failed |
| 34 | |
| 35 | Note: |
| 36 | This function never throws exceptions - all errors are handled gracefully |
| 37 | """ |
| 38 | try: |
| 39 | if api_key is None: |
| 40 | from agentops import get_client |
| 41 | |
| 42 | client = get_client() |
| 43 | if client and client.config.api_key: |
| 44 | api_key = client.config.api_key |
| 45 | else: |
| 46 | api_key = os.getenv("AGENTOPS_API_KEY") |
| 47 | if not api_key: |
| 48 | logger.warning("No API key provided and AGENTOPS_API_KEY environment variable not set") |
| 49 | return None |
| 50 | |
| 51 | # Use a separate aiohttp session for validation to avoid conflicts |
| 52 | import aiohttp |
| 53 | |
| 54 | async with aiohttp.ClientSession() as session: |
| 55 | async with session.post( |
| 56 | "https://api.agentops.ai/public/v1/auth/access_token", |
| 57 | json={"api_key": api_key}, |
| 58 | timeout=aiohttp.ClientTimeout(total=10), |
| 59 | ) as response: |
| 60 | if response.status >= 400: |
| 61 | logger.warning(f"Failed to get JWT token: HTTP {response.status} - backend may be unavailable") |
| 62 | return None |
| 63 | |
| 64 | response_data = await response.json() |
| 65 | |
| 66 | if "bearer" not in response_data: |
| 67 | logger.warning("Failed to get JWT token: No bearer token in response") |
| 68 | return None |
| 69 | |
| 70 | return response_data["bearer"] |
| 71 | |
| 72 | except Exception as e: |
| 73 | logger.warning(f"Failed to get JWT token: {e} - continuing without authentication") |
| 74 | return None |
| 75 | |
| 76 | |
| 77 | def get_jwt_token_sync(api_key: Optional[str] = None) -> Optional[str]: |
no test coverage detected
searching dependent graphs…