assassinlike commited on
Commit
05f751b
·
verified ·
1 Parent(s): 76fc4d1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__init__.py +19 -0
  3. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/__init__.cpython-311.pyc +0 -0
  4. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/exception_mapping_utils.cpython-311.pyc +0 -0
  5. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/exceptions.cpython-311.pyc +0 -0
  6. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/exception_mapping_utils.py +172 -0
  7. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/exceptions.py +41 -0
  8. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/messages/__init__.py +144 -0
  9. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/messages/__pycache__/__init__.cpython-311.pyc +0 -0
  10. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/__init__.cpython-311.pyc +0 -0
  11. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/_internal_lru_cache.cpython-311.pyc +0 -0
  12. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/azure_blob_cache.cpython-311.pyc +0 -0
  13. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/base_cache.cpython-311.pyc +0 -0
  14. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/caching.cpython-311.pyc +0 -0
  15. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/caching_handler.cpython-311.pyc +0 -0
  16. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/disk_cache.cpython-311.pyc +0 -0
  17. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/dual_cache.cpython-311.pyc +0 -0
  18. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/gcs_cache.cpython-311.pyc +0 -0
  19. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/in_memory_cache.cpython-311.pyc +0 -0
  20. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/llm_caching_handler.cpython-311.pyc +0 -0
  21. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/qdrant_semantic_cache.cpython-311.pyc +0 -0
  22. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_cache.cpython-311.pyc +0 -0
  23. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_cluster_cache.cpython-311.pyc +0 -0
  24. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_semantic_cache.cpython-311.pyc +0 -0
  25. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/s3_cache.cpython-311.pyc +0 -0
  26. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/__init__.cpython-311.pyc +0 -0
  27. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/endpoint_factory.cpython-311.pyc +0 -0
  28. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/main.cpython-311.pyc +0 -0
  29. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/utils.cpython-311.pyc +0 -0
  30. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/evals/__pycache__/__init__.cpython-311.pyc +0 -0
  31. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/evals/__pycache__/main.cpython-311.pyc +0 -0
  32. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/__init__.cpython-311.pyc +0 -0
  33. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/client.cpython-311.pyc +0 -0
  34. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/tools.cpython-311.pyc +0 -0
  35. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/files/__pycache__/main.cpython-311.pyc +0 -0
  36. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/files/__pycache__/utils.cpython-311.pyc +0 -0
  37. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/Readme.md +46 -0
  38. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/batching_handler.cpython-311.pyc +0 -0
  39. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/budget_alert_types.cpython-311.pyc +0 -0
  40. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/hanging_request_check.cpython-311.pyc +0 -0
  41. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/slack_alerting.cpython-311.pyc +0 -0
  42. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/utils.cpython-311.pyc +0 -0
  43. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/batching_handler.py +81 -0
  44. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/budget_alert_types.py +115 -0
  45. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/hanging_request_check.py +177 -0
  46. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/slack_alerting.py +1994 -0
  47. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/utils.py +99 -0
  48. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/__init__.cpython-311.pyc +0 -0
  49. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/additional_logging_utils.cpython-311.pyc +0 -0
  50. data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/anthropic_cache_control_hook.cpython-311.pyc +0 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (384 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anthropic error format utilities."""
2
+
3
+ from .exception_mapping_utils import (
4
+ ANTHROPIC_ERROR_TYPE_MAP,
5
+ AnthropicExceptionMapping,
6
+ )
7
+ from .exceptions import (
8
+ AnthropicErrorDetail,
9
+ AnthropicErrorResponse,
10
+ AnthropicErrorType,
11
+ )
12
+
13
+ __all__ = [
14
+ "AnthropicErrorType",
15
+ "AnthropicErrorDetail",
16
+ "AnthropicErrorResponse",
17
+ "ANTHROPIC_ERROR_TYPE_MAP",
18
+ "AnthropicExceptionMapping",
19
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (648 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/exception_mapping_utils.cpython-311.pyc ADDED
Binary file (6.58 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/__pycache__/exceptions.cpython-311.pyc ADDED
Binary file (1.61 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/exception_mapping_utils.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for mapping exceptions to Anthropic error format.
3
+
4
+ Similar to litellm/litellm_core_utils/exception_mapping_utils.py but for Anthropic response format.
5
+ """
6
+
7
+ from litellm.litellm_core_utils.safe_json_loads import safe_json_loads
8
+ from typing import Dict, Optional
9
+
10
+ from .exceptions import AnthropicErrorResponse, AnthropicErrorType
11
+
12
+
13
+ # HTTP status code -> Anthropic error type
14
+ # Source: https://docs.anthropic.com/en/api/errors
15
+ ANTHROPIC_ERROR_TYPE_MAP: Dict[int, AnthropicErrorType] = {
16
+ 400: "invalid_request_error",
17
+ 401: "authentication_error",
18
+ 403: "permission_error",
19
+ 404: "not_found_error",
20
+ 413: "request_too_large",
21
+ 429: "rate_limit_error",
22
+ 500: "api_error",
23
+ 529: "overloaded_error",
24
+ }
25
+
26
+
27
+ class AnthropicExceptionMapping:
28
+ """
29
+ Helper class for mapping exceptions to Anthropic error format.
30
+
31
+ Similar pattern to ExceptionCheckers in litellm_core_utils/exception_mapping_utils.py
32
+ """
33
+
34
+ @staticmethod
35
+ def get_error_type(status_code: int) -> AnthropicErrorType:
36
+ """Map HTTP status code to Anthropic error type."""
37
+ return ANTHROPIC_ERROR_TYPE_MAP.get(status_code, "api_error")
38
+
39
+ @staticmethod
40
+ def create_error_response(
41
+ status_code: int,
42
+ message: str,
43
+ request_id: Optional[str] = None,
44
+ ) -> AnthropicErrorResponse:
45
+ """
46
+ Create an Anthropic-formatted error response dict.
47
+
48
+ Anthropic error format:
49
+ {
50
+ "type": "error",
51
+ "error": {"type": "...", "message": "..."},
52
+ "request_id": "req_..."
53
+ }
54
+ """
55
+ error_type = AnthropicExceptionMapping.get_error_type(status_code)
56
+
57
+ response: AnthropicErrorResponse = {
58
+ "type": "error",
59
+ "error": {
60
+ "type": error_type,
61
+ "message": message,
62
+ },
63
+ }
64
+
65
+ if request_id:
66
+ response["request_id"] = request_id
67
+
68
+ return response
69
+
70
+ @staticmethod
71
+ def extract_error_message(raw_message: str) -> str:
72
+ """
73
+ Extract error message from various provider response formats.
74
+
75
+ Handles:
76
+ - Bedrock: {"detail": {"message": "..."}}
77
+ - AWS: {"Message": "..."}
78
+ - Generic: {"message": "..."}
79
+ - Plain strings
80
+ """
81
+ parsed = safe_json_loads(raw_message)
82
+ if isinstance(parsed, dict):
83
+ # Bedrock format
84
+ if "detail" in parsed and isinstance(parsed["detail"], dict):
85
+ return parsed["detail"].get("message", raw_message)
86
+ # AWS/generic format
87
+ return parsed.get("Message") or parsed.get("message") or raw_message
88
+ return raw_message
89
+
90
+ @staticmethod
91
+ def _is_anthropic_error_dict(parsed: dict) -> bool:
92
+ """
93
+ Check if a parsed dict is in Anthropic error format.
94
+
95
+ Anthropic error format:
96
+ {
97
+ "type": "error",
98
+ "error": {"type": "...", "message": "..."}
99
+ }
100
+ """
101
+ return (
102
+ parsed.get("type") == "error"
103
+ and isinstance(parsed.get("error"), dict)
104
+ and "type" in parsed["error"]
105
+ and "message" in parsed["error"]
106
+ )
107
+
108
+ @staticmethod
109
+ def _extract_message_from_dict(parsed: dict, raw_message: str) -> str:
110
+ """
111
+ Extract error message from a parsed provider-specific dict.
112
+
113
+ Handles:
114
+ - Bedrock: {"detail": {"message": "..."}}
115
+ - AWS: {"Message": "..."}
116
+ - Generic: {"message": "..."}
117
+ """
118
+ # Bedrock format
119
+ if "detail" in parsed and isinstance(parsed["detail"], dict):
120
+ return parsed["detail"].get("message", raw_message)
121
+ # AWS/generic format
122
+ return parsed.get("Message") or parsed.get("message") or raw_message
123
+
124
+ @staticmethod
125
+ def transform_to_anthropic_error(
126
+ status_code: int,
127
+ raw_message: str,
128
+ request_id: Optional[str] = None,
129
+ ) -> AnthropicErrorResponse:
130
+ """
131
+ Transform an error message to Anthropic format.
132
+
133
+ - If already in Anthropic format: passthrough unchanged
134
+ - Otherwise: extract message and create Anthropic error
135
+
136
+ Parses JSON only once for efficiency.
137
+
138
+ Args:
139
+ status_code: HTTP status code
140
+ raw_message: Raw error message (may be JSON string or plain text)
141
+ request_id: Optional request ID to include
142
+
143
+ Returns:
144
+ AnthropicErrorResponse dict
145
+ """
146
+ # Try to parse as JSON once
147
+ parsed: Optional[dict] = safe_json_loads(raw_message)
148
+ if not isinstance(parsed, dict):
149
+ parsed = None
150
+
151
+ # If parsed and already in Anthropic format - passthrough
152
+ if parsed is not None and AnthropicExceptionMapping._is_anthropic_error_dict(
153
+ parsed
154
+ ):
155
+ # Optionally add request_id if provided and not present
156
+ if request_id and "request_id" not in parsed:
157
+ parsed["request_id"] = request_id
158
+ return parsed # type: ignore
159
+
160
+ # Extract message - use parsed dict if available, otherwise raw string
161
+ if parsed is not None:
162
+ message = AnthropicExceptionMapping._extract_message_from_dict(
163
+ parsed, raw_message
164
+ )
165
+ else:
166
+ message = raw_message
167
+
168
+ return AnthropicExceptionMapping.create_error_response(
169
+ status_code=status_code,
170
+ message=message,
171
+ request_id=request_id,
172
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/exceptions/exceptions.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anthropic error format type definitions."""
2
+
3
+ from typing_extensions import Literal, Required, TypedDict
4
+
5
+
6
+ # Known Anthropic error types
7
+ # Source: https://docs.anthropic.com/en/api/errors
8
+ AnthropicErrorType = Literal[
9
+ "invalid_request_error",
10
+ "authentication_error",
11
+ "permission_error",
12
+ "not_found_error",
13
+ "request_too_large",
14
+ "rate_limit_error",
15
+ "api_error",
16
+ "overloaded_error",
17
+ ]
18
+
19
+
20
+ class AnthropicErrorDetail(TypedDict):
21
+ """Inner error detail in Anthropic format."""
22
+
23
+ type: AnthropicErrorType
24
+ message: str
25
+
26
+
27
+ class AnthropicErrorResponse(TypedDict, total=False):
28
+ """
29
+ Anthropic-formatted error response.
30
+
31
+ Format:
32
+ {
33
+ "type": "error",
34
+ "error": {"type": "...", "message": "..."},
35
+ "request_id": "req_..." # optional
36
+ }
37
+ """
38
+
39
+ type: Required[Literal["error"]]
40
+ error: Required[AnthropicErrorDetail]
41
+ request_id: str
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/messages/__init__.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Interface for Anthropic's messages API
3
+
4
+ Use this to call LLMs in Anthropic /messages Request/Response format
5
+
6
+ This is an __init__.py file to allow the following interface
7
+
8
+ - litellm.messages.acreate
9
+ - litellm.messages.create
10
+
11
+ """
12
+
13
+ from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Union
14
+
15
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
16
+ anthropic_messages as _async_anthropic_messages,
17
+ )
18
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
19
+ anthropic_messages_handler as _sync_anthropic_messages,
20
+ )
21
+ from litellm.types.llms.anthropic_messages.anthropic_response import (
22
+ AnthropicMessagesResponse,
23
+ )
24
+
25
+
26
+ async def acreate(
27
+ max_tokens: int,
28
+ messages: List[Dict],
29
+ model: str,
30
+ metadata: Optional[Dict] = None,
31
+ stop_sequences: Optional[List[str]] = None,
32
+ stream: Optional[bool] = False,
33
+ system: Optional[str] = None,
34
+ temperature: Optional[float] = None,
35
+ thinking: Optional[Dict] = None,
36
+ tool_choice: Optional[Dict] = None,
37
+ tools: Optional[List[Dict]] = None,
38
+ top_k: Optional[int] = None,
39
+ top_p: Optional[float] = None,
40
+ container: Optional[Dict] = None,
41
+ **kwargs
42
+ ) -> Union[AnthropicMessagesResponse, AsyncIterator]:
43
+ """
44
+ Async wrapper for Anthropic's messages API
45
+
46
+ Args:
47
+ max_tokens (int): Maximum tokens to generate (required)
48
+ messages (List[Dict]): List of message objects with role and content (required)
49
+ model (str): Model name to use (required)
50
+ metadata (Dict, optional): Request metadata
51
+ stop_sequences (List[str], optional): Custom stop sequences
52
+ stream (bool, optional): Whether to stream the response
53
+ system (str, optional): System prompt
54
+ temperature (float, optional): Sampling temperature (0.0 to 1.0)
55
+ thinking (Dict, optional): Extended thinking configuration
56
+ tool_choice (Dict, optional): Tool choice configuration
57
+ tools (List[Dict], optional): List of tool definitions
58
+ top_k (int, optional): Top K sampling parameter
59
+ top_p (float, optional): Nucleus sampling parameter
60
+ container (Dict, optional): Container config with skills for code execution
61
+ **kwargs: Additional arguments
62
+
63
+ Returns:
64
+ Dict: Response from the API
65
+ """
66
+ return await _async_anthropic_messages(
67
+ max_tokens=max_tokens,
68
+ messages=messages,
69
+ model=model,
70
+ metadata=metadata,
71
+ stop_sequences=stop_sequences,
72
+ stream=stream,
73
+ system=system,
74
+ temperature=temperature,
75
+ thinking=thinking,
76
+ tool_choice=tool_choice,
77
+ tools=tools,
78
+ top_k=top_k,
79
+ top_p=top_p,
80
+ container=container,
81
+ **kwargs,
82
+ )
83
+
84
+
85
+ def create(
86
+ max_tokens: int,
87
+ messages: List[Dict],
88
+ model: str,
89
+ metadata: Optional[Dict] = None,
90
+ stop_sequences: Optional[List[str]] = None,
91
+ stream: Optional[bool] = False,
92
+ system: Optional[str] = None,
93
+ temperature: Optional[float] = None,
94
+ thinking: Optional[Dict] = None,
95
+ tool_choice: Optional[Dict] = None,
96
+ tools: Optional[List[Dict]] = None,
97
+ top_k: Optional[int] = None,
98
+ top_p: Optional[float] = None,
99
+ container: Optional[Dict] = None,
100
+ **kwargs
101
+ ) -> Union[
102
+ AnthropicMessagesResponse,
103
+ AsyncIterator[Any],
104
+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]],
105
+ ]:
106
+ """
107
+ Async wrapper for Anthropic's messages API
108
+
109
+ Args:
110
+ max_tokens (int): Maximum tokens to generate (required)
111
+ messages (List[Dict]): List of message objects with role and content (required)
112
+ model (str): Model name to use (required)
113
+ metadata (Dict, optional): Request metadata
114
+ stop_sequences (List[str], optional): Custom stop sequences
115
+ stream (bool, optional): Whether to stream the response
116
+ system (str, optional): System prompt
117
+ temperature (float, optional): Sampling temperature (0.0 to 1.0)
118
+ thinking (Dict, optional): Extended thinking configuration
119
+ tool_choice (Dict, optional): Tool choice configuration
120
+ tools (List[Dict], optional): List of tool definitions
121
+ top_k (int, optional): Top K sampling parameter
122
+ top_p (float, optional): Nucleus sampling parameter
123
+ **kwargs: Additional arguments
124
+
125
+ Returns:
126
+ Dict: Response from the API
127
+ """
128
+ return _sync_anthropic_messages(
129
+ max_tokens=max_tokens,
130
+ messages=messages,
131
+ model=model,
132
+ metadata=metadata,
133
+ stop_sequences=stop_sequences,
134
+ stream=stream,
135
+ system=system,
136
+ temperature=temperature,
137
+ thinking=thinking,
138
+ tool_choice=tool_choice,
139
+ tools=tools,
140
+ top_k=top_k,
141
+ top_p=top_p,
142
+ container=container,
143
+ **kwargs,
144
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/anthropic_interface/messages/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (5.18 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (960 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/_internal_lru_cache.cpython-311.pyc ADDED
Binary file (1.93 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/azure_blob_cache.cpython-311.pyc ADDED
Binary file (6.71 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/base_cache.cpython-311.pyc ADDED
Binary file (3.22 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/caching.cpython-311.pyc ADDED
Binary file (39.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/caching_handler.cpython-311.pyc ADDED
Binary file (37.7 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/disk_cache.cpython-311.pyc ADDED
Binary file (5.44 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/dual_cache.cpython-311.pyc ADDED
Binary file (21.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/gcs_cache.cpython-311.pyc ADDED
Binary file (7.39 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/in_memory_cache.cpython-311.pyc ADDED
Binary file (14.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/llm_caching_handler.cpython-311.pyc ADDED
Binary file (3.28 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/qdrant_semantic_cache.cpython-311.pyc ADDED
Binary file (15.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_cache.cpython-311.pyc ADDED
Binary file (68.2 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_cluster_cache.cpython-311.pyc ADDED
Binary file (5.12 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/redis_semantic_cache.cpython-311.pyc ADDED
Binary file (18.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/caching/__pycache__/s3_cache.cpython-311.pyc ADDED
Binary file (8.86 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.13 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/endpoint_factory.cpython-311.pyc ADDED
Binary file (10.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/main.cpython-311.pyc ADDED
Binary file (37.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/containers/__pycache__/utils.cpython-311.pyc ADDED
Binary file (3.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/evals/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (758 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/evals/__pycache__/main.cpython-311.pyc ADDED
Binary file (54.6 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (346 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/client.cpython-311.pyc ADDED
Binary file (34.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/experimental_mcp_client/__pycache__/tools.cpython-311.pyc ADDED
Binary file (6.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/files/__pycache__/main.cpython-311.pyc ADDED
Binary file (30.7 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/files/__pycache__/utils.cpython-311.pyc ADDED
Binary file (1.84 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/Readme.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Slack Alerting on LiteLLM Gateway
2
+
3
+ This folder contains the Slack Alerting integration for LiteLLM Gateway.
4
+
5
+ ## Folder Structure
6
+
7
+ - `slack_alerting.py`: This is the main file that handles sending different types of alerts
8
+ - `batching_handler.py`: Handles Batching + sending Httpx Post requests to slack. Slack alerts are sent every 10s or when events are greater than X events. Done to ensure litellm has good performance under high traffic
9
+ - `types.py`: This file contains the AlertType enum which is used to define the different types of alerts that can be sent to Slack.
10
+ - `utils.py`: This file contains common utils used specifically for slack alerting
11
+
12
+ ## Budget Alert Types
13
+
14
+ The `budget_alert_types.py` module provides a flexible framework for handling different types of budget alerts:
15
+
16
+ - `BaseBudgetAlertType`: An abstract base class with abstract methods that all alert types must implement:
17
+ - `get_event_group()`: Returns the Litellm_EntityType for the alert
18
+ - `get_event_message()`: Returns the message prefix for the alert
19
+ - `get_id(user_info)`: Returns the ID to use for caching/tracking the alert
20
+
21
+ Concrete implementations include:
22
+ - `ProxyBudgetAlert`: Alerting for proxy-level budget concerns
23
+ - `SoftBudgetAlert`: Alerting when soft budgets are crossed
24
+ - `UserBudgetAlert`: Alerting for user-level budget concerns
25
+ - `TeamBudgetAlert`: Alerting for team-level budget concerns
26
+ - `TokenBudgetAlert`: Alerting for API key budget concerns
27
+ - `ProjectedLimitExceededAlert`: Alerting when projected spend will exceed budget
28
+
29
+ Use the `get_budget_alert_type()` factory function to get the appropriate alert type class for a given alert type string:
30
+
31
+ ```python
32
+ from litellm.integrations.SlackAlerting.budget_alert_types import get_budget_alert_type
33
+
34
+ # Get the appropriate handler
35
+ budget_alert_class = get_budget_alert_type("user_budget")
36
+
37
+ # Use the handler methods
38
+ event_group = budget_alert_class.get_event_group() # Returns Litellm_EntityType.USER
39
+ event_message = budget_alert_class.get_event_message() # Returns "User Budget: "
40
+ cache_id = budget_alert_class.get_id(user_info) # Returns user_id
41
+ ```
42
+
43
+ To add a new budget alert type, simply create a new class that extends `BaseBudgetAlertType` and implements all the required methods, then add it to the dictionary in the `get_budget_alert_type()` function.
44
+
45
+ ## Further Reading
46
+ - [Doc setting up Alerting on LiteLLM Proxy (Gateway)](https://docs.litellm.ai/docs/proxy/alerting)
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/batching_handler.cpython-311.pyc ADDED
Binary file (3.39 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/budget_alert_types.cpython-311.pyc ADDED
Binary file (6.76 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/hanging_request_check.cpython-311.pyc ADDED
Binary file (7.03 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/slack_alerting.cpython-311.pyc ADDED
Binary file (74.6 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/__pycache__/utils.cpython-311.pyc ADDED
Binary file (3.65 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/batching_handler.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handles Batching + sending Httpx Post requests to slack
3
+
4
+ Slack alerts are sent every 10s or when events are greater than X events
5
+
6
+ see custom_batch_logger.py for more details / defaults
7
+ """
8
+
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from litellm._logging import verbose_proxy_logger
12
+
13
+ if TYPE_CHECKING:
14
+ from .slack_alerting import SlackAlerting as _SlackAlerting
15
+
16
+ SlackAlertingType = _SlackAlerting
17
+ else:
18
+ SlackAlertingType = Any
19
+
20
+
21
+ def squash_payloads(queue):
22
+ squashed = {}
23
+ if len(queue) == 0:
24
+ return squashed
25
+ if len(queue) == 1:
26
+ return {"key": {"item": queue[0], "count": 1}}
27
+
28
+ for item in queue:
29
+ url = item["url"]
30
+ alert_type = item["alert_type"]
31
+ _key = (url, alert_type)
32
+
33
+ if _key in squashed:
34
+ squashed[_key]["count"] += 1
35
+ # Merge the payloads
36
+
37
+ else:
38
+ squashed[_key] = {"item": item, "count": 1}
39
+
40
+ return squashed
41
+
42
+
43
+ def _print_alerting_payload_warning(
44
+ payload: dict, slackAlertingInstance: SlackAlertingType
45
+ ):
46
+ """
47
+ Print the payload to the console when
48
+ slackAlertingInstance.alerting_args.log_to_console is True
49
+
50
+ Relevant issue: https://github.com/BerriAI/litellm/issues/7372
51
+ """
52
+ if slackAlertingInstance.alerting_args.log_to_console is True:
53
+ verbose_proxy_logger.warning(payload)
54
+
55
+
56
+ async def send_to_webhook(slackAlertingInstance: SlackAlertingType, item, count):
57
+ """
58
+ Send a single slack alert to the webhook
59
+ """
60
+ import json
61
+
62
+ payload = item.get("payload", {})
63
+ try:
64
+ if count > 1:
65
+ payload["text"] = f"[Num Alerts: {count}]\n\n{payload['text']}"
66
+
67
+ response = await slackAlertingInstance.async_http_handler.post(
68
+ url=item["url"],
69
+ headers=item["headers"],
70
+ data=json.dumps(payload),
71
+ )
72
+ if response.status_code != 200:
73
+ verbose_proxy_logger.debug(
74
+ f"Error sending slack alert to url={item['url']}. Error={response.text}"
75
+ )
76
+ except Exception as e:
77
+ verbose_proxy_logger.debug(f"Error sending slack alert: {str(e)}")
78
+ finally:
79
+ _print_alerting_payload_warning(
80
+ payload, slackAlertingInstance=slackAlertingInstance
81
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/budget_alert_types.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Literal
3
+
4
+ from litellm.proxy._types import CallInfo
5
+
6
+
7
+ class BaseBudgetAlertType(ABC):
8
+ """Base class for different budget alert types"""
9
+
10
+ @abstractmethod
11
+ def get_event_message(self) -> str:
12
+ """Return the event message for this alert type"""
13
+ pass
14
+
15
+ @abstractmethod
16
+ def get_id(self, user_info: CallInfo) -> str:
17
+ """Return the ID to use for caching/tracking this alert"""
18
+ pass
19
+
20
+
21
+ class ProxyBudgetAlert(BaseBudgetAlertType):
22
+ def get_event_message(self) -> str:
23
+ return "Proxy Budget: "
24
+
25
+ def get_id(self, user_info: CallInfo) -> str:
26
+ return "default_id"
27
+
28
+
29
+ class SoftBudgetAlert(BaseBudgetAlertType):
30
+ def get_event_message(self) -> str:
31
+ return "Soft Budget Crossed: "
32
+
33
+ def get_id(self, user_info: CallInfo) -> str:
34
+ return user_info.token or "default_id"
35
+
36
+
37
+ class UserBudgetAlert(BaseBudgetAlertType):
38
+ def get_event_message(self) -> str:
39
+ return "User Budget: "
40
+
41
+ def get_id(self, user_info: CallInfo) -> str:
42
+ return user_info.user_id or "default_id"
43
+
44
+
45
+ class TeamBudgetAlert(BaseBudgetAlertType):
46
+ def get_event_message(self) -> str:
47
+ return "Team Budget: "
48
+
49
+ def get_id(self, user_info: CallInfo) -> str:
50
+ return user_info.team_id or "default_id"
51
+
52
+
53
+ class OrganizationBudgetAlert(BaseBudgetAlertType):
54
+ def get_event_message(self) -> str:
55
+ return "Organization Budget: "
56
+
57
+ def get_id(self, user_info: CallInfo) -> str:
58
+ return user_info.organization_id or "default_id"
59
+
60
+
61
+ class TokenBudgetAlert(BaseBudgetAlertType):
62
+ def get_event_message(self) -> str:
63
+ return "Key Budget: "
64
+
65
+ def get_id(self, user_info: CallInfo) -> str:
66
+ return user_info.token or "default_id"
67
+
68
+
69
+ class ProjectedLimitExceededAlert(BaseBudgetAlertType):
70
+ def get_event_message(self) -> str:
71
+ return "Key Budget: Projected Limit Exceeded"
72
+
73
+ def get_id(self, user_info: CallInfo) -> str:
74
+ return user_info.token or "default_id"
75
+
76
+
77
+ class ProjectBudgetAlert(BaseBudgetAlertType):
78
+ def get_event_message(self) -> str:
79
+ return "Project Budget: "
80
+
81
+ def get_id(self, user_info: CallInfo) -> str:
82
+ return user_info.token or "default_id"
83
+
84
+
85
+ def get_budget_alert_type(
86
+ type: Literal[
87
+ "token_budget",
88
+ "user_budget",
89
+ "soft_budget",
90
+ "max_budget_alert",
91
+ "team_budget",
92
+ "organization_budget",
93
+ "proxy_budget",
94
+ "projected_limit_exceeded",
95
+ "project_budget",
96
+ ],
97
+ ) -> BaseBudgetAlertType:
98
+ """Factory function to get the appropriate budget alert type class"""
99
+
100
+ alert_types = {
101
+ "proxy_budget": ProxyBudgetAlert(),
102
+ "soft_budget": SoftBudgetAlert(),
103
+ "user_budget": UserBudgetAlert(),
104
+ "max_budget_alert": TokenBudgetAlert(),
105
+ "team_budget": TeamBudgetAlert(),
106
+ "organization_budget": OrganizationBudgetAlert(),
107
+ "token_budget": TokenBudgetAlert(),
108
+ "projected_limit_exceeded": ProjectedLimitExceededAlert(),
109
+ "project_budget": ProjectBudgetAlert(),
110
+ }
111
+
112
+ if type in alert_types:
113
+ return alert_types[type]
114
+ else:
115
+ return ProxyBudgetAlert()
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/hanging_request_check.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Class to check for LLM API hanging requests
3
+
4
+
5
+ Notes:
6
+ - Do not create tasks that sleep, that can saturate the event loop
7
+ - Do not store large objects (eg. messages in memory) that can increase RAM usage
8
+ """
9
+
10
+ import asyncio
11
+ from typing import TYPE_CHECKING, Any, Optional
12
+
13
+ import litellm
14
+ from litellm._logging import verbose_proxy_logger
15
+ from litellm.caching.in_memory_cache import InMemoryCache
16
+ from litellm.litellm_core_utils.core_helpers import get_litellm_metadata_from_kwargs
17
+ from litellm.types.integrations.slack_alerting import (
18
+ HANGING_ALERT_BUFFER_TIME_SECONDS,
19
+ MAX_OLDEST_HANGING_REQUESTS_TO_CHECK,
20
+ HangingRequestData,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
25
+ else:
26
+ SlackAlerting = Any
27
+
28
+
29
+ class AlertingHangingRequestCheck:
30
+ """
31
+ Class to safely handle checking hanging requests alerts
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ slack_alerting_object: SlackAlerting,
37
+ ):
38
+ self.slack_alerting_object = slack_alerting_object
39
+ self.hanging_request_cache = InMemoryCache(
40
+ default_ttl=int(
41
+ self.slack_alerting_object.alerting_threshold
42
+ + HANGING_ALERT_BUFFER_TIME_SECONDS
43
+ ),
44
+ )
45
+
46
+ async def add_request_to_hanging_request_check(
47
+ self,
48
+ request_data: Optional[dict] = None,
49
+ ):
50
+ """
51
+ Add a request to the hanging request cache. This is the list of request_ids that gets periodicall checked for hanging requests
52
+ """
53
+ if request_data is None:
54
+ return
55
+
56
+ request_metadata = get_litellm_metadata_from_kwargs(kwargs=request_data)
57
+ model = request_data.get("model", "")
58
+ api_base: Optional[str] = None
59
+
60
+ if request_data.get("deployment", None) is not None and isinstance(
61
+ request_data["deployment"], dict
62
+ ):
63
+ api_base = litellm.get_api_base(
64
+ model=model,
65
+ optional_params=request_data["deployment"].get("litellm_params", {}),
66
+ )
67
+
68
+ hanging_request_data = HangingRequestData(
69
+ request_id=request_data.get("litellm_call_id", ""),
70
+ model=model,
71
+ api_base=api_base,
72
+ key_alias=request_metadata.get("user_api_key_alias", ""),
73
+ team_alias=request_metadata.get("user_api_key_team_alias", ""),
74
+ )
75
+
76
+ await self.hanging_request_cache.async_set_cache(
77
+ key=hanging_request_data.request_id,
78
+ value=hanging_request_data,
79
+ ttl=int(
80
+ self.slack_alerting_object.alerting_threshold
81
+ + HANGING_ALERT_BUFFER_TIME_SECONDS
82
+ ),
83
+ )
84
+ return
85
+
86
+ async def send_alerts_for_hanging_requests(self):
87
+ """
88
+ Send alerts for hanging requests
89
+ """
90
+ from litellm.proxy.proxy_server import proxy_logging_obj
91
+
92
+ #########################################################
93
+ # Find all requests that have been hanging for more than the alerting threshold
94
+ # Get the last 50 oldest items in the cache and check if they have completed
95
+ #########################################################
96
+ # check if request_id is in internal usage cache
97
+ if proxy_logging_obj.internal_usage_cache is None:
98
+ return
99
+
100
+ hanging_requests = await self.hanging_request_cache.async_get_oldest_n_keys(
101
+ n=MAX_OLDEST_HANGING_REQUESTS_TO_CHECK,
102
+ )
103
+
104
+ for request_id in hanging_requests:
105
+ hanging_request_data: Optional[
106
+ HangingRequestData
107
+ ] = await self.hanging_request_cache.async_get_cache(
108
+ key=request_id,
109
+ )
110
+
111
+ if hanging_request_data is None:
112
+ continue
113
+
114
+ request_status = (
115
+ await proxy_logging_obj.internal_usage_cache.async_get_cache(
116
+ key="request_status:{}".format(hanging_request_data.request_id),
117
+ litellm_parent_otel_span=None,
118
+ local_only=True,
119
+ )
120
+ )
121
+ # this means the request status was either success or fail
122
+ # and is not hanging
123
+ if request_status is not None:
124
+ # clear this request from hanging request cache since the request was either success or failed
125
+ self.hanging_request_cache._remove_key(
126
+ key=request_id,
127
+ )
128
+ continue
129
+
130
+ ################
131
+ # Send the Alert on Slack
132
+ ################
133
+ await self.send_hanging_request_alert(
134
+ hanging_request_data=hanging_request_data
135
+ )
136
+
137
+ return
138
+
139
+ async def check_for_hanging_requests(
140
+ self,
141
+ ):
142
+ """
143
+ Background task that checks all request ids in self.hanging_request_cache to check if they have completed
144
+
145
+ Runs every alerting_threshold/2 seconds to check for hanging requests
146
+ """
147
+ while True:
148
+ verbose_proxy_logger.debug("Checking for hanging requests....")
149
+ await self.send_alerts_for_hanging_requests()
150
+ await asyncio.sleep(self.slack_alerting_object.alerting_threshold / 2)
151
+
152
+ async def send_hanging_request_alert(
153
+ self,
154
+ hanging_request_data: HangingRequestData,
155
+ ):
156
+ """
157
+ Send a hanging request alert
158
+ """
159
+ from litellm.integrations.SlackAlerting.slack_alerting import AlertType
160
+
161
+ ################
162
+ # Send the Alert on Slack
163
+ ################
164
+ request_info = f"""Request Model: `{hanging_request_data.model}`
165
+ API Base: `{hanging_request_data.api_base}`
166
+ Key Alias: `{hanging_request_data.key_alias}`
167
+ Team Alias: `{hanging_request_data.team_alias}`"""
168
+
169
+ alerting_message = f"`Requests are hanging - {self.slack_alerting_object.alerting_threshold}s+ request time`"
170
+ await self.slack_alerting_object.send_alert(
171
+ message=alerting_message + "\n" + request_info,
172
+ level="Medium",
173
+ alert_type=AlertType.llm_requests_hanging,
174
+ alerting_metadata=hanging_request_data.alerting_metadata or {},
175
+ request_model=hanging_request_data.model,
176
+ api_base=hanging_request_data.api_base,
177
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/slack_alerting.py ADDED
@@ -0,0 +1,1994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #### What this does ####
2
+ # Class for sending Slack Alerts #
3
+ import asyncio
4
+ import datetime
5
+ import os
6
+ import random
7
+ import time
8
+ from datetime import timedelta
9
+ from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
10
+
11
+ from openai import APIError
12
+
13
+ import litellm
14
+ import litellm.litellm_core_utils
15
+ import litellm.litellm_core_utils.litellm_logging
16
+ import litellm.types
17
+ from litellm._logging import verbose_logger, verbose_proxy_logger
18
+ from litellm.caching.caching import DualCache
19
+ from litellm.constants import HOURS_IN_A_DAY
20
+ from litellm.integrations.custom_batch_logger import CustomBatchLogger
21
+ from litellm.integrations.SlackAlerting.budget_alert_types import get_budget_alert_type
22
+ from litellm.integrations.SlackAlerting.hanging_request_check import (
23
+ AlertingHangingRequestCheck,
24
+ )
25
+ from litellm.litellm_core_utils.duration_parser import duration_in_seconds
26
+ from litellm.litellm_core_utils.exception_mapping_utils import (
27
+ _add_key_name_and_team_to_alert,
28
+ )
29
+ from litellm.llms.custom_httpx.http_handler import (
30
+ get_async_httpx_client,
31
+ httpxSpecialProvider,
32
+ )
33
+ from litellm.proxy._types import (
34
+ AlertType,
35
+ CallInfo,
36
+ Litellm_EntityType,
37
+ VirtualKeyEvent,
38
+ WebhookEvent,
39
+ )
40
+ from litellm.types.integrations.slack_alerting import *
41
+
42
+ from ..email_templates.templates import *
43
+ from .batching_handler import send_to_webhook, squash_payloads
44
+ from .utils import process_slack_alerting_variables
45
+
46
+ if TYPE_CHECKING:
47
+ from litellm.router import Router as _Router
48
+
49
+ Router = _Router
50
+ else:
51
+ Router = Any
52
+
53
+
54
+ class SlackAlerting(CustomBatchLogger):
55
+ """
56
+ Class for sending Slack Alerts
57
+ """
58
+
59
+ # Class variables or attributes
60
+ def __init__(
61
+ self,
62
+ internal_usage_cache: Optional[DualCache] = None,
63
+ alerting_threshold: Optional[
64
+ float
65
+ ] = None, # threshold for slow / hanging llm responses (in seconds)
66
+ alerting: Optional[List] = [],
67
+ alert_types: List[AlertType] = DEFAULT_ALERT_TYPES,
68
+ alert_to_webhook_url: Optional[
69
+ Dict[AlertType, Union[List[str], str]]
70
+ ] = None, # if user wants to separate alerts to diff channels
71
+ alerting_args={},
72
+ default_webhook_url: Optional[str] = None,
73
+ alert_type_config: Optional[Dict[str, dict]] = None,
74
+ **kwargs,
75
+ ):
76
+ if alerting_threshold is None:
77
+ alerting_threshold = 300
78
+ self.alerting_threshold = alerting_threshold
79
+ self.alerting = alerting
80
+ self.alert_types = alert_types
81
+ self.internal_usage_cache = internal_usage_cache or DualCache()
82
+ self.async_http_handler = get_async_httpx_client(
83
+ llm_provider=httpxSpecialProvider.LoggingCallback
84
+ )
85
+ self.alert_to_webhook_url = process_slack_alerting_variables(
86
+ alert_to_webhook_url=alert_to_webhook_url
87
+ )
88
+ self.is_running = False
89
+ self.alerting_args = SlackAlertingArgs(**alerting_args)
90
+ self.default_webhook_url = default_webhook_url
91
+ self.flush_lock = asyncio.Lock()
92
+ self.periodic_started = False
93
+ self.hanging_request_check = AlertingHangingRequestCheck(
94
+ slack_alerting_object=self,
95
+ )
96
+ self.alert_type_config: Dict[str, AlertTypeConfig] = {}
97
+ if alert_type_config:
98
+ for key, val in alert_type_config.items():
99
+ self.alert_type_config[key] = (
100
+ AlertTypeConfig(**val) if isinstance(val, dict) else val
101
+ )
102
+ self.digest_buckets: Dict[str, DigestEntry] = {}
103
+ self.digest_lock = asyncio.Lock()
104
+ super().__init__(**kwargs, flush_lock=self.flush_lock)
105
+
106
+ def update_values(
107
+ self,
108
+ alerting: Optional[List] = None,
109
+ alerting_threshold: Optional[float] = None,
110
+ alert_types: Optional[List[AlertType]] = None,
111
+ alert_to_webhook_url: Optional[Dict[AlertType, Union[List[str], str]]] = None,
112
+ alerting_args: Optional[Dict] = None,
113
+ llm_router: Optional[Router] = None,
114
+ alert_type_config: Optional[Dict[str, dict]] = None,
115
+ ):
116
+ if alerting is not None:
117
+ self.alerting = alerting
118
+ asyncio.create_task(self.periodic_flush())
119
+ self.periodic_started = True
120
+ if alerting_threshold is not None:
121
+ self.alerting_threshold = alerting_threshold
122
+ if alert_types is not None:
123
+ self.alert_types = alert_types
124
+ if alerting_args is not None:
125
+ self.alerting_args = SlackAlertingArgs(**alerting_args)
126
+ if not self.periodic_started:
127
+ asyncio.create_task(self.periodic_flush())
128
+ self.periodic_started = True
129
+ if alert_type_config is not None:
130
+ for key, val in alert_type_config.items():
131
+ self.alert_type_config[key] = (
132
+ AlertTypeConfig(**val) if isinstance(val, dict) else val
133
+ )
134
+
135
+ if alert_to_webhook_url is not None:
136
+ # update the dict
137
+ if self.alert_to_webhook_url is None:
138
+ self.alert_to_webhook_url = process_slack_alerting_variables(
139
+ alert_to_webhook_url=alert_to_webhook_url
140
+ )
141
+ else:
142
+ _new_values = (
143
+ process_slack_alerting_variables(
144
+ alert_to_webhook_url=alert_to_webhook_url
145
+ )
146
+ or {}
147
+ )
148
+ self.alert_to_webhook_url.update(_new_values)
149
+ if llm_router is not None:
150
+ self.llm_router = llm_router
151
+
152
+ def _prepare_outage_value_for_cache(
153
+ self, outage_value: Union[dict, ProviderRegionOutageModel, OutageModel]
154
+ ) -> dict:
155
+ """
156
+ Helper method to prepare outage value for Redis caching.
157
+ Converts set objects to lists for JSON serialization.
158
+ """
159
+ # Convert to dict for processing
160
+ cache_value = dict(outage_value)
161
+
162
+ if "deployment_ids" in cache_value and isinstance(
163
+ cache_value["deployment_ids"], set
164
+ ):
165
+ cache_value["deployment_ids"] = list(cache_value["deployment_ids"])
166
+ return cache_value
167
+
168
+ def _restore_outage_value_from_cache(
169
+ self, outage_value: Optional[dict]
170
+ ) -> Optional[dict]:
171
+ """
172
+ Helper method to restore outage value after retrieving from cache.
173
+ Converts list objects back to sets for proper handling.
174
+ """
175
+ if outage_value and isinstance(outage_value.get("deployment_ids"), list):
176
+ outage_value["deployment_ids"] = set(outage_value["deployment_ids"])
177
+ return outage_value
178
+
179
+ async def deployment_in_cooldown(self):
180
+ pass
181
+
182
+ async def deployment_removed_from_cooldown(self):
183
+ pass
184
+
185
+ def _all_possible_alert_types(self):
186
+ # used by the UI to show all supported alert types
187
+ # Note: This is not the alerts the user has configured, instead it's all possible alert types a user can select
188
+ # return list of all values AlertType enum
189
+ return list(AlertType)
190
+
191
+ def _response_taking_too_long_callback_helper(
192
+ self,
193
+ kwargs, # kwargs to completion
194
+ start_time,
195
+ end_time, # start/end time
196
+ ):
197
+ try:
198
+ time_difference = end_time - start_time
199
+ # Convert the timedelta to float (in seconds)
200
+ time_difference_float = time_difference.total_seconds()
201
+ litellm_params = kwargs.get("litellm_params", {})
202
+ model = kwargs.get("model", "")
203
+ api_base = litellm.get_api_base(model=model, optional_params=litellm_params)
204
+ messages = kwargs.get("messages", None)
205
+ # if messages does not exist fallback to "input"
206
+ if messages is None:
207
+ messages = kwargs.get("input", None)
208
+
209
+ # only use first 100 chars for alerting
210
+ _messages = str(messages)[:100]
211
+
212
+ return time_difference_float, model, api_base, _messages
213
+ except Exception as e:
214
+ raise e
215
+
216
+ def _get_deployment_latencies_to_alert(self, metadata=None):
217
+ if metadata is None:
218
+ return None
219
+
220
+ if "_latency_per_deployment" in metadata:
221
+ # Translate model_id to -> api_base
222
+ # _latency_per_deployment is a dictionary that looks like this:
223
+ """
224
+ _latency_per_deployment: {
225
+ api_base: 0.01336697916666667
226
+ }
227
+ """
228
+ _message_to_send = ""
229
+ _deployment_latencies = metadata["_latency_per_deployment"]
230
+ if len(_deployment_latencies) == 0:
231
+ return None
232
+ _deployment_latency_map: Optional[dict] = None
233
+ try:
234
+ # try sorting deployments by latency
235
+ _deployment_latencies = sorted(
236
+ _deployment_latencies.items(), key=lambda x: x[1]
237
+ )
238
+ _deployment_latency_map = dict(_deployment_latencies)
239
+ except Exception:
240
+ pass
241
+
242
+ if _deployment_latency_map is None:
243
+ return
244
+
245
+ for api_base, latency in _deployment_latency_map.items():
246
+ _message_to_send += f"\n{api_base}: {round(latency,2)}s"
247
+ _message_to_send = "```" + _message_to_send + "```"
248
+ return _message_to_send
249
+
250
+ async def response_taking_too_long_callback(
251
+ self,
252
+ kwargs, # kwargs to completion
253
+ completion_response, # response from completion
254
+ start_time,
255
+ end_time, # start/end time
256
+ ):
257
+ if self.alerting is None or self.alert_types is None:
258
+ return
259
+
260
+ (
261
+ time_difference_float,
262
+ model,
263
+ api_base,
264
+ messages,
265
+ ) = self._response_taking_too_long_callback_helper(
266
+ kwargs=kwargs,
267
+ start_time=start_time,
268
+ end_time=end_time,
269
+ )
270
+ if litellm.turn_off_message_logging or litellm.redact_messages_in_exceptions:
271
+ messages = "Message not logged. litellm.redact_messages_in_exceptions=True"
272
+ request_info = f"\nRequest Model: `{model}`\nAPI Base: `{api_base}`\nMessages: `{messages}`"
273
+ slow_message = f"`Responses are slow - {round(time_difference_float,2)}s response time > Alerting threshold: {self.alerting_threshold}s`"
274
+ alerting_metadata: dict = {}
275
+ if time_difference_float > self.alerting_threshold:
276
+ # add deployment latencies to alert
277
+ if (
278
+ kwargs is not None
279
+ and "litellm_params" in kwargs
280
+ and "metadata" in kwargs["litellm_params"]
281
+ ):
282
+ _metadata: dict = kwargs["litellm_params"]["metadata"]
283
+ request_info = _add_key_name_and_team_to_alert(
284
+ request_info=request_info, metadata=_metadata
285
+ )
286
+
287
+ _deployment_latency_map = self._get_deployment_latencies_to_alert(
288
+ metadata=_metadata
289
+ )
290
+ if _deployment_latency_map is not None:
291
+ request_info += (
292
+ f"\nAvailable Deployment Latencies\n{_deployment_latency_map}"
293
+ )
294
+
295
+ if "alerting_metadata" in _metadata:
296
+ alerting_metadata = _metadata["alerting_metadata"]
297
+ await self.send_alert(
298
+ message=slow_message + request_info,
299
+ level="Low",
300
+ alert_type=AlertType.llm_too_slow,
301
+ alerting_metadata=alerting_metadata,
302
+ request_model=model,
303
+ api_base=api_base,
304
+ )
305
+
306
+ async def async_update_daily_reports(
307
+ self, deployment_metrics: DeploymentMetrics
308
+ ) -> int:
309
+ """
310
+ Store the perf by deployment in cache
311
+ - Number of failed requests per deployment
312
+ - Latency / output tokens per deployment
313
+
314
+ 'deployment_id:daily_metrics:failed_requests'
315
+ 'deployment_id:daily_metrics:latency_per_output_token'
316
+
317
+ Returns
318
+ int - count of metrics set (1 - if just latency, 2 - if failed + latency)
319
+ """
320
+
321
+ return_val = 0
322
+ try:
323
+ ## FAILED REQUESTS ##
324
+ if deployment_metrics.failed_request:
325
+ await self.internal_usage_cache.async_increment_cache(
326
+ key="{}:{}".format(
327
+ deployment_metrics.id,
328
+ SlackAlertingCacheKeys.failed_requests_key.value,
329
+ ),
330
+ value=1,
331
+ parent_otel_span=None, # no attached request, this is a background operation
332
+ )
333
+
334
+ return_val += 1
335
+
336
+ ## LATENCY ##
337
+ if deployment_metrics.latency_per_output_token is not None:
338
+ await self.internal_usage_cache.async_increment_cache(
339
+ key="{}:{}".format(
340
+ deployment_metrics.id, SlackAlertingCacheKeys.latency_key.value
341
+ ),
342
+ value=deployment_metrics.latency_per_output_token,
343
+ parent_otel_span=None, # no attached request, this is a background operation
344
+ )
345
+
346
+ return_val += 1
347
+
348
+ return return_val
349
+ except Exception:
350
+ return 0
351
+
352
+ async def send_daily_reports(self, router) -> bool: # noqa: PLR0915
353
+ """
354
+ Send a daily report on:
355
+ - Top 5 deployments with most failed requests
356
+ - Top 5 slowest deployments (normalized by latency/output tokens)
357
+
358
+ Get the value from redis cache (if available) or in-memory and send it
359
+
360
+ Cleanup:
361
+ - reset values in cache -> prevent memory leak
362
+
363
+ Returns:
364
+ True -> if successfuly sent
365
+ False -> if not sent
366
+ """
367
+
368
+ ids = router.get_model_ids()
369
+
370
+ # get keys
371
+ failed_request_keys = [
372
+ "{}:{}".format(id, SlackAlertingCacheKeys.failed_requests_key.value)
373
+ for id in ids
374
+ ]
375
+ latency_keys = [
376
+ "{}:{}".format(id, SlackAlertingCacheKeys.latency_key.value) for id in ids
377
+ ]
378
+
379
+ combined_metrics_keys = failed_request_keys + latency_keys # reduce cache calls
380
+
381
+ combined_metrics_values = await self.internal_usage_cache.async_batch_get_cache(
382
+ keys=combined_metrics_keys
383
+ ) # [1, 2, None, ..]
384
+
385
+ if combined_metrics_values is None:
386
+ return False
387
+
388
+ all_none = True
389
+ for val in combined_metrics_values:
390
+ if val is not None and val > 0:
391
+ all_none = False
392
+ break
393
+
394
+ if all_none:
395
+ return False
396
+
397
+ failed_request_values = combined_metrics_values[
398
+ : len(failed_request_keys)
399
+ ] # # [1, 2, None, ..]
400
+ latency_values = combined_metrics_values[len(failed_request_keys) :]
401
+
402
+ # find top 5 failed
403
+ ## Replace None values with a placeholder value (-1 in this case)
404
+ placeholder_value = 0
405
+ replaced_failed_values = [
406
+ value if value is not None else placeholder_value
407
+ for value in failed_request_values
408
+ ]
409
+
410
+ ## Get the indices of top 5 keys with the highest numerical values (ignoring None and 0 values)
411
+ top_5_failed = sorted(
412
+ range(len(replaced_failed_values)),
413
+ key=lambda i: replaced_failed_values[i],
414
+ reverse=True,
415
+ )[:5]
416
+ top_5_failed = [
417
+ index for index in top_5_failed if replaced_failed_values[index] > 0
418
+ ]
419
+
420
+ # find top 5 slowest
421
+ # Replace None values with a placeholder value (-1 in this case)
422
+ placeholder_value = 0
423
+ replaced_slowest_values = [
424
+ value if value is not None else placeholder_value
425
+ for value in latency_values
426
+ ]
427
+
428
+ # Get the indices of top 5 values with the highest numerical values (ignoring None and 0 values)
429
+ top_5_slowest = sorted(
430
+ range(len(replaced_slowest_values)),
431
+ key=lambda i: replaced_slowest_values[i],
432
+ reverse=True,
433
+ )[:5]
434
+ top_5_slowest = [
435
+ index for index in top_5_slowest if replaced_slowest_values[index] > 0
436
+ ]
437
+
438
+ # format alert -> return the litellm model name + api base
439
+ message = f"\n\nTime: `{time.time()}`s\nHere are today's key metrics 📈: \n\n"
440
+
441
+ message += "\n\n*❗️ Top Deployments with Most Failed Requests:*\n\n"
442
+ if not top_5_failed:
443
+ message += "\tNone\n"
444
+ for i in range(len(top_5_failed)):
445
+ key = failed_request_keys[top_5_failed[i]].split(":")[0]
446
+ _deployment = router.get_model_info(key)
447
+ if isinstance(_deployment, dict):
448
+ deployment_name = _deployment["litellm_params"].get("model", "")
449
+ else:
450
+ return False
451
+
452
+ api_base = litellm.get_api_base(
453
+ model=deployment_name,
454
+ optional_params=(
455
+ _deployment["litellm_params"] if _deployment is not None else {}
456
+ ),
457
+ )
458
+ if api_base is None:
459
+ api_base = ""
460
+ value = replaced_failed_values[top_5_failed[i]]
461
+ message += f"\t{i+1}. Deployment: `{deployment_name}`, Failed Requests: `{value}`, API Base: `{api_base}`\n"
462
+
463
+ message += "\n\n*😅 Top Slowest Deployments:*\n\n"
464
+ if not top_5_slowest:
465
+ message += "\tNone\n"
466
+ for i in range(len(top_5_slowest)):
467
+ key = latency_keys[top_5_slowest[i]].split(":")[0]
468
+ _deployment = router.get_model_info(key)
469
+ if _deployment is not None:
470
+ deployment_name = _deployment["litellm_params"].get("model", "")
471
+ else:
472
+ deployment_name = ""
473
+ api_base = litellm.get_api_base(
474
+ model=deployment_name,
475
+ optional_params=(
476
+ _deployment["litellm_params"] if _deployment is not None else {}
477
+ ),
478
+ )
479
+ value = round(replaced_slowest_values[top_5_slowest[i]], 3)
480
+ message += f"\t{i+1}. Deployment: `{deployment_name}`, Latency per output token: `{value}s/token`, API Base: `{api_base}`\n\n"
481
+
482
+ # cache cleanup -> reset values to 0
483
+ latency_cache_keys = [(key, 0) for key in latency_keys]
484
+ failed_request_cache_keys = [(key, 0) for key in failed_request_keys]
485
+ combined_metrics_cache_keys = latency_cache_keys + failed_request_cache_keys
486
+ await self.internal_usage_cache.async_set_cache_pipeline(
487
+ cache_list=combined_metrics_cache_keys
488
+ )
489
+
490
+ message += f"\n\nNext Run is at: `{time.time() + self.alerting_args.daily_report_frequency}`s"
491
+
492
+ # send alert
493
+ await self.send_alert(
494
+ message=message,
495
+ level="Low",
496
+ alert_type=AlertType.daily_reports,
497
+ alerting_metadata={},
498
+ )
499
+
500
+ return True
501
+
502
+ async def response_taking_too_long(
503
+ self,
504
+ request_data: Optional[dict] = None,
505
+ ):
506
+ if self.alerting is None or self.alert_types is None:
507
+ return
508
+
509
+ if AlertType.llm_requests_hanging not in self.alert_types:
510
+ return
511
+
512
+ await self.hanging_request_check.add_request_to_hanging_request_check(
513
+ request_data=request_data
514
+ )
515
+
516
+ async def failed_tracking_alert(self, error_message: str, failing_model: str):
517
+ """
518
+ Raise alert when tracking failed for specific model
519
+
520
+ Args:
521
+ error_message (str): Error message
522
+ failing_model (str): Model that failed tracking
523
+ """
524
+ if self.alerting is None or self.alert_types is None:
525
+ # do nothing if alerting is not switched on
526
+ return
527
+ if "failed_tracking_spend" not in self.alert_types:
528
+ return
529
+
530
+ _cache: DualCache = self.internal_usage_cache
531
+ message = "Failed Tracking Cost for " + error_message
532
+ _cache_key = "budget_alerts:failed_tracking:{}".format(failing_model)
533
+ result = await _cache.async_get_cache(key=_cache_key)
534
+ if result is None:
535
+ await self.send_alert(
536
+ message=message,
537
+ level="High",
538
+ alert_type=AlertType.failed_tracking_spend,
539
+ alerting_metadata={},
540
+ )
541
+ await _cache.async_set_cache(
542
+ key=_cache_key,
543
+ value="SENT",
544
+ ttl=self.alerting_args.budget_alert_ttl,
545
+ )
546
+
547
+ async def budget_alerts(
548
+ self,
549
+ type: Literal[
550
+ "token_budget",
551
+ "user_budget",
552
+ "soft_budget",
553
+ "max_budget_alert",
554
+ "team_budget",
555
+ "organization_budget",
556
+ "proxy_budget",
557
+ "projected_limit_exceeded",
558
+ "project_budget",
559
+ ],
560
+ user_info: CallInfo,
561
+ ):
562
+ """
563
+ Send a budget alert on slack or webhook
564
+
565
+ Args:
566
+ type: The type of budget alert to send
567
+ user_info: The user info to send the alert for
568
+ """
569
+ ## PREVENTITIVE ALERTING ## - https://github.com/BerriAI/litellm/issues/2727
570
+ # - Alert once within 24hr period
571
+ # - Cache this information
572
+ # - Don't re-alert, if alert already sent
573
+ _cache: DualCache = self.internal_usage_cache
574
+
575
+ if self.alerting is None or self.alert_types is None:
576
+ # do nothing if alerting is not switched on
577
+ return
578
+ if "budget_alerts" not in self.alert_types:
579
+ return
580
+
581
+ # Get the appropriate budget alert type handler
582
+ budget_alert_class = get_budget_alert_type(type)
583
+ _id = budget_alert_class.get_id(user_info)
584
+ user_info_json = user_info.model_dump(exclude_none=True)
585
+ user_info_str = self._get_user_info_str(user_info)
586
+ event_message = budget_alert_class.get_event_message()
587
+
588
+ # Set default event unless we're in projected_limit_exceeded
589
+ event: Optional[
590
+ Literal[
591
+ "budget_crossed",
592
+ "threshold_crossed",
593
+ "projected_limit_exceeded",
594
+ "soft_budget_crossed",
595
+ ]
596
+ ] = (
597
+ "projected_limit_exceeded" if type == "projected_limit_exceeded" else None
598
+ )
599
+
600
+ webhook_event: Optional[WebhookEvent] = None
601
+
602
+ # percent of max_budget left to spend
603
+ if user_info.max_budget is None and user_info.soft_budget is None:
604
+ return
605
+
606
+ # check if crossed budget
607
+ event, event_message = self._get_event_and_event_message(
608
+ event=event,
609
+ user_info=user_info,
610
+ event_message=event_message,
611
+ )
612
+
613
+ # send alert
614
+ if event is not None and user_info.event_group is not None:
615
+ _cache_key = "budget_alerts:{}:{}".format(event, _id)
616
+ result = await _cache.async_get_cache(key=_cache_key)
617
+ if result is None:
618
+ webhook_event = WebhookEvent(
619
+ event=event,
620
+ event_message=event_message,
621
+ **user_info_json,
622
+ )
623
+ await self.send_alert(
624
+ message=event_message + "\n\n" + user_info_str,
625
+ level="High",
626
+ alert_type=AlertType.budget_alerts,
627
+ user_info=webhook_event,
628
+ alerting_metadata={},
629
+ )
630
+ await _cache.async_set_cache(
631
+ key=_cache_key,
632
+ value="SENT",
633
+ ttl=self.alerting_args.budget_alert_ttl,
634
+ )
635
+
636
+ return
637
+ return
638
+
639
+ def _get_event_and_event_message(
640
+ self,
641
+ user_info: CallInfo,
642
+ event: Optional[
643
+ Literal[
644
+ "budget_crossed",
645
+ "threshold_crossed",
646
+ "soft_budget_crossed",
647
+ "projected_limit_exceeded",
648
+ ]
649
+ ],
650
+ event_message: str,
651
+ ) -> Tuple[
652
+ Optional[
653
+ Literal[
654
+ "budget_crossed",
655
+ "threshold_crossed",
656
+ "soft_budget_crossed",
657
+ "projected_limit_exceeded",
658
+ ]
659
+ ],
660
+ str,
661
+ ]:
662
+ """
663
+ Get the event and event message for a budget alert
664
+
665
+ This will append any new information to the event_message
666
+
667
+ Handles Max Budget and Soft Budget Alerts
668
+ """
669
+ percent_left: float = self._get_percent_of_max_budget_left(user_info=user_info)
670
+
671
+ #####################################################################
672
+ # SOFT BUDGET CHECK
673
+ # Check if the key/team/user has a soft budget set and they have crossed it
674
+ #####################################################################
675
+ if user_info.soft_budget is not None:
676
+ if user_info.spend >= user_info.soft_budget:
677
+ event = "soft_budget_crossed"
678
+ event_message += f"Total Soft Budget:`{user_info.soft_budget}`"
679
+
680
+ #####################################################################
681
+ # MAX BUDGET CHECK
682
+ # Check if the key/team/user has a max budget set and they have either
683
+ ## a. Crossed their max budget
684
+ ## b. Either 5% or 15% of their max budget is left
685
+ #####################################################################
686
+ if user_info.max_budget is not None:
687
+ if user_info.spend >= user_info.max_budget:
688
+ event = "budget_crossed"
689
+ event_message += (
690
+ f"Budget Crossed\n Total Budget:`{user_info.max_budget}`"
691
+ )
692
+ elif percent_left <= SLACK_ALERTING_THRESHOLD_5_PERCENT:
693
+ event = "threshold_crossed"
694
+ event_message += "5% Threshold Crossed "
695
+ elif percent_left <= SLACK_ALERTING_THRESHOLD_15_PERCENT:
696
+ event = "threshold_crossed"
697
+ event_message += "15% Threshold Crossed"
698
+
699
+ return event, event_message
700
+
701
+ def _get_percent_of_max_budget_left(self, user_info: CallInfo) -> float:
702
+ """
703
+ Get the percent of the max budget that is left
704
+ """
705
+ percent_left: float = 0.0
706
+ current_spend: float = user_info.spend
707
+ max_budget: Optional[float] = user_info.max_budget
708
+ if max_budget is None:
709
+ return percent_left
710
+ if max_budget <= 0:
711
+ return percent_left
712
+ percent_left = (max_budget - current_spend) / max_budget
713
+ return percent_left
714
+
715
+ def _get_user_info_str(self, user_info: CallInfo) -> str:
716
+ """
717
+ Create a standard message for a budget alert
718
+ """
719
+ _all_fields_as_dict = user_info.model_dump(exclude_none=True)
720
+ _all_fields_as_dict.pop("token")
721
+ msg = ""
722
+ for k, v in _all_fields_as_dict.items():
723
+ if isinstance(v, Litellm_EntityType):
724
+ v = v.value
725
+ msg += f"*{k}:* `{v}`\n"
726
+
727
+ return msg
728
+
729
+ async def customer_spend_alert(
730
+ self,
731
+ token: Optional[str],
732
+ key_alias: Optional[str],
733
+ end_user_id: Optional[str],
734
+ response_cost: Optional[float],
735
+ max_budget: Optional[float],
736
+ ):
737
+ if (
738
+ self.alerting is not None
739
+ and "webhook" in self.alerting
740
+ and end_user_id is not None
741
+ and token is not None
742
+ and response_cost is not None
743
+ ):
744
+ # log customer spend
745
+ event = WebhookEvent(
746
+ spend=response_cost,
747
+ max_budget=max_budget,
748
+ token=token,
749
+ customer_id=end_user_id,
750
+ user_id=None,
751
+ team_id=None,
752
+ user_email=None,
753
+ key_alias=key_alias,
754
+ projected_exceeded_date=None,
755
+ projected_spend=None,
756
+ event="spend_tracked",
757
+ event_group=Litellm_EntityType.END_USER,
758
+ event_message="Customer spend tracked. Customer={}, spend={}".format(
759
+ end_user_id, response_cost
760
+ ),
761
+ )
762
+
763
+ await self.send_webhook_alert(webhook_event=event)
764
+
765
+ def _count_outage_alerts(self, alerts: List[int]) -> str:
766
+ """
767
+ Parameters:
768
+ - alerts: List[int] -> list of error codes (either 408 or 500+)
769
+
770
+ Returns:
771
+ - str -> formatted string. This is an alert message, giving a human-friendly description of the errors.
772
+ """
773
+ error_breakdown = {"Timeout Errors": 0, "API Errors": 0, "Unknown Errors": 0}
774
+ for alert in alerts:
775
+ if alert == 408:
776
+ error_breakdown["Timeout Errors"] += 1
777
+ elif alert >= 500:
778
+ error_breakdown["API Errors"] += 1
779
+ else:
780
+ error_breakdown["Unknown Errors"] += 1
781
+
782
+ error_msg = ""
783
+ for key, value in error_breakdown.items():
784
+ if value > 0:
785
+ error_msg += "\n{}: {}\n".format(key, value)
786
+
787
+ return error_msg
788
+
789
+ def _outage_alert_msg_factory(
790
+ self,
791
+ alert_type: Literal["Major", "Minor"],
792
+ key: Literal["Model", "Region"],
793
+ key_val: str,
794
+ provider: str,
795
+ api_base: Optional[str],
796
+ outage_value: BaseOutageModel,
797
+ ) -> str:
798
+ """Format an alert message for slack"""
799
+ headers = {f"{key} Name": key_val, "Provider": provider}
800
+ if api_base is not None:
801
+ headers["API Base"] = api_base # type: ignore
802
+
803
+ headers_str = "\n"
804
+ for k, v in headers.items():
805
+ headers_str += f"*{k}:* `{v}`\n"
806
+ return f"""\n\n
807
+ *⚠️ {alert_type} Service Outage*
808
+
809
+ {headers_str}
810
+
811
+ *Errors:*
812
+ {self._count_outage_alerts(alerts=outage_value["alerts"])}
813
+
814
+ *Last Check:* `{round(time.time() - outage_value["last_updated_at"], 4)}s ago`\n\n
815
+ """
816
+
817
+ async def region_outage_alerts(
818
+ self,
819
+ exception: APIError,
820
+ deployment_id: str,
821
+ ) -> None:
822
+ """
823
+ Send slack alert if specific provider region is having an outage.
824
+
825
+ Track for 408 (Timeout) and >=500 Error codes
826
+ """
827
+ ## CREATE (PROVIDER+REGION) ID ##
828
+ if self.llm_router is None:
829
+ return
830
+
831
+ deployment = self.llm_router.get_deployment(model_id=deployment_id)
832
+
833
+ if deployment is None:
834
+ return
835
+
836
+ model = deployment.litellm_params.model
837
+ ### GET PROVIDER ###
838
+ provider = deployment.litellm_params.custom_llm_provider
839
+ if provider is None:
840
+ model, provider, _, _ = litellm.get_llm_provider(model=model)
841
+
842
+ ### GET REGION ###
843
+ region_name = deployment.litellm_params.region_name
844
+ if region_name is None:
845
+ region_name = litellm.utils._get_model_region(
846
+ custom_llm_provider=provider, litellm_params=deployment.litellm_params
847
+ )
848
+
849
+ if region_name is None:
850
+ return
851
+
852
+ ### UNIQUE CACHE KEY ###
853
+ cache_key = provider + region_name
854
+
855
+ outage_value: Optional[
856
+ ProviderRegionOutageModel
857
+ ] = await self.internal_usage_cache.async_get_cache(key=cache_key)
858
+
859
+ # Convert deployment_ids back to set if it was stored as a list
860
+ if outage_value is not None:
861
+ outage_value = self._restore_outage_value_from_cache(outage_value) # type: ignore
862
+
863
+ if (
864
+ getattr(exception, "status_code", None) is None
865
+ or (
866
+ exception.status_code != 408 # type: ignore
867
+ and exception.status_code < 500 # type: ignore
868
+ )
869
+ or self.llm_router is None
870
+ ):
871
+ return
872
+
873
+ if outage_value is None:
874
+ _deployment_set = set()
875
+ _deployment_set.add(deployment_id)
876
+ outage_value = ProviderRegionOutageModel(
877
+ provider_region_id=cache_key,
878
+ alerts=[exception.status_code], # type: ignore
879
+ minor_alert_sent=False,
880
+ major_alert_sent=False,
881
+ last_updated_at=time.time(),
882
+ deployment_ids=_deployment_set,
883
+ )
884
+
885
+ ## add to cache ##
886
+ # Convert set to list for JSON serialization
887
+ cache_value = self._prepare_outage_value_for_cache(outage_value)
888
+ await self.internal_usage_cache.async_set_cache(
889
+ key=cache_key,
890
+ value=cache_value,
891
+ ttl=self.alerting_args.region_outage_alert_ttl,
892
+ )
893
+ return
894
+
895
+ if len(outage_value["alerts"]) < self.alerting_args.max_outage_alert_list_size:
896
+ outage_value["alerts"].append(exception.status_code) # type: ignore
897
+ else: # prevent memory leaks
898
+ pass
899
+ _deployment_set = outage_value["deployment_ids"]
900
+ _deployment_set.add(deployment_id)
901
+ outage_value["deployment_ids"] = _deployment_set
902
+ outage_value["last_updated_at"] = time.time()
903
+
904
+ ## MINOR OUTAGE ALERT SENT ##
905
+ if (
906
+ outage_value["minor_alert_sent"] is False
907
+ and len(outage_value["alerts"])
908
+ >= self.alerting_args.minor_outage_alert_threshold
909
+ and len(_deployment_set) > 1 # make sure it's not just 1 bad deployment
910
+ ):
911
+ msg = self._outage_alert_msg_factory(
912
+ alert_type="Minor",
913
+ key="Region",
914
+ key_val=region_name,
915
+ api_base=None,
916
+ outage_value=outage_value,
917
+ provider=provider,
918
+ )
919
+ # send minor alert
920
+ await self.send_alert(
921
+ message=msg,
922
+ level="Medium",
923
+ alert_type=AlertType.outage_alerts,
924
+ alerting_metadata={},
925
+ )
926
+ # set to true
927
+ outage_value["minor_alert_sent"] = True
928
+
929
+ ## MAJOR OUTAGE ALERT SENT ##
930
+ elif (
931
+ outage_value["major_alert_sent"] is False
932
+ and len(outage_value["alerts"])
933
+ >= self.alerting_args.major_outage_alert_threshold
934
+ and len(_deployment_set) > 1 # make sure it's not just 1 bad deployment
935
+ ):
936
+ msg = self._outage_alert_msg_factory(
937
+ alert_type="Major",
938
+ key="Region",
939
+ key_val=region_name,
940
+ api_base=None,
941
+ outage_value=outage_value,
942
+ provider=provider,
943
+ )
944
+
945
+ # send minor alert
946
+ await self.send_alert(
947
+ message=msg,
948
+ level="High",
949
+ alert_type=AlertType.outage_alerts,
950
+ alerting_metadata={},
951
+ )
952
+ # set to true
953
+ outage_value["major_alert_sent"] = True
954
+
955
+ ## update cache ##
956
+ # Convert set to list for JSON serialization
957
+ cache_value = self._prepare_outage_value_for_cache(outage_value)
958
+ await self.internal_usage_cache.async_set_cache(
959
+ key=cache_key, value=cache_value
960
+ )
961
+
962
+ async def outage_alerts(
963
+ self,
964
+ exception: APIError,
965
+ deployment_id: str,
966
+ ) -> None:
967
+ """
968
+ Send slack alert if model is badly configured / having an outage (408, 401, 429, >=500).
969
+
970
+ key = model_id
971
+
972
+ value = {
973
+ - model_id
974
+ - threshold
975
+ - alerts []
976
+ }
977
+
978
+ ttl = 1hr
979
+ max_alerts_size = 10
980
+ """
981
+ try:
982
+ outage_value: Optional[OutageModel] = await self.internal_usage_cache.async_get_cache(key=deployment_id) # type: ignore
983
+ if (
984
+ getattr(exception, "status_code", None) is None
985
+ or (
986
+ exception.status_code != 408 # type: ignore
987
+ and exception.status_code < 500 # type: ignore
988
+ )
989
+ or self.llm_router is None
990
+ ):
991
+ return
992
+
993
+ ### EXTRACT MODEL DETAILS ###
994
+ deployment = self.llm_router.get_deployment(model_id=deployment_id)
995
+ if deployment is None:
996
+ return
997
+
998
+ model = deployment.litellm_params.model
999
+ provider = deployment.litellm_params.custom_llm_provider
1000
+ if provider is None:
1001
+ try:
1002
+ model, provider, _, _ = litellm.get_llm_provider(model=model)
1003
+ except Exception:
1004
+ provider = ""
1005
+ api_base = litellm.get_api_base(
1006
+ model=model, optional_params=deployment.litellm_params
1007
+ )
1008
+
1009
+ if outage_value is None:
1010
+ outage_value = OutageModel(
1011
+ model_id=deployment_id,
1012
+ alerts=[exception.status_code], # type: ignore
1013
+ minor_alert_sent=False,
1014
+ major_alert_sent=False,
1015
+ last_updated_at=time.time(),
1016
+ )
1017
+
1018
+ ## add to cache ##
1019
+ await self.internal_usage_cache.async_set_cache(
1020
+ key=deployment_id,
1021
+ value=outage_value,
1022
+ ttl=self.alerting_args.outage_alert_ttl,
1023
+ )
1024
+ return
1025
+
1026
+ if (
1027
+ len(outage_value["alerts"])
1028
+ < self.alerting_args.max_outage_alert_list_size
1029
+ ):
1030
+ outage_value["alerts"].append(exception.status_code) # type: ignore
1031
+ else: # prevent memory leaks
1032
+ pass
1033
+
1034
+ outage_value["last_updated_at"] = time.time()
1035
+
1036
+ ## MINOR OUTAGE ALERT SENT ##
1037
+ if (
1038
+ outage_value["minor_alert_sent"] is False
1039
+ and len(outage_value["alerts"])
1040
+ >= self.alerting_args.minor_outage_alert_threshold
1041
+ ):
1042
+ msg = self._outage_alert_msg_factory(
1043
+ alert_type="Minor",
1044
+ key="Model",
1045
+ key_val=model,
1046
+ api_base=api_base,
1047
+ outage_value=outage_value,
1048
+ provider=provider,
1049
+ )
1050
+ # send minor alert
1051
+ await self.send_alert(
1052
+ message=msg,
1053
+ level="Medium",
1054
+ alert_type=AlertType.outage_alerts,
1055
+ alerting_metadata={},
1056
+ )
1057
+ # set to true
1058
+ outage_value["minor_alert_sent"] = True
1059
+ elif (
1060
+ outage_value["major_alert_sent"] is False
1061
+ and len(outage_value["alerts"])
1062
+ >= self.alerting_args.major_outage_alert_threshold
1063
+ ):
1064
+ msg = self._outage_alert_msg_factory(
1065
+ alert_type="Major",
1066
+ key="Model",
1067
+ key_val=model,
1068
+ api_base=api_base,
1069
+ outage_value=outage_value,
1070
+ provider=provider,
1071
+ )
1072
+ # send minor alert
1073
+ await self.send_alert(
1074
+ message=msg,
1075
+ level="High",
1076
+ alert_type=AlertType.outage_alerts,
1077
+ alerting_metadata={},
1078
+ )
1079
+ # set to true
1080
+ outage_value["major_alert_sent"] = True
1081
+
1082
+ ## update cache ##
1083
+ # Convert set to list for JSON serialization
1084
+ cache_value = self._prepare_outage_value_for_cache(outage_value)
1085
+ await self.internal_usage_cache.async_set_cache(
1086
+ key=deployment_id, value=cache_value
1087
+ )
1088
+ except Exception:
1089
+ pass
1090
+
1091
+ async def model_added_alert(
1092
+ self, model_name: str, litellm_model_name: str, passed_model_info: Any
1093
+ ):
1094
+ base_model_from_user = getattr(passed_model_info, "base_model", None)
1095
+ model_info = {}
1096
+ base_model = ""
1097
+ if base_model_from_user is not None:
1098
+ model_info = litellm.model_cost.get(base_model_from_user, {})
1099
+ base_model = f"Base Model: `{base_model_from_user}`\n"
1100
+ else:
1101
+ model_info = litellm.model_cost.get(litellm_model_name, {})
1102
+ model_info_str = ""
1103
+ for k, v in model_info.items():
1104
+ if k == "input_cost_per_token" or k == "output_cost_per_token":
1105
+ # when converting to string it should not be 1.63e-06
1106
+ v = "{:.8f}".format(v)
1107
+
1108
+ model_info_str += f"{k}: {v}\n"
1109
+
1110
+ message = f"""
1111
+ *🚅 New Model Added*
1112
+ Model Name: `{model_name}`
1113
+ {base_model}
1114
+
1115
+ Usage OpenAI Python SDK:
1116
+ ```
1117
+ import openai
1118
+ client = openai.OpenAI(
1119
+ api_key="your_api_key",
1120
+ base_url={os.getenv("PROXY_BASE_URL", "http://0.0.0.0:4000")}
1121
+ )
1122
+
1123
+ response = client.chat.completions.create(
1124
+ model="{model_name}", # model to send to the proxy
1125
+ messages = [
1126
+ {{
1127
+ "role": "user",
1128
+ "content": "this is a test request, write a short poem"
1129
+ }}
1130
+ ]
1131
+ )
1132
+ ```
1133
+
1134
+ Model Info:
1135
+ ```
1136
+ {model_info_str}
1137
+ ```
1138
+ """
1139
+
1140
+ alert_val = self.send_alert(
1141
+ message=message,
1142
+ level="Low",
1143
+ alert_type=AlertType.new_model_added,
1144
+ alerting_metadata={},
1145
+ )
1146
+
1147
+ if alert_val is not None and asyncio.iscoroutine(alert_val):
1148
+ await alert_val
1149
+
1150
+ async def model_removed_alert(self, model_name: str):
1151
+ pass
1152
+
1153
+ async def send_webhook_alert(self, webhook_event: WebhookEvent) -> bool:
1154
+ """
1155
+ Sends structured alert to webhook, if set.
1156
+
1157
+ Currently only implemented for budget alerts
1158
+
1159
+ Returns -> True if sent, False if not.
1160
+
1161
+ Raises Exception
1162
+ - if WEBHOOK_URL is not set
1163
+ """
1164
+
1165
+ webhook_url = os.getenv("WEBHOOK_URL", None)
1166
+ if webhook_url is None:
1167
+ raise Exception("Missing webhook_url from environment")
1168
+
1169
+ payload = webhook_event.model_dump_json()
1170
+ headers = {"Content-type": "application/json"}
1171
+
1172
+ response = await self.async_http_handler.post(
1173
+ url=webhook_url,
1174
+ headers=headers,
1175
+ data=payload,
1176
+ )
1177
+ if response.status_code == 200:
1178
+ return True
1179
+ else:
1180
+ print("Error sending webhook alert. Error=", response.text) # noqa
1181
+
1182
+ return False
1183
+
1184
+ async def _check_if_using_premium_email_feature(
1185
+ self,
1186
+ premium_user: bool,
1187
+ email_logo_url: Optional[str] = None,
1188
+ email_support_contact: Optional[str] = None,
1189
+ ):
1190
+ from litellm.proxy.proxy_server import CommonProxyErrors, premium_user
1191
+
1192
+ if premium_user is not True:
1193
+ if email_logo_url is not None or email_support_contact is not None:
1194
+ raise ValueError(
1195
+ f"Trying to Customize Email Alerting\n {CommonProxyErrors.not_premium_user.value}"
1196
+ )
1197
+ return
1198
+
1199
+ async def send_key_created_or_user_invited_email(
1200
+ self, webhook_event: WebhookEvent
1201
+ ) -> bool:
1202
+ try:
1203
+ from litellm.proxy.utils import send_email
1204
+
1205
+ if self.alerting is None or "email" not in self.alerting:
1206
+ # do nothing if user does not want email alerts
1207
+ verbose_proxy_logger.error(
1208
+ "Error sending email alert - 'email' not in self.alerting %s",
1209
+ self.alerting,
1210
+ )
1211
+ return False
1212
+ from litellm.proxy.proxy_server import premium_user, prisma_client
1213
+
1214
+ email_logo_url = os.getenv(
1215
+ "SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None)
1216
+ )
1217
+ email_support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", None)
1218
+ await self._check_if_using_premium_email_feature(
1219
+ premium_user, email_logo_url, email_support_contact
1220
+ )
1221
+ if email_logo_url is None:
1222
+ email_logo_url = LITELLM_LOGO_URL
1223
+ if email_support_contact is None:
1224
+ email_support_contact = LITELLM_SUPPORT_CONTACT
1225
+
1226
+ event_name = webhook_event.event_message
1227
+ recipient_email = webhook_event.user_email
1228
+ recipient_user_id = webhook_event.user_id
1229
+ if (
1230
+ recipient_email is None
1231
+ and recipient_user_id is not None
1232
+ and prisma_client is not None
1233
+ ):
1234
+ user_row = await prisma_client.db.litellm_usertable.find_unique(
1235
+ where={"user_id": recipient_user_id}
1236
+ )
1237
+
1238
+ if user_row is not None:
1239
+ recipient_email = user_row.user_email
1240
+
1241
+ key_token = webhook_event.token
1242
+ key_budget = webhook_event.max_budget
1243
+ base_url = os.getenv("PROXY_BASE_URL", "http://0.0.0.0:4000")
1244
+
1245
+ email_html_content = "Alert from LiteLLM Server"
1246
+ if recipient_email is None:
1247
+ verbose_proxy_logger.error(
1248
+ "Trying to send email alert to no recipient",
1249
+ extra=webhook_event.dict(),
1250
+ )
1251
+
1252
+ if webhook_event.event == "key_created":
1253
+ email_html_content = KEY_CREATED_EMAIL_TEMPLATE.format(
1254
+ email_logo_url=email_logo_url,
1255
+ recipient_email=recipient_email,
1256
+ key_budget=key_budget,
1257
+ key_token=key_token,
1258
+ base_url=base_url,
1259
+ email_support_contact=email_support_contact,
1260
+ )
1261
+ elif webhook_event.event == "internal_user_created":
1262
+ # GET TEAM NAME
1263
+ team_id = webhook_event.team_id
1264
+ team_name = "Default Team"
1265
+ if team_id is not None and prisma_client is not None:
1266
+ team_row = await prisma_client.db.litellm_teamtable.find_unique(
1267
+ where={"team_id": team_id}
1268
+ )
1269
+ if team_row is not None:
1270
+ team_name = team_row.team_alias or "-"
1271
+ email_html_content = USER_INVITED_EMAIL_TEMPLATE.format(
1272
+ email_logo_url=email_logo_url,
1273
+ recipient_email=recipient_email,
1274
+ team_name=team_name,
1275
+ base_url=base_url,
1276
+ email_support_contact=email_support_contact,
1277
+ )
1278
+ else:
1279
+ verbose_proxy_logger.error(
1280
+ "Trying to send email alert on unknown webhook event",
1281
+ extra=webhook_event.model_dump(),
1282
+ )
1283
+
1284
+ webhook_event.model_dump_json()
1285
+ email_event = {
1286
+ "to": recipient_email,
1287
+ "subject": f"LiteLLM: {event_name}",
1288
+ "html": email_html_content,
1289
+ }
1290
+
1291
+ await send_email(
1292
+ receiver_email=email_event["to"],
1293
+ subject=email_event["subject"],
1294
+ html=email_event["html"],
1295
+ )
1296
+
1297
+ return True
1298
+
1299
+ except Exception as e:
1300
+ verbose_proxy_logger.error("Error sending email alert %s", str(e))
1301
+ return False
1302
+
1303
+ async def send_email_alert_using_smtp(
1304
+ self, webhook_event: WebhookEvent, alert_type: str
1305
+ ) -> bool:
1306
+ """
1307
+ Sends structured Email alert to an SMTP server
1308
+
1309
+ Currently only implemented for budget alerts
1310
+
1311
+ Returns -> True if sent, False if not.
1312
+ """
1313
+ from litellm.proxy.proxy_server import premium_user
1314
+ from litellm.proxy.utils import send_email
1315
+
1316
+ email_logo_url = os.getenv(
1317
+ "SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None)
1318
+ )
1319
+ email_support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", None)
1320
+ await self._check_if_using_premium_email_feature(
1321
+ premium_user, email_logo_url, email_support_contact
1322
+ )
1323
+
1324
+ if email_logo_url is None:
1325
+ email_logo_url = LITELLM_LOGO_URL
1326
+ if email_support_contact is None:
1327
+ email_support_contact = LITELLM_SUPPORT_CONTACT
1328
+
1329
+ event_name = webhook_event.event_message
1330
+ recipient_email = webhook_event.user_email
1331
+ user_name = webhook_event.user_id
1332
+ max_budget = webhook_event.max_budget
1333
+ email_html_content = "Alert from LiteLLM Server"
1334
+ if recipient_email is None:
1335
+ verbose_proxy_logger.error(
1336
+ "Trying to send email alert to no recipient", extra=webhook_event.dict()
1337
+ )
1338
+
1339
+ if webhook_event.event == "budget_crossed":
1340
+ email_html_content = f"""
1341
+ <img src="{email_logo_url}" alt="LiteLLM Logo" width="150" height="50" />
1342
+
1343
+ <p> Hi {user_name}, <br/>
1344
+
1345
+ Your LLM API usage this month has reached your account's <b> monthly budget of ${max_budget} </b> <br /> <br />
1346
+
1347
+ API requests will be rejected until either (a) you increase your monthly budget or (b) your monthly usage resets at the beginning of the next calendar month. <br /> <br />
1348
+
1349
+ If you have any questions, please send an email to {email_support_contact} <br /> <br />
1350
+
1351
+ Best, <br />
1352
+ The LiteLLM team <br />
1353
+ """
1354
+
1355
+ webhook_event.model_dump_json()
1356
+ email_event = {
1357
+ "to": recipient_email,
1358
+ "subject": f"LiteLLM: {event_name}",
1359
+ "html": email_html_content,
1360
+ }
1361
+
1362
+ await send_email(
1363
+ receiver_email=email_event["to"],
1364
+ subject=email_event["subject"],
1365
+ html=email_event["html"],
1366
+ )
1367
+ if webhook_event.event_group == Litellm_EntityType.TEAM:
1368
+ from litellm.integrations.email_alerting import send_team_budget_alert
1369
+
1370
+ await send_team_budget_alert(webhook_event=webhook_event)
1371
+
1372
+ return False
1373
+
1374
+ async def send_alert( # noqa: PLR0915
1375
+ self,
1376
+ message: str,
1377
+ level: Literal["Low", "Medium", "High"],
1378
+ alert_type: AlertType,
1379
+ alerting_metadata: dict,
1380
+ user_info: Optional[WebhookEvent] = None,
1381
+ request_model: Optional[str] = None,
1382
+ api_base: Optional[str] = None,
1383
+ **kwargs,
1384
+ ):
1385
+ """
1386
+ Alerting based on thresholds: - https://github.com/BerriAI/litellm/issues/1298
1387
+
1388
+ - Responses taking too long
1389
+ - Requests are hanging
1390
+ - Calls are failing
1391
+ - DB Read/Writes are failing
1392
+ - Proxy Close to max budget
1393
+ - Key Close to max budget
1394
+
1395
+ Parameters:
1396
+ level: str - Low|Medium|High - if calls might fail (Medium) or are failing (High); Currently, no alerts would be 'Low'.
1397
+ message: str - what is the alert about
1398
+ request_model: Optional[str] - model name for digest grouping
1399
+ api_base: Optional[str] - api base for digest grouping
1400
+ """
1401
+ if self.alerting is None:
1402
+ return
1403
+
1404
+ # Start periodic flush if not already started
1405
+ if (
1406
+ not self.periodic_started
1407
+ and self.alerting is not None
1408
+ and len(self.alerting) > 0
1409
+ ):
1410
+ asyncio.create_task(self.periodic_flush())
1411
+ self.periodic_started = True
1412
+
1413
+ if (
1414
+ "webhook" in self.alerting
1415
+ and alert_type == "budget_alerts"
1416
+ and user_info is not None
1417
+ ):
1418
+ await self.send_webhook_alert(webhook_event=user_info)
1419
+
1420
+ if (
1421
+ "email" in self.alerting
1422
+ and alert_type == "budget_alerts"
1423
+ and user_info is not None
1424
+ ):
1425
+ # only send budget alerts over Email
1426
+ await self.send_email_alert_using_smtp(
1427
+ webhook_event=user_info, alert_type=alert_type
1428
+ )
1429
+
1430
+ if "slack" not in self.alerting:
1431
+ return
1432
+ if alert_type not in self.alert_types:
1433
+ return
1434
+
1435
+ from datetime import datetime
1436
+
1437
+ # Check if digest mode is enabled for this alert type
1438
+ alert_type_name_str = getattr(alert_type, "value", str(alert_type))
1439
+ _atc = self.alert_type_config.get(alert_type_name_str)
1440
+ if _atc is not None and _atc.digest:
1441
+ # Resolve webhook URL for this alert type (needed for digest entry)
1442
+ if (
1443
+ self.alert_to_webhook_url is not None
1444
+ and alert_type in self.alert_to_webhook_url
1445
+ ):
1446
+ _digest_webhook: Optional[
1447
+ Union[str, List[str]]
1448
+ ] = self.alert_to_webhook_url[alert_type]
1449
+ elif self.default_webhook_url is not None:
1450
+ _digest_webhook = self.default_webhook_url
1451
+ else:
1452
+ _digest_webhook = os.getenv("SLACK_WEBHOOK_URL", None)
1453
+ if _digest_webhook is None:
1454
+ raise ValueError("Missing SLACK_WEBHOOK_URL from environment")
1455
+
1456
+ digest_key = f"{alert_type_name_str}:{request_model or ''}:{api_base or ''}"
1457
+
1458
+ async with self.digest_lock:
1459
+ now = datetime.now()
1460
+ if digest_key in self.digest_buckets:
1461
+ self.digest_buckets[digest_key]["count"] += 1
1462
+ self.digest_buckets[digest_key]["last_time"] = now
1463
+ else:
1464
+ self.digest_buckets[digest_key] = DigestEntry(
1465
+ alert_type=alert_type_name_str,
1466
+ request_model=request_model or "",
1467
+ api_base=api_base or "",
1468
+ first_message=message,
1469
+ level=level,
1470
+ count=1,
1471
+ start_time=now,
1472
+ last_time=now,
1473
+ webhook_url=_digest_webhook,
1474
+ )
1475
+ return # Suppress immediate alert; will be emitted by _flush_digest_buckets
1476
+
1477
+ # Get the current timestamp
1478
+ current_time = datetime.now().strftime("%H:%M:%S")
1479
+ _proxy_base_url = os.getenv("PROXY_BASE_URL", None)
1480
+ # Use .name if it's an enum, otherwise use as is
1481
+ alert_type_name = getattr(alert_type, "name", alert_type)
1482
+ alert_type_formatted = f"Alert type: `{alert_type_name}`"
1483
+ if alert_type == "daily_reports" or alert_type == "new_model_added":
1484
+ formatted_message = alert_type_formatted + message
1485
+ else:
1486
+ formatted_message = f"{alert_type_formatted}\nLevel: `{level}`\nTimestamp: `{current_time}`\n\nMessage: {message}"
1487
+
1488
+ if kwargs:
1489
+ for key, value in kwargs.items():
1490
+ formatted_message += f"\n\n{key}: `{value}`\n\n"
1491
+ if alerting_metadata:
1492
+ for key, value in alerting_metadata.items():
1493
+ formatted_message += f"\n\n*Alerting Metadata*: \n{key}: `{value}`\n\n"
1494
+ if _proxy_base_url is not None:
1495
+ formatted_message += f"\n\nProxy URL: `{_proxy_base_url}`"
1496
+
1497
+ # check if we find the slack webhook url in self.alert_to_webhook_url
1498
+ if (
1499
+ self.alert_to_webhook_url is not None
1500
+ and alert_type in self.alert_to_webhook_url
1501
+ ):
1502
+ slack_webhook_url: Optional[
1503
+ Union[str, List[str]]
1504
+ ] = self.alert_to_webhook_url[alert_type]
1505
+ elif self.default_webhook_url is not None:
1506
+ slack_webhook_url = self.default_webhook_url
1507
+ else:
1508
+ slack_webhook_url = os.getenv("SLACK_WEBHOOK_URL", None)
1509
+
1510
+ if slack_webhook_url is None:
1511
+ raise ValueError("Missing SLACK_WEBHOOK_URL from environment")
1512
+ payload = {"text": formatted_message}
1513
+ headers = {"Content-type": "application/json"}
1514
+
1515
+ if isinstance(slack_webhook_url, list):
1516
+ for url in slack_webhook_url:
1517
+ self.log_queue.append(
1518
+ {
1519
+ "url": url,
1520
+ "headers": headers,
1521
+ "payload": payload,
1522
+ "alert_type": alert_type,
1523
+ }
1524
+ )
1525
+ else:
1526
+ self.log_queue.append(
1527
+ {
1528
+ "url": slack_webhook_url,
1529
+ "headers": headers,
1530
+ "payload": payload,
1531
+ "alert_type": alert_type,
1532
+ }
1533
+ )
1534
+
1535
+ if len(self.log_queue) >= self.batch_size:
1536
+ await self.flush_queue()
1537
+
1538
+ async def async_send_batch(self):
1539
+ if not self.log_queue:
1540
+ return
1541
+
1542
+ squashed_queue = squash_payloads(self.log_queue)
1543
+ tasks = [
1544
+ send_to_webhook(
1545
+ slackAlertingInstance=self, item=item["item"], count=item["count"]
1546
+ )
1547
+ for item in squashed_queue.values()
1548
+ ]
1549
+ await asyncio.gather(*tasks)
1550
+ self.log_queue.clear()
1551
+
1552
+ async def _flush_digest_buckets(self):
1553
+ """Flush any digest buckets whose interval has expired.
1554
+
1555
+ For each expired bucket, formats a digest summary message and
1556
+ appends it to the log_queue for delivery via the normal batching path.
1557
+ """
1558
+ from datetime import datetime
1559
+
1560
+ now = datetime.now()
1561
+ flushed_keys: List[str] = []
1562
+
1563
+ async with self.digest_lock:
1564
+ for key, entry in self.digest_buckets.items():
1565
+ alert_type_name = entry["alert_type"]
1566
+ _atc = self.alert_type_config.get(alert_type_name)
1567
+ if _atc is None:
1568
+ continue
1569
+ elapsed = (now - entry["start_time"]).total_seconds()
1570
+ if elapsed < _atc.digest_interval:
1571
+ continue
1572
+
1573
+ # Build digest summary message
1574
+ start_ts = entry["start_time"].strftime("%H:%M:%S")
1575
+ end_ts = entry["last_time"].strftime("%H:%M:%S")
1576
+ start_date = entry["start_time"].strftime("%Y-%m-%d")
1577
+ end_date = entry["last_time"].strftime("%Y-%m-%d")
1578
+ formatted_message = (
1579
+ f"Alert type: `{alert_type_name}` (Digest)\n"
1580
+ f"Level: `{entry['level']}`\n"
1581
+ f"Start: `{start_date} {start_ts}`\n"
1582
+ f"End: `{end_date} {end_ts}`\n"
1583
+ f"Count: `{entry['count']}`\n\n"
1584
+ f"Message: {entry['first_message']}"
1585
+ )
1586
+ _proxy_base_url = os.getenv("PROXY_BASE_URL", None)
1587
+ if _proxy_base_url is not None:
1588
+ formatted_message += f"\n\nProxy URL: `{_proxy_base_url}`"
1589
+
1590
+ payload = {"text": formatted_message}
1591
+ headers = {"Content-type": "application/json"}
1592
+ webhook_url = entry["webhook_url"]
1593
+
1594
+ if isinstance(webhook_url, list):
1595
+ for url in webhook_url:
1596
+ self.log_queue.append(
1597
+ {
1598
+ "url": url,
1599
+ "headers": headers,
1600
+ "payload": payload,
1601
+ "alert_type": alert_type_name,
1602
+ }
1603
+ )
1604
+ else:
1605
+ self.log_queue.append(
1606
+ {
1607
+ "url": webhook_url,
1608
+ "headers": headers,
1609
+ "payload": payload,
1610
+ "alert_type": alert_type_name,
1611
+ }
1612
+ )
1613
+ flushed_keys.append(key)
1614
+
1615
+ for key in flushed_keys:
1616
+ del self.digest_buckets[key]
1617
+
1618
+ async def periodic_flush(self):
1619
+ """Override base periodic_flush to also flush digest buckets."""
1620
+ while True:
1621
+ await asyncio.sleep(self.flush_interval)
1622
+ try:
1623
+ await self._flush_digest_buckets()
1624
+ except Exception as e:
1625
+ verbose_proxy_logger.debug(f"Error flushing digest buckets: {str(e)}")
1626
+ await self.flush_queue()
1627
+
1628
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
1629
+ """Log deployment latency"""
1630
+ try:
1631
+ if "daily_reports" in self.alert_types:
1632
+ litellm_params = kwargs.get("litellm_params", {}) or {}
1633
+ model_info = litellm_params.get("model_info", {}) or {}
1634
+ model_id = model_info.get("id", "") or ""
1635
+ response_s: timedelta = end_time - start_time
1636
+
1637
+ final_value = response_s
1638
+
1639
+ if isinstance(response_obj, litellm.ModelResponse) and (
1640
+ hasattr(response_obj, "usage")
1641
+ and response_obj.usage is not None # type: ignore
1642
+ and hasattr(response_obj.usage, "completion_tokens") # type: ignore
1643
+ ):
1644
+ completion_tokens = response_obj.usage.completion_tokens # type: ignore
1645
+ if completion_tokens is not None and completion_tokens > 0:
1646
+ final_value = float(
1647
+ response_s.total_seconds() / completion_tokens
1648
+ )
1649
+ if isinstance(final_value, timedelta):
1650
+ final_value = final_value.total_seconds()
1651
+
1652
+ await self.async_update_daily_reports(
1653
+ DeploymentMetrics(
1654
+ id=model_id,
1655
+ failed_request=False,
1656
+ latency_per_output_token=final_value,
1657
+ updated_at=litellm.utils.get_utc_datetime(),
1658
+ )
1659
+ )
1660
+ except Exception as e:
1661
+ verbose_proxy_logger.error(
1662
+ f"[Non-Blocking Error] Slack Alerting: Got error in logging LLM deployment latency: {str(e)}"
1663
+ )
1664
+ pass
1665
+
1666
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
1667
+ """Log failure + deployment latency"""
1668
+ _litellm_params = kwargs.get("litellm_params", {})
1669
+ _model_info = _litellm_params.get("model_info", {}) or {}
1670
+ model_id = _model_info.get("id", "")
1671
+ try:
1672
+ if "daily_reports" in self.alert_types:
1673
+ try:
1674
+ await self.async_update_daily_reports(
1675
+ DeploymentMetrics(
1676
+ id=model_id,
1677
+ failed_request=True,
1678
+ latency_per_output_token=None,
1679
+ updated_at=litellm.utils.get_utc_datetime(),
1680
+ )
1681
+ )
1682
+ except Exception as e:
1683
+ verbose_logger.debug(f"Exception raises -{str(e)}")
1684
+
1685
+ if isinstance(kwargs.get("exception", ""), APIError):
1686
+ if "outage_alerts" in self.alert_types:
1687
+ await self.outage_alerts(
1688
+ exception=kwargs["exception"],
1689
+ deployment_id=model_id,
1690
+ )
1691
+
1692
+ if "region_outage_alerts" in self.alert_types:
1693
+ await self.region_outage_alerts(
1694
+ exception=kwargs["exception"], deployment_id=model_id
1695
+ )
1696
+ except Exception:
1697
+ pass
1698
+
1699
+ async def _run_scheduler_helper(self, llm_router) -> bool:
1700
+ """
1701
+ Returns:
1702
+ - True -> report sent
1703
+ - False -> report not sent
1704
+ """
1705
+ report_sent_bool = False
1706
+
1707
+ report_sent = await self.internal_usage_cache.async_get_cache(
1708
+ key=SlackAlertingCacheKeys.report_sent_key.value,
1709
+ parent_otel_span=None,
1710
+ ) # None | float
1711
+
1712
+ current_time = time.time()
1713
+
1714
+ if report_sent is None:
1715
+ await self.internal_usage_cache.async_set_cache(
1716
+ key=SlackAlertingCacheKeys.report_sent_key.value,
1717
+ value=current_time,
1718
+ )
1719
+ elif isinstance(report_sent, float):
1720
+ # Check if current time - interval >= time last sent
1721
+ interval_seconds = self.alerting_args.daily_report_frequency
1722
+
1723
+ if current_time - report_sent >= interval_seconds:
1724
+ # Sneak in the reporting logic here
1725
+ await self.send_daily_reports(router=llm_router)
1726
+ # Also, don't forget to update the report_sent time after sending the report!
1727
+ await self.internal_usage_cache.async_set_cache(
1728
+ key=SlackAlertingCacheKeys.report_sent_key.value,
1729
+ value=current_time,
1730
+ )
1731
+ report_sent_bool = True
1732
+
1733
+ return report_sent_bool
1734
+
1735
+ async def _run_scheduled_daily_report(self, llm_router: Optional[Any] = None):
1736
+ """
1737
+ If 'daily_reports' enabled
1738
+
1739
+ Ping redis cache every 5 minutes to check if we should send the report
1740
+
1741
+ If yes -> call send_daily_report()
1742
+ """
1743
+ if llm_router is None or self.alert_types is None:
1744
+ return
1745
+
1746
+ if "daily_reports" in self.alert_types:
1747
+ while True:
1748
+ await self._run_scheduler_helper(llm_router=llm_router)
1749
+ interval = random.randint(
1750
+ self.alerting_args.report_check_interval - 3,
1751
+ self.alerting_args.report_check_interval + 3,
1752
+ ) # shuffle to prevent collisions
1753
+ await asyncio.sleep(interval)
1754
+ return
1755
+
1756
+ async def send_weekly_spend_report(
1757
+ self,
1758
+ time_range: str = "7d",
1759
+ ):
1760
+ """
1761
+ Send a spend report for a configurable time range.
1762
+
1763
+ Args:
1764
+ time_range: A string specifying the time range for the report, e.g., "1d", "7d", "30d"
1765
+ """
1766
+ if self.alerting is None or "spend_reports" not in self.alert_types:
1767
+ return
1768
+
1769
+ try:
1770
+ from litellm.proxy.spend_tracking.spend_management_endpoints import (
1771
+ _get_spend_report_for_time_range,
1772
+ )
1773
+
1774
+ # Parse the time range
1775
+ days = int(time_range[:-1])
1776
+ if time_range[-1].lower() != "d":
1777
+ raise ValueError("Time range must be specified in days, e.g., '7d'")
1778
+
1779
+ todays_date = datetime.datetime.now().date()
1780
+ start_date = todays_date - datetime.timedelta(days=days)
1781
+
1782
+ _event_cache_key = f"weekly_spend_report_sent_{start_date.strftime('%Y-%m-%d')}_{todays_date.strftime('%Y-%m-%d')}"
1783
+ if await self.internal_usage_cache.async_get_cache(key=_event_cache_key):
1784
+ return
1785
+
1786
+ _resp = await _get_spend_report_for_time_range(
1787
+ start_date=start_date.strftime("%Y-%m-%d"),
1788
+ end_date=todays_date.strftime("%Y-%m-%d"),
1789
+ )
1790
+ if _resp is None or _resp == ([], []):
1791
+ return
1792
+
1793
+ spend_per_team, spend_per_tag = _resp
1794
+
1795
+ _spend_message = f"*💸 Spend Report for `{start_date.strftime('%m-%d-%Y')} - {todays_date.strftime('%m-%d-%Y')}` ({days} days)*\n"
1796
+
1797
+ if spend_per_team is not None:
1798
+ _spend_message += "\n*Team Spend Report:*\n"
1799
+ for spend in spend_per_team:
1800
+ _team_spend = round(float(spend["total_spend"]), 4)
1801
+ _spend_message += (
1802
+ f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n"
1803
+ )
1804
+
1805
+ if spend_per_tag is not None:
1806
+ _spend_message += "\n*Tag Spend Report:*\n"
1807
+ for spend in spend_per_tag:
1808
+ _tag_spend = round(float(spend["total_spend"]), 4)
1809
+ _spend_message += f"Tag: `{spend['individual_request_tag']}` | Spend: `${_tag_spend}`\n"
1810
+
1811
+ await self.send_alert(
1812
+ message=_spend_message,
1813
+ level="Low",
1814
+ alert_type=AlertType.spend_reports,
1815
+ alerting_metadata={},
1816
+ )
1817
+
1818
+ await self.internal_usage_cache.async_set_cache(
1819
+ key=_event_cache_key,
1820
+ value="SENT",
1821
+ ttl=duration_in_seconds(time_range),
1822
+ )
1823
+
1824
+ except ValueError as ve:
1825
+ verbose_proxy_logger.error(f"Invalid time range format: {ve}")
1826
+ except Exception as e:
1827
+ verbose_proxy_logger.error(f"Error sending spend report: {e}")
1828
+
1829
+ async def send_monthly_spend_report(self):
1830
+ """ """
1831
+ try:
1832
+ from calendar import monthrange
1833
+
1834
+ from litellm.proxy.spend_tracking.spend_management_endpoints import (
1835
+ _get_spend_report_for_time_range,
1836
+ )
1837
+
1838
+ todays_date = datetime.datetime.now().date()
1839
+ first_day_of_month = todays_date.replace(day=1)
1840
+ _, last_day_of_month = monthrange(todays_date.year, todays_date.month)
1841
+ last_day_of_month = first_day_of_month + datetime.timedelta(
1842
+ days=last_day_of_month - 1
1843
+ )
1844
+
1845
+ _event_cache_key = f"monthly_spend_report_sent_{first_day_of_month.strftime('%Y-%m-%d')}_{last_day_of_month.strftime('%Y-%m-%d')}"
1846
+ if await self.internal_usage_cache.async_get_cache(key=_event_cache_key):
1847
+ return
1848
+
1849
+ _resp = await _get_spend_report_for_time_range(
1850
+ start_date=first_day_of_month.strftime("%Y-%m-%d"),
1851
+ end_date=last_day_of_month.strftime("%Y-%m-%d"),
1852
+ )
1853
+
1854
+ if _resp is None or _resp == ([], []):
1855
+ return
1856
+
1857
+ monthly_spend_per_team, monthly_spend_per_tag = _resp
1858
+
1859
+ _spend_message = f"*💸 Monthly Spend Report for `{first_day_of_month.strftime('%m-%d-%Y')} - {last_day_of_month.strftime('%m-%d-%Y')}` *\n"
1860
+
1861
+ if monthly_spend_per_team is not None:
1862
+ _spend_message += "\n*Team Spend Report:*\n"
1863
+ for spend in monthly_spend_per_team:
1864
+ _team_spend = spend["total_spend"]
1865
+ _team_spend = float(_team_spend)
1866
+ # round to 4 decimal places
1867
+ _team_spend = round(_team_spend, 4)
1868
+ _spend_message += (
1869
+ f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n"
1870
+ )
1871
+
1872
+ if monthly_spend_per_tag is not None:
1873
+ _spend_message += "\n*Tag Spend Report:*\n"
1874
+ for spend in monthly_spend_per_tag:
1875
+ _tag_spend = spend["total_spend"]
1876
+ _tag_spend = float(_tag_spend)
1877
+ # round to 4 decimal places
1878
+ _tag_spend = round(_tag_spend, 4)
1879
+ _spend_message += f"Tag: `{spend['individual_request_tag']}` | Spend: `${_tag_spend}`\n"
1880
+
1881
+ await self.send_alert(
1882
+ message=_spend_message,
1883
+ level="Low",
1884
+ alert_type=AlertType.spend_reports,
1885
+ alerting_metadata={},
1886
+ )
1887
+
1888
+ await self.internal_usage_cache.async_set_cache(
1889
+ key=_event_cache_key,
1890
+ value="SENT",
1891
+ ttl=(30 * HOURS_IN_A_DAY * 60 * 60), # 1 month
1892
+ )
1893
+
1894
+ except Exception as e:
1895
+ verbose_proxy_logger.exception("Error sending weekly spend report %s", e)
1896
+
1897
+ async def send_fallback_stats_from_prometheus(self):
1898
+ """
1899
+ Helper to send fallback statistics from prometheus server -> to slack
1900
+
1901
+ This runs once per day and sends an overview of all the fallback statistics
1902
+ """
1903
+ try:
1904
+ from litellm.integrations.prometheus_helpers.prometheus_api import (
1905
+ get_fallback_metric_from_prometheus,
1906
+ )
1907
+
1908
+ # call prometheuslogger.
1909
+ falllback_success_info_prometheus = (
1910
+ await get_fallback_metric_from_prometheus()
1911
+ )
1912
+
1913
+ fallback_message = (
1914
+ f"*Fallback Statistics:*\n{falllback_success_info_prometheus}"
1915
+ )
1916
+
1917
+ await self.send_alert(
1918
+ message=fallback_message,
1919
+ level="Low",
1920
+ alert_type=AlertType.fallback_reports,
1921
+ alerting_metadata={},
1922
+ )
1923
+
1924
+ except Exception as e:
1925
+ verbose_proxy_logger.error("Error sending weekly spend report %s", e)
1926
+
1927
+ pass
1928
+
1929
+ async def send_virtual_key_event_slack(
1930
+ self,
1931
+ key_event: VirtualKeyEvent,
1932
+ alert_type: AlertType,
1933
+ event_name: str,
1934
+ ):
1935
+ """
1936
+ Handles sending Virtual Key related alerts
1937
+
1938
+ Example:
1939
+ - New Virtual Key Created
1940
+ - Internal User Updated
1941
+ - Team Created, Updated, Deleted
1942
+ """
1943
+ try:
1944
+ message = f"`{event_name}`\n"
1945
+
1946
+ key_event_dict = key_event.model_dump()
1947
+
1948
+ # Add Created by information first
1949
+ message += "*Action Done by:*\n"
1950
+ for key, value in key_event_dict.items():
1951
+ if "created_by" in key:
1952
+ message += f"{key}: `{value}`\n"
1953
+
1954
+ # Add args sent to function in the alert
1955
+ message += "\n*Arguments passed:*\n"
1956
+ request_kwargs = key_event.request_kwargs
1957
+ for key, value in request_kwargs.items():
1958
+ if key == "user_api_key_dict":
1959
+ continue
1960
+ message += f"{key}: `{value}`\n"
1961
+
1962
+ await self.send_alert(
1963
+ message=message,
1964
+ level="High",
1965
+ alert_type=alert_type,
1966
+ alerting_metadata={},
1967
+ )
1968
+
1969
+ except Exception as e:
1970
+ verbose_proxy_logger.error(
1971
+ "Error sending send_virtual_key_event_slack %s", e
1972
+ )
1973
+
1974
+ return
1975
+
1976
+ async def _request_is_completed(self, request_data: Optional[dict]) -> bool:
1977
+ """
1978
+ Returns True if the request is completed - either as a success or failure
1979
+ """
1980
+ if request_data is None:
1981
+ return False
1982
+
1983
+ if (
1984
+ request_data.get("litellm_status", "") != "success"
1985
+ and request_data.get("litellm_status", "") != "fail"
1986
+ ):
1987
+ ## CHECK IF CACHE IS UPDATED
1988
+ litellm_call_id = request_data.get("litellm_call_id", "")
1989
+ status: Optional[str] = await self.internal_usage_cache.async_get_cache(
1990
+ key="request_status:{}".format(litellm_call_id), local_only=True
1991
+ )
1992
+ if status is not None and (status == "success" or status == "fail"):
1993
+ return True
1994
+ return False
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/SlackAlerting/utils.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils used for slack alerting
3
+ """
4
+
5
+ import asyncio
6
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
7
+
8
+ import litellm
9
+ from litellm.proxy._types import AlertType
10
+ from litellm.secret_managers.main import get_secret
11
+
12
+ if TYPE_CHECKING:
13
+ from litellm.litellm_core_utils.litellm_logging import Logging as _Logging
14
+
15
+ Logging = _Logging
16
+ else:
17
+ Logging = Any
18
+
19
+
20
+ def process_slack_alerting_variables(
21
+ alert_to_webhook_url: Optional[Dict[AlertType, Union[List[str], str]]]
22
+ ) -> Optional[Dict[AlertType, Union[List[str], str]]]:
23
+ """
24
+ process alert_to_webhook_url
25
+ - check if any urls are set as os.environ/SLACK_WEBHOOK_URL_1 read env var and set the correct value
26
+ """
27
+ if alert_to_webhook_url is None:
28
+ return None
29
+
30
+ for alert_type, webhook_urls in alert_to_webhook_url.items():
31
+ if isinstance(webhook_urls, list):
32
+ _webhook_values: List[str] = []
33
+ for webhook_url in webhook_urls:
34
+ if "os.environ/" in webhook_url:
35
+ _env_value = get_secret(secret_name=webhook_url)
36
+ if not isinstance(_env_value, str):
37
+ raise ValueError(
38
+ f"Invalid webhook url value for: {webhook_url}. Got type={type(_env_value)}"
39
+ )
40
+ _webhook_values.append(_env_value)
41
+ else:
42
+ _webhook_values.append(webhook_url)
43
+
44
+ alert_to_webhook_url[alert_type] = _webhook_values
45
+ else:
46
+ _webhook_value_str: str = webhook_urls
47
+ if "os.environ/" in webhook_urls:
48
+ _env_value = get_secret(secret_name=webhook_urls)
49
+ if not isinstance(_env_value, str):
50
+ raise ValueError(
51
+ f"Invalid webhook url value for: {webhook_urls}. Got type={type(_env_value)}"
52
+ )
53
+ _webhook_value_str = _env_value
54
+ else:
55
+ _webhook_value_str = webhook_urls
56
+
57
+ alert_to_webhook_url[alert_type] = _webhook_value_str
58
+
59
+ return alert_to_webhook_url
60
+
61
+
62
+ async def _add_langfuse_trace_id_to_alert(
63
+ request_data: Optional[dict] = None,
64
+ ) -> Optional[str]:
65
+ """
66
+ Returns langfuse trace url
67
+
68
+ - check:
69
+ -> existing_trace_id
70
+ -> trace_id
71
+ -> litellm_call_id
72
+ """
73
+ if "langfuse" not in litellm.logging_callback_manager._get_all_callbacks():
74
+ return None
75
+ #########################################################
76
+ # Only run if langfuse is added as a callback
77
+ #########################################################
78
+
79
+ if (
80
+ request_data is not None
81
+ and request_data.get("litellm_logging_obj", None) is not None
82
+ ):
83
+ trace_id: Optional[str] = None
84
+ litellm_logging_obj: Logging = request_data["litellm_logging_obj"]
85
+
86
+ for _ in range(3):
87
+ trace_id = litellm_logging_obj._get_trace_id(service_name="langfuse")
88
+ if trace_id is not None:
89
+ break
90
+ await asyncio.sleep(3) # wait 3s before retrying for trace id
91
+ #########################################################
92
+ langfuse_object = litellm_logging_obj._get_callback_object(
93
+ service_name="langfuse"
94
+ )
95
+ if langfuse_object is not None:
96
+ base_url = langfuse_object.Langfuse.base_url
97
+ return f"{base_url}/trace/{trace_id}"
98
+
99
+ return None
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (228 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/additional_logging_utils.cpython-311.pyc ADDED
Binary file (2.04 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/litellm/integrations/__pycache__/anthropic_cache_control_hook.cpython-311.pyc ADDED
Binary file (10.8 kB). View file