From 7a0cde4abef7d6619abf553dd53d65f9012fff7a Mon Sep 17 00:00:00 2001 From: Howard Gil Date: Thu, 8 Aug 2024 17:04:02 -0700 Subject: [PATCH] Adding HTTPClient get and changing timetravel to use it (#328) --- agentops/http_client.py | 55 +++++++++++++++++++++++++++++++++++++++++ agentops/time_travel.py | 2 +- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/agentops/http_client.py b/agentops/http_client.py index a625cd19..32d7d336 100644 --- a/agentops/http_client.py +++ b/agentops/http_client.py @@ -119,3 +119,58 @@ def post( raise ApiServerException("API server: - internal server error") return result + + @staticmethod + def get( + url: str, + api_key: Optional[str] = None, + jwt: Optional[str] = None, + header=None, + ) -> Response: + result = Response() + try: + # Create request session with retries configured + request_session = requests.Session() + request_session.mount(url, HTTPAdapter(max_retries=retry_config)) + + if api_key is not None: + JSON_HEADER["X-Agentops-Api-Key"] = api_key + + if jwt is not None: + JSON_HEADER["Authorization"] = f"Bearer {jwt}" + + res = request_session.get(url, headers=JSON_HEADER, timeout=20) + + result.parse(res) + except requests.exceptions.Timeout: + result.code = 408 + result.status = HttpStatus.TIMEOUT + raise ApiServerException( + "Could not reach API server - connection timed out" + ) + except requests.exceptions.HTTPError as e: + try: + result.parse(e.response) + except Exception: + result = Response() + result.code = e.response.status_code + result.status = Response.get_status(e.response.status_code) + result.body = {"error": str(e)} + raise ApiServerException(f"HTTPError: {e}") + except requests.exceptions.RequestException as e: + result.body = {"error": str(e)} + raise ApiServerException(f"RequestException: {e}") + + if result.code == 401: + raise ApiServerException( + f"API server: invalid API key: {api_key}. Find your API key at https://app.agentops.ai/settings/projects" + ) + if result.code == 400: + if "message" in result.body: + raise ApiServerException(f"API server: {result.body['message']}") + else: + raise ApiServerException(f"API server: {result.body}") + if result.code == 500: + raise ApiServerException("API server: - internal server error") + + return result diff --git a/agentops/time_travel.py b/agentops/time_travel.py index be84e190..a6de34b3 100644 --- a/agentops/time_travel.py +++ b/agentops/time_travel.py @@ -34,7 +34,7 @@ def fetch_time_travel_id(ttd_id): try: endpoint = environ.get("AGENTOPS_API_ENDPOINT", "https://api.agentops.ai") payload = json.dumps({"ttd_id": ttd_id}).encode("utf-8") - ttd_res = HttpClient.post(f"{endpoint}/v2/get_ttd", payload) + ttd_res = HttpClient.get(f"{endpoint}/v2/ttd/{ttd_id}") if ttd_res.code != 200: raise Exception( f"Failed to fetch TTD with status code {ttd_res.status_code}"