Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /BerriAI_litellm /litellm /integrations /lago.py
| # What is this? | |
| ## On Success events log cost to Lago - https://github.com/BerriAI/litellm/issues/3639 | |
| import json | |
| import os | |
| from typing import Final, Literal | |
| import httpx | |
| import litellm | |
| from litellm._logging import verbose_logger | |
| from litellm._uuid import uuid | |
| from litellm.integrations.custom_logger import CustomLogger | |
| from litellm.llms.custom_httpx.http_handler import ( | |
| HTTPHandler, | |
| get_async_httpx_client, | |
| httpxSpecialProvider, | |
| ) | |
| def get_utc_datetime(): | |
| import datetime as dt | |
| from datetime import datetime | |
| if hasattr(dt, "UTC"): | |
| return datetime.now(dt.UTC) | |
| else: | |
| return datetime.utcnow() | |
| class LagoLogger(CustomLogger): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| self.validate_environment() | |
| self.async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) | |
| self.sync_http_handler = HTTPHandler() | |
| def validate_environment(self): | |
| """ | |
| Expects | |
| LAGO_API_BASE, | |
| LAGO_API_KEY, | |
| LAGO_API_EVENT_CODE, | |
| Optional: | |
| LAGO_API_CHARGE_BY | |
| in the environment | |
| """ | |
| missing_keys: Final = [] | |
| if os.getenv("LAGO_API_KEY", None) is None: | |
| missing_keys.append("LAGO_API_KEY") | |
| if os.getenv("LAGO_API_BASE", None) is None: | |
| missing_keys.append("LAGO_API_BASE") | |
| if os.getenv("LAGO_API_EVENT_CODE", None) is None: | |
| missing_keys.append("LAGO_API_EVENT_CODE") | |
| if len(missing_keys) > 0: | |
| raise Exception(f"Missing keys={missing_keys} in environment.") | |
| def _common_logic(self, kwargs: dict, response_obj) -> dict: | |
| response_obj.get("id", kwargs.get("litellm_call_id")) | |
| get_utc_datetime().isoformat() | |
| cost: Final = kwargs.get("response_cost", None) | |
| model: Final = kwargs.get("model") | |
| usage = {} | |
| if ( | |
| isinstance(response_obj, litellm.ModelResponse) or isinstance(response_obj, litellm.EmbeddingResponse) | |
| ) and hasattr(response_obj, "usage"): | |
| usage = { | |
| "prompt_tokens": response_obj["usage"].get("prompt_tokens", 0), | |
| "completion_tokens": response_obj["usage"].get("completion_tokens", 0), | |
| "total_tokens": response_obj["usage"].get("total_tokens"), | |
| } | |
| litellm_params: Final = kwargs.get("litellm_params", {}) or {} | |
| proxy_server_request: Final = litellm_params.get("proxy_server_request") or {} | |
| end_user_id: Final = proxy_server_request.get("body", {}).get("user", None) | |
| user_id: Final = litellm_params["metadata"].get("user_api_key_user_id", None) | |
| team_id: Final = litellm_params["metadata"].get("user_api_key_team_id", None) | |
| litellm_params["metadata"].get("user_api_key_org_id", None) | |
| charge_by: Literal["end_user_id", "team_id", "user_id"] = "end_user_id" | |
| external_customer_id: str | None = None | |
| if os.getenv("LAGO_API_CHARGE_BY", None) is not None and isinstance(os.environ["LAGO_API_CHARGE_BY"], str): | |
| if os.environ["LAGO_API_CHARGE_BY"] in [ | |
| "end_user_id", | |
| "user_id", | |
| "team_id", | |
| ]: | |
| charge_by = os.environ["LAGO_API_CHARGE_BY"] | |
| else: | |
| raise Exception("invalid LAGO_API_CHARGE_BY set") | |
| if charge_by == "end_user_id": | |
| external_customer_id = end_user_id | |
| elif charge_by == "team_id": | |
| external_customer_id = team_id | |
| elif charge_by == "user_id": | |
| external_customer_id = user_id | |
| if external_customer_id is None: | |
| raise Exception( | |
| f"External Customer ID is not set. Charge_by={charge_by}. User_id={user_id}. End_user_id={end_user_id}. Team_id={team_id}" | |
| ) | |
| returned_val: Final = { | |
| "event": { | |
| "transaction_id": str(uuid.uuid4()), | |
| "external_subscription_id": external_customer_id, | |
| "code": os.getenv("LAGO_API_EVENT_CODE"), | |
| "properties": {"model": model, "response_cost": cost, **usage}, | |
| } | |
| } | |
| verbose_logger.debug("\x1b[91mLogged Lago Object:\n%s\x1b[0m\n", returned_val) | |
| return returned_val | |
| def log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| _url = os.getenv("LAGO_API_BASE") | |
| assert _url is not None and isinstance(_url, str), ( | |
| f"LAGO_API_BASE missing or not set correctly. LAGO_API_BASE={_url}" | |
| ) | |
| if _url.endswith("/"): | |
| _url += "api/v1/events" | |
| else: | |
| _url += "/api/v1/events" | |
| api_key: Final = os.getenv("LAGO_API_KEY") | |
| _data: Final = self._common_logic(kwargs=kwargs, response_obj=response_obj) | |
| _headers: Final = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {api_key}", | |
| } | |
| try: | |
| response: Final = self.sync_http_handler.post( | |
| url=_url, | |
| data=json.dumps(_data), | |
| headers=_headers, | |
| ) | |
| response.raise_for_status() | |
| except Exception as e: | |
| error_response: Final = getattr(e, "response", None) | |
| if error_response is not None and hasattr(error_response, "text"): | |
| verbose_logger.debug("\nError Message: %s", error_response.text) | |
| raise e | |
| async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| try: | |
| verbose_logger.debug("ENTERS LAGO CALLBACK") | |
| _url = os.getenv("LAGO_API_BASE") | |
| assert _url is not None and isinstance(_url, str), ( | |
| f"LAGO_API_BASE missing or not set correctly. LAGO_API_BASE={_url}" | |
| ) | |
| if _url.endswith("/"): | |
| _url += "api/v1/events" | |
| else: | |
| _url += "/api/v1/events" | |
| api_key: Final = os.getenv("LAGO_API_KEY") | |
| _data: Final = self._common_logic(kwargs=kwargs, response_obj=response_obj) | |
| _headers: Final = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {api_key}", | |
| } | |
| except Exception as e: | |
| raise e | |
| response: httpx.Response | None = None | |
| try: | |
| response = await self.async_http_handler.post( | |
| url=_url, | |
| data=json.dumps(_data), | |
| headers=_headers, | |
| ) | |
| response.raise_for_status() | |
| verbose_logger.debug("Logged Lago Object: %s", response.text) | |
| except Exception as e: | |
| if response is not None and hasattr(response, "text"): | |
| verbose_logger.debug("\nError Message: %s", response.text) | |
| raise e | |
Xet Storage Details
- Size:
- 6.87 kB
- Xet hash:
- af905d19b9db00ba475876e5671e6232fe83b18409bcc8d80fd43db42996d79a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.