assassinlike commited on
Commit
4c2938e
·
verified ·
1 Parent(s): 260bc2e

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/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_internal_context.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports_registry.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_logging.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis_credential_provider.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_service_logger.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_uuid.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_version.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/anthropic_beta_headers_manager.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/budget_manager.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/constants.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/cost_calculator.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/exceptions.cpython-310.pyc +0 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/scheduler.cpython-310.pyc +0 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/setup_wizard.cpython-310.pyc +0 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/timeout.cpython-310.pyc +0 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/__init__.py +73 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/card_resolver.py +144 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/client.py +109 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/cost_calculator.py +107 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exception_mapping_utils.py +203 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exceptions.py +150 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/main.py +744 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/streaming_iterator.py +184 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/utils.py +138 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/__init__.py +7 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/readme.md +116 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/main.py +1484 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/utils.py +161 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/Readme.md +41 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/__init__.py +11 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/_internal_lru_cache.py +30 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/azure_blob_cache.py +107 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/base_cache.py +64 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching.py +987 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching_handler.py +1209 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/disk_cache.py +93 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/dual_cache.py +539 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/gcs_cache.py +114 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/in_memory_cache.py +289 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/llm_caching_handler.py +50 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/qdrant_semantic_cache.py +498 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cache.py +1710 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cluster_cache.py +109 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_semantic_cache.py +556 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/s3_cache.py +193 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/README.md +4 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/__init__.py +3 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (62.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_internal_context.cpython-310.pyc ADDED
Binary file (586 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports_registry.cpython-310.pyc ADDED
Binary file (29.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_logging.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis_credential_provider.cpython-310.pyc ADDED
Binary file (3.75 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_service_logger.cpython-310.pyc ADDED
Binary file (7.29 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_uuid.cpython-310.pyc ADDED
Binary file (458 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_version.cpython-310.pyc ADDED
Binary file (297 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/anthropic_beta_headers_manager.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/budget_manager.cpython-310.pyc ADDED
Binary file (6.44 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/constants.cpython-310.pyc ADDED
Binary file (38.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/cost_calculator.cpython-310.pyc ADDED
Binary file (44.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (23.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/scheduler.cpython-310.pyc ADDED
Binary file (4.65 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/setup_wizard.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/timeout.cpython-310.pyc ADDED
Binary file (3.76 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/__init__.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LiteLLM A2A - Wrapper for invoking A2A protocol agents.
3
+
4
+ This module provides a thin wrapper around the official `a2a` SDK that:
5
+ - Handles httpx client creation and agent card resolution
6
+ - Adds LiteLLM logging via @client decorator
7
+ - Matches the A2A SDK interface (SendMessageRequest, SendMessageResponse, etc.)
8
+
9
+ Example usage (standalone functions with @client decorator):
10
+ ```python
11
+ from litellm.a2a_protocol import asend_message
12
+ from a2a.types import SendMessageRequest, MessageSendParams
13
+ from uuid import uuid4
14
+
15
+ request = SendMessageRequest(
16
+ id=str(uuid4()),
17
+ params=MessageSendParams(
18
+ message={
19
+ "role": "user",
20
+ "parts": [{"kind": "text", "text": "Hello!"}],
21
+ "messageId": uuid4().hex,
22
+ }
23
+ )
24
+ )
25
+ response = await asend_message(
26
+ base_url="http://localhost:10001",
27
+ request=request,
28
+ )
29
+ print(response.model_dump(mode='json', exclude_none=True))
30
+ ```
31
+
32
+ Example usage (class-based):
33
+ ```python
34
+ from litellm.a2a_protocol import A2AClient
35
+
36
+ client = A2AClient(base_url="http://localhost:10001")
37
+ response = await client.send_message(request)
38
+ ```
39
+ """
40
+
41
+ from litellm.a2a_protocol.client import A2AClient
42
+ from litellm.a2a_protocol.exceptions import (
43
+ A2AAgentCardError,
44
+ A2AConnectionError,
45
+ A2AError,
46
+ A2ALocalhostURLError,
47
+ )
48
+ from litellm.a2a_protocol.main import (
49
+ aget_agent_card,
50
+ asend_message,
51
+ asend_message_streaming,
52
+ create_a2a_client,
53
+ send_message,
54
+ )
55
+ from litellm.types.agents import LiteLLMSendMessageResponse
56
+
57
+ __all__ = [
58
+ # Client
59
+ "A2AClient",
60
+ # Functions
61
+ "asend_message",
62
+ "send_message",
63
+ "asend_message_streaming",
64
+ "aget_agent_card",
65
+ "create_a2a_client",
66
+ # Response types
67
+ "LiteLLMSendMessageResponse",
68
+ # Exceptions
69
+ "A2AError",
70
+ "A2AConnectionError",
71
+ "A2AAgentCardError",
72
+ "A2ALocalhostURLError",
73
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/card_resolver.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom A2A Card Resolver for LiteLLM.
3
+
4
+ Extends the A2A SDK's card resolver to support multiple well-known paths.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, Any, Dict, Optional
8
+
9
+ from litellm._logging import verbose_logger
10
+ from litellm.constants import LOCALHOST_URL_PATTERNS
11
+
12
+ if TYPE_CHECKING:
13
+ from a2a.types import AgentCard
14
+
15
+ # Runtime imports with availability check
16
+ _A2ACardResolver: Any = None
17
+ AGENT_CARD_WELL_KNOWN_PATH: str = "/.well-known/agent-card.json"
18
+ PREV_AGENT_CARD_WELL_KNOWN_PATH: str = "/.well-known/agent.json"
19
+
20
+ try:
21
+ from a2a.client import A2ACardResolver as _A2ACardResolver # type: ignore[no-redef]
22
+ from a2a.utils.constants import ( # type: ignore[no-redef]
23
+ AGENT_CARD_WELL_KNOWN_PATH,
24
+ PREV_AGENT_CARD_WELL_KNOWN_PATH,
25
+ )
26
+ except ImportError:
27
+ pass
28
+
29
+
30
+ def is_localhost_or_internal_url(url: Optional[str]) -> bool:
31
+ """
32
+ Check if a URL is a localhost or internal URL.
33
+
34
+ This detects common development URLs that are accidentally left in
35
+ agent cards when deploying to production.
36
+
37
+ Args:
38
+ url: The URL to check
39
+
40
+ Returns:
41
+ True if the URL is localhost/internal
42
+ """
43
+ if not url:
44
+ return False
45
+
46
+ url_lower = url.lower()
47
+
48
+ return any(pattern in url_lower for pattern in LOCALHOST_URL_PATTERNS)
49
+
50
+
51
+ def fix_agent_card_url(agent_card: "AgentCard", base_url: str) -> "AgentCard":
52
+ """
53
+ Fix the agent card URL if it contains a localhost/internal address.
54
+
55
+ Many A2A agents are deployed with agent cards that contain internal URLs
56
+ like "http://0.0.0.0:8001/" or "http://localhost:8000/". This function
57
+ replaces such URLs with the provided base_url.
58
+
59
+ Args:
60
+ agent_card: The agent card to fix
61
+ base_url: The base URL to use as replacement
62
+
63
+ Returns:
64
+ The agent card with the URL fixed if necessary
65
+ """
66
+ card_url = getattr(agent_card, "url", None)
67
+
68
+ if card_url and is_localhost_or_internal_url(card_url):
69
+ # Normalize base_url to ensure it ends with /
70
+ fixed_url = base_url.rstrip("/") + "/"
71
+ agent_card.url = fixed_url
72
+
73
+ return agent_card
74
+
75
+
76
+ class LiteLLMA2ACardResolver(_A2ACardResolver): # type: ignore[misc]
77
+ """
78
+ Custom A2A card resolver that supports multiple well-known paths.
79
+
80
+ Extends the base A2ACardResolver to try both:
81
+ - /.well-known/agent-card.json (standard)
82
+ - /.well-known/agent.json (previous/alternative)
83
+ """
84
+
85
+ async def get_agent_card(
86
+ self,
87
+ relative_card_path: Optional[str] = None,
88
+ http_kwargs: Optional[Dict[str, Any]] = None,
89
+ ) -> "AgentCard":
90
+ """
91
+ Fetch the agent card, trying multiple well-known paths.
92
+
93
+ First tries the standard path, then falls back to the previous path.
94
+
95
+ Args:
96
+ relative_card_path: Optional path to the agent card endpoint.
97
+ If None, tries both well-known paths.
98
+ http_kwargs: Optional dictionary of keyword arguments to pass to httpx.get
99
+
100
+ Returns:
101
+ AgentCard from the A2A agent
102
+
103
+ Raises:
104
+ A2AClientHTTPError or A2AClientJSONError if both paths fail
105
+ """
106
+ # If a specific path is provided, use the parent implementation
107
+ if relative_card_path is not None:
108
+ return await super().get_agent_card(
109
+ relative_card_path=relative_card_path,
110
+ http_kwargs=http_kwargs,
111
+ )
112
+
113
+ # Try both well-known paths
114
+ paths = [
115
+ AGENT_CARD_WELL_KNOWN_PATH,
116
+ PREV_AGENT_CARD_WELL_KNOWN_PATH,
117
+ ]
118
+
119
+ last_error = None
120
+ for path in paths:
121
+ try:
122
+ verbose_logger.debug(
123
+ f"Attempting to fetch agent card from {self.base_url}{path}"
124
+ )
125
+ return await super().get_agent_card(
126
+ relative_card_path=path,
127
+ http_kwargs=http_kwargs,
128
+ )
129
+ except Exception as e:
130
+ verbose_logger.debug(
131
+ f"Failed to fetch agent card from {self.base_url}{path}: {e}"
132
+ )
133
+ last_error = e
134
+ continue
135
+
136
+ # If we get here, all paths failed - re-raise the last error
137
+ if last_error is not None:
138
+ raise last_error
139
+
140
+ # This shouldn't happen, but just in case
141
+ raise Exception(
142
+ f"Failed to fetch agent card from {self.base_url}. "
143
+ f"Tried paths: {', '.join(paths)}"
144
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/client.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LiteLLM A2A Client class.
3
+
4
+ Provides a class-based interface for A2A agent invocation.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, AsyncIterator, Dict, Optional
8
+
9
+ from litellm.types.agents import LiteLLMSendMessageResponse
10
+
11
+ if TYPE_CHECKING:
12
+ from a2a.client import A2AClient as A2AClientType
13
+ from a2a.types import (
14
+ AgentCard,
15
+ SendMessageRequest,
16
+ SendStreamingMessageRequest,
17
+ SendStreamingMessageResponse,
18
+ )
19
+
20
+
21
+ class A2AClient:
22
+ """
23
+ LiteLLM wrapper for A2A agent invocation.
24
+
25
+ Creates the underlying A2A client once on first use and reuses it.
26
+
27
+ Example:
28
+ ```python
29
+ from litellm.a2a_protocol import A2AClient
30
+ from a2a.types import SendMessageRequest, MessageSendParams
31
+ from uuid import uuid4
32
+
33
+ client = A2AClient(base_url="http://localhost:10001")
34
+
35
+ request = SendMessageRequest(
36
+ id=str(uuid4()),
37
+ params=MessageSendParams(
38
+ message={
39
+ "role": "user",
40
+ "parts": [{"kind": "text", "text": "Hello!"}],
41
+ "messageId": uuid4().hex,
42
+ }
43
+ )
44
+ )
45
+ response = await client.send_message(request)
46
+ ```
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ base_url: str,
52
+ timeout: float = 60.0,
53
+ extra_headers: Optional[Dict[str, str]] = None,
54
+ ):
55
+ """
56
+ Initialize the A2A client wrapper.
57
+
58
+ Args:
59
+ base_url: The base URL of the A2A agent (e.g., "http://localhost:10001")
60
+ timeout: Request timeout in seconds (default: 60.0)
61
+ extra_headers: Optional additional headers to include in requests
62
+ """
63
+ self.base_url = base_url
64
+ self.timeout = timeout
65
+ self.extra_headers = extra_headers
66
+ self._a2a_client: Optional["A2AClientType"] = None
67
+
68
+ async def _get_client(self) -> "A2AClientType":
69
+ """Get or create the underlying A2A client."""
70
+ if self._a2a_client is None:
71
+ from litellm.a2a_protocol.main import create_a2a_client
72
+
73
+ self._a2a_client = await create_a2a_client(
74
+ base_url=self.base_url,
75
+ timeout=self.timeout,
76
+ extra_headers=self.extra_headers,
77
+ )
78
+ return self._a2a_client
79
+
80
+ async def get_agent_card(self) -> "AgentCard":
81
+ """Fetch the agent card from the server."""
82
+ from litellm.a2a_protocol.main import aget_agent_card
83
+
84
+ return await aget_agent_card(
85
+ base_url=self.base_url,
86
+ timeout=self.timeout,
87
+ extra_headers=self.extra_headers,
88
+ )
89
+
90
+ async def send_message(
91
+ self, request: "SendMessageRequest"
92
+ ) -> LiteLLMSendMessageResponse:
93
+ """Send a message to the A2A agent."""
94
+ from litellm.a2a_protocol.main import asend_message
95
+
96
+ a2a_client = await self._get_client()
97
+ return await asend_message(a2a_client=a2a_client, request=request)
98
+
99
+ async def send_message_streaming(
100
+ self, request: "SendStreamingMessageRequest"
101
+ ) -> AsyncIterator["SendStreamingMessageResponse"]:
102
+ """Send a streaming message to the A2A agent."""
103
+ from litellm.a2a_protocol.main import asend_message_streaming
104
+
105
+ a2a_client = await self._get_client()
106
+ async for chunk in asend_message_streaming(
107
+ a2a_client=a2a_client, request=request
108
+ ):
109
+ yield chunk
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/cost_calculator.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cost calculator for A2A (Agent-to-Agent) calls.
3
+
4
+ Supports dynamic cost parameters that allow platform owners
5
+ to define custom costs per agent query or per token.
6
+ """
7
+
8
+ from typing import TYPE_CHECKING, Any, Optional
9
+
10
+ if TYPE_CHECKING:
11
+ from litellm.litellm_core_utils.litellm_logging import (
12
+ Logging as LitellmLoggingObject,
13
+ )
14
+ else:
15
+ LitellmLoggingObject = Any
16
+
17
+
18
+ class A2ACostCalculator:
19
+ @staticmethod
20
+ def calculate_a2a_cost(
21
+ litellm_logging_obj: Optional[LitellmLoggingObject],
22
+ ) -> float:
23
+ """
24
+ Calculate the cost of an A2A send_message call.
25
+
26
+ Supports multiple cost parameters for platform owners:
27
+ - cost_per_query: Fixed cost per query
28
+ - input_cost_per_token + output_cost_per_token: Token-based pricing
29
+
30
+ Priority order:
31
+ 1. response_cost - if set directly (backward compatibility)
32
+ 2. cost_per_query - fixed cost per query
33
+ 3. input_cost_per_token + output_cost_per_token - token-based cost
34
+ 4. Default to 0.0
35
+
36
+ Args:
37
+ litellm_logging_obj: The LiteLLM logging object containing call details
38
+
39
+ Returns:
40
+ float: The cost of the A2A call
41
+ """
42
+ if litellm_logging_obj is None:
43
+ return 0.0
44
+
45
+ model_call_details = litellm_logging_obj.model_call_details
46
+
47
+ # Check if user set a custom response cost (backward compatibility)
48
+ response_cost = model_call_details.get("response_cost", None)
49
+ if response_cost is not None:
50
+ return float(response_cost)
51
+
52
+ # Get litellm_params for cost parameters
53
+ litellm_params = model_call_details.get("litellm_params", {}) or {}
54
+
55
+ # Check for cost_per_query (fixed cost per query)
56
+ if litellm_params.get("cost_per_query") is not None:
57
+ return float(litellm_params["cost_per_query"])
58
+
59
+ # Check for token-based pricing
60
+ input_cost_per_token = litellm_params.get("input_cost_per_token")
61
+ output_cost_per_token = litellm_params.get("output_cost_per_token")
62
+
63
+ if input_cost_per_token is not None or output_cost_per_token is not None:
64
+ return A2ACostCalculator._calculate_token_based_cost(
65
+ model_call_details=model_call_details,
66
+ input_cost_per_token=input_cost_per_token,
67
+ output_cost_per_token=output_cost_per_token,
68
+ )
69
+
70
+ # Default to 0.0 for A2A calls
71
+ return 0.0
72
+
73
+ @staticmethod
74
+ def _calculate_token_based_cost(
75
+ model_call_details: dict,
76
+ input_cost_per_token: Optional[float],
77
+ output_cost_per_token: Optional[float],
78
+ ) -> float:
79
+ """
80
+ Calculate cost based on token usage and per-token pricing.
81
+
82
+ Args:
83
+ model_call_details: The model call details containing usage
84
+ input_cost_per_token: Cost per input token (can be None, defaults to 0)
85
+ output_cost_per_token: Cost per output token (can be None, defaults to 0)
86
+
87
+ Returns:
88
+ float: The calculated cost
89
+ """
90
+ # Get usage from model_call_details
91
+ usage = model_call_details.get("usage")
92
+ if usage is None:
93
+ return 0.0
94
+
95
+ # Get token counts
96
+ prompt_tokens = getattr(usage, "prompt_tokens", 0) or 0
97
+ completion_tokens = getattr(usage, "completion_tokens", 0) or 0
98
+
99
+ # Calculate costs
100
+ input_cost = prompt_tokens * (
101
+ float(input_cost_per_token) if input_cost_per_token else 0.0
102
+ )
103
+ output_cost = completion_tokens * (
104
+ float(output_cost_per_token) if output_cost_per_token else 0.0
105
+ )
106
+
107
+ return input_cost + output_cost
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exception_mapping_utils.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A2A Protocol Exception Mapping Utils.
3
+
4
+ Maps A2A SDK exceptions to LiteLLM A2A exception types.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, Any, Optional
8
+
9
+ from litellm._logging import verbose_logger
10
+ from litellm.a2a_protocol.card_resolver import (
11
+ fix_agent_card_url,
12
+ is_localhost_or_internal_url,
13
+ )
14
+ from litellm.a2a_protocol.exceptions import (
15
+ A2AAgentCardError,
16
+ A2AConnectionError,
17
+ A2AError,
18
+ A2ALocalhostURLError,
19
+ )
20
+ from litellm.constants import CONNECTION_ERROR_PATTERNS
21
+
22
+ if TYPE_CHECKING:
23
+ from a2a.client import A2AClient as A2AClientType
24
+
25
+
26
+ # Runtime import
27
+ A2A_SDK_AVAILABLE = False
28
+ try:
29
+ from a2a.client import A2AClient as _A2AClient # type: ignore[no-redef]
30
+
31
+ A2A_SDK_AVAILABLE = True
32
+ except ImportError:
33
+ _A2AClient = None # type: ignore[assignment, misc]
34
+
35
+
36
+ class A2AExceptionCheckers:
37
+ """
38
+ Helper class for checking various A2A error conditions.
39
+ """
40
+
41
+ @staticmethod
42
+ def is_connection_error(error_str: str) -> bool:
43
+ """
44
+ Check if an error string indicates a connection error.
45
+
46
+ Args:
47
+ error_str: The error string to check
48
+
49
+ Returns:
50
+ True if the error indicates a connection issue
51
+ """
52
+ if not isinstance(error_str, str):
53
+ return False
54
+
55
+ error_str_lower = error_str.lower()
56
+ return any(pattern in error_str_lower for pattern in CONNECTION_ERROR_PATTERNS)
57
+
58
+ @staticmethod
59
+ def is_localhost_url(url: Optional[str]) -> bool:
60
+ """
61
+ Check if a URL is a localhost/internal URL.
62
+
63
+ Args:
64
+ url: The URL to check
65
+
66
+ Returns:
67
+ True if the URL is localhost/internal
68
+ """
69
+ return is_localhost_or_internal_url(url)
70
+
71
+ @staticmethod
72
+ def is_agent_card_error(error_str: str) -> bool:
73
+ """
74
+ Check if an error string indicates an agent card error.
75
+
76
+ Args:
77
+ error_str: The error string to check
78
+
79
+ Returns:
80
+ True if the error is related to agent card fetching/parsing
81
+ """
82
+ if not isinstance(error_str, str):
83
+ return False
84
+
85
+ error_str_lower = error_str.lower()
86
+ agent_card_patterns = [
87
+ "agent card",
88
+ "agent-card",
89
+ ".well-known",
90
+ "card not found",
91
+ "invalid agent",
92
+ ]
93
+ return any(pattern in error_str_lower for pattern in agent_card_patterns)
94
+
95
+
96
+ def map_a2a_exception(
97
+ original_exception: Exception,
98
+ card_url: Optional[str] = None,
99
+ api_base: Optional[str] = None,
100
+ model: Optional[str] = None,
101
+ ) -> Exception:
102
+ """
103
+ Map an A2A SDK exception to a LiteLLM A2A exception type.
104
+
105
+ Args:
106
+ original_exception: The original exception from the A2A SDK
107
+ card_url: The URL from the agent card (if available)
108
+ api_base: The original API base URL
109
+ model: The model/agent name
110
+
111
+ Returns:
112
+ A mapped LiteLLM A2A exception
113
+
114
+ Raises:
115
+ A2ALocalhostURLError: If the error is a connection error to a localhost URL
116
+ A2AConnectionError: If the error is a general connection error
117
+ A2AAgentCardError: If the error is related to agent card issues
118
+ A2AError: For other A2A-related errors
119
+ """
120
+ error_str = str(original_exception)
121
+
122
+ # Check for localhost URL connection error (special case - retryable)
123
+ if (
124
+ card_url
125
+ and api_base
126
+ and A2AExceptionCheckers.is_localhost_url(card_url)
127
+ and A2AExceptionCheckers.is_connection_error(error_str)
128
+ ):
129
+ raise A2ALocalhostURLError(
130
+ localhost_url=card_url,
131
+ base_url=api_base,
132
+ original_error=original_exception,
133
+ model=model,
134
+ )
135
+
136
+ # Check for agent card errors
137
+ if A2AExceptionCheckers.is_agent_card_error(error_str):
138
+ raise A2AAgentCardError(
139
+ message=error_str,
140
+ url=api_base,
141
+ model=model,
142
+ )
143
+
144
+ # Check for general connection errors
145
+ if A2AExceptionCheckers.is_connection_error(error_str):
146
+ raise A2AConnectionError(
147
+ message=error_str,
148
+ url=card_url or api_base,
149
+ model=model,
150
+ )
151
+
152
+ # Default: wrap in generic A2AError
153
+ raise A2AError(
154
+ message=error_str,
155
+ model=model,
156
+ )
157
+
158
+
159
+ def handle_a2a_localhost_retry(
160
+ error: A2ALocalhostURLError,
161
+ agent_card: Any,
162
+ a2a_client: "A2AClientType",
163
+ is_streaming: bool = False,
164
+ ) -> "A2AClientType":
165
+ """
166
+ Handle A2ALocalhostURLError by fixing the URL and creating a new client.
167
+
168
+ This is called when we catch an A2ALocalhostURLError and want to retry
169
+ with the corrected URL.
170
+
171
+ Args:
172
+ error: The localhost URL error
173
+ agent_card: The agent card object to fix
174
+ a2a_client: The current A2A client
175
+ is_streaming: Whether this is a streaming request (for logging)
176
+
177
+ Returns:
178
+ A new A2A client with the fixed URL
179
+
180
+ Raises:
181
+ ImportError: If the A2A SDK is not installed
182
+ """
183
+ if not A2A_SDK_AVAILABLE or _A2AClient is None:
184
+ raise ImportError(
185
+ "A2A SDK is required for localhost retry handling. "
186
+ "Install it with: pip install a2a"
187
+ )
188
+
189
+ request_type = "streaming " if is_streaming else ""
190
+ verbose_logger.warning(
191
+ f"A2A {request_type}request to '{error.localhost_url}' failed: {error.original_error}. "
192
+ f"Agent card contains localhost/internal URL. "
193
+ f"Retrying with base_url '{error.base_url}'."
194
+ )
195
+
196
+ # Fix the agent card URL
197
+ fix_agent_card_url(agent_card, error.base_url)
198
+
199
+ # Create a new client with the fixed agent card (transport caches URL)
200
+ return _A2AClient(
201
+ httpx_client=a2a_client._transport.httpx_client, # type: ignore[union-attr]
202
+ agent_card=agent_card,
203
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exceptions.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A2A Protocol Exceptions.
3
+
4
+ Custom exception types for A2A protocol operations, following LiteLLM's exception pattern.
5
+ """
6
+
7
+ from typing import Optional
8
+
9
+ import httpx
10
+
11
+
12
+ class A2AError(Exception):
13
+ """
14
+ Base exception for A2A protocol errors.
15
+
16
+ Follows the same pattern as LiteLLM's main exceptions.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ status_code: int = 500,
23
+ llm_provider: str = "a2a_agent",
24
+ model: Optional[str] = None,
25
+ response: Optional[httpx.Response] = None,
26
+ litellm_debug_info: Optional[str] = None,
27
+ max_retries: Optional[int] = None,
28
+ num_retries: Optional[int] = None,
29
+ ):
30
+ self.status_code = status_code
31
+ self.message = f"litellm.A2AError: {message}"
32
+ self.llm_provider = llm_provider
33
+ self.model = model
34
+ self.litellm_debug_info = litellm_debug_info
35
+ self.max_retries = max_retries
36
+ self.num_retries = num_retries
37
+ self.response = response or httpx.Response(
38
+ status_code=self.status_code,
39
+ request=httpx.Request(method="POST", url="https://litellm.ai"),
40
+ )
41
+ super().__init__(self.message)
42
+
43
+ def __str__(self) -> str:
44
+ _message = self.message
45
+ if self.num_retries:
46
+ _message += f" LiteLLM Retried: {self.num_retries} times"
47
+ if self.max_retries:
48
+ _message += f", LiteLLM Max Retries: {self.max_retries}"
49
+ return _message
50
+
51
+ def __repr__(self) -> str:
52
+ return self.__str__()
53
+
54
+
55
+ class A2AConnectionError(A2AError):
56
+ """
57
+ Raised when connection to an A2A agent fails.
58
+
59
+ This typically occurs when:
60
+ - The agent is unreachable
61
+ - The agent card contains a localhost/internal URL
62
+ - Network issues prevent connection
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ message: str,
68
+ url: Optional[str] = None,
69
+ model: Optional[str] = None,
70
+ response: Optional[httpx.Response] = None,
71
+ litellm_debug_info: Optional[str] = None,
72
+ max_retries: Optional[int] = None,
73
+ num_retries: Optional[int] = None,
74
+ ):
75
+ self.url = url
76
+ super().__init__(
77
+ message=message,
78
+ status_code=503,
79
+ llm_provider="a2a_agent",
80
+ model=model,
81
+ response=response,
82
+ litellm_debug_info=litellm_debug_info,
83
+ max_retries=max_retries,
84
+ num_retries=num_retries,
85
+ )
86
+
87
+
88
+ class A2AAgentCardError(A2AError):
89
+ """
90
+ Raised when there's an issue with the agent card.
91
+
92
+ This includes:
93
+ - Failed to fetch agent card
94
+ - Invalid agent card format
95
+ - Missing required fields
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ message: str,
101
+ url: Optional[str] = None,
102
+ model: Optional[str] = None,
103
+ response: Optional[httpx.Response] = None,
104
+ litellm_debug_info: Optional[str] = None,
105
+ ):
106
+ self.url = url
107
+ super().__init__(
108
+ message=message,
109
+ status_code=404,
110
+ llm_provider="a2a_agent",
111
+ model=model,
112
+ response=response,
113
+ litellm_debug_info=litellm_debug_info,
114
+ )
115
+
116
+
117
+ class A2ALocalhostURLError(A2AConnectionError):
118
+ """
119
+ Raised when an agent card contains a localhost/internal URL.
120
+
121
+ Many A2A agents are deployed with agent cards that contain internal URLs
122
+ like "http://0.0.0.0:8001/" or "http://localhost:8000/". This error
123
+ indicates that the URL needs to be corrected and the request should be retried.
124
+
125
+ Attributes:
126
+ localhost_url: The localhost/internal URL found in the agent card
127
+ base_url: The public base URL that should be used instead
128
+ original_error: The original connection error that was raised
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ localhost_url: str,
134
+ base_url: str,
135
+ original_error: Optional[Exception] = None,
136
+ model: Optional[str] = None,
137
+ ):
138
+ self.localhost_url = localhost_url
139
+ self.base_url = base_url
140
+ self.original_error = original_error
141
+
142
+ message = (
143
+ f"Agent card contains localhost/internal URL '{localhost_url}'. "
144
+ f"Retrying with base URL '{base_url}'."
145
+ )
146
+ super().__init__(
147
+ message=message,
148
+ url=localhost_url,
149
+ model=model,
150
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/main.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LiteLLM A2A SDK functions.
3
+
4
+ Provides standalone functions with @client decorator for LiteLLM logging integration.
5
+ """
6
+
7
+ import asyncio
8
+ import datetime
9
+ import uuid
10
+ from typing import TYPE_CHECKING, Any, AsyncIterator, Coroutine, Dict, Optional, Union
11
+
12
+ import litellm
13
+ from litellm._logging import verbose_logger, verbose_proxy_logger
14
+ from litellm.a2a_protocol.streaming_iterator import A2AStreamingIterator
15
+ from litellm.a2a_protocol.utils import A2ARequestUtils
16
+ from litellm.constants import DEFAULT_A2A_AGENT_TIMEOUT
17
+ from litellm.litellm_core_utils.litellm_logging import Logging
18
+ from litellm.llms.custom_httpx.http_handler import (
19
+ get_async_httpx_client,
20
+ httpxSpecialProvider,
21
+ )
22
+ from litellm.types.agents import LiteLLMSendMessageResponse
23
+ from litellm.utils import client
24
+
25
+ if TYPE_CHECKING:
26
+ from a2a.client import A2AClient as A2AClientType
27
+ from a2a.types import AgentCard, SendMessageRequest, SendStreamingMessageRequest
28
+
29
+ # Runtime imports with availability check
30
+ A2A_SDK_AVAILABLE = False
31
+ A2ACardResolver: Any = None
32
+ _A2AClient: Any = None
33
+
34
+ try:
35
+ from a2a.client import A2AClient as _A2AClient # type: ignore[no-redef]
36
+
37
+ A2A_SDK_AVAILABLE = True
38
+ except ImportError:
39
+ pass
40
+
41
+ # Import our custom card resolver that supports multiple well-known paths
42
+ from litellm.a2a_protocol.card_resolver import LiteLLMA2ACardResolver
43
+ from litellm.a2a_protocol.exception_mapping_utils import (
44
+ handle_a2a_localhost_retry,
45
+ map_a2a_exception,
46
+ )
47
+ from litellm.a2a_protocol.exceptions import A2ALocalhostURLError
48
+
49
+ # Use our custom resolver instead of the default A2A SDK resolver
50
+ A2ACardResolver = LiteLLMA2ACardResolver
51
+
52
+
53
+ def _set_usage_on_logging_obj(
54
+ kwargs: Dict[str, Any],
55
+ prompt_tokens: int,
56
+ completion_tokens: int,
57
+ ) -> None:
58
+ """
59
+ Set usage on litellm_logging_obj for standard logging payload.
60
+
61
+ Args:
62
+ kwargs: The kwargs dict containing litellm_logging_obj
63
+ prompt_tokens: Number of input tokens
64
+ completion_tokens: Number of output tokens
65
+ """
66
+ litellm_logging_obj = kwargs.get("litellm_logging_obj")
67
+ if litellm_logging_obj is not None:
68
+ usage = litellm.Usage(
69
+ prompt_tokens=prompt_tokens,
70
+ completion_tokens=completion_tokens,
71
+ total_tokens=prompt_tokens + completion_tokens,
72
+ )
73
+ litellm_logging_obj.model_call_details["usage"] = usage
74
+
75
+
76
+ def _set_agent_id_on_logging_obj(
77
+ kwargs: Dict[str, Any],
78
+ agent_id: Optional[str],
79
+ ) -> None:
80
+ """
81
+ Set agent_id on litellm_logging_obj for SpendLogs tracking.
82
+
83
+ Args:
84
+ kwargs: The kwargs dict containing litellm_logging_obj
85
+ agent_id: The A2A agent ID
86
+ """
87
+ if agent_id is None:
88
+ return
89
+
90
+ litellm_logging_obj = kwargs.get("litellm_logging_obj")
91
+ if litellm_logging_obj is not None:
92
+ # Set agent_id directly on model_call_details (same pattern as custom_llm_provider)
93
+ litellm_logging_obj.model_call_details["agent_id"] = agent_id
94
+
95
+
96
+ def _get_a2a_model_info(a2a_client: Any, kwargs: Dict[str, Any]) -> str:
97
+ """
98
+ Extract agent info and set model/custom_llm_provider for cost tracking.
99
+
100
+ Sets model info on the litellm_logging_obj if available.
101
+ Returns the agent name for logging.
102
+ """
103
+ agent_name = "unknown"
104
+
105
+ # Try to get agent card from our stored attribute first, then fallback to SDK attribute
106
+ agent_card = getattr(a2a_client, "_litellm_agent_card", None)
107
+ if agent_card is None:
108
+ agent_card = getattr(a2a_client, "agent_card", None)
109
+
110
+ if agent_card is not None:
111
+ agent_name = getattr(agent_card, "name", "unknown") or "unknown"
112
+
113
+ # Build model string
114
+ model = f"a2a_agent/{agent_name}"
115
+ custom_llm_provider = "a2a_agent"
116
+
117
+ # Set on litellm_logging_obj if available (for standard logging payload)
118
+ litellm_logging_obj = kwargs.get("litellm_logging_obj")
119
+ if litellm_logging_obj is not None:
120
+ litellm_logging_obj.model = model
121
+ litellm_logging_obj.custom_llm_provider = custom_llm_provider
122
+ litellm_logging_obj.model_call_details["model"] = model
123
+ litellm_logging_obj.model_call_details["custom_llm_provider"] = (
124
+ custom_llm_provider
125
+ )
126
+
127
+ return agent_name
128
+
129
+
130
+ async def _send_message_via_completion_bridge(
131
+ request: "SendMessageRequest",
132
+ custom_llm_provider: str,
133
+ api_base: Optional[str],
134
+ litellm_params: Dict[str, Any],
135
+ ) -> LiteLLMSendMessageResponse:
136
+ """
137
+ Route a send_message through the LiteLLM completion bridge (e.g. LangGraph, Bedrock AgentCore).
138
+
139
+ Requires request; api_base is optional for providers that derive endpoint from model.
140
+ """
141
+ verbose_logger.info(
142
+ f"A2A using completion bridge: provider={custom_llm_provider}, api_base={api_base}"
143
+ )
144
+
145
+ from litellm.a2a_protocol.litellm_completion_bridge.handler import (
146
+ A2ACompletionBridgeHandler,
147
+ )
148
+
149
+ params = (
150
+ request.params.model_dump(mode="json")
151
+ if hasattr(request.params, "model_dump")
152
+ else dict(request.params)
153
+ )
154
+
155
+ response_dict = await A2ACompletionBridgeHandler.handle_non_streaming(
156
+ request_id=str(request.id),
157
+ params=params,
158
+ litellm_params=litellm_params,
159
+ api_base=api_base,
160
+ )
161
+
162
+ return LiteLLMSendMessageResponse.from_dict(response_dict)
163
+
164
+
165
+ async def _execute_a2a_send_with_retry(
166
+ a2a_client: Any,
167
+ request: Any,
168
+ agent_card: Any,
169
+ card_url: Optional[str],
170
+ api_base: Optional[str],
171
+ agent_name: Optional[str],
172
+ ) -> Any:
173
+ """Send an A2A message with retry logic for localhost URL errors."""
174
+ a2a_response = None
175
+ for _ in range(2): # max 2 attempts: original + 1 retry
176
+ try:
177
+ a2a_response = await a2a_client.send_message(request)
178
+ break # success, exit retry loop
179
+ except A2ALocalhostURLError as e:
180
+ a2a_client = handle_a2a_localhost_retry(
181
+ error=e,
182
+ agent_card=agent_card,
183
+ a2a_client=a2a_client,
184
+ is_streaming=False,
185
+ )
186
+ card_url = agent_card.url if agent_card else None
187
+ except Exception as e:
188
+ try:
189
+ map_a2a_exception(e, card_url, api_base, model=agent_name)
190
+ except A2ALocalhostURLError as localhost_err:
191
+ a2a_client = handle_a2a_localhost_retry(
192
+ error=localhost_err,
193
+ agent_card=agent_card,
194
+ a2a_client=a2a_client,
195
+ is_streaming=False,
196
+ )
197
+ card_url = agent_card.url if agent_card else None
198
+ continue
199
+ except Exception:
200
+ raise
201
+ if a2a_response is None:
202
+ raise RuntimeError(
203
+ "A2A send_message failed: no response received after retry attempts."
204
+ )
205
+ return a2a_response
206
+
207
+
208
+ @client
209
+ async def asend_message(
210
+ a2a_client: Optional["A2AClientType"] = None,
211
+ request: Optional["SendMessageRequest"] = None,
212
+ api_base: Optional[str] = None,
213
+ litellm_params: Optional[Dict[str, Any]] = None,
214
+ agent_id: Optional[str] = None,
215
+ agent_extra_headers: Optional[Dict[str, str]] = None,
216
+ **kwargs: Any,
217
+ ) -> LiteLLMSendMessageResponse:
218
+ """
219
+ Async: Send a message to an A2A agent.
220
+
221
+ Uses the @client decorator for LiteLLM logging and tracking.
222
+ If litellm_params contains custom_llm_provider, routes through the completion bridge.
223
+
224
+ Args:
225
+ a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
226
+ request: SendMessageRequest from a2a.types (optional if using completion bridge with api_base)
227
+ api_base: API base URL (required for completion bridge, optional for standard A2A)
228
+ litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
229
+ agent_id: Optional agent ID for tracking in SpendLogs
230
+ **kwargs: Additional arguments passed to the client decorator
231
+
232
+ Returns:
233
+ LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params)
234
+
235
+ Example (standard A2A):
236
+ ```python
237
+ from litellm.a2a_protocol import asend_message, create_a2a_client
238
+ from a2a.types import SendMessageRequest, MessageSendParams
239
+ from uuid import uuid4
240
+
241
+ a2a_client = await create_a2a_client(base_url="http://localhost:10001")
242
+ request = SendMessageRequest(
243
+ id=str(uuid4()),
244
+ params=MessageSendParams(
245
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
246
+ )
247
+ )
248
+ response = await asend_message(a2a_client=a2a_client, request=request)
249
+ ```
250
+
251
+ Example (completion bridge with LangGraph):
252
+ ```python
253
+ from litellm.a2a_protocol import asend_message
254
+ from a2a.types import SendMessageRequest, MessageSendParams
255
+ from uuid import uuid4
256
+
257
+ request = SendMessageRequest(
258
+ id=str(uuid4()),
259
+ params=MessageSendParams(
260
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
261
+ )
262
+ )
263
+ response = await asend_message(
264
+ request=request,
265
+ api_base="http://localhost:2024",
266
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
267
+ )
268
+ ```
269
+ """
270
+ litellm_params = litellm_params or {}
271
+ logging_obj = kwargs.get("litellm_logging_obj")
272
+ trace_id = getattr(logging_obj, "litellm_trace_id", None) if logging_obj else None
273
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
274
+
275
+ # Route through completion bridge if custom_llm_provider is set
276
+ if custom_llm_provider:
277
+ if request is None:
278
+ raise ValueError("request is required for completion bridge")
279
+ return await _send_message_via_completion_bridge(
280
+ request=request,
281
+ custom_llm_provider=custom_llm_provider,
282
+ api_base=api_base,
283
+ litellm_params=litellm_params,
284
+ )
285
+
286
+ # Standard A2A client flow
287
+ if request is None:
288
+ raise ValueError("request is required")
289
+
290
+ # Create A2A client if not provided but api_base is available
291
+ if a2a_client is None:
292
+ if api_base is None:
293
+ raise ValueError(
294
+ "Either a2a_client or api_base is required for standard A2A flow"
295
+ )
296
+ trace_id = trace_id or str(uuid.uuid4())
297
+ extra_headers: Dict[str, str] = {"X-LiteLLM-Trace-Id": trace_id}
298
+ if agent_id:
299
+ extra_headers["X-LiteLLM-Agent-Id"] = agent_id
300
+ # Overlay agent-level headers (agent headers take precedence over LiteLLM internal ones)
301
+ if agent_extra_headers:
302
+ extra_headers.update(agent_extra_headers)
303
+ a2a_client = await create_a2a_client(
304
+ base_url=api_base, extra_headers=extra_headers
305
+ )
306
+
307
+ # Type assertion: a2a_client is guaranteed to be non-None here
308
+ assert a2a_client is not None
309
+
310
+ agent_name = _get_a2a_model_info(a2a_client, kwargs)
311
+
312
+ verbose_logger.info(f"A2A send_message request_id={request.id}, agent={agent_name}")
313
+
314
+ # Get agent card URL for localhost retry logic
315
+ agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr(
316
+ a2a_client, "agent_card", None
317
+ )
318
+ card_url = getattr(agent_card, "url", None) if agent_card else None
319
+
320
+ context_id = trace_id or str(uuid.uuid4())
321
+ message = request.params.message
322
+ if isinstance(message, dict):
323
+ if message.get("context_id") is None:
324
+ message["context_id"] = context_id
325
+ else:
326
+ if getattr(message, "context_id", None) is None:
327
+ message.context_id = context_id
328
+
329
+ a2a_response = await _execute_a2a_send_with_retry(
330
+ a2a_client=a2a_client,
331
+ request=request,
332
+ agent_card=agent_card,
333
+ card_url=card_url,
334
+ api_base=api_base,
335
+ agent_name=agent_name,
336
+ )
337
+
338
+ verbose_logger.info(f"A2A send_message completed, request_id={request.id}")
339
+
340
+ # Wrap in LiteLLM response type for _hidden_params support
341
+ response = LiteLLMSendMessageResponse.from_a2a_response(a2a_response)
342
+
343
+ # Calculate token usage from request and response
344
+ response_dict = a2a_response.model_dump(mode="json", exclude_none=True)
345
+ (
346
+ prompt_tokens,
347
+ completion_tokens,
348
+ _,
349
+ ) = A2ARequestUtils.calculate_usage_from_request_response(
350
+ request=request,
351
+ response_dict=response_dict,
352
+ )
353
+
354
+ # Set usage on logging obj for standard logging payload
355
+ _set_usage_on_logging_obj(
356
+ kwargs=kwargs,
357
+ prompt_tokens=prompt_tokens,
358
+ completion_tokens=completion_tokens,
359
+ )
360
+
361
+ # Set agent_id on logging obj for SpendLogs tracking
362
+ _set_agent_id_on_logging_obj(kwargs=kwargs, agent_id=agent_id)
363
+
364
+ return response
365
+
366
+
367
+ @client
368
+ def send_message(
369
+ a2a_client: "A2AClientType",
370
+ request: "SendMessageRequest",
371
+ **kwargs: Any,
372
+ ) -> Union[LiteLLMSendMessageResponse, Coroutine[Any, Any, LiteLLMSendMessageResponse]]:
373
+ """
374
+ Sync: Send a message to an A2A agent.
375
+
376
+ Uses the @client decorator for LiteLLM logging and tracking.
377
+
378
+ Args:
379
+ a2a_client: An initialized a2a.client.A2AClient instance
380
+ request: SendMessageRequest from a2a.types
381
+ **kwargs: Additional arguments passed to the client decorator
382
+
383
+ Returns:
384
+ LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params)
385
+ """
386
+ try:
387
+ loop = asyncio.get_running_loop()
388
+ except RuntimeError:
389
+ loop = None
390
+
391
+ if loop is not None:
392
+ return asend_message(a2a_client=a2a_client, request=request, **kwargs)
393
+ else:
394
+ return asyncio.run(
395
+ asend_message(a2a_client=a2a_client, request=request, **kwargs)
396
+ )
397
+
398
+
399
+ def _build_streaming_logging_obj(
400
+ request: "SendStreamingMessageRequest",
401
+ agent_name: str,
402
+ agent_id: Optional[str],
403
+ litellm_params: Optional[Dict[str, Any]],
404
+ metadata: Optional[Dict[str, Any]],
405
+ proxy_server_request: Optional[Dict[str, Any]],
406
+ ) -> Logging:
407
+ """Build logging object for streaming A2A requests."""
408
+ start_time = datetime.datetime.now()
409
+ model = f"a2a_agent/{agent_name}"
410
+
411
+ logging_obj = Logging(
412
+ model=model,
413
+ messages=[{"role": "user", "content": "streaming-request"}],
414
+ stream=False,
415
+ call_type="asend_message_streaming",
416
+ start_time=start_time,
417
+ litellm_call_id=str(request.id),
418
+ function_id=str(request.id),
419
+ )
420
+ logging_obj.model = model
421
+ logging_obj.custom_llm_provider = "a2a_agent"
422
+ logging_obj.model_call_details["model"] = model
423
+ logging_obj.model_call_details["custom_llm_provider"] = "a2a_agent"
424
+ if agent_id:
425
+ logging_obj.model_call_details["agent_id"] = agent_id
426
+
427
+ _litellm_params = litellm_params.copy() if litellm_params else {}
428
+ if metadata:
429
+ _litellm_params["metadata"] = metadata
430
+ if proxy_server_request:
431
+ _litellm_params["proxy_server_request"] = proxy_server_request
432
+
433
+ logging_obj.litellm_params = _litellm_params
434
+ logging_obj.optional_params = _litellm_params
435
+ logging_obj.model_call_details["litellm_params"] = _litellm_params
436
+ logging_obj.model_call_details["metadata"] = metadata or {}
437
+
438
+ return logging_obj
439
+
440
+
441
+ async def asend_message_streaming( # noqa: PLR0915
442
+ a2a_client: Optional["A2AClientType"] = None,
443
+ request: Optional["SendStreamingMessageRequest"] = None,
444
+ api_base: Optional[str] = None,
445
+ litellm_params: Optional[Dict[str, Any]] = None,
446
+ agent_id: Optional[str] = None,
447
+ metadata: Optional[Dict[str, Any]] = None,
448
+ proxy_server_request: Optional[Dict[str, Any]] = None,
449
+ agent_extra_headers: Optional[Dict[str, str]] = None,
450
+ ) -> AsyncIterator[Any]:
451
+ """
452
+ Async: Send a streaming message to an A2A agent.
453
+
454
+ If litellm_params contains custom_llm_provider, routes through the completion bridge.
455
+
456
+ Args:
457
+ a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
458
+ request: SendStreamingMessageRequest from a2a.types
459
+ api_base: API base URL (required for completion bridge)
460
+ litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
461
+ agent_id: Optional agent ID for tracking in SpendLogs
462
+ metadata: Optional metadata dict (contains user_api_key, user_id, team_id, etc.)
463
+ proxy_server_request: Optional proxy server request data
464
+
465
+ Yields:
466
+ SendStreamingMessageResponse chunks from the agent
467
+
468
+ Example (completion bridge with LangGraph):
469
+ ```python
470
+ from litellm.a2a_protocol import asend_message_streaming
471
+ from a2a.types import SendStreamingMessageRequest, MessageSendParams
472
+ from uuid import uuid4
473
+
474
+ request = SendStreamingMessageRequest(
475
+ id=str(uuid4()),
476
+ params=MessageSendParams(
477
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
478
+ )
479
+ )
480
+ async for chunk in asend_message_streaming(
481
+ request=request,
482
+ api_base="http://localhost:2024",
483
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
484
+ ):
485
+ print(chunk)
486
+ ```
487
+ """
488
+ litellm_params = litellm_params or {}
489
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
490
+
491
+ # Route through completion bridge if custom_llm_provider is set
492
+ if custom_llm_provider:
493
+ if request is None:
494
+ raise ValueError("request is required for completion bridge")
495
+ # api_base is optional for providers that derive endpoint from model (e.g., bedrock/agentcore)
496
+
497
+ verbose_logger.info(
498
+ f"A2A streaming using completion bridge: provider={custom_llm_provider}"
499
+ )
500
+
501
+ from litellm.a2a_protocol.litellm_completion_bridge.handler import (
502
+ A2ACompletionBridgeHandler,
503
+ )
504
+
505
+ # Extract params from request
506
+ params = (
507
+ request.params.model_dump(mode="json")
508
+ if hasattr(request.params, "model_dump")
509
+ else dict(request.params)
510
+ )
511
+
512
+ async for chunk in A2ACompletionBridgeHandler.handle_streaming(
513
+ request_id=str(request.id),
514
+ params=params,
515
+ litellm_params=litellm_params,
516
+ api_base=api_base,
517
+ ):
518
+ yield chunk
519
+ return
520
+
521
+ # Standard A2A client flow
522
+ if request is None:
523
+ raise ValueError("request is required")
524
+
525
+ # Create A2A client if not provided but api_base is available
526
+ if a2a_client is None:
527
+ if api_base is None:
528
+ raise ValueError(
529
+ "Either a2a_client or api_base is required for standard A2A flow"
530
+ )
531
+ # Mirror the non-streaming path: always include trace and agent-id headers
532
+ streaming_extra_headers: Dict[str, str] = {
533
+ "X-LiteLLM-Trace-Id": str(request.id),
534
+ }
535
+ if agent_id:
536
+ streaming_extra_headers["X-LiteLLM-Agent-Id"] = agent_id
537
+ if agent_extra_headers:
538
+ streaming_extra_headers.update(agent_extra_headers)
539
+ a2a_client = await create_a2a_client(
540
+ base_url=api_base, extra_headers=streaming_extra_headers
541
+ )
542
+
543
+ # Type assertion: a2a_client is guaranteed to be non-None here
544
+ assert a2a_client is not None
545
+
546
+ verbose_logger.info(f"A2A send_message_streaming request_id={request.id}")
547
+
548
+ # Build logging object for streaming completion callbacks
549
+ agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr(
550
+ a2a_client, "agent_card", None
551
+ )
552
+ card_url = getattr(agent_card, "url", None) if agent_card else None
553
+ agent_name = getattr(agent_card, "name", "unknown") if agent_card else "unknown"
554
+
555
+ logging_obj = _build_streaming_logging_obj(
556
+ request=request,
557
+ agent_name=agent_name,
558
+ agent_id=agent_id,
559
+ litellm_params=litellm_params,
560
+ metadata=metadata,
561
+ proxy_server_request=proxy_server_request,
562
+ )
563
+
564
+ # Retry loop: if connection fails due to localhost URL in agent card, retry with fixed URL
565
+ # Connection errors in streaming typically occur on first chunk iteration
566
+ first_chunk = True
567
+ for attempt in range(2): # max 2 attempts: original + 1 retry
568
+ stream = a2a_client.send_message_streaming(request)
569
+ iterator = A2AStreamingIterator(
570
+ stream=stream,
571
+ request=request,
572
+ logging_obj=logging_obj,
573
+ agent_name=agent_name,
574
+ )
575
+
576
+ try:
577
+ first_chunk = True
578
+ async for chunk in iterator:
579
+ if first_chunk:
580
+ first_chunk = False # connection succeeded
581
+ yield chunk
582
+ return # stream completed successfully
583
+ except A2ALocalhostURLError as e:
584
+ # Only retry on first chunk, not mid-stream
585
+ if first_chunk and attempt == 0:
586
+ a2a_client = handle_a2a_localhost_retry(
587
+ error=e,
588
+ agent_card=agent_card,
589
+ a2a_client=a2a_client,
590
+ is_streaming=True,
591
+ )
592
+ card_url = agent_card.url if agent_card else None
593
+ else:
594
+ raise
595
+ except Exception as e:
596
+ # Only map exception on first chunk
597
+ if first_chunk and attempt == 0:
598
+ try:
599
+ map_a2a_exception(e, card_url, api_base, model=agent_name)
600
+ except A2ALocalhostURLError as localhost_err:
601
+ # Localhost URL error - fix and retry
602
+ a2a_client = handle_a2a_localhost_retry(
603
+ error=localhost_err,
604
+ agent_card=agent_card,
605
+ a2a_client=a2a_client,
606
+ is_streaming=True,
607
+ )
608
+ card_url = agent_card.url if agent_card else None
609
+ continue
610
+ except Exception:
611
+ # Re-raise the mapped exception
612
+ raise
613
+ raise
614
+
615
+
616
+ async def create_a2a_client(
617
+ base_url: str,
618
+ timeout: float = DEFAULT_A2A_AGENT_TIMEOUT,
619
+ extra_headers: Optional[Dict[str, str]] = None,
620
+ ) -> "A2AClientType":
621
+ """
622
+ Create an A2A client for the given agent URL.
623
+
624
+ This resolves the agent card and returns a ready-to-use A2A client.
625
+ The client can be reused for multiple requests.
626
+
627
+ Args:
628
+ base_url: The base URL of the A2A agent (e.g., "http://localhost:10001")
629
+ timeout: Request timeout in seconds (default: ``DEFAULT_A2A_AGENT_TIMEOUT`` / env ``DEFAULT_A2A_AGENT_TIMEOUT``)
630
+ extra_headers: Optional additional headers to include in requests
631
+
632
+ Returns:
633
+ An initialized a2a.client.A2AClient instance
634
+
635
+ Example:
636
+ ```python
637
+ from litellm.a2a_protocol import create_a2a_client, asend_message
638
+
639
+ # Create client once
640
+ client = await create_a2a_client(base_url="http://localhost:10001")
641
+
642
+ # Reuse for multiple requests
643
+ response1 = await asend_message(a2a_client=client, request=request1)
644
+ response2 = await asend_message(a2a_client=client, request=request2)
645
+ ```
646
+ """
647
+ if not A2A_SDK_AVAILABLE:
648
+ raise ImportError(
649
+ "The 'a2a' package is required for A2A agent invocation. "
650
+ "Install it with: pip install a2a-sdk"
651
+ )
652
+
653
+ verbose_logger.info(f"Creating A2A client for {base_url}")
654
+
655
+ # Use get_async_httpx_client with per-agent params so that different agents
656
+ # (with different extra_headers) get separate cached clients. The params
657
+ # dict is hashed into the cache key, keeping agent auth isolated while
658
+ # still reusing connections within the same agent.
659
+ #
660
+ # Only pass params that AsyncHTTPHandler.__init__ accepts (e.g. timeout).
661
+ # Use "disable_aiohttp_transport" key for cache-key-only data (it's
662
+ # filtered out before reaching the constructor).
663
+ _client_params: dict = {"timeout": timeout}
664
+ if extra_headers:
665
+ # Encode headers into a cache-key-only param so each unique header
666
+ # set produces a distinct cache key.
667
+ _client_params["disable_aiohttp_transport"] = str(sorted(extra_headers.items()))
668
+ _async_handler = get_async_httpx_client(
669
+ llm_provider=httpxSpecialProvider.A2AProvider,
670
+ params=_client_params,
671
+ )
672
+ httpx_client = _async_handler.client
673
+ if extra_headers:
674
+ httpx_client.headers.update(extra_headers)
675
+ verbose_proxy_logger.debug(
676
+ f"A2A client created with extra_headers={list(extra_headers.keys())}"
677
+ )
678
+
679
+ # Resolve agent card
680
+ resolver = A2ACardResolver(
681
+ httpx_client=httpx_client,
682
+ base_url=base_url,
683
+ )
684
+ agent_card = await resolver.get_agent_card()
685
+
686
+ verbose_logger.debug(
687
+ f"Resolved agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}"
688
+ )
689
+
690
+ # Create A2A client
691
+ a2a_client = _A2AClient(
692
+ httpx_client=httpx_client,
693
+ agent_card=agent_card,
694
+ )
695
+
696
+ # Store agent_card on client for later retrieval (SDK doesn't expose it)
697
+ a2a_client._litellm_agent_card = agent_card # type: ignore[attr-defined]
698
+
699
+ verbose_logger.info(f"A2A client created for {base_url}")
700
+
701
+ return a2a_client
702
+
703
+
704
+ async def aget_agent_card(
705
+ base_url: str,
706
+ timeout: float = DEFAULT_A2A_AGENT_TIMEOUT,
707
+ extra_headers: Optional[Dict[str, str]] = None,
708
+ ) -> "AgentCard":
709
+ """
710
+ Fetch the agent card from an A2A agent.
711
+
712
+ Args:
713
+ base_url: The base URL of the A2A agent (e.g., "http://localhost:10001")
714
+ timeout: Request timeout in seconds (default: ``DEFAULT_A2A_AGENT_TIMEOUT`` / env ``DEFAULT_A2A_AGENT_TIMEOUT``)
715
+ extra_headers: Optional additional headers to include in requests
716
+
717
+ Returns:
718
+ AgentCard from the A2A agent
719
+ """
720
+ if not A2A_SDK_AVAILABLE:
721
+ raise ImportError(
722
+ "The 'a2a' package is required for A2A agent invocation. "
723
+ "Install it with: pip install a2a-sdk"
724
+ )
725
+
726
+ verbose_logger.info(f"Fetching agent card from {base_url}")
727
+
728
+ # Use LiteLLM's cached httpx client
729
+ http_handler = get_async_httpx_client(
730
+ llm_provider=httpxSpecialProvider.A2A,
731
+ params={"timeout": timeout},
732
+ )
733
+ httpx_client = http_handler.client
734
+
735
+ resolver = A2ACardResolver(
736
+ httpx_client=httpx_client,
737
+ base_url=base_url,
738
+ )
739
+ agent_card = await resolver.get_agent_card()
740
+
741
+ verbose_logger.info(
742
+ f"Fetched agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}"
743
+ )
744
+ return agent_card
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/streaming_iterator.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A2A Streaming Iterator with token tracking and logging support.
3
+ """
4
+
5
+ import asyncio
6
+ from datetime import datetime
7
+ from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional
8
+
9
+ import litellm
10
+ from litellm._logging import verbose_logger
11
+ from litellm.a2a_protocol.cost_calculator import A2ACostCalculator
12
+ from litellm.a2a_protocol.utils import A2ARequestUtils
13
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
14
+ from litellm.litellm_core_utils.thread_pool_executor import executor
15
+
16
+ if TYPE_CHECKING:
17
+ from a2a.types import SendStreamingMessageRequest, SendStreamingMessageResponse
18
+
19
+
20
+ class A2AStreamingIterator:
21
+ """
22
+ Async iterator for A2A streaming responses with token tracking.
23
+
24
+ Collects chunks, extracts text, and logs usage on completion.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ stream: AsyncIterator["SendStreamingMessageResponse"],
30
+ request: "SendStreamingMessageRequest",
31
+ logging_obj: LiteLLMLoggingObj,
32
+ agent_name: str = "unknown",
33
+ ):
34
+ self.stream = stream
35
+ self.request = request
36
+ self.logging_obj = logging_obj
37
+ self.agent_name = agent_name
38
+ self.start_time = datetime.now()
39
+
40
+ # Collect chunks for token counting
41
+ self.chunks: List[Any] = []
42
+ self.collected_text_parts: List[str] = []
43
+ self.final_chunk: Optional[Any] = None
44
+
45
+ def __aiter__(self):
46
+ return self
47
+
48
+ async def __anext__(self) -> "SendStreamingMessageResponse":
49
+ try:
50
+ chunk = await self.stream.__anext__()
51
+
52
+ # Store chunk
53
+ self.chunks.append(chunk)
54
+
55
+ # Extract text from chunk for token counting
56
+ self._collect_text_from_chunk(chunk)
57
+
58
+ # Check if this is the final chunk (completed status)
59
+ if self._is_completed_chunk(chunk):
60
+ self.final_chunk = chunk
61
+
62
+ return chunk
63
+
64
+ except StopAsyncIteration:
65
+ # Stream ended - handle logging
66
+ if self.final_chunk is None and self.chunks:
67
+ self.final_chunk = self.chunks[-1]
68
+ await self._handle_stream_complete()
69
+ raise
70
+
71
+ def _collect_text_from_chunk(self, chunk: Any) -> None:
72
+ """Extract text from a streaming chunk and add to collected parts."""
73
+ try:
74
+ chunk_dict = (
75
+ chunk.model_dump(mode="json", exclude_none=True)
76
+ if hasattr(chunk, "model_dump")
77
+ else {}
78
+ )
79
+ text = A2ARequestUtils.extract_text_from_response(chunk_dict)
80
+ if text:
81
+ self.collected_text_parts.append(text)
82
+ except Exception:
83
+ verbose_logger.debug("Failed to extract text from A2A streaming chunk")
84
+
85
+ def _is_completed_chunk(self, chunk: Any) -> bool:
86
+ """Check if chunk indicates stream completion."""
87
+ try:
88
+ chunk_dict = (
89
+ chunk.model_dump(mode="json", exclude_none=True)
90
+ if hasattr(chunk, "model_dump")
91
+ else {}
92
+ )
93
+ result = chunk_dict.get("result", {})
94
+ if isinstance(result, dict):
95
+ status = result.get("status", {})
96
+ if isinstance(status, dict):
97
+ return status.get("state") == "completed"
98
+ except Exception:
99
+ pass
100
+ return False
101
+
102
+ async def _handle_stream_complete(self) -> None:
103
+ """Handle logging and token counting when stream completes."""
104
+ try:
105
+ end_time = datetime.now()
106
+
107
+ # Calculate tokens from collected text
108
+ input_message = A2ARequestUtils.get_input_message_from_request(self.request)
109
+ input_text = A2ARequestUtils.extract_text_from_message(input_message)
110
+ prompt_tokens = A2ARequestUtils.count_tokens(input_text)
111
+
112
+ # Use the last (most complete) text from chunks
113
+ output_text = (
114
+ self.collected_text_parts[-1] if self.collected_text_parts else ""
115
+ )
116
+ completion_tokens = A2ARequestUtils.count_tokens(output_text)
117
+
118
+ total_tokens = prompt_tokens + completion_tokens
119
+
120
+ # Create usage object
121
+ usage = litellm.Usage(
122
+ prompt_tokens=prompt_tokens,
123
+ completion_tokens=completion_tokens,
124
+ total_tokens=total_tokens,
125
+ )
126
+
127
+ # Set usage on logging obj
128
+ self.logging_obj.model_call_details["usage"] = usage
129
+ # Mark stream flag for downstream callbacks
130
+ self.logging_obj.model_call_details["stream"] = False
131
+
132
+ # Calculate cost using A2ACostCalculator
133
+ response_cost = A2ACostCalculator.calculate_a2a_cost(self.logging_obj)
134
+ self.logging_obj.model_call_details["response_cost"] = response_cost
135
+
136
+ # Build result for logging
137
+ result = self._build_logging_result(usage)
138
+
139
+ # Call success handlers - they will build standard_logging_object
140
+ asyncio.create_task(
141
+ self.logging_obj.async_success_handler(
142
+ result=result,
143
+ start_time=self.start_time,
144
+ end_time=end_time,
145
+ cache_hit=None,
146
+ )
147
+ )
148
+
149
+ executor.submit(
150
+ self.logging_obj.success_handler,
151
+ result=result,
152
+ cache_hit=None,
153
+ start_time=self.start_time,
154
+ end_time=end_time,
155
+ )
156
+
157
+ verbose_logger.info(
158
+ f"A2A streaming completed: prompt_tokens={prompt_tokens}, "
159
+ f"completion_tokens={completion_tokens}, total_tokens={total_tokens}, "
160
+ f"response_cost={response_cost}"
161
+ )
162
+
163
+ except Exception as e:
164
+ verbose_logger.debug(f"Error in A2A streaming completion handler: {e}")
165
+
166
+ def _build_logging_result(self, usage: litellm.Usage) -> Dict[str, Any]:
167
+ """Build a result dict for logging."""
168
+ result: Dict[str, Any] = {
169
+ "id": getattr(self.request, "id", "unknown"),
170
+ "jsonrpc": "2.0",
171
+ "usage": (
172
+ usage.model_dump() if hasattr(usage, "model_dump") else dict(usage)
173
+ ),
174
+ }
175
+
176
+ # Add final chunk result if available
177
+ if self.final_chunk:
178
+ try:
179
+ chunk_dict = self.final_chunk.model_dump(mode="json", exclude_none=True)
180
+ result["result"] = chunk_dict.get("result", {})
181
+ except Exception:
182
+ pass
183
+
184
+ return result
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/utils.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for A2A protocol.
3
+ """
4
+
5
+ from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
6
+
7
+ import litellm
8
+ from litellm._logging import verbose_logger
9
+
10
+ if TYPE_CHECKING:
11
+ from a2a.types import SendMessageRequest, SendStreamingMessageRequest
12
+
13
+
14
+ class A2ARequestUtils:
15
+ """Utility class for A2A request/response processing."""
16
+
17
+ @staticmethod
18
+ def extract_text_from_message(message: Any) -> str:
19
+ """
20
+ Extract text content from A2A message parts.
21
+
22
+ Args:
23
+ message: A2A message dict or object with 'parts' containing text parts
24
+
25
+ Returns:
26
+ Concatenated text from all text parts
27
+ """
28
+ if message is None:
29
+ return ""
30
+
31
+ # Handle both dict and object access
32
+ if isinstance(message, dict):
33
+ parts = message.get("parts", [])
34
+ else:
35
+ parts = getattr(message, "parts", []) or []
36
+
37
+ text_parts: List[str] = []
38
+ for part in parts:
39
+ if isinstance(part, dict):
40
+ if part.get("kind") == "text":
41
+ text_parts.append(part.get("text", ""))
42
+ else:
43
+ if getattr(part, "kind", None) == "text":
44
+ text_parts.append(getattr(part, "text", ""))
45
+
46
+ return " ".join(text_parts)
47
+
48
+ @staticmethod
49
+ def extract_text_from_response(response_dict: Dict[str, Any]) -> str:
50
+ """
51
+ Extract text content from A2A response result.
52
+
53
+ Args:
54
+ response_dict: A2A response dict with 'result' containing message
55
+
56
+ Returns:
57
+ Text from response message parts
58
+ """
59
+ result = response_dict.get("result", {})
60
+ if not isinstance(result, dict):
61
+ return ""
62
+
63
+ message = result.get("message", {})
64
+ return A2ARequestUtils.extract_text_from_message(message)
65
+
66
+ @staticmethod
67
+ def get_input_message_from_request(
68
+ request: "Union[SendMessageRequest, SendStreamingMessageRequest]",
69
+ ) -> Any:
70
+ """
71
+ Extract the input message from an A2A request.
72
+
73
+ Args:
74
+ request: The A2A SendMessageRequest or SendStreamingMessageRequest
75
+
76
+ Returns:
77
+ The message object/dict or None
78
+ """
79
+ params = getattr(request, "params", None)
80
+ if params is None:
81
+ return None
82
+ return getattr(params, "message", None)
83
+
84
+ @staticmethod
85
+ def count_tokens(text: str) -> int:
86
+ """
87
+ Count tokens in text using litellm.token_counter.
88
+
89
+ Args:
90
+ text: Text to count tokens for
91
+
92
+ Returns:
93
+ Token count, or 0 if counting fails
94
+ """
95
+ if not text:
96
+ return 0
97
+ try:
98
+ return litellm.token_counter(text=text)
99
+ except Exception:
100
+ verbose_logger.debug("Failed to count tokens")
101
+ return 0
102
+
103
+ @staticmethod
104
+ def calculate_usage_from_request_response(
105
+ request: "Union[SendMessageRequest, SendStreamingMessageRequest]",
106
+ response_dict: Dict[str, Any],
107
+ ) -> Tuple[int, int, int]:
108
+ """
109
+ Calculate token usage from A2A request and response.
110
+
111
+ Args:
112
+ request: The A2A SendMessageRequest or SendStreamingMessageRequest
113
+ response_dict: The A2A response as a dict
114
+
115
+ Returns:
116
+ Tuple of (prompt_tokens, completion_tokens, total_tokens)
117
+ """
118
+ # Count input tokens
119
+ input_message = A2ARequestUtils.get_input_message_from_request(request)
120
+ input_text = A2ARequestUtils.extract_text_from_message(input_message)
121
+ prompt_tokens = A2ARequestUtils.count_tokens(input_text)
122
+
123
+ # Count output tokens
124
+ output_text = A2ARequestUtils.extract_text_from_response(response_dict)
125
+ completion_tokens = A2ARequestUtils.count_tokens(output_text)
126
+
127
+ total_tokens = prompt_tokens + completion_tokens
128
+
129
+ return prompt_tokens, completion_tokens, total_tokens
130
+
131
+
132
+ # Backwards compatibility aliases
133
+ def extract_text_from_a2a_message(message: Any) -> str:
134
+ return A2ARequestUtils.extract_text_from_message(message)
135
+
136
+
137
+ def extract_text_from_a2a_response(response_dict: Dict[str, Any]) -> str:
138
+ return A2ARequestUtils.extract_text_from_response(response_dict)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """
2
+ Anthropic module for LiteLLM
3
+ """
4
+
5
+ from .messages import acreate, create
6
+
7
+ __all__ = ["acreate", "create"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/readme.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Use LLM API endpoints in Anthropic Interface
2
+
3
+ Note: This is called `anthropic_interface` because `anthropic` is a known python package and was failing mypy type checking.
4
+
5
+
6
+ ## Usage
7
+ ---
8
+
9
+ ### LiteLLM Python SDK
10
+
11
+ #### Non-streaming example
12
+ ```python showLineNumbers title="Example using LiteLLM Python SDK"
13
+ import litellm
14
+ response = await litellm.anthropic.messages.acreate(
15
+ messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],
16
+ api_key=api_key,
17
+ model="anthropic/claude-3-haiku-20240307",
18
+ max_tokens=100,
19
+ )
20
+ ```
21
+
22
+ Example response:
23
+ ```json
24
+ {
25
+ "content": [
26
+ {
27
+ "text": "Hi! this is a very short joke",
28
+ "type": "text"
29
+ }
30
+ ],
31
+ "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
32
+ "model": "claude-3-7-sonnet-20250219",
33
+ "role": "assistant",
34
+ "stop_reason": "end_turn",
35
+ "stop_sequence": null,
36
+ "type": "message",
37
+ "usage": {
38
+ "input_tokens": 2095,
39
+ "output_tokens": 503,
40
+ "cache_creation_input_tokens": 2095,
41
+ "cache_read_input_tokens": 0
42
+ }
43
+ }
44
+ ```
45
+
46
+ #### Streaming example
47
+ ```python showLineNumbers title="Example using LiteLLM Python SDK"
48
+ import litellm
49
+ response = await litellm.anthropic.messages.acreate(
50
+ messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],
51
+ api_key=api_key,
52
+ model="anthropic/claude-3-haiku-20240307",
53
+ max_tokens=100,
54
+ stream=True,
55
+ )
56
+ async for chunk in response:
57
+ print(chunk)
58
+ ```
59
+
60
+ ### LiteLLM Proxy Server
61
+
62
+
63
+ 1. Setup config.yaml
64
+
65
+ ```yaml
66
+ model_list:
67
+ - model_name: anthropic-claude
68
+ litellm_params:
69
+ model: claude-3-7-sonnet-latest
70
+ ```
71
+
72
+ 2. Start proxy
73
+
74
+ ```bash
75
+ litellm --config /path/to/config.yaml
76
+ ```
77
+
78
+ 3. Test it!
79
+
80
+ <Tabs>
81
+ <TabItem label="Anthropic Python SDK" value="python">
82
+
83
+ ```python showLineNumbers title="Example using LiteLLM Proxy Server"
84
+ import anthropic
85
+
86
+ # point anthropic sdk to litellm proxy
87
+ client = anthropic.Anthropic(
88
+ base_url="http://0.0.0.0:4000",
89
+ api_key="sk-1234",
90
+ )
91
+
92
+ response = client.messages.create(
93
+ messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],
94
+ model="anthropic/claude-3-haiku-20240307",
95
+ max_tokens=100,
96
+ )
97
+ ```
98
+ </TabItem>
99
+ <TabItem label="curl" value="curl">
100
+
101
+ ```bash showLineNumbers title="Example using LiteLLM Proxy Server"
102
+ curl -L -X POST 'http://0.0.0.0:4000/v1/messages' \
103
+ -H 'content-type: application/json' \
104
+ -H 'x-api-key: $LITELLM_API_KEY' \
105
+ -H 'anthropic-version: 2023-06-01' \
106
+ -d '{
107
+ "model": "anthropic-claude",
108
+ "messages": [
109
+ {
110
+ "role": "user",
111
+ "content": "Hello, can you tell me a short joke?"
112
+ }
113
+ ],
114
+ "max_tokens": 100
115
+ }'
116
+ ```
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/main.py ADDED
@@ -0,0 +1,1484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What is this?
2
+ ## Main file for assistants API logic
3
+ import asyncio
4
+ import contextvars
5
+ import os
6
+ from functools import partial
7
+ from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Union
8
+
9
+ import httpx
10
+ from openai import AsyncOpenAI, OpenAI
11
+ from openai.types.beta.assistant import Assistant
12
+ from openai.types.beta.assistant_deleted import AssistantDeleted
13
+
14
+ import litellm
15
+ from litellm.types.router import GenericLiteLLMParams
16
+ from litellm.utils import (
17
+ exception_type,
18
+ get_litellm_params,
19
+ get_llm_provider,
20
+ get_secret,
21
+ supports_httpx_timeout,
22
+ )
23
+
24
+ from ..llms.azure.assistants import AzureAssistantsAPI
25
+ from ..llms.openai.openai import OpenAIAssistantsAPI
26
+ from ..types.llms.openai import *
27
+ from ..types.router import *
28
+ from .utils import get_optional_params_add_message
29
+
30
+ ####### ENVIRONMENT VARIABLES ###################
31
+ openai_assistants_api = OpenAIAssistantsAPI()
32
+ azure_assistants_api = AzureAssistantsAPI()
33
+
34
+ ### ASSISTANTS ###
35
+
36
+
37
+ async def aget_assistants(
38
+ custom_llm_provider: Literal["openai", "azure"],
39
+ client: Optional[AsyncOpenAI] = None,
40
+ **kwargs,
41
+ ) -> AsyncCursorPage[Assistant]:
42
+ loop = asyncio.get_event_loop()
43
+ ### PASS ARGS TO GET ASSISTANTS ###
44
+ kwargs["aget_assistants"] = True
45
+ try:
46
+ # Use a partial function to pass your keyword arguments
47
+ func = partial(get_assistants, custom_llm_provider, client, **kwargs)
48
+
49
+ # Add the context to the function
50
+ ctx = contextvars.copy_context()
51
+ func_with_context = partial(ctx.run, func)
52
+
53
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
54
+ model="", custom_llm_provider=custom_llm_provider
55
+ ) # type: ignore
56
+
57
+ # Await normally
58
+ init_response = await loop.run_in_executor(None, func_with_context)
59
+ if asyncio.iscoroutine(init_response):
60
+ response = await init_response
61
+ else:
62
+ response = init_response
63
+ return response # type: ignore
64
+ except Exception as e:
65
+ raise exception_type(
66
+ model="",
67
+ custom_llm_provider=custom_llm_provider,
68
+ original_exception=e,
69
+ completion_kwargs={},
70
+ extra_kwargs=kwargs,
71
+ )
72
+
73
+
74
+ def get_assistants(
75
+ custom_llm_provider: Literal["openai", "azure"],
76
+ client: Optional[Any] = None,
77
+ api_key: Optional[str] = None,
78
+ api_base: Optional[str] = None,
79
+ api_version: Optional[str] = None,
80
+ **kwargs,
81
+ ) -> SyncCursorPage[Assistant]:
82
+ aget_assistants: Optional[bool] = kwargs.pop("aget_assistants", None)
83
+ if aget_assistants is not None and not isinstance(aget_assistants, bool):
84
+ raise Exception(
85
+ "Invalid value passed in for aget_assistants. Only bool or None allowed"
86
+ )
87
+ optional_params = GenericLiteLLMParams(
88
+ api_key=api_key, api_base=api_base, api_version=api_version, **kwargs
89
+ )
90
+ litellm_params_dict = get_litellm_params(**kwargs)
91
+
92
+ ### TIMEOUT LOGIC ###
93
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
94
+ # set timeout for 10 minutes by default
95
+
96
+ if (
97
+ timeout is not None
98
+ and isinstance(timeout, httpx.Timeout)
99
+ and supports_httpx_timeout(custom_llm_provider) is False
100
+ ):
101
+ read_timeout = timeout.read or 600
102
+ timeout = read_timeout # default 10 min timeout
103
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
104
+ timeout = float(timeout) # type: ignore
105
+ elif timeout is None:
106
+ timeout = 600.0
107
+
108
+ response: Optional[SyncCursorPage[Assistant]] = None
109
+ if custom_llm_provider == "openai":
110
+ api_base = (
111
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
112
+ or litellm.api_base
113
+ or os.getenv("OPENAI_BASE_URL")
114
+ or os.getenv("OPENAI_API_BASE")
115
+ or "https://api.openai.com/v1"
116
+ )
117
+ organization = (
118
+ optional_params.organization
119
+ or litellm.organization
120
+ or os.getenv("OPENAI_ORGANIZATION", None)
121
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
122
+ )
123
+ # set API KEY
124
+ api_key = (
125
+ optional_params.api_key
126
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
127
+ or litellm.openai_key
128
+ or os.getenv("OPENAI_API_KEY")
129
+ )
130
+
131
+ response = openai_assistants_api.get_assistants(
132
+ api_base=api_base,
133
+ api_key=api_key,
134
+ timeout=timeout,
135
+ max_retries=optional_params.max_retries,
136
+ organization=organization,
137
+ client=client,
138
+ aget_assistants=aget_assistants, # type: ignore
139
+ ) # type: ignore
140
+ elif custom_llm_provider == "azure":
141
+ api_base = (
142
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
143
+ ) # type: ignore
144
+
145
+ api_version = (
146
+ optional_params.api_version
147
+ or litellm.api_version
148
+ or get_secret("AZURE_API_VERSION")
149
+ ) # type: ignore
150
+
151
+ api_key = (
152
+ optional_params.api_key
153
+ or litellm.api_key
154
+ or litellm.azure_key
155
+ or get_secret("AZURE_OPENAI_API_KEY")
156
+ or get_secret("AZURE_API_KEY")
157
+ ) # type: ignore
158
+
159
+ extra_body = optional_params.get("extra_body", {})
160
+ azure_ad_token: Optional[str] = None
161
+ if extra_body is not None:
162
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
163
+ else:
164
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
165
+
166
+ response = azure_assistants_api.get_assistants(
167
+ api_base=api_base,
168
+ api_key=api_key,
169
+ api_version=api_version,
170
+ azure_ad_token=azure_ad_token,
171
+ timeout=timeout,
172
+ max_retries=optional_params.max_retries,
173
+ client=client,
174
+ aget_assistants=aget_assistants, # type: ignore
175
+ litellm_params=litellm_params_dict,
176
+ )
177
+ else:
178
+ raise litellm.exceptions.BadRequestError(
179
+ message="LiteLLM doesn't support {} for 'get_assistants'. Only 'openai' is supported.".format(
180
+ custom_llm_provider
181
+ ),
182
+ model="n/a",
183
+ llm_provider=custom_llm_provider,
184
+ response=httpx.Response(
185
+ status_code=400,
186
+ content="Unsupported provider",
187
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
188
+ ),
189
+ )
190
+
191
+ if response is None:
192
+ raise litellm.exceptions.BadRequestError(
193
+ message="LiteLLM doesn't support {} for 'get_assistants'. Only 'openai' is supported.".format(
194
+ custom_llm_provider
195
+ ),
196
+ model="n/a",
197
+ llm_provider=custom_llm_provider,
198
+ response=httpx.Response(
199
+ status_code=400,
200
+ content="Unsupported provider",
201
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
202
+ ),
203
+ )
204
+
205
+ return response
206
+
207
+
208
+ async def acreate_assistants(
209
+ custom_llm_provider: Literal["openai", "azure"],
210
+ client: Optional[AsyncOpenAI] = None,
211
+ **kwargs,
212
+ ) -> Assistant:
213
+ loop = asyncio.get_event_loop()
214
+ ### PASS ARGS TO GET ASSISTANTS ###
215
+ kwargs["async_create_assistants"] = True
216
+ model = kwargs.pop("model", None)
217
+ try:
218
+ kwargs["client"] = client
219
+ # Use a partial function to pass your keyword arguments
220
+ func = partial(create_assistants, custom_llm_provider, model, **kwargs)
221
+
222
+ # Add the context to the function
223
+ ctx = contextvars.copy_context()
224
+ func_with_context = partial(ctx.run, func)
225
+
226
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
227
+ model=model, custom_llm_provider=custom_llm_provider
228
+ ) # type: ignore
229
+
230
+ # Await normally
231
+ init_response = await loop.run_in_executor(None, func_with_context)
232
+ if asyncio.iscoroutine(init_response):
233
+ response = await init_response
234
+ else:
235
+ response = init_response
236
+ return response # type: ignore
237
+ except Exception as e:
238
+ raise exception_type(
239
+ model=model,
240
+ custom_llm_provider=custom_llm_provider,
241
+ original_exception=e,
242
+ completion_kwargs={},
243
+ extra_kwargs=kwargs,
244
+ )
245
+
246
+
247
+ def create_assistants(
248
+ custom_llm_provider: Literal["openai", "azure"],
249
+ model: str,
250
+ name: Optional[str] = None,
251
+ description: Optional[str] = None,
252
+ instructions: Optional[str] = None,
253
+ tools: Optional[List[Dict[str, Any]]] = None,
254
+ tool_resources: Optional[Dict[str, Any]] = None,
255
+ metadata: Optional[Dict[str, str]] = None,
256
+ temperature: Optional[float] = None,
257
+ top_p: Optional[float] = None,
258
+ response_format: Optional[Union[str, Dict[str, str]]] = None,
259
+ client: Optional[Any] = None,
260
+ api_key: Optional[str] = None,
261
+ api_base: Optional[str] = None,
262
+ api_version: Optional[str] = None,
263
+ **kwargs,
264
+ ) -> Union[Assistant, Coroutine[Any, Any, Assistant]]:
265
+ async_create_assistants: Optional[bool] = kwargs.pop(
266
+ "async_create_assistants", None
267
+ )
268
+ if async_create_assistants is not None and not isinstance(
269
+ async_create_assistants, bool
270
+ ):
271
+ raise ValueError(
272
+ "Invalid value passed in for async_create_assistants. Only bool or None allowed"
273
+ )
274
+ optional_params = GenericLiteLLMParams(
275
+ api_key=api_key, api_base=api_base, api_version=api_version, **kwargs
276
+ )
277
+ litellm_params_dict = get_litellm_params(**kwargs)
278
+
279
+ ### TIMEOUT LOGIC ###
280
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
281
+ # set timeout for 10 minutes by default
282
+
283
+ if (
284
+ timeout is not None
285
+ and isinstance(timeout, httpx.Timeout)
286
+ and supports_httpx_timeout(custom_llm_provider) is False
287
+ ):
288
+ read_timeout = timeout.read or 600
289
+ timeout = read_timeout # default 10 min timeout
290
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
291
+ timeout = float(timeout) # type: ignore
292
+ elif timeout is None:
293
+ timeout = 600.0
294
+
295
+ create_assistant_data = {
296
+ "model": model,
297
+ "name": name,
298
+ "description": description,
299
+ "instructions": instructions,
300
+ "tools": tools,
301
+ "tool_resources": tool_resources,
302
+ "metadata": metadata,
303
+ "temperature": temperature,
304
+ "top_p": top_p,
305
+ "response_format": response_format,
306
+ }
307
+
308
+ # only send params that are not None
309
+ create_assistant_data = {
310
+ k: v for k, v in create_assistant_data.items() if v is not None
311
+ }
312
+
313
+ response: Optional[Union[Coroutine[Any, Any, Assistant], Assistant]] = None
314
+ if custom_llm_provider == "openai":
315
+ api_base = (
316
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
317
+ or litellm.api_base
318
+ or os.getenv("OPENAI_BASE_URL")
319
+ or os.getenv("OPENAI_API_BASE")
320
+ or "https://api.openai.com/v1"
321
+ )
322
+ organization = (
323
+ optional_params.organization
324
+ or litellm.organization
325
+ or os.getenv("OPENAI_ORGANIZATION", None)
326
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
327
+ )
328
+ # set API KEY
329
+ api_key = (
330
+ optional_params.api_key
331
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
332
+ or litellm.openai_key
333
+ or os.getenv("OPENAI_API_KEY")
334
+ )
335
+
336
+ response = openai_assistants_api.create_assistants(
337
+ api_base=api_base,
338
+ api_key=api_key,
339
+ timeout=timeout,
340
+ max_retries=optional_params.max_retries,
341
+ organization=organization,
342
+ create_assistant_data=create_assistant_data,
343
+ client=client,
344
+ async_create_assistants=async_create_assistants, # type: ignore
345
+ ) # type: ignore
346
+ elif custom_llm_provider == "azure":
347
+ api_base = (
348
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
349
+ ) # type: ignore
350
+
351
+ api_version = (
352
+ optional_params.api_version
353
+ or litellm.api_version
354
+ or get_secret("AZURE_API_VERSION")
355
+ ) # type: ignore
356
+
357
+ api_key = (
358
+ optional_params.api_key
359
+ or litellm.api_key
360
+ or litellm.azure_key
361
+ or get_secret("AZURE_OPENAI_API_KEY")
362
+ or get_secret("AZURE_API_KEY")
363
+ ) # type: ignore
364
+
365
+ extra_body = optional_params.get("extra_body", {})
366
+ azure_ad_token: Optional[str] = None
367
+ if extra_body is not None:
368
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
369
+ else:
370
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
371
+
372
+ if isinstance(client, OpenAI):
373
+ client = None # only pass client if it's AzureOpenAI
374
+
375
+ response = azure_assistants_api.create_assistants(
376
+ api_base=api_base,
377
+ api_key=api_key,
378
+ azure_ad_token=azure_ad_token,
379
+ api_version=api_version,
380
+ timeout=timeout,
381
+ max_retries=optional_params.max_retries,
382
+ client=client,
383
+ async_create_assistants=async_create_assistants,
384
+ create_assistant_data=create_assistant_data,
385
+ litellm_params=litellm_params_dict,
386
+ )
387
+ else:
388
+ raise litellm.exceptions.BadRequestError(
389
+ message="LiteLLM doesn't support {} for 'create_assistants'. Only 'openai' is supported.".format(
390
+ custom_llm_provider
391
+ ),
392
+ model="n/a",
393
+ llm_provider=custom_llm_provider,
394
+ response=httpx.Response(
395
+ status_code=400,
396
+ content="Unsupported provider",
397
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
398
+ ),
399
+ )
400
+ if response is None:
401
+ raise litellm.exceptions.InternalServerError(
402
+ message="No response returned from 'create_assistants'",
403
+ model=model,
404
+ llm_provider=custom_llm_provider,
405
+ )
406
+ return response
407
+
408
+
409
+ async def adelete_assistant(
410
+ custom_llm_provider: Literal["openai", "azure"],
411
+ client: Optional[AsyncOpenAI] = None,
412
+ **kwargs,
413
+ ) -> AssistantDeleted:
414
+ loop = asyncio.get_event_loop()
415
+ ### PASS ARGS TO GET ASSISTANTS ###
416
+ kwargs["async_delete_assistants"] = True
417
+ try:
418
+ kwargs["client"] = client
419
+ # Use a partial function to pass your keyword arguments
420
+ func = partial(delete_assistant, custom_llm_provider, **kwargs)
421
+
422
+ # Add the context to the function
423
+ ctx = contextvars.copy_context()
424
+ func_with_context = partial(ctx.run, func)
425
+
426
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
427
+ model="", custom_llm_provider=custom_llm_provider
428
+ ) # type: ignore
429
+
430
+ # Await normally
431
+ init_response = await loop.run_in_executor(None, func_with_context)
432
+ if asyncio.iscoroutine(init_response):
433
+ response = await init_response
434
+ else:
435
+ response = init_response
436
+ return response # type: ignore
437
+ except Exception as e:
438
+ raise exception_type(
439
+ model="",
440
+ custom_llm_provider=custom_llm_provider,
441
+ original_exception=e,
442
+ completion_kwargs={},
443
+ extra_kwargs=kwargs,
444
+ )
445
+
446
+
447
+ def delete_assistant(
448
+ custom_llm_provider: Literal["openai", "azure"],
449
+ assistant_id: str,
450
+ client: Optional[Any] = None,
451
+ api_key: Optional[str] = None,
452
+ api_base: Optional[str] = None,
453
+ api_version: Optional[str] = None,
454
+ **kwargs,
455
+ ) -> Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]]:
456
+ optional_params = GenericLiteLLMParams(
457
+ api_key=api_key, api_base=api_base, api_version=api_version, **kwargs
458
+ )
459
+
460
+ litellm_params_dict = get_litellm_params(**kwargs)
461
+
462
+ async_delete_assistants: Optional[bool] = kwargs.pop(
463
+ "async_delete_assistants", None
464
+ )
465
+ if async_delete_assistants is not None and not isinstance(
466
+ async_delete_assistants, bool
467
+ ):
468
+ raise ValueError(
469
+ "Invalid value passed in for async_delete_assistants. Only bool or None allowed"
470
+ )
471
+
472
+ ### TIMEOUT LOGIC ###
473
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
474
+ # set timeout for 10 minutes by default
475
+
476
+ if (
477
+ timeout is not None
478
+ and isinstance(timeout, httpx.Timeout)
479
+ and supports_httpx_timeout(custom_llm_provider) is False
480
+ ):
481
+ read_timeout = timeout.read or 600
482
+ timeout = read_timeout # default 10 min timeout
483
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
484
+ timeout = float(timeout) # type: ignore
485
+ elif timeout is None:
486
+ timeout = 600.0
487
+
488
+ response: Optional[
489
+ Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]]
490
+ ] = None
491
+ if custom_llm_provider == "openai":
492
+ api_base = (
493
+ optional_params.api_base
494
+ or litellm.api_base
495
+ or os.getenv("OPENAI_BASE_URL")
496
+ or os.getenv("OPENAI_API_BASE")
497
+ or "https://api.openai.com/v1"
498
+ )
499
+ organization = (
500
+ optional_params.organization
501
+ or litellm.organization
502
+ or os.getenv("OPENAI_ORGANIZATION", None)
503
+ or None
504
+ )
505
+ # set API KEY
506
+ api_key = (
507
+ optional_params.api_key
508
+ or litellm.api_key
509
+ or litellm.openai_key
510
+ or os.getenv("OPENAI_API_KEY")
511
+ )
512
+
513
+ response = openai_assistants_api.delete_assistant(
514
+ api_base=api_base,
515
+ api_key=api_key,
516
+ timeout=timeout,
517
+ max_retries=optional_params.max_retries,
518
+ organization=organization,
519
+ assistant_id=assistant_id,
520
+ client=client,
521
+ async_delete_assistants=async_delete_assistants,
522
+ )
523
+ elif custom_llm_provider == "azure":
524
+ api_base = (
525
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
526
+ ) # type: ignore
527
+
528
+ api_version = (
529
+ optional_params.api_version
530
+ or litellm.api_version
531
+ or get_secret("AZURE_API_VERSION")
532
+ ) # type: ignore
533
+
534
+ api_key = (
535
+ optional_params.api_key
536
+ or litellm.api_key
537
+ or litellm.azure_key
538
+ or get_secret("AZURE_OPENAI_API_KEY")
539
+ or get_secret("AZURE_API_KEY")
540
+ ) # type: ignore
541
+
542
+ extra_body = optional_params.get("extra_body", {})
543
+ azure_ad_token: Optional[str] = None
544
+ if extra_body is not None:
545
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
546
+ else:
547
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
548
+
549
+ if isinstance(client, OpenAI):
550
+ client = None # only pass client if it's AzureOpenAI
551
+
552
+ response = azure_assistants_api.delete_assistant(
553
+ assistant_id=assistant_id,
554
+ api_base=api_base,
555
+ api_key=api_key,
556
+ azure_ad_token=azure_ad_token,
557
+ api_version=api_version,
558
+ timeout=timeout,
559
+ max_retries=optional_params.max_retries,
560
+ client=client,
561
+ async_delete_assistants=async_delete_assistants,
562
+ litellm_params=litellm_params_dict,
563
+ )
564
+ else:
565
+ raise litellm.exceptions.BadRequestError(
566
+ message="LiteLLM doesn't support {} for 'delete_assistant'. Only 'openai' is supported.".format(
567
+ custom_llm_provider
568
+ ),
569
+ model="n/a",
570
+ llm_provider=custom_llm_provider,
571
+ response=httpx.Response(
572
+ status_code=400,
573
+ content="Unsupported provider",
574
+ request=httpx.Request(
575
+ method="delete_assistant", url="https://github.com/BerriAI/litellm"
576
+ ),
577
+ ),
578
+ )
579
+ if response is None:
580
+ raise litellm.exceptions.InternalServerError(
581
+ message="No response returned from 'delete_assistant'",
582
+ model="n/a",
583
+ llm_provider=custom_llm_provider,
584
+ )
585
+ return response
586
+
587
+
588
+ ### THREADS ###
589
+
590
+
591
+ async def acreate_thread(
592
+ custom_llm_provider: Literal["openai", "azure"], **kwargs
593
+ ) -> Thread:
594
+ loop = asyncio.get_event_loop()
595
+ ### PASS ARGS TO GET ASSISTANTS ###
596
+ kwargs["acreate_thread"] = True
597
+ try:
598
+ # Use a partial function to pass your keyword arguments
599
+ func = partial(create_thread, custom_llm_provider, **kwargs)
600
+
601
+ # Add the context to the function
602
+ ctx = contextvars.copy_context()
603
+ func_with_context = partial(ctx.run, func)
604
+
605
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
606
+ model="", custom_llm_provider=custom_llm_provider
607
+ ) # type: ignore
608
+
609
+ # Await normally
610
+ init_response = await loop.run_in_executor(None, func_with_context)
611
+ if asyncio.iscoroutine(init_response):
612
+ response = await init_response
613
+ else:
614
+ response = init_response
615
+ return response # type: ignore
616
+ except Exception as e:
617
+ raise exception_type(
618
+ model="",
619
+ custom_llm_provider=custom_llm_provider,
620
+ original_exception=e,
621
+ completion_kwargs={},
622
+ extra_kwargs=kwargs,
623
+ )
624
+
625
+
626
+ def create_thread(
627
+ custom_llm_provider: Literal["openai", "azure"],
628
+ messages: Optional[Iterable[OpenAICreateThreadParamsMessage]] = None,
629
+ metadata: Optional[dict] = None,
630
+ tool_resources: Optional[OpenAICreateThreadParamsToolResources] = None,
631
+ client: Optional[OpenAI] = None,
632
+ **kwargs,
633
+ ) -> Thread:
634
+ """
635
+ - get the llm provider
636
+ - if openai - route it there
637
+ - pass through relevant params
638
+
639
+ ```
640
+ from litellm import create_thread
641
+
642
+ create_thread(
643
+ custom_llm_provider="openai",
644
+ ### OPTIONAL ###
645
+ messages = {
646
+ "role": "user",
647
+ "content": "Hello, what is AI?"
648
+ },
649
+ {
650
+ "role": "user",
651
+ "content": "How does AI work? Explain it in simple terms."
652
+ }]
653
+ )
654
+ ```
655
+ """
656
+ acreate_thread = kwargs.get("acreate_thread", None)
657
+ optional_params = GenericLiteLLMParams(**kwargs)
658
+ litellm_params_dict = get_litellm_params(**kwargs)
659
+
660
+ ### TIMEOUT LOGIC ###
661
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
662
+ # set timeout for 10 minutes by default
663
+
664
+ if (
665
+ timeout is not None
666
+ and isinstance(timeout, httpx.Timeout)
667
+ and supports_httpx_timeout(custom_llm_provider) is False
668
+ ):
669
+ read_timeout = timeout.read or 600
670
+ timeout = read_timeout # default 10 min timeout
671
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
672
+ timeout = float(timeout) # type: ignore
673
+ elif timeout is None:
674
+ timeout = 600.0
675
+
676
+ api_base: Optional[str] = None
677
+ api_key: Optional[str] = None
678
+
679
+ response: Optional[Thread] = None
680
+ if custom_llm_provider == "openai":
681
+ api_base = (
682
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
683
+ or litellm.api_base
684
+ or os.getenv("OPENAI_BASE_URL")
685
+ or os.getenv("OPENAI_API_BASE")
686
+ or "https://api.openai.com/v1"
687
+ )
688
+ organization = (
689
+ optional_params.organization
690
+ or litellm.organization
691
+ or os.getenv("OPENAI_ORGANIZATION", None)
692
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
693
+ )
694
+ # set API KEY
695
+ api_key = (
696
+ optional_params.api_key
697
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
698
+ or litellm.openai_key
699
+ or os.getenv("OPENAI_API_KEY")
700
+ )
701
+ response = openai_assistants_api.create_thread(
702
+ messages=messages,
703
+ metadata=metadata,
704
+ api_base=api_base,
705
+ api_key=api_key,
706
+ timeout=timeout,
707
+ max_retries=optional_params.max_retries,
708
+ organization=organization,
709
+ client=client,
710
+ acreate_thread=acreate_thread,
711
+ )
712
+ elif custom_llm_provider == "azure":
713
+ api_base = (
714
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
715
+ ) # type: ignore
716
+
717
+ api_key = (
718
+ optional_params.api_key
719
+ or litellm.api_key
720
+ or litellm.azure_key
721
+ or get_secret("AZURE_OPENAI_API_KEY")
722
+ or get_secret("AZURE_API_KEY")
723
+ ) # type: ignore
724
+
725
+ api_version: Optional[str] = (
726
+ optional_params.api_version
727
+ or litellm.api_version
728
+ or get_secret("AZURE_API_VERSION")
729
+ ) # type: ignore
730
+
731
+ extra_body = optional_params.get("extra_body", {})
732
+ azure_ad_token: Optional[str] = None
733
+ if extra_body is not None:
734
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
735
+ else:
736
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
737
+
738
+ if isinstance(client, OpenAI):
739
+ client = None # only pass client if it's AzureOpenAI
740
+
741
+ response = azure_assistants_api.create_thread(
742
+ messages=messages,
743
+ metadata=metadata,
744
+ api_base=api_base,
745
+ api_key=api_key,
746
+ azure_ad_token=azure_ad_token,
747
+ api_version=api_version,
748
+ timeout=timeout,
749
+ max_retries=optional_params.max_retries,
750
+ client=client,
751
+ acreate_thread=acreate_thread,
752
+ litellm_params=litellm_params_dict,
753
+ )
754
+ else:
755
+ raise litellm.exceptions.BadRequestError(
756
+ message="LiteLLM doesn't support {} for 'create_thread'. Only 'openai' is supported.".format(
757
+ custom_llm_provider
758
+ ),
759
+ model="n/a",
760
+ llm_provider=custom_llm_provider,
761
+ response=httpx.Response(
762
+ status_code=400,
763
+ content="Unsupported provider",
764
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
765
+ ),
766
+ )
767
+ return response # type: ignore
768
+
769
+
770
+ async def aget_thread(
771
+ custom_llm_provider: Literal["openai", "azure"],
772
+ thread_id: str,
773
+ client: Optional[AsyncOpenAI] = None,
774
+ **kwargs,
775
+ ) -> Thread:
776
+ loop = asyncio.get_event_loop()
777
+ ### PASS ARGS TO GET ASSISTANTS ###
778
+ kwargs["aget_thread"] = True
779
+ try:
780
+ # Use a partial function to pass your keyword arguments
781
+ func = partial(get_thread, custom_llm_provider, thread_id, client, **kwargs)
782
+
783
+ # Add the context to the function
784
+ ctx = contextvars.copy_context()
785
+ func_with_context = partial(ctx.run, func)
786
+
787
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
788
+ model="", custom_llm_provider=custom_llm_provider
789
+ ) # type: ignore
790
+
791
+ # Await normally
792
+ init_response = await loop.run_in_executor(None, func_with_context)
793
+ if asyncio.iscoroutine(init_response):
794
+ response = await init_response
795
+ else:
796
+ response = init_response
797
+ return response # type: ignore
798
+ except Exception as e:
799
+ raise exception_type(
800
+ model="",
801
+ custom_llm_provider=custom_llm_provider,
802
+ original_exception=e,
803
+ completion_kwargs={},
804
+ extra_kwargs=kwargs,
805
+ )
806
+
807
+
808
+ def get_thread(
809
+ custom_llm_provider: Literal["openai", "azure"],
810
+ thread_id: str,
811
+ client=None,
812
+ **kwargs,
813
+ ) -> Thread:
814
+ """Get the thread object, given a thread_id"""
815
+ aget_thread = kwargs.pop("aget_thread", None)
816
+ optional_params = GenericLiteLLMParams(**kwargs)
817
+ litellm_params_dict = get_litellm_params(**kwargs)
818
+ ### TIMEOUT LOGIC ###
819
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
820
+ # set timeout for 10 minutes by default
821
+
822
+ if (
823
+ timeout is not None
824
+ and isinstance(timeout, httpx.Timeout)
825
+ and supports_httpx_timeout(custom_llm_provider) is False
826
+ ):
827
+ read_timeout = timeout.read or 600
828
+ timeout = read_timeout # default 10 min timeout
829
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
830
+ timeout = float(timeout) # type: ignore
831
+ elif timeout is None:
832
+ timeout = 600.0
833
+ api_base: Optional[str] = None
834
+ api_key: Optional[str] = None
835
+ response: Optional[Thread] = None
836
+ if custom_llm_provider == "openai":
837
+ api_base = (
838
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
839
+ or litellm.api_base
840
+ or os.getenv("OPENAI_BASE_URL")
841
+ or os.getenv("OPENAI_API_BASE")
842
+ or "https://api.openai.com/v1"
843
+ )
844
+ organization = (
845
+ optional_params.organization
846
+ or litellm.organization
847
+ or os.getenv("OPENAI_ORGANIZATION", None)
848
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
849
+ )
850
+ # set API KEY
851
+ api_key = (
852
+ optional_params.api_key
853
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
854
+ or litellm.openai_key
855
+ or os.getenv("OPENAI_API_KEY")
856
+ )
857
+
858
+ response = openai_assistants_api.get_thread(
859
+ thread_id=thread_id,
860
+ api_base=api_base,
861
+ api_key=api_key,
862
+ timeout=timeout,
863
+ max_retries=optional_params.max_retries,
864
+ organization=organization,
865
+ client=client,
866
+ aget_thread=aget_thread,
867
+ )
868
+ elif custom_llm_provider == "azure":
869
+ api_base = (
870
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
871
+ ) # type: ignore
872
+
873
+ api_version: Optional[str] = (
874
+ optional_params.api_version
875
+ or litellm.api_version
876
+ or get_secret("AZURE_API_VERSION")
877
+ ) # type: ignore
878
+
879
+ api_key = (
880
+ optional_params.api_key
881
+ or litellm.api_key
882
+ or litellm.azure_key
883
+ or get_secret("AZURE_OPENAI_API_KEY")
884
+ or get_secret("AZURE_API_KEY")
885
+ ) # type: ignore
886
+
887
+ extra_body = optional_params.get("extra_body", {})
888
+ azure_ad_token: Optional[str] = None
889
+ if extra_body is not None:
890
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
891
+ else:
892
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
893
+
894
+ if isinstance(client, OpenAI):
895
+ client = None # only pass client if it's AzureOpenAI
896
+
897
+ response = azure_assistants_api.get_thread(
898
+ thread_id=thread_id,
899
+ api_base=api_base,
900
+ api_key=api_key,
901
+ azure_ad_token=azure_ad_token,
902
+ api_version=api_version,
903
+ timeout=timeout,
904
+ max_retries=optional_params.max_retries,
905
+ client=client,
906
+ aget_thread=aget_thread,
907
+ litellm_params=litellm_params_dict,
908
+ )
909
+ else:
910
+ raise litellm.exceptions.BadRequestError(
911
+ message="LiteLLM doesn't support {} for 'get_thread'. Only 'openai' is supported.".format(
912
+ custom_llm_provider
913
+ ),
914
+ model="n/a",
915
+ llm_provider=custom_llm_provider,
916
+ response=httpx.Response(
917
+ status_code=400,
918
+ content="Unsupported provider",
919
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
920
+ ),
921
+ )
922
+ return response # type: ignore
923
+
924
+
925
+ ### MESSAGES ###
926
+
927
+
928
+ async def a_add_message(
929
+ custom_llm_provider: Literal["openai", "azure"],
930
+ thread_id: str,
931
+ role: Literal["user", "assistant"],
932
+ content: str,
933
+ attachments: Optional[List[Attachment]] = None,
934
+ metadata: Optional[dict] = None,
935
+ client=None,
936
+ **kwargs,
937
+ ) -> OpenAIMessage:
938
+ loop = asyncio.get_event_loop()
939
+ ### PASS ARGS TO GET ASSISTANTS ###
940
+ kwargs["a_add_message"] = True
941
+ try:
942
+ # Use a partial function to pass your keyword arguments
943
+ func = partial(
944
+ add_message,
945
+ custom_llm_provider,
946
+ thread_id,
947
+ role,
948
+ content,
949
+ attachments,
950
+ metadata,
951
+ client,
952
+ **kwargs,
953
+ )
954
+
955
+ # Add the context to the function
956
+ ctx = contextvars.copy_context()
957
+ func_with_context = partial(ctx.run, func)
958
+
959
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
960
+ model="", custom_llm_provider=custom_llm_provider
961
+ ) # type: ignore
962
+
963
+ # Await normally
964
+ init_response = await loop.run_in_executor(None, func_with_context)
965
+ if asyncio.iscoroutine(init_response):
966
+ response = await init_response
967
+ else:
968
+ # Call the synchronous function using run_in_executor
969
+ response = init_response
970
+ return response # type: ignore
971
+ except Exception as e:
972
+ raise exception_type(
973
+ model="",
974
+ custom_llm_provider=custom_llm_provider,
975
+ original_exception=e,
976
+ completion_kwargs={},
977
+ extra_kwargs=kwargs,
978
+ )
979
+
980
+
981
+ def add_message(
982
+ custom_llm_provider: Literal["openai", "azure"],
983
+ thread_id: str,
984
+ role: Literal["user", "assistant"],
985
+ content: str,
986
+ attachments: Optional[List[Attachment]] = None,
987
+ metadata: Optional[dict] = None,
988
+ client=None,
989
+ **kwargs,
990
+ ) -> OpenAIMessage:
991
+ ### COMMON OBJECTS ###
992
+ a_add_message = kwargs.pop("a_add_message", None)
993
+ _message_data = MessageData(
994
+ role=role, content=content, attachments=attachments, metadata=metadata
995
+ )
996
+ litellm_params_dict = get_litellm_params(**kwargs)
997
+ optional_params = GenericLiteLLMParams(**kwargs)
998
+
999
+ message_data = get_optional_params_add_message(
1000
+ role=_message_data["role"],
1001
+ content=_message_data["content"],
1002
+ attachments=_message_data["attachments"],
1003
+ metadata=_message_data["metadata"],
1004
+ custom_llm_provider=custom_llm_provider,
1005
+ )
1006
+
1007
+ ### TIMEOUT LOGIC ###
1008
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
1009
+ # set timeout for 10 minutes by default
1010
+
1011
+ if (
1012
+ timeout is not None
1013
+ and isinstance(timeout, httpx.Timeout)
1014
+ and supports_httpx_timeout(custom_llm_provider) is False
1015
+ ):
1016
+ read_timeout = timeout.read or 600
1017
+ timeout = read_timeout # default 10 min timeout
1018
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
1019
+ timeout = float(timeout) # type: ignore
1020
+ elif timeout is None:
1021
+ timeout = 600.0
1022
+ api_key: Optional[str] = None
1023
+ api_base: Optional[str] = None
1024
+ response: Optional[OpenAIMessage] = None
1025
+ if custom_llm_provider == "openai":
1026
+ api_base = (
1027
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
1028
+ or litellm.api_base
1029
+ or os.getenv("OPENAI_BASE_URL")
1030
+ or os.getenv("OPENAI_API_BASE")
1031
+ or "https://api.openai.com/v1"
1032
+ )
1033
+ organization = (
1034
+ optional_params.organization
1035
+ or litellm.organization
1036
+ or os.getenv("OPENAI_ORGANIZATION", None)
1037
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
1038
+ )
1039
+ # set API KEY
1040
+ api_key = (
1041
+ optional_params.api_key
1042
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
1043
+ or litellm.openai_key
1044
+ or os.getenv("OPENAI_API_KEY")
1045
+ )
1046
+ response = openai_assistants_api.add_message(
1047
+ thread_id=thread_id,
1048
+ message_data=message_data,
1049
+ api_base=api_base,
1050
+ api_key=api_key,
1051
+ timeout=timeout,
1052
+ max_retries=optional_params.max_retries,
1053
+ organization=organization,
1054
+ client=client,
1055
+ a_add_message=a_add_message,
1056
+ )
1057
+ elif custom_llm_provider == "azure":
1058
+ api_base = (
1059
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
1060
+ ) # type: ignore
1061
+
1062
+ api_version: Optional[str] = (
1063
+ optional_params.api_version
1064
+ or litellm.api_version
1065
+ or get_secret("AZURE_API_VERSION")
1066
+ ) # type: ignore
1067
+
1068
+ api_key = (
1069
+ optional_params.api_key
1070
+ or litellm.api_key
1071
+ or litellm.azure_key
1072
+ or get_secret("AZURE_OPENAI_API_KEY")
1073
+ or get_secret("AZURE_API_KEY")
1074
+ ) # type: ignore
1075
+
1076
+ extra_body = optional_params.get("extra_body", {})
1077
+ azure_ad_token: Optional[str] = None
1078
+ if extra_body is not None:
1079
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
1080
+ else:
1081
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
1082
+
1083
+ response = azure_assistants_api.add_message(
1084
+ thread_id=thread_id,
1085
+ message_data=message_data,
1086
+ api_base=api_base,
1087
+ api_key=api_key,
1088
+ api_version=api_version,
1089
+ azure_ad_token=azure_ad_token,
1090
+ timeout=timeout,
1091
+ max_retries=optional_params.max_retries,
1092
+ client=client,
1093
+ a_add_message=a_add_message,
1094
+ litellm_params=litellm_params_dict,
1095
+ )
1096
+ else:
1097
+ raise litellm.exceptions.BadRequestError(
1098
+ message="LiteLLM doesn't support {} for 'create_thread'. Only 'openai' is supported.".format(
1099
+ custom_llm_provider
1100
+ ),
1101
+ model="n/a",
1102
+ llm_provider=custom_llm_provider,
1103
+ response=httpx.Response(
1104
+ status_code=400,
1105
+ content="Unsupported provider",
1106
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
1107
+ ),
1108
+ )
1109
+
1110
+ return response # type: ignore
1111
+
1112
+
1113
+ async def aget_messages(
1114
+ custom_llm_provider: Literal["openai", "azure"],
1115
+ thread_id: str,
1116
+ client: Optional[AsyncOpenAI] = None,
1117
+ **kwargs,
1118
+ ) -> AsyncCursorPage[OpenAIMessage]:
1119
+ loop = asyncio.get_event_loop()
1120
+ ### PASS ARGS TO GET ASSISTANTS ###
1121
+ kwargs["aget_messages"] = True
1122
+ try:
1123
+ # Use a partial function to pass your keyword arguments
1124
+ func = partial(
1125
+ get_messages,
1126
+ custom_llm_provider,
1127
+ thread_id,
1128
+ client,
1129
+ **kwargs,
1130
+ )
1131
+
1132
+ # Add the context to the function
1133
+ ctx = contextvars.copy_context()
1134
+ func_with_context = partial(ctx.run, func)
1135
+
1136
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
1137
+ model="", custom_llm_provider=custom_llm_provider
1138
+ ) # type: ignore
1139
+
1140
+ # Await normally
1141
+ init_response = await loop.run_in_executor(None, func_with_context)
1142
+ if asyncio.iscoroutine(init_response):
1143
+ response = await init_response
1144
+ else:
1145
+ # Call the synchronous function using run_in_executor
1146
+ response = init_response
1147
+ return response # type: ignore
1148
+ except Exception as e:
1149
+ raise exception_type(
1150
+ model="",
1151
+ custom_llm_provider=custom_llm_provider,
1152
+ original_exception=e,
1153
+ completion_kwargs={},
1154
+ extra_kwargs=kwargs,
1155
+ )
1156
+
1157
+
1158
+ def get_messages(
1159
+ custom_llm_provider: Literal["openai", "azure"],
1160
+ thread_id: str,
1161
+ client: Optional[Any] = None,
1162
+ **kwargs,
1163
+ ) -> SyncCursorPage[OpenAIMessage]:
1164
+ aget_messages = kwargs.pop("aget_messages", None)
1165
+ optional_params = GenericLiteLLMParams(**kwargs)
1166
+ litellm_params_dict = get_litellm_params(**kwargs)
1167
+
1168
+ ### TIMEOUT LOGIC ###
1169
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
1170
+ # set timeout for 10 minutes by default
1171
+
1172
+ if (
1173
+ timeout is not None
1174
+ and isinstance(timeout, httpx.Timeout)
1175
+ and supports_httpx_timeout(custom_llm_provider) is False
1176
+ ):
1177
+ read_timeout = timeout.read or 600
1178
+ timeout = read_timeout # default 10 min timeout
1179
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
1180
+ timeout = float(timeout) # type: ignore
1181
+ elif timeout is None:
1182
+ timeout = 600.0
1183
+
1184
+ response: Optional[SyncCursorPage[OpenAIMessage]] = None
1185
+ api_key: Optional[str] = None
1186
+ api_base: Optional[str] = None
1187
+ if custom_llm_provider == "openai":
1188
+ api_base = (
1189
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
1190
+ or litellm.api_base
1191
+ or os.getenv("OPENAI_BASE_URL")
1192
+ or os.getenv("OPENAI_API_BASE")
1193
+ or "https://api.openai.com/v1"
1194
+ )
1195
+ organization = (
1196
+ optional_params.organization
1197
+ or litellm.organization
1198
+ or os.getenv("OPENAI_ORGANIZATION", None)
1199
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
1200
+ )
1201
+ # set API KEY
1202
+ api_key = (
1203
+ optional_params.api_key
1204
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
1205
+ or litellm.openai_key
1206
+ or os.getenv("OPENAI_API_KEY")
1207
+ )
1208
+ response = openai_assistants_api.get_messages(
1209
+ thread_id=thread_id,
1210
+ api_base=api_base,
1211
+ api_key=api_key,
1212
+ timeout=timeout,
1213
+ max_retries=optional_params.max_retries,
1214
+ organization=organization,
1215
+ client=client,
1216
+ aget_messages=aget_messages,
1217
+ )
1218
+ elif custom_llm_provider == "azure":
1219
+ api_base = (
1220
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
1221
+ ) # type: ignore
1222
+
1223
+ api_version: Optional[str] = (
1224
+ optional_params.api_version
1225
+ or litellm.api_version
1226
+ or get_secret("AZURE_API_VERSION")
1227
+ ) # type: ignore
1228
+
1229
+ api_key = (
1230
+ optional_params.api_key
1231
+ or litellm.api_key
1232
+ or litellm.azure_key
1233
+ or get_secret("AZURE_OPENAI_API_KEY")
1234
+ or get_secret("AZURE_API_KEY")
1235
+ ) # type: ignore
1236
+
1237
+ extra_body = optional_params.get("extra_body", {})
1238
+ azure_ad_token: Optional[str] = None
1239
+ if extra_body is not None:
1240
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
1241
+ else:
1242
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
1243
+
1244
+ response = azure_assistants_api.get_messages(
1245
+ thread_id=thread_id,
1246
+ api_base=api_base,
1247
+ api_key=api_key,
1248
+ api_version=api_version,
1249
+ azure_ad_token=azure_ad_token,
1250
+ timeout=timeout,
1251
+ max_retries=optional_params.max_retries,
1252
+ client=client,
1253
+ aget_messages=aget_messages,
1254
+ litellm_params=litellm_params_dict,
1255
+ )
1256
+ else:
1257
+ raise litellm.exceptions.BadRequestError(
1258
+ message="LiteLLM doesn't support {} for 'get_messages'. Only 'openai' is supported.".format(
1259
+ custom_llm_provider
1260
+ ),
1261
+ model="n/a",
1262
+ llm_provider=custom_llm_provider,
1263
+ response=httpx.Response(
1264
+ status_code=400,
1265
+ content="Unsupported provider",
1266
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
1267
+ ),
1268
+ )
1269
+
1270
+ return response # type: ignore
1271
+
1272
+
1273
+ ### RUNS ###
1274
+ def arun_thread_stream(
1275
+ *,
1276
+ event_handler: Optional[AssistantEventHandler] = None,
1277
+ **kwargs,
1278
+ ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]:
1279
+ kwargs["arun_thread"] = True
1280
+ return run_thread(stream=True, event_handler=event_handler, **kwargs) # type: ignore
1281
+
1282
+
1283
+ async def arun_thread(
1284
+ custom_llm_provider: Literal["openai", "azure"],
1285
+ thread_id: str,
1286
+ assistant_id: str,
1287
+ additional_instructions: Optional[str] = None,
1288
+ instructions: Optional[str] = None,
1289
+ metadata: Optional[dict] = None,
1290
+ model: Optional[str] = None,
1291
+ stream: Optional[bool] = None,
1292
+ tools: Optional[Iterable[AssistantToolParam]] = None,
1293
+ client: Optional[Any] = None,
1294
+ **kwargs,
1295
+ ) -> Run:
1296
+ loop = asyncio.get_event_loop()
1297
+ ### PASS ARGS TO GET ASSISTANTS ###
1298
+ kwargs["arun_thread"] = True
1299
+ try:
1300
+ # Use a partial function to pass your keyword arguments
1301
+ func = partial(
1302
+ run_thread,
1303
+ custom_llm_provider,
1304
+ thread_id,
1305
+ assistant_id,
1306
+ additional_instructions,
1307
+ instructions,
1308
+ metadata,
1309
+ model,
1310
+ stream,
1311
+ tools,
1312
+ client,
1313
+ **kwargs,
1314
+ )
1315
+
1316
+ # Add the context to the function
1317
+ ctx = contextvars.copy_context()
1318
+ func_with_context = partial(ctx.run, func)
1319
+
1320
+ _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore
1321
+ model="", custom_llm_provider=custom_llm_provider
1322
+ ) # type: ignore
1323
+
1324
+ # Await normally
1325
+ init_response = await loop.run_in_executor(None, func_with_context)
1326
+ if asyncio.iscoroutine(init_response):
1327
+ response = await init_response
1328
+ else:
1329
+ # Call the synchronous function using run_in_executor
1330
+ response = init_response
1331
+ return response # type: ignore
1332
+ except Exception as e:
1333
+ raise exception_type(
1334
+ model="",
1335
+ custom_llm_provider=custom_llm_provider,
1336
+ original_exception=e,
1337
+ completion_kwargs={},
1338
+ extra_kwargs=kwargs,
1339
+ )
1340
+
1341
+
1342
+ def run_thread_stream(
1343
+ *,
1344
+ event_handler: Optional[AssistantEventHandler] = None,
1345
+ **kwargs,
1346
+ ) -> AssistantStreamManager[AssistantEventHandler]:
1347
+ return run_thread(stream=True, event_handler=event_handler, **kwargs) # type: ignore
1348
+
1349
+
1350
+ def run_thread(
1351
+ custom_llm_provider: Literal["openai", "azure"],
1352
+ thread_id: str,
1353
+ assistant_id: str,
1354
+ additional_instructions: Optional[str] = None,
1355
+ instructions: Optional[str] = None,
1356
+ metadata: Optional[dict] = None,
1357
+ model: Optional[str] = None,
1358
+ stream: Optional[bool] = None,
1359
+ tools: Optional[Iterable[AssistantToolParam]] = None,
1360
+ client: Optional[Any] = None,
1361
+ event_handler: Optional[AssistantEventHandler] = None, # for stream=True calls
1362
+ **kwargs,
1363
+ ) -> Run:
1364
+ """Run a given thread + assistant."""
1365
+ arun_thread = kwargs.pop("arun_thread", None)
1366
+ optional_params = GenericLiteLLMParams(**kwargs)
1367
+ litellm_params_dict = get_litellm_params(**kwargs)
1368
+
1369
+ ### TIMEOUT LOGIC ###
1370
+ timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
1371
+ # set timeout for 10 minutes by default
1372
+
1373
+ if (
1374
+ timeout is not None
1375
+ and isinstance(timeout, httpx.Timeout)
1376
+ and supports_httpx_timeout(custom_llm_provider) is False
1377
+ ):
1378
+ read_timeout = timeout.read or 600
1379
+ timeout = read_timeout # default 10 min timeout
1380
+ elif timeout is not None and not isinstance(timeout, httpx.Timeout):
1381
+ timeout = float(timeout) # type: ignore
1382
+ elif timeout is None:
1383
+ timeout = 600.0
1384
+
1385
+ response: Optional[Run] = None
1386
+ if custom_llm_provider == "openai":
1387
+ api_base = (
1388
+ optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there
1389
+ or litellm.api_base
1390
+ or os.getenv("OPENAI_BASE_URL")
1391
+ or os.getenv("OPENAI_API_BASE")
1392
+ or "https://api.openai.com/v1"
1393
+ )
1394
+ organization = (
1395
+ optional_params.organization
1396
+ or litellm.organization
1397
+ or os.getenv("OPENAI_ORGANIZATION", None)
1398
+ or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105
1399
+ )
1400
+ # set API KEY
1401
+ api_key = (
1402
+ optional_params.api_key
1403
+ or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there
1404
+ or litellm.openai_key
1405
+ or os.getenv("OPENAI_API_KEY")
1406
+ )
1407
+
1408
+ response = openai_assistants_api.run_thread(
1409
+ thread_id=thread_id,
1410
+ assistant_id=assistant_id,
1411
+ additional_instructions=additional_instructions,
1412
+ instructions=instructions,
1413
+ metadata=metadata,
1414
+ model=model,
1415
+ stream=stream,
1416
+ tools=tools,
1417
+ api_base=api_base,
1418
+ api_key=api_key,
1419
+ timeout=timeout,
1420
+ max_retries=optional_params.max_retries,
1421
+ organization=organization,
1422
+ client=client,
1423
+ arun_thread=arun_thread,
1424
+ event_handler=event_handler,
1425
+ )
1426
+ elif custom_llm_provider == "azure":
1427
+ api_base = (
1428
+ optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE")
1429
+ ) # type: ignore
1430
+
1431
+ api_version = (
1432
+ optional_params.api_version
1433
+ or litellm.api_version
1434
+ or get_secret("AZURE_API_VERSION")
1435
+ ) # type: ignore
1436
+
1437
+ api_key = (
1438
+ optional_params.api_key
1439
+ or litellm.api_key
1440
+ or litellm.azure_key
1441
+ or get_secret("AZURE_OPENAI_API_KEY")
1442
+ or get_secret("AZURE_API_KEY")
1443
+ ) # type: ignore
1444
+
1445
+ extra_body = optional_params.get("extra_body", {})
1446
+ azure_ad_token = None
1447
+ if extra_body is not None:
1448
+ azure_ad_token = extra_body.pop("azure_ad_token", None)
1449
+ else:
1450
+ azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore
1451
+
1452
+ response = azure_assistants_api.run_thread(
1453
+ thread_id=thread_id,
1454
+ assistant_id=assistant_id,
1455
+ additional_instructions=additional_instructions,
1456
+ instructions=instructions,
1457
+ metadata=metadata,
1458
+ model=model,
1459
+ stream=stream,
1460
+ tools=tools,
1461
+ api_base=str(api_base) if api_base is not None else None,
1462
+ api_key=str(api_key) if api_key is not None else None,
1463
+ api_version=str(api_version) if api_version is not None else None,
1464
+ azure_ad_token=str(azure_ad_token) if azure_ad_token is not None else None,
1465
+ timeout=timeout,
1466
+ max_retries=optional_params.max_retries,
1467
+ client=client,
1468
+ arun_thread=arun_thread,
1469
+ litellm_params=litellm_params_dict,
1470
+ ) # type: ignore
1471
+ else:
1472
+ raise litellm.exceptions.BadRequestError(
1473
+ message="LiteLLM doesn't support {} for 'run_thread'. Only 'openai' is supported.".format(
1474
+ custom_llm_provider
1475
+ ),
1476
+ model="n/a",
1477
+ llm_provider=custom_llm_provider,
1478
+ response=httpx.Response(
1479
+ status_code=400,
1480
+ content="Unsupported provider",
1481
+ request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore
1482
+ ),
1483
+ )
1484
+ return response # type: ignore
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/utils.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import litellm
4
+
5
+ from ..exceptions import UnsupportedParamsError
6
+ from ..types.llms.openai import *
7
+
8
+
9
+ def get_optional_params_add_message(
10
+ role: Optional[str],
11
+ content: Optional[
12
+ Union[
13
+ str,
14
+ List[
15
+ Union[
16
+ MessageContentTextObject,
17
+ MessageContentImageFileObject,
18
+ MessageContentImageURLObject,
19
+ ]
20
+ ],
21
+ ]
22
+ ],
23
+ attachments: Optional[List[Attachment]],
24
+ metadata: Optional[dict],
25
+ custom_llm_provider: str,
26
+ **kwargs,
27
+ ):
28
+ """
29
+ Azure doesn't support 'attachments' for creating a message
30
+
31
+ Reference - https://learn.microsoft.com/en-us/azure/ai-services/openai/assistants-reference-messages?tabs=python#create-message
32
+ """
33
+ passed_params = locals()
34
+ custom_llm_provider = passed_params.pop("custom_llm_provider")
35
+ special_params = passed_params.pop("kwargs")
36
+ for k, v in special_params.items():
37
+ passed_params[k] = v
38
+
39
+ default_params = {
40
+ "role": None,
41
+ "content": None,
42
+ "attachments": None,
43
+ "metadata": None,
44
+ }
45
+
46
+ non_default_params = {
47
+ k: v
48
+ for k, v in passed_params.items()
49
+ if (k in default_params and v != default_params[k])
50
+ }
51
+ optional_params = {}
52
+
53
+ ## raise exception if non-default value passed for non-openai/azure embedding calls
54
+ def _check_valid_arg(supported_params):
55
+ if len(non_default_params.keys()) > 0:
56
+ keys = list(non_default_params.keys())
57
+ for k in keys:
58
+ if (
59
+ litellm.drop_params is True and k not in supported_params
60
+ ): # drop the unsupported non-default values
61
+ non_default_params.pop(k, None)
62
+ elif k not in supported_params:
63
+ raise litellm.utils.UnsupportedParamsError(
64
+ status_code=500,
65
+ message="k={}, not supported by {}. Supported params={}. To drop it from the call, set `litellm.drop_params = True`.".format(
66
+ k, custom_llm_provider, supported_params
67
+ ),
68
+ )
69
+ return non_default_params
70
+
71
+ if custom_llm_provider == "openai":
72
+ optional_params = non_default_params
73
+ elif custom_llm_provider == "azure":
74
+ supported_params = (
75
+ litellm.AzureOpenAIAssistantsAPIConfig().get_supported_openai_create_message_params()
76
+ )
77
+ _check_valid_arg(supported_params=supported_params)
78
+ optional_params = litellm.AzureOpenAIAssistantsAPIConfig().map_openai_params_create_message_params(
79
+ non_default_params=non_default_params, optional_params=optional_params
80
+ )
81
+ for k in passed_params.keys():
82
+ if k not in default_params.keys():
83
+ optional_params[k] = passed_params[k]
84
+ return optional_params
85
+
86
+
87
+ def get_optional_params_image_gen(
88
+ n: Optional[int] = None,
89
+ quality: Optional[str] = None,
90
+ response_format: Optional[str] = None,
91
+ size: Optional[str] = None,
92
+ style: Optional[str] = None,
93
+ user: Optional[str] = None,
94
+ custom_llm_provider: Optional[str] = None,
95
+ **kwargs,
96
+ ):
97
+ # retrieve all parameters passed to the function
98
+ passed_params = locals()
99
+ custom_llm_provider = passed_params.pop("custom_llm_provider")
100
+ special_params = passed_params.pop("kwargs")
101
+ for k, v in special_params.items():
102
+ passed_params[k] = v
103
+
104
+ default_params = {
105
+ "n": None,
106
+ "quality": None,
107
+ "response_format": None,
108
+ "size": None,
109
+ "style": None,
110
+ "user": None,
111
+ }
112
+
113
+ non_default_params = {
114
+ k: v
115
+ for k, v in passed_params.items()
116
+ if (k in default_params and v != default_params[k])
117
+ }
118
+ optional_params = {}
119
+
120
+ ## raise exception if non-default value passed for non-openai/azure embedding calls
121
+ def _check_valid_arg(supported_params):
122
+ if len(non_default_params.keys()) > 0:
123
+ keys = list(non_default_params.keys())
124
+ for k in keys:
125
+ if (
126
+ litellm.drop_params is True and k not in supported_params
127
+ ): # drop the unsupported non-default values
128
+ non_default_params.pop(k, None)
129
+ elif k not in supported_params:
130
+ raise UnsupportedParamsError(
131
+ status_code=500,
132
+ message=f"Setting user/encoding format is not supported by {custom_llm_provider}. To drop it from the call, set `litellm.drop_params = True`.",
133
+ )
134
+ return non_default_params
135
+
136
+ if (
137
+ custom_llm_provider == "openai"
138
+ or custom_llm_provider == "azure"
139
+ or custom_llm_provider in litellm.openai_compatible_providers
140
+ ):
141
+ optional_params = non_default_params
142
+ elif custom_llm_provider == "bedrock":
143
+ supported_params = ["size"]
144
+ _check_valid_arg(supported_params=supported_params)
145
+ if size is not None:
146
+ width, height = size.split("x")
147
+ optional_params["width"] = int(width)
148
+ optional_params["height"] = int(height)
149
+ elif custom_llm_provider == "vertex_ai":
150
+ supported_params = ["n"]
151
+ """
152
+ All params here: https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/imagegeneration?project=adroit-crow-413218
153
+ """
154
+ _check_valid_arg(supported_params=supported_params)
155
+ if n is not None:
156
+ optional_params["sampleCount"] = int(n)
157
+
158
+ for k in passed_params.keys():
159
+ if k not in default_params.keys():
160
+ optional_params[k] = passed_params[k]
161
+ return optional_params
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/Readme.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Caching on LiteLLM
2
+
3
+ LiteLLM supports multiple caching mechanisms. This allows users to choose the most suitable caching solution for their use case.
4
+
5
+ The following caching mechanisms are supported:
6
+
7
+ 1. **RedisCache**
8
+ 2. **RedisSemanticCache**
9
+ 3. **QdrantSemanticCache**
10
+ 4. **InMemoryCache**
11
+ 5. **DiskCache**
12
+ 6. **S3Cache**
13
+ 7. **AzureBlobCache**
14
+ 8. **DualCache** (updates both Redis and an in-memory cache simultaneously)
15
+
16
+ ## Folder Structure
17
+
18
+ ```
19
+ litellm/caching/
20
+ ├── base_cache.py
21
+ ├── caching.py
22
+ ├── caching_handler.py
23
+ ├── disk_cache.py
24
+ ├── dual_cache.py
25
+ ├── in_memory_cache.py
26
+ ├── qdrant_semantic_cache.py
27
+ ├── redis_cache.py
28
+ ├── redis_semantic_cache.py
29
+ ├── s3_cache.py
30
+ ```
31
+
32
+ ## Documentation
33
+ - [Caching on LiteLLM Gateway](https://docs.litellm.ai/docs/proxy/caching)
34
+ - [Caching on LiteLLM Python](https://docs.litellm.ai/docs/caching/all_caches)
35
+
36
+
37
+
38
+
39
+
40
+
41
+
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .azure_blob_cache import AzureBlobCache
2
+ from .caching import Cache, LiteLLMCacheType
3
+ from .disk_cache import DiskCache
4
+ from .dual_cache import DualCache
5
+ from .in_memory_cache import InMemoryCache
6
+ from .qdrant_semantic_cache import QdrantSemanticCache
7
+ from .redis_cache import RedisCache
8
+ from .redis_cluster_cache import RedisClusterCache
9
+ from .redis_semantic_cache import RedisSemanticCache
10
+ from .s3_cache import S3Cache
11
+ from .gcs_cache import GCSCache
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/_internal_lru_cache.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from typing import Callable, Optional, TypeVar
3
+
4
+ T = TypeVar("T")
5
+
6
+
7
+ def lru_cache_wrapper(
8
+ maxsize: Optional[int] = None,
9
+ ) -> Callable[[Callable[..., T]], Callable[..., T]]:
10
+ """
11
+ Wrapper for lru_cache that caches success and exceptions
12
+ """
13
+
14
+ def decorator(f: Callable[..., T]) -> Callable[..., T]:
15
+ @lru_cache(maxsize=maxsize)
16
+ def wrapper(*args, **kwargs):
17
+ try:
18
+ return ("success", f(*args, **kwargs))
19
+ except Exception as e:
20
+ return ("error", e)
21
+
22
+ def wrapped(*args, **kwargs):
23
+ result = wrapper(*args, **kwargs)
24
+ if result[0] == "error":
25
+ raise result[1]
26
+ return result[1]
27
+
28
+ return wrapped
29
+
30
+ return decorator
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/azure_blob_cache.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Azure Blob Cache implementation
3
+
4
+ Has 4 methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ import asyncio
12
+ import json
13
+ from contextlib import suppress
14
+
15
+ from litellm._logging import print_verbose, verbose_logger
16
+
17
+ from .base_cache import BaseCache
18
+
19
+
20
+ class AzureBlobCache(BaseCache):
21
+ def __init__(self, account_url, container) -> None:
22
+ from azure.storage.blob import BlobServiceClient
23
+ from azure.core.exceptions import ResourceExistsError
24
+ from azure.identity import DefaultAzureCredential
25
+ from azure.identity.aio import (
26
+ DefaultAzureCredential as AsyncDefaultAzureCredential,
27
+ )
28
+ from azure.storage.blob.aio import BlobServiceClient as AsyncBlobServiceClient
29
+
30
+ self.container_client = BlobServiceClient(
31
+ account_url=account_url,
32
+ credential=DefaultAzureCredential(),
33
+ ).get_container_client(container)
34
+ self.async_container_client = AsyncBlobServiceClient(
35
+ account_url=account_url,
36
+ credential=AsyncDefaultAzureCredential(),
37
+ ).get_container_client(container)
38
+
39
+ with suppress(ResourceExistsError):
40
+ self.container_client.create_container()
41
+
42
+ def set_cache(self, key, value, **kwargs) -> None:
43
+ print_verbose(f"LiteLLM SET Cache - Azure Blob. Key={key}. Value={value}")
44
+ serialized_value = json.dumps(value)
45
+ try:
46
+ self.container_client.upload_blob(key, serialized_value)
47
+ except Exception as e:
48
+ # NON blocking - notify users Azure Blob is throwing an exception
49
+ print_verbose(f"LiteLLM set_cache() - Got exception from Azure Blob: {e}")
50
+
51
+ async def async_set_cache(self, key, value, **kwargs) -> None:
52
+ print_verbose(f"LiteLLM SET Cache - Azure Blob. Key={key}. Value={value}")
53
+ serialized_value = json.dumps(value)
54
+ try:
55
+ await self.async_container_client.upload_blob(
56
+ key, serialized_value, overwrite=True
57
+ )
58
+ except Exception as e:
59
+ # NON blocking - notify users Azure Blob is throwing an exception
60
+ print_verbose(f"LiteLLM set_cache() - Got exception from Azure Blob: {e}")
61
+
62
+ def get_cache(self, key, **kwargs):
63
+ from azure.core.exceptions import ResourceNotFoundError
64
+
65
+ try:
66
+ print_verbose(f"Get Azure Blob Cache: key: {key}")
67
+ as_bytes = self.container_client.download_blob(key).readall()
68
+ as_str = as_bytes.decode("utf-8")
69
+ cached_response = json.loads(as_str)
70
+
71
+ verbose_logger.debug(
72
+ f"Got Azure Blob Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}"
73
+ )
74
+
75
+ return cached_response
76
+ except ResourceNotFoundError:
77
+ return None
78
+
79
+ async def async_get_cache(self, key, **kwargs):
80
+ from azure.core.exceptions import ResourceNotFoundError
81
+
82
+ try:
83
+ print_verbose(f"Get Azure Blob Cache: key: {key}")
84
+ blob = await self.async_container_client.download_blob(key)
85
+ as_bytes = await blob.readall()
86
+ as_str = as_bytes.decode("utf-8")
87
+ cached_response = json.loads(as_str)
88
+ verbose_logger.debug(
89
+ f"Got Azure Blob Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}"
90
+ )
91
+ return cached_response
92
+ except ResourceNotFoundError:
93
+ return None
94
+
95
+ def flush_cache(self) -> None:
96
+ for blob in self.container_client.walk_blobs():
97
+ self.container_client.delete_blob(blob.name)
98
+
99
+ async def disconnect(self) -> None:
100
+ self.container_client.close()
101
+ await self.async_container_client.close()
102
+
103
+ async def async_set_cache_pipeline(self, cache_list, **kwargs) -> None:
104
+ tasks = []
105
+ for val in cache_list:
106
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
107
+ await asyncio.gather(*tasks)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/base_cache.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Base Cache implementation. All cache implementations should inherit from this class.
3
+
4
+ Has 4 methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ from abc import ABC, abstractmethod
12
+ from typing import TYPE_CHECKING, Any, Optional, Union
13
+
14
+ if TYPE_CHECKING:
15
+ from opentelemetry.trace import Span as _Span
16
+
17
+ Span = Union[_Span, Any]
18
+ else:
19
+ Span = Any
20
+
21
+
22
+ class BaseCache(ABC):
23
+ def __init__(self, default_ttl: int = 60):
24
+ self.default_ttl = default_ttl
25
+
26
+ def get_ttl(self, **kwargs) -> Optional[int]:
27
+ kwargs_ttl: Optional[int] = kwargs.get("ttl")
28
+ if kwargs_ttl is not None:
29
+ try:
30
+ return int(kwargs_ttl)
31
+ except ValueError:
32
+ return self.default_ttl
33
+ return self.default_ttl
34
+
35
+ def set_cache(self, key, value, **kwargs):
36
+ raise NotImplementedError
37
+
38
+ async def async_set_cache(self, key, value, **kwargs):
39
+ raise NotImplementedError
40
+
41
+ @abstractmethod
42
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
43
+ pass
44
+
45
+ def get_cache(self, key, **kwargs):
46
+ raise NotImplementedError
47
+
48
+ async def async_get_cache(self, key, **kwargs):
49
+ raise NotImplementedError
50
+
51
+ async def batch_cache_write(self, key, value, **kwargs):
52
+ raise NotImplementedError
53
+
54
+ async def disconnect(self):
55
+ raise NotImplementedError
56
+
57
+ async def test_connection(self) -> dict:
58
+ """
59
+ Test the cache connection.
60
+
61
+ Returns:
62
+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}
63
+ """
64
+ raise NotImplementedError
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # +-----------------------------------------------+
2
+ # | |
3
+ # | Give Feedback / Get Help |
4
+ # | https://github.com/BerriAI/litellm/issues/new |
5
+ # | |
6
+ # +-----------------------------------------------+
7
+ #
8
+ # Thank you users! We ❤️ you! - Krrish & Ishaan
9
+
10
+ import ast
11
+ import hashlib
12
+ import json
13
+ import time
14
+ import traceback
15
+ from enum import Enum
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ from pydantic import BaseModel
19
+
20
+ import litellm
21
+ from litellm._logging import verbose_logger
22
+ from litellm.constants import CACHED_STREAMING_CHUNK_DELAY
23
+ from litellm.litellm_core_utils.model_param_helper import ModelParamHelper
24
+ from litellm.types.caching import *
25
+ from litellm.types.utils import EmbeddingResponse, all_litellm_params
26
+
27
+ from .azure_blob_cache import AzureBlobCache
28
+ from .base_cache import BaseCache
29
+ from .disk_cache import DiskCache
30
+ from .dual_cache import DualCache # noqa
31
+ from .gcs_cache import GCSCache
32
+ from .in_memory_cache import InMemoryCache
33
+ from .qdrant_semantic_cache import QdrantSemanticCache
34
+ from .redis_cache import RedisCache
35
+ from .redis_cluster_cache import RedisClusterCache
36
+ from .redis_semantic_cache import RedisSemanticCache
37
+ from .s3_cache import S3Cache
38
+
39
+
40
+ def print_verbose(print_statement):
41
+ try:
42
+ verbose_logger.debug(print_statement)
43
+ if litellm.set_verbose:
44
+ print(print_statement) # noqa
45
+ except Exception:
46
+ pass
47
+
48
+
49
+ class CacheMode(str, Enum):
50
+ default_on = "default_on"
51
+ default_off = "default_off"
52
+
53
+
54
+ #### LiteLLM.Completion / Embedding Cache ####
55
+ class Cache:
56
+ def __init__(
57
+ self,
58
+ type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,
59
+ mode: Optional[
60
+ CacheMode
61
+ ] = CacheMode.default_on, # when default_on cache is always on, when default_off cache is opt in
62
+ host: Optional[str] = None,
63
+ port: Optional[str] = None,
64
+ password: Optional[str] = None,
65
+ namespace: Optional[str] = None,
66
+ ttl: Optional[float] = None,
67
+ default_in_memory_ttl: Optional[float] = None,
68
+ default_in_redis_ttl: Optional[float] = None,
69
+ similarity_threshold: Optional[float] = None,
70
+ supported_call_types: Optional[List[CachingSupportedCallTypes]] = [
71
+ "completion",
72
+ "acompletion",
73
+ "embedding",
74
+ "aembedding",
75
+ "atranscription",
76
+ "transcription",
77
+ "atext_completion",
78
+ "text_completion",
79
+ "arerank",
80
+ "rerank",
81
+ "responses",
82
+ "aresponses",
83
+ ],
84
+ # s3 Bucket, boto3 configuration
85
+ azure_account_url: Optional[str] = None,
86
+ azure_blob_container: Optional[str] = None,
87
+ s3_bucket_name: Optional[str] = None,
88
+ s3_region_name: Optional[str] = None,
89
+ s3_api_version: Optional[str] = None,
90
+ s3_use_ssl: Optional[bool] = True,
91
+ s3_verify: Optional[Union[bool, str]] = None,
92
+ s3_endpoint_url: Optional[str] = None,
93
+ s3_aws_access_key_id: Optional[str] = None,
94
+ s3_aws_secret_access_key: Optional[str] = None,
95
+ s3_aws_session_token: Optional[str] = None,
96
+ s3_config: Optional[Any] = None,
97
+ s3_path: Optional[str] = None,
98
+ gcs_bucket_name: Optional[str] = None,
99
+ gcs_path_service_account: Optional[str] = None,
100
+ gcs_path: Optional[str] = None,
101
+ redis_semantic_cache_embedding_model: str = "text-embedding-ada-002",
102
+ redis_semantic_cache_index_name: Optional[str] = None,
103
+ redis_flush_size: Optional[int] = None,
104
+ redis_startup_nodes: Optional[List] = None,
105
+ disk_cache_dir: Optional[str] = None,
106
+ qdrant_api_base: Optional[str] = None,
107
+ qdrant_api_key: Optional[str] = None,
108
+ qdrant_collection_name: Optional[str] = None,
109
+ qdrant_quantization_config: Optional[str] = None,
110
+ qdrant_semantic_cache_embedding_model: str = "text-embedding-ada-002",
111
+ qdrant_semantic_cache_vector_size: Optional[int] = None,
112
+ # GCP IAM authentication parameters
113
+ gcp_service_account: Optional[str] = None,
114
+ gcp_ssl_ca_certs: Optional[str] = None,
115
+ **kwargs,
116
+ ):
117
+ """
118
+ Initializes the cache based on the given type.
119
+
120
+ Args:
121
+ type (str, optional): The type of cache to initialize. Can be "local", "redis", "redis-semantic", "qdrant-semantic", "s3" or "disk". Defaults to "local".
122
+
123
+ # Redis Cache Args
124
+ host (str, optional): The host address for the Redis cache. Required if type is "redis".
125
+ port (int, optional): The port number for the Redis cache. Required if type is "redis".
126
+ password (str, optional): The password for the Redis cache. Required if type is "redis".
127
+ namespace (str, optional): The namespace for the Redis cache. Required if type is "redis".
128
+ ttl (float, optional): The ttl for the Redis cache
129
+ redis_flush_size (int, optional): The number of keys to flush at a time. Defaults to 1000. Only used if batch redis set caching is used.
130
+ redis_startup_nodes (list, optional): The list of startup nodes for the Redis cache. Defaults to None.
131
+
132
+ # Qdrant Cache Args
133
+ qdrant_api_base (str, optional): The url for your qdrant cluster. Required if type is "qdrant-semantic".
134
+ qdrant_api_key (str, optional): The api_key for the local or cloud qdrant cluster.
135
+ qdrant_collection_name (str, optional): The name for your qdrant collection. Required if type is "qdrant-semantic".
136
+ similarity_threshold (float, optional): The similarity threshold for semantic-caching, Required if type is "redis-semantic" or "qdrant-semantic".
137
+
138
+ # Disk Cache Args
139
+ disk_cache_dir (str, optional): The directory for the disk cache. Defaults to None.
140
+
141
+ # S3 Cache Args
142
+ s3_bucket_name (str, optional): The bucket name for the s3 cache. Defaults to None.
143
+ s3_region_name (str, optional): The region name for the s3 cache. Defaults to None.
144
+ s3_api_version (str, optional): The api version for the s3 cache. Defaults to None.
145
+ s3_use_ssl (bool, optional): The use ssl for the s3 cache. Defaults to True.
146
+ s3_verify (bool, optional): The verify for the s3 cache. Defaults to None.
147
+ s3_endpoint_url (str, optional): The endpoint url for the s3 cache. Defaults to None.
148
+ s3_aws_access_key_id (str, optional): The aws access key id for the s3 cache. Defaults to None.
149
+ s3_aws_secret_access_key (str, optional): The aws secret access key for the s3 cache. Defaults to None.
150
+ s3_aws_session_token (str, optional): The aws session token for the s3 cache. Defaults to None.
151
+ s3_config (dict, optional): The config for the s3 cache. Defaults to None.
152
+
153
+ # GCS Cache Args
154
+ gcs_bucket_name (str, optional): The bucket name for the gcs cache. Defaults to None.
155
+ gcs_path_service_account (str, optional): Path to the service account json.
156
+ gcs_path (str, optional): Folder path inside the bucket to store cache files.
157
+
158
+ # Common Cache Args
159
+ supported_call_types (list, optional): List of call types to cache for. Defaults to cache == on for all call types.
160
+ **kwargs: Additional keyword arguments for redis.Redis() cache
161
+
162
+ Raises:
163
+ ValueError: If an invalid cache type is provided.
164
+
165
+ Returns:
166
+ None. Cache is set as a litellm param
167
+ """
168
+ if type == LiteLLMCacheType.REDIS:
169
+ # Check REDIS_CLUSTER_NODES env var if no explicit startup nodes
170
+ if not redis_startup_nodes:
171
+ _env_cluster_nodes = litellm.get_secret("REDIS_CLUSTER_NODES")
172
+ if _env_cluster_nodes is not None and isinstance(
173
+ _env_cluster_nodes, str
174
+ ):
175
+ redis_startup_nodes = json.loads(_env_cluster_nodes)
176
+
177
+ if redis_startup_nodes:
178
+ # Only pass GCP parameters if they are provided
179
+ cluster_kwargs = {
180
+ "host": host,
181
+ "port": port,
182
+ "password": password,
183
+ "redis_flush_size": redis_flush_size,
184
+ "startup_nodes": redis_startup_nodes,
185
+ **kwargs,
186
+ }
187
+ if gcp_service_account is not None:
188
+ cluster_kwargs["gcp_service_account"] = gcp_service_account
189
+ if gcp_ssl_ca_certs is not None:
190
+ cluster_kwargs["gcp_ssl_ca_certs"] = gcp_ssl_ca_certs
191
+
192
+ self.cache: BaseCache = RedisClusterCache(**cluster_kwargs)
193
+ else:
194
+ self.cache = RedisCache(
195
+ host=host,
196
+ port=port,
197
+ password=password,
198
+ redis_flush_size=redis_flush_size,
199
+ **kwargs,
200
+ )
201
+ elif type == LiteLLMCacheType.REDIS_SEMANTIC:
202
+ self.cache = RedisSemanticCache(
203
+ host=host,
204
+ port=port,
205
+ password=password,
206
+ similarity_threshold=similarity_threshold,
207
+ embedding_model=redis_semantic_cache_embedding_model,
208
+ index_name=redis_semantic_cache_index_name,
209
+ **kwargs,
210
+ )
211
+ elif type == LiteLLMCacheType.QDRANT_SEMANTIC:
212
+ self.cache = QdrantSemanticCache(
213
+ qdrant_api_base=qdrant_api_base,
214
+ qdrant_api_key=qdrant_api_key,
215
+ collection_name=qdrant_collection_name,
216
+ similarity_threshold=similarity_threshold,
217
+ quantization_config=qdrant_quantization_config,
218
+ embedding_model=qdrant_semantic_cache_embedding_model,
219
+ vector_size=qdrant_semantic_cache_vector_size,
220
+ )
221
+ elif type == LiteLLMCacheType.LOCAL:
222
+ self.cache = InMemoryCache()
223
+ elif type == LiteLLMCacheType.S3:
224
+ self.cache = S3Cache(
225
+ s3_bucket_name=s3_bucket_name,
226
+ s3_region_name=s3_region_name,
227
+ s3_api_version=s3_api_version,
228
+ s3_use_ssl=s3_use_ssl,
229
+ s3_verify=s3_verify,
230
+ s3_endpoint_url=s3_endpoint_url,
231
+ s3_aws_access_key_id=s3_aws_access_key_id,
232
+ s3_aws_secret_access_key=s3_aws_secret_access_key,
233
+ s3_aws_session_token=s3_aws_session_token,
234
+ s3_config=s3_config,
235
+ s3_path=s3_path,
236
+ **kwargs,
237
+ )
238
+ elif type == LiteLLMCacheType.GCS:
239
+ self.cache = GCSCache(
240
+ bucket_name=gcs_bucket_name,
241
+ path_service_account=gcs_path_service_account,
242
+ gcs_path=gcs_path,
243
+ )
244
+ elif type == LiteLLMCacheType.AZURE_BLOB:
245
+ self.cache = AzureBlobCache(
246
+ account_url=azure_account_url,
247
+ container=azure_blob_container,
248
+ )
249
+ elif type == LiteLLMCacheType.DISK:
250
+ self.cache = DiskCache(disk_cache_dir=disk_cache_dir)
251
+ if "cache" not in litellm.input_callback:
252
+ litellm.input_callback.append("cache")
253
+ if "cache" not in litellm.success_callback:
254
+ litellm.logging_callback_manager.add_litellm_success_callback("cache")
255
+ if "cache" not in litellm._async_success_callback:
256
+ litellm.logging_callback_manager.add_litellm_async_success_callback("cache")
257
+ self.supported_call_types = supported_call_types # default to ["completion", "acompletion", "embedding", "aembedding"]
258
+ self.type = type
259
+ self.namespace = namespace
260
+ self.redis_flush_size = redis_flush_size
261
+ self.ttl = ttl
262
+ self.mode: CacheMode = mode or CacheMode.default_on
263
+
264
+ if self.type == LiteLLMCacheType.LOCAL and default_in_memory_ttl is not None:
265
+ self.ttl = default_in_memory_ttl
266
+
267
+ if (
268
+ self.type == LiteLLMCacheType.REDIS
269
+ or self.type == LiteLLMCacheType.REDIS_SEMANTIC
270
+ ) and default_in_redis_ttl is not None:
271
+ self.ttl = default_in_redis_ttl
272
+
273
+ if self.namespace is not None and isinstance(self.cache, RedisCache):
274
+ self.cache.namespace = self.namespace
275
+
276
+ def get_cache_key(self, **kwargs) -> str:
277
+ """
278
+ Get the cache key for the given arguments.
279
+
280
+ Args:
281
+ **kwargs: kwargs to litellm.completion() or embedding()
282
+
283
+ Returns:
284
+ str: The cache key generated from the arguments, or None if no cache key could be generated.
285
+ """
286
+ cache_key = ""
287
+ # verbose_logger.debug("\nGetting Cache key. Kwargs: %s", kwargs)
288
+
289
+ preset_cache_key = self._get_preset_cache_key_from_kwargs(**kwargs)
290
+ if preset_cache_key is not None:
291
+ verbose_logger.debug("\nReturning preset cache key: %s", preset_cache_key)
292
+ return preset_cache_key
293
+
294
+ combined_kwargs = ModelParamHelper._get_all_llm_api_params()
295
+ litellm_param_kwargs = all_litellm_params
296
+ for param in kwargs:
297
+ if param in combined_kwargs:
298
+ param_value: Optional[str] = self._get_param_value(param, kwargs)
299
+ if param_value is not None:
300
+ cache_key += f"{str(param)}: {str(param_value)}"
301
+ elif (
302
+ param not in litellm_param_kwargs
303
+ ): # check if user passed in optional param - e.g. top_k
304
+ if (
305
+ litellm.enable_caching_on_provider_specific_optional_params is True
306
+ ): # feature flagged for now
307
+ if kwargs[param] is None:
308
+ continue # ignore None params
309
+ param_value = kwargs[param]
310
+ cache_key += f"{str(param)}: {str(param_value)}"
311
+
312
+ verbose_logger.debug("\nCreated cache key: %s", cache_key)
313
+ hashed_cache_key = Cache._get_hashed_cache_key(cache_key)
314
+ hashed_cache_key = self._add_namespace_to_cache_key(hashed_cache_key, **kwargs)
315
+ # Remove preset_cache_key from kwargs to avoid "got multiple values" TypeError
316
+ # when kwargs already contains preset_cache_key from upstream callers
317
+ kwargs_for_preset = {k: v for k, v in kwargs.items() if k != "preset_cache_key"}
318
+ self._set_preset_cache_key_in_kwargs(
319
+ preset_cache_key=hashed_cache_key, **kwargs_for_preset
320
+ )
321
+ return hashed_cache_key
322
+
323
+ def _get_param_value(
324
+ self,
325
+ param: str,
326
+ kwargs: dict,
327
+ ) -> Optional[str]:
328
+ """
329
+ Get the value for the given param from kwargs
330
+ """
331
+ if param == "model":
332
+ return self._get_model_param_value(kwargs)
333
+ elif param == "file":
334
+ return self._get_file_param_value(kwargs)
335
+ return kwargs[param]
336
+
337
+ def _get_model_param_value(self, kwargs: dict) -> str:
338
+ """
339
+ Handles getting the value for the 'model' param from kwargs
340
+
341
+ 1. If caching groups are set, then return the caching group as the model https://docs.litellm.ai/docs/routing#caching-across-model-groups
342
+ 2. Else if a model_group is set, then return the model_group as the model. This is used for all requests sent through the litellm.Router()
343
+ 3. Else use the `model` passed in kwargs
344
+ """
345
+ metadata: Dict = kwargs.get("metadata", {}) or {}
346
+ litellm_params: Dict = kwargs.get("litellm_params", {}) or {}
347
+ metadata_in_litellm_params: Dict = litellm_params.get("metadata", {}) or {}
348
+ model_group: Optional[str] = metadata.get(
349
+ "model_group"
350
+ ) or metadata_in_litellm_params.get("model_group")
351
+ caching_group = self._get_caching_group(metadata, model_group)
352
+ return caching_group or model_group or kwargs["model"]
353
+
354
+ def _get_caching_group(
355
+ self, metadata: dict, model_group: Optional[str]
356
+ ) -> Optional[str]:
357
+ caching_groups: Optional[List] = metadata.get("caching_groups", [])
358
+ if caching_groups:
359
+ for group in caching_groups:
360
+ if model_group in group:
361
+ return str(group)
362
+ return None
363
+
364
+ def _get_file_param_value(self, kwargs: dict) -> str:
365
+ """
366
+ Handles getting the value for the 'file' param from kwargs. Used for `transcription` requests
367
+ """
368
+ file = kwargs.get("file")
369
+ metadata = kwargs.get("metadata", {})
370
+ litellm_params = kwargs.get("litellm_params", {})
371
+ return (
372
+ metadata.get("file_checksum")
373
+ or getattr(file, "name", None)
374
+ or metadata.get("file_name")
375
+ or litellm_params.get("file_name")
376
+ )
377
+
378
+ def _get_preset_cache_key_from_kwargs(self, **kwargs) -> Optional[str]:
379
+ """
380
+ Get the preset cache key from kwargs["litellm_params"]
381
+
382
+ We use _get_preset_cache_keys for two reasons
383
+
384
+ 1. optional params like max_tokens, get transformed for bedrock -> max_new_tokens
385
+ 2. avoid doing duplicate / repeated work
386
+ """
387
+ if kwargs:
388
+ if "litellm_params" in kwargs:
389
+ return kwargs["litellm_params"].get("preset_cache_key", None)
390
+ return None
391
+
392
+ def _set_preset_cache_key_in_kwargs(self, preset_cache_key: str, **kwargs) -> None:
393
+ """
394
+ Set the calculated cache key in kwargs
395
+
396
+ This is used to avoid doing duplicate / repeated work
397
+
398
+ Placed in kwargs["litellm_params"]
399
+ """
400
+ if kwargs:
401
+ if "litellm_params" in kwargs:
402
+ kwargs["litellm_params"]["preset_cache_key"] = preset_cache_key
403
+
404
+ @staticmethod
405
+ def _get_hashed_cache_key(cache_key: str) -> str:
406
+ """
407
+ Get the hashed cache key for the given cache key.
408
+
409
+ Use hashlib to create a sha256 hash of the cache key
410
+
411
+ Args:
412
+ cache_key (str): The cache key to hash.
413
+
414
+ Returns:
415
+ str: The hashed cache key.
416
+ """
417
+ hash_object = hashlib.sha256(cache_key.encode())
418
+ # Hexadecimal representation of the hash
419
+ hash_hex = hash_object.hexdigest()
420
+ verbose_logger.debug("Hashed cache key (SHA-256): %s", hash_hex)
421
+ return hash_hex
422
+
423
+ def _add_namespace_to_cache_key(self, hash_hex: str, **kwargs) -> str:
424
+ """
425
+ If a redis namespace is provided, add it to the cache key
426
+
427
+ Args:
428
+ hash_hex (str): The hashed cache key.
429
+ **kwargs: Additional keyword arguments.
430
+
431
+ Returns:
432
+ str: The final hashed cache key with the redis namespace.
433
+ """
434
+ dynamic_cache_control: DynamicCacheControl = kwargs.get("cache", {})
435
+ metadata = kwargs.get("metadata") or {}
436
+ namespace = (
437
+ dynamic_cache_control.get("namespace")
438
+ or metadata.get("redis_namespace")
439
+ or self.namespace
440
+ )
441
+ if namespace:
442
+ hash_hex = f"{namespace}:{hash_hex}"
443
+ verbose_logger.debug("Final hashed key: %s", hash_hex)
444
+ return hash_hex
445
+
446
+ def generate_streaming_content(self, content):
447
+ chunk_size = 5 # Adjust the chunk size as needed
448
+ for i in range(0, len(content), chunk_size):
449
+ yield {
450
+ "choices": [
451
+ {
452
+ "delta": {
453
+ "role": "assistant",
454
+ "content": content[i : i + chunk_size],
455
+ }
456
+ }
457
+ ]
458
+ }
459
+ time.sleep(CACHED_STREAMING_CHUNK_DELAY)
460
+
461
+ def _get_cache_logic(
462
+ self,
463
+ cached_result: Optional[Any],
464
+ max_age: Optional[float],
465
+ ):
466
+ """
467
+ Common get cache logic across sync + async implementations
468
+ """
469
+ # Check if a timestamp was stored with the cached response
470
+ if (
471
+ cached_result is not None
472
+ and isinstance(cached_result, dict)
473
+ and "timestamp" in cached_result
474
+ ):
475
+ timestamp = cached_result["timestamp"]
476
+ current_time = time.time()
477
+
478
+ # Calculate age of the cached response
479
+ response_age = current_time - timestamp
480
+
481
+ # Check if the cached response is older than the max-age
482
+ if max_age is not None and response_age > max_age:
483
+ return None # Cached response is too old
484
+
485
+ # If the response is fresh, or there's no max-age requirement, return the cached response
486
+ # cached_response is in `b{} convert it to ModelResponse
487
+ cached_response = cached_result.get("response")
488
+ try:
489
+ if isinstance(cached_response, dict):
490
+ pass
491
+ else:
492
+ cached_response = json.loads(
493
+ cached_response # type: ignore
494
+ ) # Convert string to dictionary
495
+ except Exception:
496
+ cached_response = ast.literal_eval(cached_response) # type: ignore
497
+ return cached_response
498
+ return cached_result
499
+
500
+ def get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs):
501
+ """
502
+ Retrieves the cached result for the given arguments.
503
+
504
+ Args:
505
+ *args: args to litellm.completion() or embedding()
506
+ **kwargs: kwargs to litellm.completion() or embedding()
507
+
508
+ Returns:
509
+ The cached result if it exists, otherwise None.
510
+ """
511
+ try: # never block execution
512
+ if self.should_use_cache(**kwargs) is not True:
513
+ return
514
+ messages = kwargs.get("messages", [])
515
+ if "cache_key" in kwargs:
516
+ cache_key = kwargs["cache_key"]
517
+ else:
518
+ cache_key = self.get_cache_key(**kwargs)
519
+ if cache_key is not None:
520
+ cache_control_args: DynamicCacheControl = kwargs.get("cache", {})
521
+ max_age = (
522
+ cache_control_args.get("s-maxage")
523
+ or cache_control_args.get("s-max-age")
524
+ or float("inf")
525
+ )
526
+ if dynamic_cache_object is not None:
527
+ cached_result = dynamic_cache_object.get_cache(
528
+ cache_key, messages=messages
529
+ )
530
+ else:
531
+ cached_result = self.cache.get_cache(cache_key, messages=messages)
532
+ return self._get_cache_logic(
533
+ cached_result=cached_result, max_age=max_age
534
+ )
535
+ except Exception:
536
+ print_verbose(f"An exception occurred: {traceback.format_exc()}")
537
+ return None
538
+
539
+ async def async_get_cache(
540
+ self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs
541
+ ):
542
+ """
543
+ Async get cache implementation.
544
+
545
+ Used for embedding calls in async wrapper
546
+ """
547
+
548
+ try: # never block execution
549
+ if self.should_use_cache(**kwargs) is not True:
550
+ return
551
+
552
+ kwargs.get("messages", [])
553
+ if "cache_key" in kwargs:
554
+ cache_key = kwargs["cache_key"]
555
+ else:
556
+ cache_key = self.get_cache_key(**kwargs)
557
+ if cache_key is not None:
558
+ cache_control_args = kwargs.get("cache", {})
559
+ max_age = cache_control_args.get(
560
+ "s-max-age", cache_control_args.get("s-maxage", float("inf"))
561
+ )
562
+ if dynamic_cache_object is not None:
563
+ cached_result = await dynamic_cache_object.async_get_cache(
564
+ cache_key, **kwargs
565
+ )
566
+ else:
567
+ cached_result = await self.cache.async_get_cache(
568
+ cache_key, **kwargs
569
+ )
570
+ return self._get_cache_logic(
571
+ cached_result=cached_result, max_age=max_age
572
+ )
573
+ except Exception:
574
+ print_verbose(f"An exception occurred: {traceback.format_exc()}")
575
+ return None
576
+
577
+ def _add_cache_logic(self, result, **kwargs):
578
+ """
579
+ Common implementation across sync + async add_cache functions
580
+ """
581
+ try:
582
+ if "cache_key" in kwargs:
583
+ cache_key = kwargs["cache_key"]
584
+ else:
585
+ cache_key = self.get_cache_key(**kwargs)
586
+ if cache_key is not None:
587
+ if isinstance(result, BaseModel):
588
+ result = result.model_dump_json()
589
+
590
+ ## DEFAULT TTL ##
591
+ if self.ttl is not None:
592
+ kwargs["ttl"] = self.ttl
593
+ ## Get Cache-Controls ##
594
+ _cache_kwargs = kwargs.get("cache", None)
595
+ if isinstance(_cache_kwargs, dict):
596
+ for k, v in _cache_kwargs.items():
597
+ if k == "ttl":
598
+ kwargs["ttl"] = v
599
+
600
+ cached_data = {"timestamp": time.time(), "response": result}
601
+ return cache_key, cached_data, kwargs
602
+ else:
603
+ raise Exception("cache key is None")
604
+ except Exception as e:
605
+ raise e
606
+
607
+ def add_cache(self, result, **kwargs):
608
+ """
609
+ Adds a result to the cache.
610
+
611
+ Args:
612
+ *args: args to litellm.completion() or embedding()
613
+ **kwargs: kwargs to litellm.completion() or embedding()
614
+
615
+ Returns:
616
+ None
617
+ """
618
+ try:
619
+ if self.should_use_cache(**kwargs) is not True:
620
+ return
621
+ cache_key, cached_data, kwargs = self._add_cache_logic(
622
+ result=result, **kwargs
623
+ )
624
+ self.cache.set_cache(cache_key, cached_data, **kwargs)
625
+ except Exception as e:
626
+ verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}")
627
+
628
+ async def async_add_cache(
629
+ self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs
630
+ ):
631
+ """
632
+ Async implementation of add_cache
633
+ """
634
+ try:
635
+ if self.should_use_cache(**kwargs) is not True:
636
+ return
637
+ if self.type == "redis" and self.redis_flush_size is not None:
638
+ # high traffic - fill in results in memory and then flush
639
+ await self.batch_cache_write(result, **kwargs)
640
+ else:
641
+ cache_key, cached_data, kwargs = self._add_cache_logic(
642
+ result=result, **kwargs
643
+ )
644
+ if dynamic_cache_object is not None:
645
+ await dynamic_cache_object.async_set_cache(
646
+ cache_key, cached_data, **kwargs
647
+ )
648
+ else:
649
+ await self.cache.async_set_cache(cache_key, cached_data, **kwargs)
650
+ except Exception as e:
651
+ verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}")
652
+
653
+ def _convert_to_cached_embedding(
654
+ self,
655
+ embedding_response: Any,
656
+ model: Optional[str],
657
+ prompt_tokens_details: Optional[dict] = None,
658
+ ) -> CachedEmbedding:
659
+ """
660
+ Convert any embedding response into the standardized CachedEmbedding TypedDict format.
661
+ """
662
+ try:
663
+ if isinstance(embedding_response, dict):
664
+ return {
665
+ "embedding": embedding_response.get("embedding"),
666
+ "index": embedding_response.get("index"),
667
+ "object": embedding_response.get("object"),
668
+ "model": model,
669
+ "prompt_tokens_details": prompt_tokens_details,
670
+ }
671
+ elif hasattr(embedding_response, "model_dump"):
672
+ data = embedding_response.model_dump()
673
+ return {
674
+ "embedding": data.get("embedding"),
675
+ "index": data.get("index"),
676
+ "object": data.get("object"),
677
+ "model": model,
678
+ "prompt_tokens_details": prompt_tokens_details,
679
+ }
680
+ else:
681
+ data = vars(embedding_response)
682
+ return {
683
+ "embedding": data.get("embedding"),
684
+ "index": data.get("index"),
685
+ "object": data.get("object"),
686
+ "model": model,
687
+ "prompt_tokens_details": prompt_tokens_details,
688
+ }
689
+ except KeyError as e:
690
+ raise ValueError(f"Missing expected key in embedding response: {e}")
691
+
692
+ def _get_per_item_prompt_tokens_details(
693
+ self,
694
+ result: EmbeddingResponse,
695
+ idx_in_result_data: int,
696
+ ) -> Optional[dict]:
697
+ """
698
+ Extract per-item prompt_tokens_details from a response for caching.
699
+
700
+ For single-item responses (common for multimodal providers like Bedrock Titan,
701
+ Nova, Vertex AI), returns the full prompt_tokens_details.
702
+ For multi-item responses, distributes integer fields evenly across items
703
+ so that summing all per-item details reconstructs the original totals.
704
+ """
705
+ if result.usage is None or result.usage.prompt_tokens_details is None:
706
+ return None
707
+
708
+ details = result.usage.prompt_tokens_details
709
+ if hasattr(details, "model_dump"):
710
+ details_dict = details.model_dump(exclude_none=True)
711
+ elif isinstance(details, dict):
712
+ details_dict = {k: v for k, v in details.items() if v is not None}
713
+ else:
714
+ return None
715
+
716
+ if not details_dict:
717
+ return None
718
+
719
+ num_items = len(result.data)
720
+ if num_items <= 1:
721
+ return details_dict
722
+
723
+ # Distribute integer/float fields evenly across items
724
+ per_item: dict = {}
725
+ for key, value in details_dict.items():
726
+ if isinstance(value, int):
727
+ quotient, remainder = divmod(value, num_items)
728
+ per_item[key] = quotient + (1 if idx_in_result_data < remainder else 0)
729
+ elif isinstance(value, float):
730
+ per_item[key] = value / num_items
731
+ else:
732
+ per_item[key] = value
733
+ return per_item if per_item else None
734
+
735
+ def add_embedding_response_to_cache(
736
+ self,
737
+ result: EmbeddingResponse,
738
+ input: str,
739
+ kwargs: dict,
740
+ idx_in_result_data: int = 0,
741
+ ) -> Tuple[str, dict, dict]:
742
+ preset_cache_key = self.get_cache_key(**{**kwargs, "input": input})
743
+ kwargs["cache_key"] = preset_cache_key
744
+ embedding_response = result.data[idx_in_result_data]
745
+
746
+ # Extract per-item prompt_tokens_details from response usage
747
+ prompt_tokens_details = self._get_per_item_prompt_tokens_details(
748
+ result=result,
749
+ idx_in_result_data=idx_in_result_data,
750
+ )
751
+
752
+ # Always convert to properly typed CachedEmbedding
753
+ model_name = result.model
754
+ embedding_dict: CachedEmbedding = self._convert_to_cached_embedding(
755
+ embedding_response,
756
+ model_name,
757
+ prompt_tokens_details=prompt_tokens_details,
758
+ )
759
+
760
+ cache_key, cached_data, kwargs = self._add_cache_logic(
761
+ result=embedding_dict,
762
+ **kwargs,
763
+ )
764
+ return cache_key, cached_data, kwargs
765
+
766
+ async def async_add_cache_pipeline(
767
+ self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs
768
+ ):
769
+ """
770
+ Async implementation of add_cache for Embedding calls
771
+
772
+ Does a bulk write, to prevent using too many clients
773
+ """
774
+ try:
775
+ if self.should_use_cache(**kwargs) is not True:
776
+ return
777
+
778
+ # set default ttl if not set
779
+ if self.ttl is not None:
780
+ kwargs["ttl"] = self.ttl
781
+
782
+ cache_list = []
783
+ if isinstance(kwargs["input"], list):
784
+ for idx, i in enumerate(kwargs["input"]):
785
+ (
786
+ cache_key,
787
+ cached_data,
788
+ kwargs,
789
+ ) = self.add_embedding_response_to_cache(result, i, kwargs, idx)
790
+ cache_list.append((cache_key, cached_data))
791
+ elif isinstance(kwargs["input"], str):
792
+ cache_key, cached_data, kwargs = self.add_embedding_response_to_cache(
793
+ result, kwargs["input"], kwargs
794
+ )
795
+ cache_list.append((cache_key, cached_data))
796
+
797
+ if dynamic_cache_object is not None:
798
+ await dynamic_cache_object.async_set_cache_pipeline(
799
+ cache_list=cache_list, **kwargs
800
+ )
801
+ else:
802
+ await self.cache.async_set_cache_pipeline(
803
+ cache_list=cache_list, **kwargs
804
+ )
805
+ except Exception as e:
806
+ verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}")
807
+
808
+ def should_use_cache(self, **kwargs):
809
+ """
810
+ Returns true if we should use the cache for LLM API calls
811
+
812
+ If cache is default_on then this is True
813
+ If cache is default_off then this is only true when user has opted in to use cache
814
+ """
815
+ if self.mode == CacheMode.default_on:
816
+ return True
817
+
818
+ # when mode == default_off -> Cache is opt in only
819
+ _cache = kwargs.get("cache", None)
820
+ verbose_logger.debug("should_use_cache: kwargs: %s; _cache: %s", kwargs, _cache)
821
+ if _cache and isinstance(_cache, dict):
822
+ if _cache.get("use-cache", False) is True:
823
+ return True
824
+ return False
825
+
826
+ async def batch_cache_write(self, result, **kwargs):
827
+ cache_key, cached_data, kwargs = self._add_cache_logic(result=result, **kwargs)
828
+ await self.cache.batch_cache_write(cache_key, cached_data, **kwargs)
829
+
830
+ async def ping(self):
831
+ cache_ping = getattr(self.cache, "ping")
832
+ if cache_ping:
833
+ return await cache_ping()
834
+ return None
835
+
836
+ async def delete_cache_keys(self, keys):
837
+ cache_delete_cache_keys = getattr(self.cache, "delete_cache_keys")
838
+ if cache_delete_cache_keys:
839
+ return await cache_delete_cache_keys(keys)
840
+ return None
841
+
842
+ async def disconnect(self):
843
+ if hasattr(self.cache, "disconnect"):
844
+ await self.cache.disconnect()
845
+
846
+ def _supports_async(self) -> bool:
847
+ """
848
+ Internal method to check if the cache type supports async get/set operations
849
+
850
+ All cache types now support async operations
851
+
852
+ """
853
+ return True
854
+
855
+
856
+ def enable_cache(
857
+ type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,
858
+ host: Optional[str] = None,
859
+ port: Optional[str] = None,
860
+ password: Optional[str] = None,
861
+ supported_call_types: Optional[List[CachingSupportedCallTypes]] = [
862
+ "completion",
863
+ "acompletion",
864
+ "embedding",
865
+ "aembedding",
866
+ "atranscription",
867
+ "transcription",
868
+ "atext_completion",
869
+ "text_completion",
870
+ "arerank",
871
+ "rerank",
872
+ "responses",
873
+ "aresponses",
874
+ ],
875
+ **kwargs,
876
+ ):
877
+ """
878
+ Enable cache with the specified configuration.
879
+
880
+ Args:
881
+ type (Optional[Literal["local", "redis", "s3", "disk"]]): The type of cache to enable. Defaults to "local".
882
+ host (Optional[str]): The host address of the cache server. Defaults to None.
883
+ port (Optional[str]): The port number of the cache server. Defaults to None.
884
+ password (Optional[str]): The password for the cache server. Defaults to None.
885
+ supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]):
886
+ The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"].
887
+ **kwargs: Additional keyword arguments.
888
+
889
+ Returns:
890
+ None
891
+
892
+ Raises:
893
+ None
894
+ """
895
+ print_verbose("LiteLLM: Enabling Cache")
896
+ if "cache" not in litellm.input_callback:
897
+ litellm.input_callback.append("cache")
898
+ if "cache" not in litellm.success_callback:
899
+ litellm.logging_callback_manager.add_litellm_success_callback("cache")
900
+ if "cache" not in litellm._async_success_callback:
901
+ litellm.logging_callback_manager.add_litellm_async_success_callback("cache")
902
+
903
+ if litellm.cache is None:
904
+ litellm.cache = Cache(
905
+ type=type,
906
+ host=host,
907
+ port=port,
908
+ password=password,
909
+ supported_call_types=supported_call_types,
910
+ **kwargs,
911
+ )
912
+ print_verbose(f"LiteLLM: Cache enabled, litellm.cache={litellm.cache}")
913
+ print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}")
914
+
915
+
916
+ def update_cache(
917
+ type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,
918
+ host: Optional[str] = None,
919
+ port: Optional[str] = None,
920
+ password: Optional[str] = None,
921
+ supported_call_types: Optional[List[CachingSupportedCallTypes]] = [
922
+ "completion",
923
+ "acompletion",
924
+ "embedding",
925
+ "aembedding",
926
+ "atranscription",
927
+ "transcription",
928
+ "atext_completion",
929
+ "text_completion",
930
+ "arerank",
931
+ "rerank",
932
+ "responses",
933
+ "aresponses",
934
+ ],
935
+ **kwargs,
936
+ ):
937
+ """
938
+ Update the cache for LiteLLM.
939
+
940
+ Args:
941
+ type (Optional[Literal["local", "redis", "s3", "disk"]]): The type of cache. Defaults to "local".
942
+ host (Optional[str]): The host of the cache. Defaults to None.
943
+ port (Optional[str]): The port of the cache. Defaults to None.
944
+ password (Optional[str]): The password for the cache. Defaults to None.
945
+ supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]):
946
+ The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"].
947
+ **kwargs: Additional keyword arguments for the cache.
948
+
949
+ Returns:
950
+ None
951
+
952
+ """
953
+ print_verbose("LiteLLM: Updating Cache")
954
+ litellm.cache = Cache(
955
+ type=type,
956
+ host=host,
957
+ port=port,
958
+ password=password,
959
+ supported_call_types=supported_call_types,
960
+ **kwargs,
961
+ )
962
+ print_verbose(f"LiteLLM: Cache Updated, litellm.cache={litellm.cache}")
963
+ print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}")
964
+
965
+
966
+ def disable_cache():
967
+ """
968
+ Disable the cache used by LiteLLM.
969
+
970
+ This function disables the cache used by the LiteLLM module. It removes the cache-related callbacks from the input_callback, success_callback, and _async_success_callback lists. It also sets the litellm.cache attribute to None.
971
+
972
+ Parameters:
973
+ None
974
+
975
+ Returns:
976
+ None
977
+ """
978
+ from contextlib import suppress
979
+
980
+ print_verbose("LiteLLM: Disabling Cache")
981
+ with suppress(ValueError):
982
+ litellm.input_callback.remove("cache")
983
+ litellm.success_callback.remove("cache")
984
+ litellm._async_success_callback.remove("cache")
985
+
986
+ litellm.cache = None
987
+ print_verbose(f"LiteLLM: Cache disabled, litellm.cache={litellm.cache}")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching_handler.py ADDED
@@ -0,0 +1,1209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This contains LLMCachingHandler
3
+
4
+ This exposes two methods:
5
+ - async_get_cache
6
+ - async_set_cache
7
+
8
+ This file is a wrapper around caching.py
9
+
10
+ This class is used to handle caching logic specific for LLM API requests (completion / embedding / text_completion / transcription etc)
11
+
12
+ It utilizes the (RedisCache, s3Cache, RedisSemanticCache, QdrantSemanticCache, InMemoryCache, DiskCache) based on what the user has setup
13
+
14
+ In each method it will call the appropriate method from caching.py
15
+ """
16
+
17
+ import asyncio
18
+ import datetime
19
+ import inspect
20
+ import time
21
+ from typing import (
22
+ TYPE_CHECKING,
23
+ Any,
24
+ AsyncGenerator,
25
+ Callable,
26
+ Dict,
27
+ Generator,
28
+ List,
29
+ Optional,
30
+ Tuple,
31
+ Union,
32
+ )
33
+
34
+ from pydantic import BaseModel
35
+
36
+ import litellm
37
+ from litellm._logging import print_verbose, verbose_logger
38
+ from litellm.caching import InMemoryCache
39
+ from litellm.caching.caching import S3Cache
40
+ from litellm.litellm_core_utils.llm_response_utils.response_metadata import (
41
+ update_response_metadata,
42
+ )
43
+ from litellm.litellm_core_utils.logging_utils import (
44
+ _assemble_complete_response_from_streaming_chunks,
45
+ )
46
+ from litellm.types.caching import CachedEmbedding
47
+ from litellm.types.llms.openai import ResponsesAPIResponse
48
+ from litellm.types.rerank import RerankResponse
49
+ from litellm.types.utils import (
50
+ CachingDetails,
51
+ CallTypes,
52
+ Embedding,
53
+ EmbeddingResponse,
54
+ ModelResponse,
55
+ TextCompletionResponse,
56
+ TranscriptionResponse,
57
+ Usage,
58
+ )
59
+
60
+ if TYPE_CHECKING:
61
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
62
+ from litellm.types.utils import PromptTokensDetailsWrapper
63
+ else:
64
+ LiteLLMLoggingObj = Any
65
+
66
+
67
+ from litellm.litellm_core_utils.core_helpers import (
68
+ _get_parent_otel_span_from_kwargs,
69
+ )
70
+ from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
71
+
72
+
73
+ class CachingHandlerResponse(BaseModel):
74
+ """
75
+ This is the response object for the caching handler. We need to separate embedding cached responses and (completion / text_completion / transcription) cached responses
76
+
77
+ For embeddings there can be a cache hit for some of the inputs in the list and a cache miss for others
78
+ """
79
+
80
+ cached_result: Optional[Any] = None
81
+ final_embedding_cached_response: Optional[EmbeddingResponse] = None
82
+ embedding_all_elements_cache_hit: bool = (
83
+ False # this is set to True when all elements in the list have a cache hit in the embedding cache, if true return the final_embedding_cached_response no need to make an API call
84
+ )
85
+
86
+
87
+ in_memory_cache_obj = InMemoryCache()
88
+
89
+
90
+ def _should_defer_streaming_cache_hit_callbacks(*, kwargs: Dict[str, Any]) -> bool:
91
+ """
92
+ When stream=True, do not run success callbacks at cache-hit time.
93
+
94
+ Cached chat/text completion replay uses CustomStreamWrapper; cached Responses
95
+ replay uses CachedResponsesAPIStreamingIterator. Both invoke logging success
96
+ handlers when the stream finishes; firing them here too would double-count
97
+ spend and callback records.
98
+ """
99
+ return kwargs.get("stream", False) is True
100
+
101
+
102
+ class LLMCachingHandler:
103
+ def __init__(
104
+ self,
105
+ original_function: Callable,
106
+ request_kwargs: Dict[str, Any],
107
+ start_time: datetime.datetime,
108
+ ):
109
+ from litellm.caching import DualCache, RedisCache
110
+
111
+ self.async_streaming_chunks: List[ModelResponse] = []
112
+ self.sync_streaming_chunks: List[ModelResponse] = []
113
+ self.request_kwargs = request_kwargs
114
+ self.preset_cache_key: Optional[str] = None
115
+ self.original_function = original_function
116
+ self.start_time = start_time
117
+ if litellm.cache is not None and isinstance(litellm.cache.cache, RedisCache):
118
+ self.dual_cache: Optional[DualCache] = DualCache(
119
+ redis_cache=litellm.cache.cache,
120
+ in_memory_cache=in_memory_cache_obj,
121
+ )
122
+ else:
123
+ self.dual_cache = None
124
+ pass
125
+
126
+ async def _async_get_cache(
127
+ self,
128
+ model: str,
129
+ original_function: Callable,
130
+ logging_obj: LiteLLMLoggingObj,
131
+ start_time: datetime.datetime,
132
+ call_type: str,
133
+ kwargs: Dict[str, Any],
134
+ args: Optional[Tuple[Any, ...]] = None,
135
+ ) -> Optional[CachingHandlerResponse]:
136
+ """
137
+ Internal method to get from the cache.
138
+ Handles different call types (embeddings, chat/completions, text_completion, transcription)
139
+ and accordingly returns the cached response
140
+
141
+ Args:
142
+ model: str:
143
+ original_function: Callable:
144
+ logging_obj: LiteLLMLoggingObj:
145
+ start_time: datetime.datetime:
146
+ call_type: str:
147
+ kwargs: Dict[str, Any]:
148
+ args: Optional[Tuple[Any, ...]] = None:
149
+
150
+
151
+ Returns:
152
+ CachingHandlerResponse:
153
+ Raises:
154
+ None
155
+ """
156
+ # Check if caching should be performed BEFORE doing expensive operations
157
+ if (
158
+ (kwargs.get("caching", None) is None and litellm.cache is not None)
159
+ or kwargs.get("caching", False) is True
160
+ ) and (
161
+ kwargs.get("cache", {}).get("no-cache", False) is not True
162
+ ): # allow users to control returning cached responses from the completion function
163
+ args = args or ()
164
+ final_embedding_cached_response: Optional[EmbeddingResponse] = None
165
+ embedding_all_elements_cache_hit: bool = False
166
+ cached_result: Optional[Any] = None
167
+ kwargs = kwargs.copy()
168
+ #########################################################
169
+ # Init cache timing metrics
170
+ #########################################################
171
+ cache_check_start_time = time.perf_counter()
172
+ cache_check_end_time: Optional[float] = None
173
+ #########################################################
174
+ parent_otel_span = _get_parent_otel_span_from_kwargs(kwargs)
175
+ kwargs["parent_otel_span"] = parent_otel_span
176
+
177
+ if litellm.cache is not None and self._is_call_type_supported_by_cache(
178
+ original_function=original_function
179
+ ):
180
+ verbose_logger.debug("Checking Async Cache")
181
+ cached_result = await self._retrieve_from_cache(
182
+ call_type=call_type,
183
+ kwargs=kwargs,
184
+ args=args,
185
+ )
186
+ cache_check_end_time = time.perf_counter()
187
+
188
+ if cached_result is not None and not isinstance(cached_result, list):
189
+ verbose_logger.debug("Cache Hit!")
190
+ cache_hit = True
191
+ end_time = datetime.datetime.now()
192
+ model, custom_llm_provider, _, _ = litellm.get_llm_provider(
193
+ model=model,
194
+ custom_llm_provider=kwargs.get("custom_llm_provider", None),
195
+ api_base=kwargs.get("api_base", None),
196
+ api_key=kwargs.get("api_key", None),
197
+ )
198
+ cache_duration_ms = (
199
+ cache_check_end_time - cache_check_start_time
200
+ ) * 1000
201
+ self._update_litellm_logging_obj_environment(
202
+ logging_obj=logging_obj,
203
+ model=model,
204
+ kwargs=kwargs,
205
+ cached_result=cached_result,
206
+ is_async=True,
207
+ custom_llm_provider=custom_llm_provider,
208
+ cache_duration_ms=cache_duration_ms,
209
+ )
210
+
211
+ call_type = original_function.__name__
212
+
213
+ cached_result = self._convert_cached_result_to_model_response(
214
+ cached_result=cached_result,
215
+ call_type=call_type,
216
+ kwargs=kwargs,
217
+ logging_obj=logging_obj,
218
+ model=model,
219
+ custom_llm_provider=kwargs.get("custom_llm_provider", None),
220
+ args=args,
221
+ )
222
+ if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs):
223
+ # LOG SUCCESS
224
+ self._async_log_cache_hit_on_callbacks(
225
+ logging_obj=logging_obj,
226
+ cached_result=cached_result,
227
+ start_time=start_time,
228
+ end_time=end_time,
229
+ cache_hit=cache_hit,
230
+ )
231
+ cache_key = (
232
+ self.preset_cache_key
233
+ or self.request_kwargs.get("cache_key")
234
+ or litellm.cache.get_cache_key(**self.request_kwargs)
235
+ )
236
+ if hasattr(cached_result, "_hidden_params"):
237
+ cached_result._hidden_params["cache_key"] = cache_key # type: ignore
238
+ return CachingHandlerResponse(cached_result=cached_result)
239
+ elif (
240
+ call_type == CallTypes.aembedding.value
241
+ and cached_result is not None
242
+ and isinstance(cached_result, list)
243
+ and litellm.cache is not None
244
+ and not isinstance(
245
+ litellm.cache.cache, S3Cache
246
+ ) # s3 doesn't support bulk writing. Exclude.
247
+ ):
248
+ (
249
+ final_embedding_cached_response,
250
+ embedding_all_elements_cache_hit,
251
+ ) = self._process_async_embedding_cached_response(
252
+ final_embedding_cached_response=final_embedding_cached_response,
253
+ cached_result=cached_result,
254
+ kwargs=kwargs,
255
+ logging_obj=logging_obj,
256
+ start_time=start_time,
257
+ model=model,
258
+ )
259
+ return CachingHandlerResponse(
260
+ final_embedding_cached_response=final_embedding_cached_response,
261
+ embedding_all_elements_cache_hit=embedding_all_elements_cache_hit,
262
+ )
263
+
264
+ verbose_logger.debug(f"CACHE RESULT: {cached_result}")
265
+ return CachingHandlerResponse(
266
+ cached_result=cached_result,
267
+ final_embedding_cached_response=final_embedding_cached_response,
268
+ )
269
+ # Caching disabled - return None to indicate no caching attempted
270
+ return None
271
+
272
+ def _sync_get_cache(
273
+ self,
274
+ model: str,
275
+ original_function: Callable,
276
+ logging_obj: LiteLLMLoggingObj,
277
+ start_time: datetime.datetime,
278
+ call_type: str,
279
+ kwargs: Dict[str, Any],
280
+ args: Optional[Tuple[Any, ...]] = None,
281
+ ) -> CachingHandlerResponse:
282
+ cached_result: Optional[Any] = None
283
+
284
+ # Check if caching should be performed BEFORE doing expensive kwargs copy
285
+ if litellm.cache is not None and self._is_call_type_supported_by_cache(
286
+ original_function=original_function
287
+ ):
288
+ args = args or ()
289
+ # Now that we confirmed caching will happen, prepare kwargs
290
+ new_kwargs = kwargs.copy()
291
+ new_kwargs.update(
292
+ convert_args_to_kwargs(
293
+ self.original_function,
294
+ args,
295
+ )
296
+ )
297
+ if new_kwargs.get("metadata") is None:
298
+ new_kwargs.pop("metadata", None)
299
+ if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs:
300
+ new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs)
301
+ self.request_kwargs = new_kwargs
302
+ print_verbose("Checking Sync Cache")
303
+ cached_result = litellm.cache.get_cache(**new_kwargs)
304
+ if cached_result is not None:
305
+ if "detail" in cached_result:
306
+ # implies an error occurred
307
+ pass
308
+ else:
309
+ call_type = original_function.__name__
310
+ cached_result = self._convert_cached_result_to_model_response(
311
+ cached_result=cached_result,
312
+ call_type=call_type,
313
+ kwargs=kwargs,
314
+ logging_obj=logging_obj,
315
+ model=model,
316
+ custom_llm_provider=kwargs.get("custom_llm_provider", None),
317
+ args=args,
318
+ )
319
+
320
+ # LOG SUCCESS
321
+ cache_hit = True
322
+ end_time = datetime.datetime.now()
323
+ (
324
+ model,
325
+ custom_llm_provider,
326
+ dynamic_api_key,
327
+ api_base,
328
+ ) = litellm.get_llm_provider(
329
+ model=model or "",
330
+ custom_llm_provider=kwargs.get("custom_llm_provider", None),
331
+ api_base=kwargs.get("api_base", None),
332
+ api_key=kwargs.get("api_key", None),
333
+ )
334
+ self._update_litellm_logging_obj_environment(
335
+ logging_obj=logging_obj,
336
+ model=f"{custom_llm_provider}/{model}",
337
+ kwargs=kwargs,
338
+ cached_result=cached_result,
339
+ is_async=False,
340
+ )
341
+
342
+ if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs):
343
+ logging_obj.handle_sync_success_callbacks_for_async_calls(
344
+ result=cached_result,
345
+ start_time=start_time,
346
+ end_time=end_time,
347
+ cache_hit=cache_hit,
348
+ )
349
+ cache_key = (
350
+ self.preset_cache_key
351
+ or self.request_kwargs.get("cache_key")
352
+ or litellm.cache.get_cache_key(**self.request_kwargs)
353
+ )
354
+ if hasattr(cached_result, "_hidden_params"):
355
+ cached_result._hidden_params["cache_key"] = cache_key # type: ignore
356
+ return CachingHandlerResponse(cached_result=cached_result)
357
+ return CachingHandlerResponse(cached_result=cached_result)
358
+
359
+ def handle_kwargs_input_list_or_str(self, kwargs: Dict[str, Any]) -> List[str]:
360
+ """
361
+ Handles the input of kwargs['input'] being a list or a string
362
+ """
363
+ if isinstance(kwargs["input"], str):
364
+ return [kwargs["input"]]
365
+ elif isinstance(kwargs["input"], list):
366
+ return kwargs["input"]
367
+ else:
368
+ raise ValueError("input must be a string or a list")
369
+
370
+ def _extract_model_from_cached_results(
371
+ self, non_null_list: List[Tuple[int, CachedEmbedding]]
372
+ ) -> Optional[str]:
373
+ """
374
+ Helper method to extract the model name from cached results.
375
+
376
+ Args:
377
+ non_null_list: List of (idx, cr) tuples where cr is the cached result dict
378
+
379
+ Returns:
380
+ Optional[str]: The model name if found, None otherwise
381
+ """
382
+ for _, cr in non_null_list:
383
+ if isinstance(cr, dict) and cr.get("model"):
384
+ return cr["model"]
385
+ return None
386
+
387
+ def _process_async_embedding_cached_response(
388
+ self,
389
+ final_embedding_cached_response: Optional[EmbeddingResponse],
390
+ cached_result: List[Optional[CachedEmbedding]],
391
+ kwargs: Dict[str, Any],
392
+ logging_obj: LiteLLMLoggingObj,
393
+ start_time: datetime.datetime,
394
+ model: str,
395
+ ) -> Tuple[Optional[EmbeddingResponse], bool]:
396
+ """
397
+ Returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit
398
+
399
+ For embedding responses, there can be a cache hit for some of the inputs in the list and a cache miss for others
400
+ This function processes the cached embedding responses and returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit
401
+
402
+ Args:
403
+ final_embedding_cached_response: Optional[EmbeddingResponse]:
404
+ cached_result: List[Optional[Dict[str, Any]]]:
405
+ kwargs: Dict[str, Any]:
406
+ logging_obj: LiteLLMLoggingObj:
407
+ start_time: datetime.datetime:
408
+ model: str:
409
+
410
+ Returns:
411
+ Tuple[Optional[EmbeddingResponse], bool]:
412
+ Returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit
413
+
414
+
415
+ """
416
+ embedding_all_elements_cache_hit: bool = False
417
+ remaining_list = []
418
+ non_null_list = []
419
+ kwargs_input_as_list = self.handle_kwargs_input_list_or_str(kwargs)
420
+ for idx, cr in enumerate(cached_result):
421
+ if cr is None:
422
+ remaining_list.append(kwargs_input_as_list[idx])
423
+ else:
424
+ non_null_list.append((idx, cr))
425
+ kwargs["input"] = remaining_list
426
+ if len(non_null_list) > 0:
427
+ # Use the model from the first non-null cached result, fallback to kwargs if not present
428
+ model_name = self._extract_model_from_cached_results(non_null_list)
429
+ if not model_name:
430
+ model_name = kwargs.get("model")
431
+ final_embedding_cached_response = EmbeddingResponse(
432
+ model=model_name,
433
+ data=[None] * len(kwargs_input_as_list),
434
+ )
435
+ final_embedding_cached_response._hidden_params["cache_hit"] = True
436
+
437
+ prompt_tokens = 0
438
+ aggregated_details: Optional[dict] = None
439
+ for val in non_null_list:
440
+ idx, cr = val # (idx, cr) tuple
441
+ if cr is not None:
442
+ embedding_data = cr.get("embedding")
443
+ if embedding_data is not None:
444
+ final_embedding_cached_response.data[idx] = Embedding(
445
+ embedding=embedding_data,
446
+ index=idx,
447
+ object="embedding",
448
+ )
449
+ if isinstance(kwargs_input_as_list[idx], str):
450
+ from litellm.utils import token_counter
451
+
452
+ prompt_tokens += token_counter(
453
+ text=kwargs_input_as_list[idx], count_response_tokens=True
454
+ )
455
+ # Aggregate prompt_tokens_details from cached items
456
+ item_details = cr.get("prompt_tokens_details")
457
+ if item_details:
458
+ if aggregated_details is None:
459
+ aggregated_details = {}
460
+ for key, value in item_details.items():
461
+ if isinstance(value, (int, float)):
462
+ aggregated_details[key] = (
463
+ aggregated_details.get(key, 0) + value
464
+ )
465
+ else:
466
+ aggregated_details[key] = value
467
+
468
+ ## USAGE
469
+ prompt_tokens_details: Optional["PromptTokensDetailsWrapper"] = None
470
+ if aggregated_details:
471
+ from litellm.types.utils import PromptTokensDetailsWrapper
472
+
473
+ try:
474
+ prompt_tokens_details = PromptTokensDetailsWrapper(
475
+ **aggregated_details
476
+ )
477
+ except Exception:
478
+ prompt_tokens_details = None
479
+ usage = Usage(
480
+ prompt_tokens=prompt_tokens,
481
+ completion_tokens=0,
482
+ total_tokens=prompt_tokens,
483
+ prompt_tokens_details=prompt_tokens_details,
484
+ )
485
+ final_embedding_cached_response.usage = usage
486
+ if len(remaining_list) == 0:
487
+ # LOG SUCCESS
488
+ cache_hit = True
489
+ embedding_all_elements_cache_hit = True
490
+ end_time = datetime.datetime.now()
491
+ (
492
+ model,
493
+ custom_llm_provider,
494
+ dynamic_api_key,
495
+ api_base,
496
+ ) = litellm.get_llm_provider(
497
+ model=model,
498
+ custom_llm_provider=kwargs.get("custom_llm_provider", None),
499
+ api_base=kwargs.get("api_base", None),
500
+ api_key=kwargs.get("api_key", None),
501
+ )
502
+
503
+ self._update_litellm_logging_obj_environment(
504
+ logging_obj=logging_obj,
505
+ model=model,
506
+ kwargs=kwargs,
507
+ cached_result=final_embedding_cached_response,
508
+ is_async=True,
509
+ is_embedding=True,
510
+ )
511
+ self._async_log_cache_hit_on_callbacks(
512
+ logging_obj=logging_obj,
513
+ cached_result=final_embedding_cached_response,
514
+ start_time=start_time,
515
+ end_time=end_time,
516
+ cache_hit=cache_hit,
517
+ )
518
+ return final_embedding_cached_response, embedding_all_elements_cache_hit
519
+ return final_embedding_cached_response, embedding_all_elements_cache_hit
520
+
521
+ def combine_usage(self, usage1: Usage, usage2: Usage) -> Usage:
522
+ return Usage(
523
+ prompt_tokens=usage1.prompt_tokens + usage2.prompt_tokens,
524
+ completion_tokens=usage1.completion_tokens + usage2.completion_tokens,
525
+ total_tokens=usage1.total_tokens + usage2.total_tokens,
526
+ prompt_tokens_details=self._merge_prompt_tokens_details(
527
+ usage1.prompt_tokens_details,
528
+ usage2.prompt_tokens_details,
529
+ ),
530
+ )
531
+
532
+ def _merge_prompt_tokens_details(
533
+ self,
534
+ details1: Optional["PromptTokensDetailsWrapper"],
535
+ details2: Optional["PromptTokensDetailsWrapper"],
536
+ ) -> Optional["PromptTokensDetailsWrapper"]:
537
+ """Merge two PromptTokensDetailsWrapper objects by summing numeric fields."""
538
+ if details1 is None and details2 is None:
539
+ return None
540
+ if details1 is None:
541
+ return details2
542
+ if details2 is None:
543
+ return details1
544
+
545
+ dict1 = (
546
+ details1.model_dump(exclude_none=True)
547
+ if hasattr(details1, "model_dump")
548
+ else {}
549
+ )
550
+ dict2 = (
551
+ details2.model_dump(exclude_none=True)
552
+ if hasattr(details2, "model_dump")
553
+ else {}
554
+ )
555
+
556
+ merged: dict = {}
557
+ for key in set(dict1.keys()) | set(dict2.keys()):
558
+ v1 = dict1.get(key, 0)
559
+ v2 = dict2.get(key, 0)
560
+ if isinstance(v1, (int, float)) and isinstance(v2, (int, float)):
561
+ merged[key] = v1 + v2
562
+ elif isinstance(v1, dict) and isinstance(v2, dict):
563
+ # Recursively merge nested dicts (e.g. cache_creation_token_details)
564
+ nested: dict = {}
565
+ for nk in set(v1.keys()) | set(v2.keys()):
566
+ nv1 = v1.get(nk, 0)
567
+ nv2 = v2.get(nk, 0)
568
+ if isinstance(nv1, (int, float)) and isinstance(nv2, (int, float)):
569
+ nested[nk] = nv1 + nv2
570
+ elif nv1:
571
+ nested[nk] = nv1
572
+ else:
573
+ nested[nk] = nv2
574
+ merged[key] = nested
575
+ elif v1:
576
+ merged[key] = v1
577
+ else:
578
+ merged[key] = v2
579
+
580
+ if not merged:
581
+ return None
582
+
583
+ from litellm.types.utils import PromptTokensDetailsWrapper
584
+
585
+ try:
586
+ return PromptTokensDetailsWrapper(**merged)
587
+ except Exception:
588
+ return None
589
+
590
+ def _combine_cached_embedding_response_with_api_result(
591
+ self,
592
+ _caching_handler_response: CachingHandlerResponse,
593
+ embedding_response: EmbeddingResponse,
594
+ start_time: datetime.datetime,
595
+ end_time: datetime.datetime,
596
+ ) -> EmbeddingResponse:
597
+ """
598
+ Combines the cached embedding response with the API EmbeddingResponse
599
+
600
+ For caching there can be a cache hit for some of the inputs in the list and a cache miss for others
601
+ This function combines the cached embedding response with the API EmbeddingResponse
602
+
603
+ Args:
604
+ caching_handler_response: CachingHandlerResponse:
605
+ embedding_response: EmbeddingResponse:
606
+
607
+ Returns:
608
+ EmbeddingResponse:
609
+ """
610
+ if _caching_handler_response.final_embedding_cached_response is None:
611
+ return embedding_response
612
+
613
+ idx = 0
614
+ final_data_list = []
615
+ for item in _caching_handler_response.final_embedding_cached_response.data:
616
+ if item is None and embedding_response.data is not None:
617
+ final_data_list.append(embedding_response.data[idx])
618
+ idx += 1
619
+ else:
620
+ final_data_list.append(item)
621
+
622
+ _caching_handler_response.final_embedding_cached_response.data = final_data_list
623
+ _caching_handler_response.final_embedding_cached_response._hidden_params[
624
+ "cache_hit"
625
+ ] = True
626
+ _caching_handler_response.final_embedding_cached_response._response_ms = (
627
+ end_time - start_time
628
+ ).total_seconds() * 1000
629
+
630
+ ## USAGE
631
+ if (
632
+ _caching_handler_response.final_embedding_cached_response.usage is not None
633
+ and embedding_response.usage is not None
634
+ ):
635
+ _caching_handler_response.final_embedding_cached_response.usage = self.combine_usage(
636
+ usage1=_caching_handler_response.final_embedding_cached_response.usage,
637
+ usage2=embedding_response.usage,
638
+ )
639
+
640
+ return _caching_handler_response.final_embedding_cached_response
641
+
642
+ def _async_log_cache_hit_on_callbacks(
643
+ self,
644
+ logging_obj: LiteLLMLoggingObj,
645
+ cached_result: Any,
646
+ start_time: datetime.datetime,
647
+ end_time: datetime.datetime,
648
+ cache_hit: bool,
649
+ ):
650
+ """
651
+ Helper function to log the success of a cached result on callbacks
652
+
653
+ Args:
654
+ logging_obj (LiteLLMLoggingObj): The logging object.
655
+ cached_result: The cached result.
656
+ start_time (datetime): The start time of the operation.
657
+ end_time (datetime): The end time of the operation.
658
+ cache_hit (bool): Whether it was a cache hit.
659
+ """
660
+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
661
+
662
+ GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(
663
+ async_coroutine=logging_obj.async_success_handler(
664
+ result=cached_result,
665
+ start_time=start_time,
666
+ end_time=end_time,
667
+ cache_hit=cache_hit,
668
+ )
669
+ )
670
+
671
+ logging_obj.handle_sync_success_callbacks_for_async_calls(
672
+ result=cached_result,
673
+ start_time=start_time,
674
+ end_time=end_time,
675
+ cache_hit=cache_hit,
676
+ )
677
+
678
+ async def _retrieve_from_cache(
679
+ self, call_type: str, kwargs: Dict[str, Any], args: Tuple[Any, ...]
680
+ ) -> Optional[Any]:
681
+ """
682
+ Internal method to
683
+ - get cache key
684
+ - check what type of cache is used - Redis, RedisSemantic, Qdrant, S3
685
+ - async get cache value
686
+ - return the cached value
687
+
688
+ Args:
689
+ call_type: str:
690
+ kwargs: Dict[str, Any]:
691
+ args: Optional[Tuple[Any, ...]] = None:
692
+
693
+ Returns:
694
+ Optional[Any]:
695
+ Raises:
696
+ None
697
+ """
698
+ if litellm.cache is None:
699
+ return None
700
+
701
+ new_kwargs = kwargs.copy()
702
+ new_kwargs.update(
703
+ convert_args_to_kwargs(
704
+ self.original_function,
705
+ args,
706
+ )
707
+ )
708
+ if new_kwargs.get("metadata") is None:
709
+ new_kwargs.pop("metadata", None)
710
+ if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs:
711
+ new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs)
712
+ self.request_kwargs = new_kwargs
713
+ cached_result: Optional[Any] = None
714
+ if call_type == CallTypes.aembedding.value:
715
+ if isinstance(new_kwargs["input"], str):
716
+ new_kwargs["input"] = [new_kwargs["input"]]
717
+ elif not isinstance(new_kwargs["input"], list):
718
+ raise ValueError("input must be a string or a list")
719
+ tasks = []
720
+ for idx, i in enumerate(new_kwargs["input"]):
721
+ preset_cache_key = litellm.cache.get_cache_key(
722
+ **{**new_kwargs, "input": i}
723
+ )
724
+ tasks.append(
725
+ litellm.cache.async_get_cache(
726
+ cache_key=preset_cache_key,
727
+ dynamic_cache_object=self.dual_cache,
728
+ )
729
+ )
730
+ cached_result = await asyncio.gather(*tasks)
731
+ ## check if cached result is None ##
732
+ if cached_result is not None and isinstance(cached_result, list):
733
+ # set cached_result to None if all elements are None
734
+ if all(result is None for result in cached_result):
735
+ cached_result = None
736
+ else:
737
+ request_kwargs = new_kwargs.copy()
738
+ request_cache_key = request_kwargs.pop("cache_key", None)
739
+ if litellm.cache._supports_async() is True:
740
+ ## check if dual cache is supported ##
741
+ self.preset_cache_key = (
742
+ request_cache_key or litellm.cache.get_cache_key(**request_kwargs)
743
+ )
744
+ cached_result = await litellm.cache.async_get_cache(
745
+ dynamic_cache_object=self.dual_cache,
746
+ cache_key=self.preset_cache_key,
747
+ **request_kwargs,
748
+ )
749
+ else: # fallback for caches that don't support async
750
+ self.preset_cache_key = (
751
+ request_cache_key or litellm.cache.get_cache_key(**request_kwargs)
752
+ )
753
+ cached_result = litellm.cache.get_cache(
754
+ dynamic_cache_object=self.dual_cache,
755
+ cache_key=self.preset_cache_key,
756
+ **request_kwargs,
757
+ )
758
+ return cached_result
759
+
760
+ def _convert_cached_result_to_model_response(
761
+ self,
762
+ cached_result: Any,
763
+ call_type: str,
764
+ kwargs: Dict[str, Any],
765
+ logging_obj: LiteLLMLoggingObj,
766
+ model: str,
767
+ args: Tuple[Any, ...],
768
+ custom_llm_provider: Optional[str] = None,
769
+ ) -> Optional[
770
+ Union[
771
+ ModelResponse,
772
+ TextCompletionResponse,
773
+ EmbeddingResponse,
774
+ RerankResponse,
775
+ TranscriptionResponse,
776
+ CustomStreamWrapper,
777
+ ]
778
+ ]:
779
+ """
780
+ Internal method to process the cached result
781
+
782
+ Checks the call type and converts the cached result to the appropriate model response object
783
+ example if call type is text_completion -> returns TextCompletionResponse object
784
+
785
+ Args:
786
+ cached_result: Any:
787
+ call_type: str:
788
+ kwargs: Dict[str, Any]:
789
+ logging_obj: LiteLLMLoggingObj:
790
+ model: str:
791
+ custom_llm_provider: Optional[str] = None:
792
+ args: Optional[Tuple[Any, ...]] = None:
793
+
794
+ Returns:
795
+ Optional[Any]:
796
+ """
797
+ from litellm.utils import convert_to_model_response_object
798
+
799
+ if (
800
+ call_type == CallTypes.acompletion.value
801
+ or call_type == CallTypes.completion.value
802
+ ) and isinstance(cached_result, dict):
803
+ if kwargs.get("stream", False) is True:
804
+ cached_result = self._convert_cached_stream_response(
805
+ cached_result=cached_result,
806
+ call_type=call_type,
807
+ logging_obj=logging_obj,
808
+ model=model,
809
+ )
810
+ else:
811
+ cached_result = convert_to_model_response_object(
812
+ response_object=cached_result,
813
+ model_response_object=ModelResponse(),
814
+ )
815
+ if (
816
+ call_type == CallTypes.atext_completion.value
817
+ or call_type == CallTypes.text_completion.value
818
+ ) and isinstance(cached_result, dict):
819
+ if kwargs.get("stream", False) is True:
820
+ cached_result = self._convert_cached_stream_response(
821
+ cached_result=cached_result,
822
+ call_type=call_type,
823
+ logging_obj=logging_obj,
824
+ model=model,
825
+ )
826
+ else:
827
+ cached_result = TextCompletionResponse(**cached_result)
828
+ elif (
829
+ call_type == CallTypes.aembedding.value
830
+ or call_type == CallTypes.embedding.value
831
+ ) and isinstance(cached_result, dict):
832
+ cached_result = convert_to_model_response_object(
833
+ response_object=cached_result,
834
+ model_response_object=EmbeddingResponse(),
835
+ response_type="embedding",
836
+ )
837
+
838
+ elif (
839
+ call_type == CallTypes.arerank.value or call_type == CallTypes.rerank.value
840
+ ) and isinstance(cached_result, dict):
841
+ cached_result = convert_to_model_response_object(
842
+ response_object=cached_result,
843
+ model_response_object=None,
844
+ response_type="rerank",
845
+ )
846
+ elif (
847
+ call_type == CallTypes.atranscription.value
848
+ or call_type == CallTypes.transcription.value
849
+ ) and isinstance(cached_result, dict):
850
+ hidden_params = {
851
+ "model": "whisper-1",
852
+ "custom_llm_provider": custom_llm_provider,
853
+ "cache_hit": True,
854
+ }
855
+ cached_result = convert_to_model_response_object(
856
+ response_object=cached_result,
857
+ model_response_object=TranscriptionResponse(),
858
+ response_type="audio_transcription",
859
+ hidden_params=hidden_params,
860
+ )
861
+ elif (call_type == "aresponses" or call_type == "responses") and isinstance(
862
+ cached_result, dict
863
+ ):
864
+ from litellm.responses.streaming_iterator import (
865
+ CachedResponsesAPIStreamingIterator,
866
+ )
867
+
868
+ response_obj = ResponsesAPIResponse(**cached_result)
869
+ if (
870
+ hasattr(response_obj, "_hidden_params")
871
+ and response_obj._hidden_params is not None
872
+ and isinstance(response_obj._hidden_params, dict)
873
+ ):
874
+ response_obj._hidden_params["cache_hit"] = True
875
+
876
+ if kwargs.get("stream", False) is True:
877
+ cached_result = CachedResponsesAPIStreamingIterator(
878
+ response=response_obj,
879
+ logging_obj=logging_obj,
880
+ request_data=kwargs,
881
+ call_type=call_type,
882
+ )
883
+ else:
884
+ cached_result = response_obj
885
+
886
+ if (
887
+ hasattr(cached_result, "_hidden_params")
888
+ and cached_result._hidden_params is not None
889
+ and isinstance(cached_result._hidden_params, dict)
890
+ ):
891
+ cached_result._hidden_params["cache_hit"] = True
892
+
893
+ #########################################################
894
+ # Add final timing metrics to the cached result
895
+ #########################################################
896
+ update_response_metadata(
897
+ result=cached_result,
898
+ logging_obj=logging_obj,
899
+ model=model,
900
+ kwargs=kwargs,
901
+ start_time=self.start_time,
902
+ end_time=datetime.datetime.now(),
903
+ )
904
+ return cached_result
905
+
906
+ def _convert_cached_stream_response(
907
+ self,
908
+ cached_result: Any,
909
+ call_type: str,
910
+ logging_obj: LiteLLMLoggingObj,
911
+ model: str,
912
+ ) -> CustomStreamWrapper:
913
+ from litellm.utils import (
914
+ CustomStreamWrapper,
915
+ convert_to_streaming_response,
916
+ convert_to_streaming_response_async,
917
+ )
918
+
919
+ _stream_cached_result: Union[AsyncGenerator, Generator]
920
+ if (
921
+ call_type == CallTypes.acompletion.value
922
+ or call_type == CallTypes.atext_completion.value
923
+ ):
924
+ _stream_cached_result = convert_to_streaming_response_async(
925
+ response_object=cached_result,
926
+ )
927
+ else:
928
+ _stream_cached_result = convert_to_streaming_response(
929
+ response_object=cached_result,
930
+ )
931
+ return CustomStreamWrapper(
932
+ completion_stream=_stream_cached_result,
933
+ model=model,
934
+ custom_llm_provider="cached_response",
935
+ logging_obj=logging_obj,
936
+ )
937
+
938
+ async def async_set_cache(
939
+ self,
940
+ result: Any,
941
+ original_function: Callable,
942
+ kwargs: Dict[str, Any],
943
+ args: Optional[Tuple[Any, ...]] = None,
944
+ ):
945
+ """
946
+ Internal method to check the type of the result & cache used and adds the result to the cache accordingly
947
+
948
+ Args:
949
+ result: Any:
950
+ original_function: Callable:
951
+ kwargs: Dict[str, Any]:
952
+ args: Optional[Tuple[Any, ...]] = None:
953
+
954
+ Returns:
955
+ None
956
+ Raises:
957
+ None
958
+ """
959
+ from litellm.litellm_core_utils.core_helpers import (
960
+ _get_parent_otel_span_from_kwargs,
961
+ )
962
+
963
+ if litellm.cache is None:
964
+ return
965
+
966
+ new_kwargs = kwargs.copy()
967
+ new_kwargs.update(
968
+ convert_args_to_kwargs(
969
+ original_function,
970
+ args,
971
+ )
972
+ )
973
+ parent_otel_span = _get_parent_otel_span_from_kwargs(new_kwargs)
974
+ new_kwargs["parent_otel_span"] = parent_otel_span
975
+ # [OPTIONAL] ADD TO CACHE
976
+ if self._should_store_result_in_cache(
977
+ original_function=original_function, kwargs=new_kwargs
978
+ ):
979
+ if (
980
+ isinstance(result, litellm.ModelResponse)
981
+ or isinstance(result, litellm.EmbeddingResponse)
982
+ or isinstance(result, TranscriptionResponse)
983
+ or isinstance(result, RerankResponse)
984
+ or isinstance(result, ResponsesAPIResponse)
985
+ ):
986
+ if (
987
+ isinstance(result, EmbeddingResponse)
988
+ and litellm.cache is not None
989
+ and not isinstance(
990
+ litellm.cache.cache, S3Cache
991
+ ) # s3 doesn't support bulk writing. Exclude.
992
+ ):
993
+ asyncio.create_task(
994
+ litellm.cache.async_add_cache_pipeline(
995
+ result, dynamic_cache_object=self.dual_cache, **new_kwargs
996
+ )
997
+ )
998
+ else:
999
+ asyncio.create_task(
1000
+ litellm.cache.async_add_cache(
1001
+ result.model_dump_json(),
1002
+ dynamic_cache_object=self.dual_cache,
1003
+ **new_kwargs,
1004
+ )
1005
+ )
1006
+ else:
1007
+ asyncio.create_task(litellm.cache.async_add_cache(result, **new_kwargs))
1008
+
1009
+ def sync_set_cache(
1010
+ self,
1011
+ result: Any,
1012
+ kwargs: Dict[str, Any],
1013
+ args: Optional[Tuple[Any, ...]] = None,
1014
+ ):
1015
+ """
1016
+ Sync internal method to add the result to the cache
1017
+ """
1018
+
1019
+ new_kwargs = kwargs.copy()
1020
+ new_kwargs.update(
1021
+ convert_args_to_kwargs(
1022
+ self.original_function,
1023
+ args,
1024
+ )
1025
+ )
1026
+ if litellm.cache is None:
1027
+ return
1028
+
1029
+ if self._should_store_result_in_cache(
1030
+ original_function=self.original_function, kwargs=new_kwargs
1031
+ ):
1032
+ litellm.cache.add_cache(result, **new_kwargs)
1033
+
1034
+ return
1035
+
1036
+ def _should_store_result_in_cache(
1037
+ self, original_function: Callable, kwargs: Dict[str, Any]
1038
+ ) -> bool:
1039
+ """
1040
+ Helper function to determine if the result should be stored in the cache.
1041
+
1042
+ Returns:
1043
+ bool: True if the result should be stored in the cache, False otherwise.
1044
+ """
1045
+ return (
1046
+ (litellm.cache is not None)
1047
+ and litellm.cache.supported_call_types is not None
1048
+ and (str(original_function.__name__) in litellm.cache.supported_call_types)
1049
+ and (kwargs.get("cache", {}).get("no-store", False) is not True)
1050
+ )
1051
+
1052
+ def _is_call_type_supported_by_cache(
1053
+ self,
1054
+ original_function: Callable,
1055
+ ) -> bool:
1056
+ """
1057
+ Helper function to determine if the call type is supported by the cache.
1058
+
1059
+ call types are acompletion, aembedding, atext_completion, atranscription, arerank
1060
+
1061
+ Defined on `litellm.types.utils.CallTypes`
1062
+
1063
+ Returns:
1064
+ bool: True if the call type is supported by the cache, False otherwise.
1065
+ """
1066
+ if (
1067
+ litellm.cache is not None
1068
+ and litellm.cache.supported_call_types is not None
1069
+ and str(original_function.__name__) in litellm.cache.supported_call_types
1070
+ ):
1071
+ return True
1072
+ return False
1073
+
1074
+ async def _add_streaming_response_to_cache(self, processed_chunk: ModelResponse):
1075
+ """
1076
+ Internal method to add the streaming response to the cache
1077
+
1078
+
1079
+ - If 'streaming_chunk' has a 'finish_reason' then assemble a litellm.ModelResponse object
1080
+ - Else append the chunk to self.async_streaming_chunks
1081
+
1082
+ """
1083
+
1084
+ complete_streaming_response: Optional[
1085
+ Union[ModelResponse, TextCompletionResponse]
1086
+ ] = _assemble_complete_response_from_streaming_chunks(
1087
+ result=processed_chunk,
1088
+ start_time=self.start_time,
1089
+ end_time=datetime.datetime.now(),
1090
+ request_kwargs=self.request_kwargs,
1091
+ streaming_chunks=self.async_streaming_chunks,
1092
+ is_async=True,
1093
+ )
1094
+ # if a complete_streaming_response is assembled, add it to the cache
1095
+ if complete_streaming_response is not None:
1096
+ await self.async_set_cache(
1097
+ result=complete_streaming_response,
1098
+ original_function=self.original_function,
1099
+ kwargs=self.request_kwargs,
1100
+ )
1101
+
1102
+ def _sync_add_streaming_response_to_cache(self, processed_chunk: ModelResponse):
1103
+ """
1104
+ Sync internal method to add the streaming response to the cache
1105
+ """
1106
+ complete_streaming_response: Optional[
1107
+ Union[ModelResponse, TextCompletionResponse]
1108
+ ] = _assemble_complete_response_from_streaming_chunks(
1109
+ result=processed_chunk,
1110
+ start_time=self.start_time,
1111
+ end_time=datetime.datetime.now(),
1112
+ request_kwargs=self.request_kwargs,
1113
+ streaming_chunks=self.sync_streaming_chunks,
1114
+ is_async=False,
1115
+ )
1116
+
1117
+ # if a complete_streaming_response is assembled, add it to the cache
1118
+ if complete_streaming_response is not None:
1119
+ self.sync_set_cache(
1120
+ result=complete_streaming_response,
1121
+ kwargs=self.request_kwargs,
1122
+ )
1123
+
1124
+ def _update_litellm_logging_obj_environment(
1125
+ self,
1126
+ logging_obj: LiteLLMLoggingObj,
1127
+ model: str,
1128
+ kwargs: Dict[str, Any],
1129
+ cached_result: Any,
1130
+ is_async: bool,
1131
+ is_embedding: bool = False,
1132
+ custom_llm_provider: Optional[str] = None,
1133
+ cache_duration_ms: Optional[float] = None,
1134
+ ):
1135
+ """
1136
+ Helper function to update the LiteLLMLoggingObj environment variables.
1137
+
1138
+ Args:
1139
+ logging_obj (LiteLLMLoggingObj): The logging object to update.
1140
+ model (str): The model being used.
1141
+ kwargs (Dict[str, Any]): The keyword arguments from the original function call.
1142
+ cached_result (Any): The cached result to log.
1143
+ is_async (bool): Whether the call is asynchronous or not.
1144
+ is_embedding (bool): Whether the call is for embeddings or not.
1145
+ custom_llm_provider (Optional[str]): The custom llm provider being used.
1146
+
1147
+ Returns:
1148
+ None
1149
+ """
1150
+ litellm_params = {
1151
+ "logger_fn": kwargs.get("logger_fn", None),
1152
+ "acompletion": is_async,
1153
+ "api_base": kwargs.get("api_base", ""),
1154
+ "metadata": kwargs.get("metadata", {}),
1155
+ "model_info": kwargs.get("model_info", {}),
1156
+ "proxy_server_request": kwargs.get("proxy_server_request", None),
1157
+ "stream_response": kwargs.get("stream_response", {}),
1158
+ "custom_llm_provider": custom_llm_provider,
1159
+ }
1160
+
1161
+ if litellm.cache is not None:
1162
+ litellm_params["preset_cache_key"] = (
1163
+ litellm.cache._get_preset_cache_key_from_kwargs(**kwargs)
1164
+ )
1165
+ else:
1166
+ litellm_params["preset_cache_key"] = None
1167
+
1168
+ logging_obj.update_environment_variables(
1169
+ model=model,
1170
+ user=kwargs.get("user", None),
1171
+ optional_params={},
1172
+ litellm_params=litellm_params,
1173
+ input=(
1174
+ kwargs.get("messages", "")
1175
+ if not is_embedding
1176
+ else kwargs.get("input", "")
1177
+ ),
1178
+ api_key=kwargs.get("api_key", None),
1179
+ original_response=str(cached_result),
1180
+ additional_args=None,
1181
+ stream=kwargs.get("stream", False),
1182
+ custom_llm_provider=custom_llm_provider,
1183
+ )
1184
+
1185
+ logging_obj.caching_details = CachingDetails(
1186
+ cache_hit=True,
1187
+ cache_duration_ms=cache_duration_ms,
1188
+ )
1189
+
1190
+
1191
+ def convert_args_to_kwargs(
1192
+ original_function: Callable,
1193
+ args: Optional[Tuple[Any, ...]] = None,
1194
+ ) -> Dict[str, Any]:
1195
+ # Get the signature of the original function
1196
+ signature = inspect.signature(original_function)
1197
+
1198
+ # Get parameter names in the order they appear in the original function
1199
+ param_names = list(signature.parameters.keys())
1200
+
1201
+ # Create a mapping of positional arguments to parameter names
1202
+ args_to_kwargs = {}
1203
+ if args:
1204
+ for index, arg in enumerate(args):
1205
+ if index < len(param_names):
1206
+ param_name = param_names[index]
1207
+ args_to_kwargs[param_name] = arg
1208
+
1209
+ return args_to_kwargs
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/disk_cache.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import TYPE_CHECKING, Any, Optional, Union
3
+
4
+ from .base_cache import BaseCache
5
+
6
+ if TYPE_CHECKING:
7
+ from opentelemetry.trace import Span as _Span
8
+
9
+ Span = Union[_Span, Any]
10
+ else:
11
+ Span = Any
12
+
13
+
14
+ class DiskCache(BaseCache):
15
+ def __init__(self, disk_cache_dir: Optional[str] = None):
16
+ try:
17
+ import diskcache as dc
18
+ except ModuleNotFoundError as e:
19
+ raise ModuleNotFoundError(
20
+ "Please install litellm with `litellm[caching]` to use disk caching."
21
+ ) from e
22
+
23
+ # if users don't provider one, use the default litellm cache
24
+ if disk_cache_dir is None:
25
+ self.disk_cache = dc.Cache(".litellm_cache")
26
+ else:
27
+ self.disk_cache = dc.Cache(disk_cache_dir)
28
+
29
+ def set_cache(self, key, value, **kwargs):
30
+ if "ttl" in kwargs:
31
+ self.disk_cache.set(key, value, expire=kwargs["ttl"])
32
+ else:
33
+ self.disk_cache.set(key, value)
34
+
35
+ async def async_set_cache(self, key, value, **kwargs):
36
+ self.set_cache(key=key, value=value, **kwargs)
37
+
38
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
39
+ for cache_key, cache_value in cache_list:
40
+ if "ttl" in kwargs:
41
+ self.set_cache(key=cache_key, value=cache_value, ttl=kwargs["ttl"])
42
+ else:
43
+ self.set_cache(key=cache_key, value=cache_value)
44
+
45
+ def get_cache(self, key, **kwargs):
46
+ original_cached_response = self.disk_cache.get(key)
47
+ if original_cached_response:
48
+ try:
49
+ cached_response = json.loads(original_cached_response) # type: ignore
50
+ except Exception:
51
+ cached_response = original_cached_response
52
+ return cached_response
53
+ return None
54
+
55
+ def batch_get_cache(self, keys: list, **kwargs):
56
+ return_val = []
57
+ for k in keys:
58
+ val = self.get_cache(key=k, **kwargs)
59
+ return_val.append(val)
60
+ return return_val
61
+
62
+ def increment_cache(self, key, value: int, **kwargs) -> int:
63
+ # get the value
64
+ init_value = self.get_cache(key=key) or 0
65
+ value = init_value + value # type: ignore
66
+ self.set_cache(key, value, **kwargs)
67
+ return value
68
+
69
+ async def async_get_cache(self, key, **kwargs):
70
+ return self.get_cache(key=key, **kwargs)
71
+
72
+ async def async_batch_get_cache(self, keys: list, **kwargs):
73
+ return_val = []
74
+ for k in keys:
75
+ val = self.get_cache(key=k, **kwargs)
76
+ return_val.append(val)
77
+ return return_val
78
+
79
+ async def async_increment(self, key, value: int, **kwargs) -> int:
80
+ # get the value
81
+ init_value = await self.async_get_cache(key=key) or 0
82
+ value = init_value + value # type: ignore
83
+ await self.async_set_cache(key, value, **kwargs)
84
+ return value
85
+
86
+ def flush_cache(self):
87
+ self.disk_cache.clear()
88
+
89
+ async def disconnect(self):
90
+ pass
91
+
92
+ def delete_cache(self, key):
93
+ self.disk_cache.pop(key)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/dual_cache.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dual Cache implementation - Class to update both Redis and an in-memory cache simultaneously.
3
+
4
+ Has 4 primary methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ import asyncio
12
+ import time
13
+ import traceback
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from threading import Lock
16
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
17
+
18
+ if TYPE_CHECKING:
19
+ from litellm.types.caching import RedisPipelineIncrementOperation
20
+
21
+ import litellm
22
+ from litellm._logging import print_verbose, verbose_logger
23
+ from litellm.constants import DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE
24
+
25
+ from .base_cache import BaseCache
26
+ from .in_memory_cache import InMemoryCache
27
+ from .redis_cache import RedisCache
28
+
29
+ if TYPE_CHECKING:
30
+ from opentelemetry.trace import Span as _Span
31
+
32
+ Span = Union[_Span, Any]
33
+ else:
34
+ Span = Any
35
+
36
+ from collections import OrderedDict
37
+
38
+
39
+ class LimitedSizeOrderedDict(OrderedDict):
40
+ def __init__(self, *args, max_size=100, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+ self.max_size = max_size
43
+
44
+ def __setitem__(self, key, value):
45
+ # If inserting a new key exceeds max size, remove the oldest item
46
+ if len(self) >= self.max_size:
47
+ self.popitem(last=False)
48
+ super().__setitem__(key, value)
49
+
50
+
51
+ class DualCache(BaseCache):
52
+ """
53
+ DualCache is a cache implementation that updates both Redis and an in-memory cache simultaneously.
54
+ When data is updated or inserted, it is written to both the in-memory cache + Redis.
55
+ This ensures that even if Redis hasn't been updated yet, the in-memory cache reflects the most recent data.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ in_memory_cache: Optional[InMemoryCache] = None,
61
+ redis_cache: Optional[RedisCache] = None,
62
+ default_in_memory_ttl: Optional[float] = None,
63
+ default_redis_ttl: Optional[float] = None,
64
+ default_redis_batch_cache_expiry: Optional[float] = None,
65
+ default_max_redis_batch_cache_size: int = DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE,
66
+ ) -> None:
67
+ super().__init__()
68
+ # If in_memory_cache is not provided, use the default InMemoryCache
69
+ self.in_memory_cache = in_memory_cache or InMemoryCache()
70
+ # If redis_cache is not provided, use the default RedisCache
71
+ self.redis_cache = redis_cache
72
+ self.last_redis_batch_access_time = LimitedSizeOrderedDict(
73
+ max_size=default_max_redis_batch_cache_size
74
+ )
75
+ self._last_redis_batch_access_time_lock = Lock()
76
+ self.redis_batch_cache_expiry = (
77
+ default_redis_batch_cache_expiry
78
+ or litellm.default_redis_batch_cache_expiry
79
+ or 10
80
+ )
81
+ self.default_in_memory_ttl = (
82
+ default_in_memory_ttl or litellm.default_in_memory_ttl
83
+ )
84
+ self.default_redis_ttl = default_redis_ttl or litellm.default_redis_ttl
85
+
86
+ def update_cache_ttl(
87
+ self, default_in_memory_ttl: Optional[float], default_redis_ttl: Optional[float]
88
+ ):
89
+ if default_in_memory_ttl is not None:
90
+ self.default_in_memory_ttl = default_in_memory_ttl
91
+
92
+ if default_redis_ttl is not None:
93
+ self.default_redis_ttl = default_redis_ttl
94
+
95
+ def attach_redis_cache(
96
+ self,
97
+ redis_cache: Optional[RedisCache] = None,
98
+ *,
99
+ default_redis_ttl: Optional[float] = None,
100
+ ) -> None:
101
+ """
102
+ Attach a Redis backend if this DualCache does not already have one.
103
+
104
+ No-op when ``redis_cache`` is None or when Redis was already set (constructor
105
+ or a prior attach). Use this for lazy wiring after a shared Redis client exists.
106
+ Does not backfill in-memory-only keys to Redis.
107
+ """
108
+ if redis_cache is None or self.redis_cache is not None:
109
+ return
110
+ self.redis_cache = redis_cache
111
+ if default_redis_ttl is not None:
112
+ self.default_redis_ttl = default_redis_ttl
113
+
114
+ def set_cache(self, key, value, local_only: bool = False, **kwargs):
115
+ # Update both Redis and in-memory cache
116
+ try:
117
+ if self.in_memory_cache is not None:
118
+ if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
119
+ kwargs["ttl"] = self.default_in_memory_ttl
120
+
121
+ self.in_memory_cache.set_cache(key, value, **kwargs)
122
+
123
+ if self.redis_cache is not None and local_only is False:
124
+ self.redis_cache.set_cache(key, value, **kwargs)
125
+ except Exception as e:
126
+ print_verbose(e)
127
+
128
+ def increment_cache(
129
+ self, key, value: int, local_only: bool = False, **kwargs
130
+ ) -> int:
131
+ """
132
+ Key - the key in cache
133
+
134
+ Value - int - the value you want to increment by
135
+
136
+ Returns - int - the incremented value
137
+ """
138
+ try:
139
+ result: int = value
140
+ if self.in_memory_cache is not None:
141
+ result = self.in_memory_cache.increment_cache(key, value, **kwargs)
142
+
143
+ if self.redis_cache is not None and local_only is False:
144
+ result = self.redis_cache.increment_cache(key, value, **kwargs)
145
+
146
+ return result
147
+ except Exception as e:
148
+ verbose_logger.error(f"LiteLLM Cache: Excepton async add_cache: {str(e)}")
149
+ raise e
150
+
151
+ def get_cache(
152
+ self,
153
+ key,
154
+ parent_otel_span: Optional[Span] = None,
155
+ local_only: bool = False,
156
+ **kwargs,
157
+ ):
158
+ # Try to fetch from in-memory cache first
159
+ try:
160
+ result = None
161
+ if self.in_memory_cache is not None:
162
+ in_memory_result = self.in_memory_cache.get_cache(key, **kwargs)
163
+
164
+ if in_memory_result is not None:
165
+ result = in_memory_result
166
+
167
+ if result is None and self.redis_cache is not None and local_only is False:
168
+ # If not found in in-memory cache, try fetching from Redis
169
+ redis_result = self.redis_cache.get_cache(
170
+ key, parent_otel_span=parent_otel_span
171
+ )
172
+
173
+ if redis_result is not None:
174
+ # Update in-memory cache with the value from Redis
175
+ self.in_memory_cache.set_cache(key, redis_result, **kwargs)
176
+
177
+ result = redis_result
178
+
179
+ print_verbose(f"get cache: cache result: {result}")
180
+ return result
181
+ except Exception:
182
+ verbose_logger.error(traceback.format_exc())
183
+
184
+ def batch_get_cache(
185
+ self,
186
+ keys: list,
187
+ parent_otel_span: Optional[Span] = None,
188
+ local_only: bool = False,
189
+ **kwargs,
190
+ ):
191
+ received_args = locals()
192
+ received_args.pop("self")
193
+
194
+ def run_in_new_loop():
195
+ """Run the coroutine in a new event loop within this thread."""
196
+ new_loop = asyncio.new_event_loop()
197
+ try:
198
+ asyncio.set_event_loop(new_loop)
199
+ return new_loop.run_until_complete(
200
+ self.async_batch_get_cache(**received_args)
201
+ )
202
+ finally:
203
+ new_loop.close()
204
+ asyncio.set_event_loop(None)
205
+
206
+ try:
207
+ # First, try to get the current event loop
208
+ _ = asyncio.get_running_loop()
209
+ # If we're already in an event loop, run in a separate thread
210
+ # to avoid nested event loop issues
211
+ with ThreadPoolExecutor(max_workers=1) as executor:
212
+ future = executor.submit(run_in_new_loop)
213
+ return future.result()
214
+
215
+ except RuntimeError:
216
+ # No running event loop, we can safely run in this thread
217
+ return run_in_new_loop()
218
+
219
+ async def async_get_cache(
220
+ self,
221
+ key,
222
+ parent_otel_span: Optional[Span] = None,
223
+ local_only: bool = False,
224
+ **kwargs,
225
+ ):
226
+ # Try to fetch from in-memory cache first
227
+ try:
228
+ print_verbose(
229
+ f"async get cache: cache key: {key}; local_only: {local_only}"
230
+ )
231
+ result = None
232
+ if self.in_memory_cache is not None:
233
+ in_memory_result = await self.in_memory_cache.async_get_cache(
234
+ key, **kwargs
235
+ )
236
+
237
+ print_verbose(f"in_memory_result: {in_memory_result}")
238
+ if in_memory_result is not None:
239
+ result = in_memory_result
240
+
241
+ if result is None and self.redis_cache is not None and local_only is False:
242
+ # If not found in in-memory cache, try fetching from Redis
243
+ redis_result = await self.redis_cache.async_get_cache(
244
+ key, parent_otel_span=parent_otel_span
245
+ )
246
+
247
+ if redis_result is not None:
248
+ # Update in-memory cache with the value from Redis
249
+ await self.in_memory_cache.async_set_cache(
250
+ key, redis_result, **kwargs
251
+ )
252
+
253
+ result = redis_result
254
+
255
+ print_verbose(f"get cache: cache result: {result}")
256
+ return result
257
+ except Exception:
258
+ verbose_logger.error(traceback.format_exc())
259
+
260
+ def _reserve_redis_batch_keys(
261
+ self,
262
+ current_time: float,
263
+ keys: List[str],
264
+ result: List[Any],
265
+ ) -> Tuple[List[str], Dict[str, Optional[float]]]:
266
+ """
267
+ Atomically choose keys to fetch from Redis and reserve their access time.
268
+ This prevents check-then-act races under concurrent async callers.
269
+ """
270
+ sublist_keys: List[str] = []
271
+ previous_access_times: Dict[str, Optional[float]] = {}
272
+
273
+ with self._last_redis_batch_access_time_lock:
274
+ for key, value in zip(keys, result):
275
+ if value is not None:
276
+ continue
277
+
278
+ if (
279
+ key not in self.last_redis_batch_access_time
280
+ or current_time - self.last_redis_batch_access_time[key]
281
+ >= self.redis_batch_cache_expiry
282
+ ):
283
+ sublist_keys.append(key)
284
+ previous_access_times[key] = self.last_redis_batch_access_time.get(
285
+ key
286
+ )
287
+ self.last_redis_batch_access_time[key] = current_time
288
+
289
+ return sublist_keys, previous_access_times
290
+
291
+ def _rollback_redis_batch_key_reservations(
292
+ self, previous_access_times: Dict[str, Optional[float]]
293
+ ) -> None:
294
+ with self._last_redis_batch_access_time_lock:
295
+ for key, previous_time in previous_access_times.items():
296
+ if previous_time is None:
297
+ self.last_redis_batch_access_time.pop(key, None)
298
+ else:
299
+ self.last_redis_batch_access_time[key] = previous_time
300
+
301
+ async def async_batch_get_cache(
302
+ self,
303
+ keys: list,
304
+ parent_otel_span: Optional[Span] = None,
305
+ local_only: bool = False,
306
+ **kwargs,
307
+ ):
308
+ try:
309
+ result = [None] * len(keys)
310
+ if self.in_memory_cache is not None:
311
+ in_memory_result = await self.in_memory_cache.async_batch_get_cache(
312
+ keys, **kwargs
313
+ )
314
+
315
+ if in_memory_result is not None:
316
+ result = in_memory_result
317
+
318
+ if None in result and self.redis_cache is not None and local_only is False:
319
+ """
320
+ - for the none values in the result
321
+ - check the redis cache
322
+ """
323
+ current_time = time.time()
324
+ sublist_keys, previous_access_times = self._reserve_redis_batch_keys(
325
+ current_time, keys, result
326
+ )
327
+
328
+ # Only hit Redis if enough time has passed since last access.
329
+ if len(sublist_keys) > 0:
330
+ try:
331
+ # If not found in in-memory cache, try fetching from Redis
332
+ redis_result = await self.redis_cache.async_batch_get_cache(
333
+ sublist_keys, parent_otel_span=parent_otel_span
334
+ )
335
+ except Exception:
336
+ # Do not throttle subsequent callers if the Redis read fails.
337
+ self._rollback_redis_batch_key_reservations(
338
+ previous_access_times
339
+ )
340
+ raise
341
+
342
+ # Short-circuit if redis_result is None or contains only None values
343
+ if redis_result is None or all(
344
+ v is None for v in redis_result.values()
345
+ ):
346
+ return result
347
+
348
+ # Pre-compute key-to-index mapping for O(1) lookup
349
+ key_to_index = {key: i for i, key in enumerate(keys)}
350
+
351
+ # Update both result and in-memory cache in a single loop
352
+ for key, value in redis_result.items():
353
+ result[key_to_index[key]] = value
354
+
355
+ if value is not None and self.in_memory_cache is not None:
356
+ await self.in_memory_cache.async_set_cache(
357
+ key, value, **kwargs
358
+ )
359
+
360
+ return result
361
+ except Exception:
362
+ verbose_logger.error(traceback.format_exc())
363
+
364
+ async def async_set_cache(self, key, value, local_only: bool = False, **kwargs):
365
+ print_verbose(
366
+ f"async set cache: cache key: {key}; local_only: {local_only}; value: {value}"
367
+ )
368
+ try:
369
+ if self.in_memory_cache is not None:
370
+ if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
371
+ kwargs["ttl"] = self.default_in_memory_ttl
372
+ await self.in_memory_cache.async_set_cache(key, value, **kwargs)
373
+
374
+ if self.redis_cache is not None and local_only is False:
375
+ await self.redis_cache.async_set_cache(key, value, **kwargs)
376
+ except Exception as e:
377
+ verbose_logger.exception(
378
+ f"LiteLLM Cache: Excepton async add_cache: {str(e)}"
379
+ )
380
+
381
+ # async_batch_set_cache
382
+ async def async_set_cache_pipeline(
383
+ self, cache_list: list, local_only: bool = False, **kwargs
384
+ ):
385
+ """
386
+ Batch write values to the cache
387
+ """
388
+ print_verbose(
389
+ f"async batch set cache: cache keys: {cache_list}; local_only: {local_only}"
390
+ )
391
+ try:
392
+ if self.in_memory_cache is not None:
393
+ if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
394
+ kwargs["ttl"] = self.default_in_memory_ttl
395
+ await self.in_memory_cache.async_set_cache_pipeline(
396
+ cache_list=cache_list, **kwargs
397
+ )
398
+
399
+ if self.redis_cache is not None and local_only is False:
400
+ await self.redis_cache.async_set_cache_pipeline(
401
+ cache_list=cache_list, ttl=kwargs.pop("ttl", None), **kwargs
402
+ )
403
+ except Exception as e:
404
+ verbose_logger.exception(
405
+ f"LiteLLM Cache: Excepton async add_cache: {str(e)}"
406
+ )
407
+
408
+ async def async_increment_cache(
409
+ self,
410
+ key,
411
+ value: float,
412
+ parent_otel_span: Optional[Span] = None,
413
+ local_only: bool = False,
414
+ refresh_ttl: bool = False,
415
+ **kwargs,
416
+ ) -> Optional[float]:
417
+ """
418
+ Key - the key in cache
419
+
420
+ Value - float - the value you want to increment by
421
+
422
+ Refresh_ttl - bool - if True, resets the Redis TTL on every write.
423
+ Default False preserves window-style semantics.
424
+
425
+ Returns - the incremented value, or None if no cache backend is
426
+ available (in_memory_cache is None and Redis failed/is absent).
427
+ """
428
+ result: Optional[float] = None
429
+ try:
430
+ if self.in_memory_cache is not None:
431
+ result = await self.in_memory_cache.async_increment(
432
+ key, value, **kwargs
433
+ )
434
+
435
+ if self.redis_cache is not None and local_only is False:
436
+ result = await self.redis_cache.async_increment(
437
+ key,
438
+ value,
439
+ parent_otel_span=parent_otel_span,
440
+ ttl=kwargs.get("ttl", None),
441
+ refresh_ttl=refresh_ttl,
442
+ )
443
+
444
+ return result
445
+ except Exception as e:
446
+ verbose_logger.warning(
447
+ "Redis async_increment_cache failed, falling back to in-memory result: %s",
448
+ e,
449
+ )
450
+ return result
451
+
452
+ async def async_increment_cache_pipeline(
453
+ self,
454
+ increment_list: List["RedisPipelineIncrementOperation"],
455
+ local_only: bool = False,
456
+ parent_otel_span: Optional[Span] = None,
457
+ **kwargs,
458
+ ) -> Optional[List[float]]:
459
+ result: Optional[List[float]] = None
460
+ try:
461
+ if self.in_memory_cache is not None:
462
+ result = await self.in_memory_cache.async_increment_pipeline(
463
+ increment_list=increment_list,
464
+ parent_otel_span=parent_otel_span,
465
+ )
466
+
467
+ if self.redis_cache is not None and local_only is False:
468
+ result = await self.redis_cache.async_increment_pipeline(
469
+ increment_list=increment_list,
470
+ parent_otel_span=parent_otel_span,
471
+ )
472
+
473
+ return result
474
+ except Exception as e:
475
+ verbose_logger.warning(
476
+ "Redis async_increment_cache_pipeline failed, falling back to in-memory result: %s",
477
+ e,
478
+ )
479
+ return result
480
+
481
+ async def async_set_cache_sadd(
482
+ self, key, value: List, local_only: bool = False, **kwargs
483
+ ) -> None:
484
+ """
485
+ Add value to a set
486
+
487
+ Key - the key in cache
488
+
489
+ Value - str - the value you want to add to the set
490
+
491
+ Returns - None
492
+ """
493
+ try:
494
+ if self.in_memory_cache is not None:
495
+ _ = await self.in_memory_cache.async_set_cache_sadd(
496
+ key, value, ttl=kwargs.get("ttl", None)
497
+ )
498
+
499
+ if self.redis_cache is not None and local_only is False:
500
+ _ = await self.redis_cache.async_set_cache_sadd(
501
+ key, value, ttl=kwargs.get("ttl", None)
502
+ )
503
+
504
+ return None
505
+ except Exception as e:
506
+ raise e # don't log, if exception is raised
507
+
508
+ def flush_cache(self):
509
+ if self.in_memory_cache is not None:
510
+ self.in_memory_cache.flush_cache()
511
+ if self.redis_cache is not None:
512
+ self.redis_cache.flush_cache()
513
+
514
+ def delete_cache(self, key):
515
+ """
516
+ Delete a key from the cache
517
+ """
518
+ if self.in_memory_cache is not None:
519
+ self.in_memory_cache.delete_cache(key)
520
+ if self.redis_cache is not None:
521
+ self.redis_cache.delete_cache(key)
522
+
523
+ async def async_delete_cache(self, key: str):
524
+ """
525
+ Delete a key from the cache
526
+ """
527
+ if self.in_memory_cache is not None:
528
+ self.in_memory_cache.delete_cache(key)
529
+ if self.redis_cache is not None:
530
+ await self.redis_cache.async_delete_cache(key)
531
+
532
+ async def async_get_ttl(self, key: str) -> Optional[int]:
533
+ """
534
+ Get the remaining TTL of a key in in-memory cache or redis
535
+ """
536
+ ttl = await self.in_memory_cache.async_get_ttl(key)
537
+ if ttl is None and self.redis_cache is not None:
538
+ ttl = await self.redis_cache.async_get_ttl(key)
539
+ return ttl
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/gcs_cache.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GCS Cache implementation
2
+ Supports syncing responses to Google Cloud Storage Buckets using HTTP requests.
3
+ """
4
+
5
+ import json
6
+ import asyncio
7
+ from typing import Optional
8
+
9
+ from litellm._logging import print_verbose, verbose_logger
10
+ from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
11
+ from litellm.llms.custom_httpx.http_handler import (
12
+ get_async_httpx_client,
13
+ _get_httpx_client,
14
+ httpxSpecialProvider,
15
+ )
16
+ from .base_cache import BaseCache
17
+
18
+
19
+ class GCSCache(BaseCache):
20
+ def __init__(
21
+ self,
22
+ bucket_name: Optional[str] = None,
23
+ path_service_account: Optional[str] = None,
24
+ gcs_path: Optional[str] = None,
25
+ ) -> None:
26
+ super().__init__()
27
+ self.bucket_name = bucket_name or GCSBucketBase(bucket_name=None).BUCKET_NAME
28
+ self.path_service_account = (
29
+ path_service_account
30
+ or GCSBucketBase(bucket_name=None).path_service_account_json
31
+ )
32
+ self.key_prefix = gcs_path.rstrip("/") + "/" if gcs_path else ""
33
+ # create httpx clients
34
+ self.async_client = get_async_httpx_client(
35
+ llm_provider=httpxSpecialProvider.LoggingCallback
36
+ )
37
+ self.sync_client = _get_httpx_client()
38
+
39
+ def _construct_headers(self) -> dict:
40
+ base = GCSBucketBase(bucket_name=self.bucket_name)
41
+ base.path_service_account_json = self.path_service_account
42
+ base.BUCKET_NAME = self.bucket_name
43
+ return base.sync_construct_request_headers()
44
+
45
+ def set_cache(self, key, value, **kwargs):
46
+ try:
47
+ print_verbose(f"LiteLLM SET Cache - GCS. Key={key}. Value={value}")
48
+ headers = self._construct_headers()
49
+ object_name = self.key_prefix + key
50
+ bucket_name = self.bucket_name
51
+ url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}"
52
+ data = json.dumps(value)
53
+ self.sync_client.post(url=url, data=data, headers=headers)
54
+ except Exception as e:
55
+ print_verbose(f"GCS Caching: set_cache() - Got exception from GCS: {e}")
56
+
57
+ async def async_set_cache(self, key, value, **kwargs):
58
+ try:
59
+ headers = self._construct_headers()
60
+ object_name = self.key_prefix + key
61
+ bucket_name = self.bucket_name
62
+ url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}"
63
+ data = json.dumps(value)
64
+ await self.async_client.post(url=url, data=data, headers=headers)
65
+ except Exception as e:
66
+ print_verbose(
67
+ f"GCS Caching: async_set_cache() - Got exception from GCS: {e}"
68
+ )
69
+
70
+ def get_cache(self, key, **kwargs):
71
+ try:
72
+ headers = self._construct_headers()
73
+ object_name = self.key_prefix + key
74
+ bucket_name = self.bucket_name
75
+ url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media"
76
+ response = self.sync_client.get(url=url, headers=headers)
77
+ if response.status_code == 200:
78
+ cached_response = json.loads(response.text)
79
+ verbose_logger.debug(
80
+ f"Got GCS Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}"
81
+ )
82
+ return cached_response
83
+ return None
84
+ except Exception as e:
85
+ verbose_logger.error(
86
+ f"GCS Caching: get_cache() - Got exception from GCS: {e}"
87
+ )
88
+
89
+ async def async_get_cache(self, key, **kwargs):
90
+ try:
91
+ headers = self._construct_headers()
92
+ object_name = self.key_prefix + key
93
+ bucket_name = self.bucket_name
94
+ url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media"
95
+ response = await self.async_client.get(url=url, headers=headers)
96
+ if response.status_code == 200:
97
+ return json.loads(response.text)
98
+ return None
99
+ except Exception as e:
100
+ verbose_logger.error(
101
+ f"GCS Caching: async_get_cache() - Got exception from GCS: {e}"
102
+ )
103
+
104
+ def flush_cache(self):
105
+ pass
106
+
107
+ async def disconnect(self):
108
+ pass
109
+
110
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
111
+ tasks = []
112
+ for val in cache_list:
113
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
114
+ await asyncio.gather(*tasks)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/in_memory_cache.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ In-Memory Cache implementation
3
+
4
+ Has 4 methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ import json
12
+ import sys
13
+ import time
14
+ import heapq
15
+ from typing import TYPE_CHECKING, Any, List, Optional
16
+
17
+ if TYPE_CHECKING:
18
+ from litellm.types.caching import RedisPipelineIncrementOperation
19
+
20
+ from pydantic import BaseModel
21
+
22
+ from litellm.constants import MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB
23
+
24
+ from .base_cache import BaseCache
25
+
26
+
27
+ class InMemoryCache(BaseCache):
28
+ def __init__(
29
+ self,
30
+ max_size_in_memory: Optional[int] = 200,
31
+ default_ttl: Optional[
32
+ int
33
+ ] = 600, # default ttl is 10 minutes. At maximum litellm rate limiting logic requires objects to be in memory for 1 minute
34
+ max_size_per_item: Optional[int] = 1024, # 1MB = 1024KB
35
+ ):
36
+ """
37
+ max_size_in_memory [int]: Maximum number of items in cache. done to prevent memory leaks. Use 200 items as a default
38
+ """
39
+ self.max_size_in_memory = (
40
+ max_size_in_memory if max_size_in_memory is not None else 200
41
+ ) # set an upper bound of 200 items in-memory
42
+ self.default_ttl = default_ttl or 600
43
+ self.max_size_per_item = (
44
+ max_size_per_item or MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB
45
+ ) # 1MB = 1024KB
46
+
47
+ # in-memory cache
48
+ self.cache_dict: dict = {}
49
+ self.ttl_dict: dict = {}
50
+ self.expiration_heap: list[tuple[float, str]] = []
51
+
52
+ def check_value_size(self, value: Any):
53
+ """
54
+ Check if value size exceeds max_size_per_item (1MB)
55
+ Returns True if value size is acceptable, False otherwise
56
+ """
57
+ try:
58
+ # Fast path for common primitive types that are typically small
59
+ if (
60
+ isinstance(value, (bool, int, float, str))
61
+ and len(str(value))
62
+ < self.max_size_per_item * MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB
63
+ ): # Conservative estimate
64
+ return True
65
+
66
+ # Direct size check for bytes objects
67
+ if isinstance(value, bytes):
68
+ return sys.getsizeof(value) / 1024 <= self.max_size_per_item
69
+
70
+ # Handle special types without full conversion when possible
71
+ if hasattr(value, "__sizeof__"): # Use __sizeof__ if available
72
+ size = value.__sizeof__() / 1024
73
+ return size <= self.max_size_per_item
74
+
75
+ # Fallback for complex types
76
+ if isinstance(value, BaseModel) and hasattr(
77
+ value, "model_dump"
78
+ ): # Pydantic v2
79
+ value = value.model_dump()
80
+ elif hasattr(value, "isoformat"): # datetime objects
81
+ return True # datetime strings are always small
82
+
83
+ # Only convert to JSON if absolutely necessary
84
+ if not isinstance(value, (str, bytes)):
85
+ value = json.dumps(value, default=str)
86
+
87
+ return sys.getsizeof(value) / 1024 <= self.max_size_per_item
88
+
89
+ except Exception:
90
+ return False
91
+
92
+ def _is_key_expired(self, key: str) -> bool:
93
+ """
94
+ Check if a specific key is expired
95
+ """
96
+ return key in self.ttl_dict and time.time() > self.ttl_dict[key]
97
+
98
+ def _remove_key(self, key: str) -> None:
99
+ """
100
+ Remove a key from both cache_dict and ttl_dict
101
+ """
102
+ self.cache_dict.pop(key, None)
103
+ self.ttl_dict.pop(key, None)
104
+
105
+ def evict_cache(self):
106
+ """
107
+ Eviction policy:
108
+ 1. First, remove expired items from ttl_dict and cache_dict
109
+ 2. If cache is still at or above max_size_in_memory, evict items with earliest expiration times
110
+
111
+
112
+ This guarantees the following:
113
+ - 1. When item ttl not set: At minimum each item will remain in memory for the default ttl
114
+ - 2. When ttl is set: the item will remain in memory for at least that amount of time, unless cache size requires eviction
115
+ - 3. the size of in-memory cache is bounded
116
+
117
+ """
118
+ current_time = time.time()
119
+
120
+ # Step 1: Remove expired or outdated items
121
+ while self.expiration_heap:
122
+ expiration_time, key = self.expiration_heap[0]
123
+
124
+ # Case 1: Heap entry is outdated
125
+ if expiration_time != self.ttl_dict.get(key):
126
+ heapq.heappop(self.expiration_heap)
127
+ # Case 2: Entry is valid but expired
128
+ elif expiration_time <= current_time:
129
+ heapq.heappop(self.expiration_heap)
130
+ self._remove_key(key)
131
+ else:
132
+ # Case 3: Entry is valid and not expired
133
+ break
134
+
135
+ # Step 2: Evict if cache is still full
136
+ while len(self.cache_dict) >= self.max_size_in_memory:
137
+ expiration_time, key = heapq.heappop(self.expiration_heap)
138
+ # Skip if key was removed or updated
139
+ if self.ttl_dict.get(key) == expiration_time:
140
+ self._remove_key(key)
141
+
142
+ # de-reference the removed item
143
+ # https://www.geeksforgeeks.org/diagnosing-and-fixing-memory-leaks-in-python/
144
+ # One of the most common causes of memory leaks in Python is the retention of objects that are no longer being used.
145
+ # This can occur when an object is referenced by another object, but the reference is never removed.
146
+
147
+ def allow_ttl_override(self, key: str) -> bool:
148
+ """
149
+ Check if ttl is set for a key
150
+ """
151
+ ttl_time = self.ttl_dict.get(key)
152
+ if ttl_time is None: # if ttl is not set, allow override
153
+ return True
154
+ elif float(ttl_time) < time.time(): # if ttl is expired, allow override
155
+ return True
156
+ else:
157
+ return False
158
+
159
+ def set_cache(self, key, value, **kwargs):
160
+ # Handle the edge case where max_size_in_memory is 0
161
+ if self.max_size_in_memory == 0:
162
+ return # Don't cache anything if max size is 0
163
+
164
+ # Always prune expired/outdated heap roots before inserting.
165
+ # This keeps expiration_heap bounded even when the live cache stays
166
+ # below max_size_in_memory and keys are reinserted after TTL expiry.
167
+ self.evict_cache()
168
+ if not self.check_value_size(value):
169
+ return
170
+
171
+ self.cache_dict[key] = value
172
+ if self.allow_ttl_override(key): # if ttl is not set, set it to default ttl
173
+ if "ttl" in kwargs and kwargs["ttl"] is not None:
174
+ self.ttl_dict[key] = time.time() + float(kwargs["ttl"])
175
+ heapq.heappush(self.expiration_heap, (self.ttl_dict[key], key))
176
+ else:
177
+ self.ttl_dict[key] = time.time() + self.default_ttl
178
+ heapq.heappush(self.expiration_heap, (self.ttl_dict[key], key))
179
+
180
+ async def async_set_cache(self, key, value, **kwargs):
181
+ self.set_cache(key=key, value=value, **kwargs)
182
+
183
+ async def async_set_cache_pipeline(self, cache_list, ttl=None, **kwargs):
184
+ for cache_key, cache_value in cache_list:
185
+ if ttl is not None:
186
+ self.set_cache(key=cache_key, value=cache_value, ttl=ttl)
187
+ else:
188
+ self.set_cache(key=cache_key, value=cache_value)
189
+
190
+ async def async_set_cache_sadd(self, key, value: List, ttl: Optional[float]):
191
+ """
192
+ Add value to set
193
+ """
194
+ # get the value
195
+ init_value = self.get_cache(key=key) or set()
196
+ for val in value:
197
+ init_value.add(val)
198
+ self.set_cache(key, init_value, ttl=ttl)
199
+ return value
200
+
201
+ def evict_element_if_expired(self, key: str) -> bool:
202
+ """
203
+ Returns True if the element is expired and removed from the cache
204
+
205
+ Returns False if the element is not expired
206
+ """
207
+ if self._is_key_expired(key):
208
+ self._remove_key(key)
209
+ return True
210
+ return False
211
+
212
+ def get_cache(self, key, **kwargs):
213
+ if key in self.cache_dict:
214
+ if self.evict_element_if_expired(key):
215
+ return None
216
+ original_cached_response = self.cache_dict[key]
217
+ try:
218
+ cached_response = json.loads(original_cached_response)
219
+ except Exception:
220
+ cached_response = original_cached_response
221
+ return cached_response
222
+ return None
223
+
224
+ def batch_get_cache(self, keys: list, **kwargs):
225
+ return_val = []
226
+ for k in keys:
227
+ val = self.get_cache(key=k, **kwargs)
228
+ return_val.append(val)
229
+ return return_val
230
+
231
+ def increment_cache(self, key, value: int, **kwargs) -> int:
232
+ # get the value
233
+ init_value = self.get_cache(key=key) or 0
234
+ value = init_value + value
235
+ self.set_cache(key, value, **kwargs)
236
+ return value
237
+
238
+ async def async_get_cache(self, key, **kwargs):
239
+ return self.get_cache(key=key, **kwargs)
240
+
241
+ async def async_batch_get_cache(self, keys: list, **kwargs):
242
+ return_val = []
243
+ for k in keys:
244
+ val = self.get_cache(key=k, **kwargs)
245
+ return_val.append(val)
246
+ return return_val
247
+
248
+ async def async_increment(self, key, value: float, **kwargs) -> float:
249
+ # get the value
250
+ init_value = await self.async_get_cache(key=key) or 0
251
+ value = init_value + value
252
+ await self.async_set_cache(key, value, **kwargs)
253
+ return value
254
+
255
+ async def async_increment_pipeline(
256
+ self, increment_list: List["RedisPipelineIncrementOperation"], **kwargs
257
+ ) -> Optional[List[float]]:
258
+ results = []
259
+ for increment in increment_list:
260
+ result = await self.async_increment(
261
+ increment["key"], increment["increment_value"], **kwargs
262
+ )
263
+ results.append(result)
264
+ return results
265
+
266
+ def flush_cache(self):
267
+ self.cache_dict.clear()
268
+ self.ttl_dict.clear()
269
+ self.expiration_heap.clear()
270
+
271
+ async def disconnect(self):
272
+ pass
273
+
274
+ def delete_cache(self, key):
275
+ self._remove_key(key)
276
+
277
+ async def async_get_ttl(self, key: str) -> Optional[int]:
278
+ """
279
+ Get the remaining TTL of a key in in-memory cache
280
+ """
281
+ return self.ttl_dict.get(key, None)
282
+
283
+ async def async_get_oldest_n_keys(self, n: int) -> List[str]:
284
+ """
285
+ Get the oldest n keys in the cache
286
+ """
287
+ # sorted ttl dict by ttl
288
+ sorted_ttl_dict = sorted(self.ttl_dict.items(), key=lambda x: x[1])
289
+ return [key for key, _ in sorted_ttl_dict[:n]]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/llm_caching_handler.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Add the event loop to the cache key, to prevent event loop closed errors.
3
+ """
4
+
5
+ import asyncio
6
+
7
+ from .in_memory_cache import InMemoryCache
8
+
9
+
10
+ class LLMClientCache(InMemoryCache):
11
+ """Cache for LLM HTTP clients (OpenAI, Azure, httpx, etc.).
12
+
13
+ IMPORTANT: This cache intentionally does NOT close clients on eviction.
14
+ Evicted clients may still be in use by in-flight requests. Closing them
15
+ eagerly causes ``RuntimeError: Cannot send a request, as the client has
16
+ been closed.`` errors in production after the TTL (1 hour) expires.
17
+
18
+ Clients that are no longer referenced will be garbage-collected normally.
19
+ For explicit shutdown cleanup, use ``close_litellm_async_clients()``.
20
+ """
21
+
22
+ def update_cache_key_with_event_loop(self, key):
23
+ """
24
+ Add the event loop to the cache key, to prevent event loop closed errors.
25
+ If none, use the key as is.
26
+ """
27
+ try:
28
+ event_loop = asyncio.get_running_loop()
29
+ stringified_event_loop = str(id(event_loop))
30
+ return f"{key}-{stringified_event_loop}"
31
+ except RuntimeError: # handle no current running event loop
32
+ return key
33
+
34
+ def set_cache(self, key, value, **kwargs):
35
+ key = self.update_cache_key_with_event_loop(key)
36
+ return super().set_cache(key, value, **kwargs)
37
+
38
+ async def async_set_cache(self, key, value, **kwargs):
39
+ key = self.update_cache_key_with_event_loop(key)
40
+ return await super().async_set_cache(key, value, **kwargs)
41
+
42
+ def get_cache(self, key, **kwargs):
43
+ key = self.update_cache_key_with_event_loop(key)
44
+
45
+ return super().get_cache(key, **kwargs)
46
+
47
+ async def async_get_cache(self, key, **kwargs):
48
+ key = self.update_cache_key_with_event_loop(key)
49
+
50
+ return await super().async_get_cache(key, **kwargs)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/qdrant_semantic_cache.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qdrant Semantic Cache implementation
3
+
4
+ Has 4 methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ import ast
12
+ import asyncio
13
+ import json
14
+ import os
15
+ from typing import Any, Dict, cast
16
+
17
+ import litellm
18
+ from litellm._logging import print_verbose
19
+ from litellm.constants import QDRANT_SCALAR_QUANTILE, QDRANT_VECTOR_SIZE
20
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
21
+ get_str_from_messages,
22
+ )
23
+ from litellm.types.utils import EmbeddingResponse
24
+
25
+ from .base_cache import BaseCache
26
+
27
+
28
+ class QdrantSemanticCache(BaseCache):
29
+ CACHE_KEY_FIELD_NAME = "litellm_cache_key"
30
+
31
+ def __init__( # noqa: PLR0915
32
+ self,
33
+ qdrant_api_base=None,
34
+ qdrant_api_key=None,
35
+ collection_name=None,
36
+ similarity_threshold=None,
37
+ quantization_config=None,
38
+ embedding_model="text-embedding-ada-002",
39
+ host_type=None,
40
+ vector_size=None,
41
+ ):
42
+ from litellm.llms.custom_httpx.http_handler import (
43
+ _get_httpx_client,
44
+ get_async_httpx_client,
45
+ httpxSpecialProvider,
46
+ )
47
+ from litellm.secret_managers.main import get_secret_str
48
+
49
+ if collection_name is None:
50
+ raise Exception("collection_name must be provided, passed None")
51
+
52
+ self.collection_name = collection_name
53
+ print_verbose(
54
+ f"qdrant semantic-cache initializing COLLECTION - {self.collection_name}"
55
+ )
56
+
57
+ if similarity_threshold is None:
58
+ raise Exception("similarity_threshold must be provided, passed None")
59
+ self.similarity_threshold = similarity_threshold
60
+ self.embedding_model = embedding_model
61
+ self.vector_size = (
62
+ vector_size if vector_size is not None else QDRANT_VECTOR_SIZE
63
+ )
64
+ headers = {}
65
+
66
+ # check if defined as os.environ/ variable
67
+ if qdrant_api_base:
68
+ if isinstance(qdrant_api_base, str) and qdrant_api_base.startswith(
69
+ "os.environ/"
70
+ ):
71
+ qdrant_api_base = get_secret_str(qdrant_api_base)
72
+ if qdrant_api_key:
73
+ if isinstance(qdrant_api_key, str) and qdrant_api_key.startswith(
74
+ "os.environ/"
75
+ ):
76
+ qdrant_api_key = get_secret_str(qdrant_api_key)
77
+
78
+ qdrant_api_base = (
79
+ qdrant_api_base or os.getenv("QDRANT_URL") or os.getenv("QDRANT_API_BASE")
80
+ )
81
+ qdrant_api_key = qdrant_api_key or os.getenv("QDRANT_API_KEY")
82
+ headers = {"Content-Type": "application/json"}
83
+ if qdrant_api_key:
84
+ headers["api-key"] = qdrant_api_key
85
+
86
+ if qdrant_api_base is None:
87
+ raise ValueError("Qdrant url must be provided")
88
+
89
+ self.qdrant_api_base = qdrant_api_base
90
+ self.qdrant_api_key = qdrant_api_key
91
+ print_verbose(f"qdrant semantic-cache qdrant_api_base: {self.qdrant_api_base}")
92
+
93
+ self.headers = headers
94
+
95
+ self.sync_client = _get_httpx_client()
96
+ self.async_client = get_async_httpx_client(
97
+ llm_provider=httpxSpecialProvider.Caching
98
+ )
99
+
100
+ if quantization_config is None:
101
+ print_verbose(
102
+ "Quantization config is not provided. Default binary quantization will be used."
103
+ )
104
+ collection_exists = self.sync_client.get(
105
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/exists",
106
+ headers=self.headers,
107
+ )
108
+ if collection_exists.status_code != 200:
109
+ raise ValueError(
110
+ f"Error from qdrant checking if /collections exist {collection_exists.text}"
111
+ )
112
+
113
+ if collection_exists.json()["result"]["exists"]:
114
+ collection_details = self.sync_client.get(
115
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}",
116
+ headers=self.headers,
117
+ )
118
+ self.collection_info = collection_details.json()
119
+ print_verbose(
120
+ f"Collection already exists.\nCollection details:{self.collection_info}"
121
+ )
122
+ self._ensure_cache_key_payload_index()
123
+ else:
124
+ quantization_params: Dict[str, Any]
125
+ if quantization_config is None or quantization_config == "binary":
126
+ quantization_params = {
127
+ "binary": {
128
+ "always_ram": False,
129
+ }
130
+ }
131
+ elif quantization_config == "scalar":
132
+ quantization_params = {
133
+ "scalar": {
134
+ "type": "int8",
135
+ "quantile": QDRANT_SCALAR_QUANTILE,
136
+ "always_ram": False,
137
+ }
138
+ }
139
+ elif quantization_config == "product":
140
+ quantization_params = {
141
+ "product": {"compression": "x16", "always_ram": False}
142
+ }
143
+ else:
144
+ raise Exception(
145
+ "Quantization config must be one of 'scalar', 'binary' or 'product'"
146
+ )
147
+
148
+ new_collection_status = self.sync_client.put(
149
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}",
150
+ json={
151
+ "vectors": {"size": self.vector_size, "distance": "Cosine"},
152
+ "quantization_config": quantization_params,
153
+ },
154
+ headers=self.headers,
155
+ )
156
+ if new_collection_status.json()["result"]:
157
+ collection_details = self.sync_client.get(
158
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}",
159
+ headers=self.headers,
160
+ )
161
+ self.collection_info = collection_details.json()
162
+ print_verbose(
163
+ f"New collection created.\nCollection details:{self.collection_info}"
164
+ )
165
+ self._ensure_cache_key_payload_index()
166
+ else:
167
+ raise Exception("Error while creating new collection")
168
+
169
+ def _get_cache_logic(self, cached_response: Any):
170
+ if cached_response is None:
171
+ return cached_response
172
+ try:
173
+ cached_response = json.loads(
174
+ cached_response
175
+ ) # Convert string to dictionary
176
+ except Exception:
177
+ cached_response = ast.literal_eval(cached_response)
178
+ return cached_response
179
+
180
+ def _get_qdrant_cache_key_filter(self, key: str) -> dict:
181
+ return {
182
+ "must": [
183
+ {
184
+ "key": self.CACHE_KEY_FIELD_NAME,
185
+ "match": {"value": str(key)},
186
+ }
187
+ ]
188
+ }
189
+
190
+ def _add_cache_key_filter_to_search_data(self, data: dict, key: str) -> None:
191
+ data["filter"] = self._get_qdrant_cache_key_filter(key)
192
+
193
+ def _ensure_cache_key_payload_index(self) -> None:
194
+ try:
195
+ response = self.sync_client.put(
196
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/index",
197
+ headers=self.headers,
198
+ json={
199
+ "field_name": self.CACHE_KEY_FIELD_NAME,
200
+ "field_schema": "keyword",
201
+ },
202
+ )
203
+ if response.status_code not in (200, 201):
204
+ print_verbose(
205
+ "Qdrant semantic-cache could not create cache-key payload index: "
206
+ f"{response.text}"
207
+ )
208
+ except Exception as exc:
209
+ print_verbose(
210
+ "Qdrant semantic-cache could not create cache-key payload index: "
211
+ f"{str(exc)}"
212
+ )
213
+
214
+ def _payload_matches_cache_key(self, payload: dict, key: str) -> bool:
215
+ # Pre-isolation points stored only prompt + response with no cache-key
216
+ # payload field. Reassigning them to a caller's key would risk
217
+ # cross-scope hits, so they're treated as misses and re-populated on
218
+ # the next set_cache.
219
+ cached_key = payload.get(self.CACHE_KEY_FIELD_NAME)
220
+ return cached_key is not None and str(cached_key) == str(key)
221
+
222
+ async def _get_async_embedding(self, prompt: str, **kwargs) -> Any:
223
+ llm_model_list = None
224
+ llm_router = None
225
+
226
+ try:
227
+ from litellm.proxy.proxy_server import (
228
+ llm_model_list as proxy_llm_model_list,
229
+ llm_router as proxy_llm_router,
230
+ )
231
+
232
+ llm_model_list = proxy_llm_model_list
233
+ llm_router = proxy_llm_router
234
+ except ImportError:
235
+ pass
236
+
237
+ router_model_names = (
238
+ [m["model_name"] for m in llm_model_list]
239
+ if llm_model_list is not None
240
+ else []
241
+ )
242
+ if llm_router is not None and self.embedding_model in router_model_names:
243
+ user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
244
+ return await llm_router.aembedding(
245
+ model=self.embedding_model,
246
+ input=prompt,
247
+ cache={"no-store": True, "no-cache": True},
248
+ metadata={
249
+ "user_api_key": user_api_key,
250
+ "semantic-cache-embedding": True,
251
+ "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
252
+ },
253
+ )
254
+
255
+ return await litellm.aembedding(
256
+ model=self.embedding_model,
257
+ input=prompt,
258
+ cache={"no-store": True, "no-cache": True},
259
+ )
260
+
261
+ def set_cache(self, key, value, **kwargs):
262
+ print_verbose(f"qdrant semantic-cache set_cache, kwargs: {kwargs}")
263
+ from litellm._uuid import uuid
264
+
265
+ # get the prompt
266
+ messages = kwargs["messages"]
267
+ prompt = get_str_from_messages(messages)
268
+
269
+ # create an embedding for prompt
270
+ embedding_response = cast(
271
+ EmbeddingResponse,
272
+ litellm.embedding(
273
+ model=self.embedding_model,
274
+ input=prompt,
275
+ cache={"no-store": True, "no-cache": True},
276
+ ),
277
+ )
278
+
279
+ # get the embedding
280
+ embedding = embedding_response["data"][0]["embedding"]
281
+
282
+ value = str(value)
283
+ assert isinstance(value, str)
284
+
285
+ data = {
286
+ "points": [
287
+ {
288
+ "id": str(uuid.uuid4()),
289
+ "vector": embedding,
290
+ "payload": {
291
+ self.CACHE_KEY_FIELD_NAME: str(key),
292
+ "text": prompt,
293
+ "response": value,
294
+ },
295
+ },
296
+ ]
297
+ }
298
+ self.sync_client.put(
299
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points",
300
+ headers=self.headers,
301
+ json=data,
302
+ )
303
+ return
304
+
305
+ def get_cache(self, key, **kwargs):
306
+ print_verbose(f"sync qdrant semantic-cache get_cache, kwargs: {kwargs}")
307
+
308
+ # get the messages
309
+ messages = kwargs["messages"]
310
+ prompt = get_str_from_messages(messages)
311
+
312
+ # convert to embedding
313
+ embedding_response = cast(
314
+ EmbeddingResponse,
315
+ litellm.embedding(
316
+ model=self.embedding_model,
317
+ input=prompt,
318
+ cache={"no-store": True, "no-cache": True},
319
+ ),
320
+ )
321
+
322
+ # get the embedding
323
+ embedding = embedding_response["data"][0]["embedding"]
324
+
325
+ data = {
326
+ "vector": embedding,
327
+ "params": {
328
+ "quantization": {
329
+ "ignore": False,
330
+ "rescore": True,
331
+ "oversampling": 3.0,
332
+ }
333
+ },
334
+ "limit": 1,
335
+ "with_payload": True,
336
+ }
337
+ self._add_cache_key_filter_to_search_data(data=data, key=key)
338
+
339
+ search_response = self.sync_client.post(
340
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points/search",
341
+ headers=self.headers,
342
+ json=data,
343
+ )
344
+ results = search_response.json()["result"]
345
+
346
+ if results is None:
347
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
348
+ return None
349
+ if isinstance(results, list):
350
+ if len(results) == 0:
351
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
352
+ return None
353
+
354
+ similarity = results[0]["score"]
355
+ payload = results[0]["payload"]
356
+ if not self._payload_matches_cache_key(payload=payload, key=key):
357
+ print_verbose("Qdrant semantic-cache hit did not match cache key scope")
358
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
359
+ return None
360
+
361
+ cached_prompt = payload["text"]
362
+
363
+ # check similarity, if more than self.similarity_threshold, return results
364
+ print_verbose(
365
+ f"semantic cache: similarity threshold: {self.similarity_threshold}, similarity: {similarity}, prompt: {prompt}, closest_cached_prompt: {cached_prompt}"
366
+ )
367
+
368
+ # update kwargs["metadata"] with similarity, don't rewrite the original metadata
369
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity
370
+
371
+ if similarity >= self.similarity_threshold:
372
+ # cache hit !
373
+ cached_value = payload["response"]
374
+ print_verbose(
375
+ f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}"
376
+ )
377
+ return self._get_cache_logic(cached_response=cached_value)
378
+ else:
379
+ # cache miss !
380
+ return None
381
+ pass
382
+
383
+ async def async_set_cache(self, key, value, **kwargs):
384
+ from litellm._uuid import uuid
385
+
386
+ print_verbose(f"async qdrant semantic-cache set_cache, kwargs: {kwargs}")
387
+
388
+ # get the prompt
389
+ messages = kwargs["messages"]
390
+ prompt = get_str_from_messages(messages)
391
+ embedding_response = await self._get_async_embedding(prompt, **kwargs)
392
+
393
+ # get the embedding
394
+ embedding = embedding_response["data"][0]["embedding"]
395
+
396
+ value = str(value)
397
+ assert isinstance(value, str)
398
+
399
+ data = {
400
+ "points": [
401
+ {
402
+ "id": str(uuid.uuid4()),
403
+ "vector": embedding,
404
+ "payload": {
405
+ self.CACHE_KEY_FIELD_NAME: str(key),
406
+ "text": prompt,
407
+ "response": value,
408
+ },
409
+ },
410
+ ]
411
+ }
412
+
413
+ await self.async_client.put(
414
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points",
415
+ headers=self.headers,
416
+ json=data,
417
+ )
418
+ return
419
+
420
+ async def async_get_cache(self, key, **kwargs):
421
+ print_verbose(f"async qdrant semantic-cache get_cache, kwargs: {kwargs}")
422
+
423
+ # get the messages
424
+ messages = kwargs["messages"]
425
+ prompt = get_str_from_messages(messages)
426
+
427
+ embedding_response = await self._get_async_embedding(prompt, **kwargs)
428
+
429
+ # get the embedding
430
+ embedding = embedding_response["data"][0]["embedding"]
431
+
432
+ data = {
433
+ "vector": embedding,
434
+ "params": {
435
+ "quantization": {
436
+ "ignore": False,
437
+ "rescore": True,
438
+ "oversampling": 3.0,
439
+ }
440
+ },
441
+ "limit": 1,
442
+ "with_payload": True,
443
+ }
444
+ self._add_cache_key_filter_to_search_data(data=data, key=key)
445
+
446
+ search_response = await self.async_client.post(
447
+ url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points/search",
448
+ headers=self.headers,
449
+ json=data,
450
+ )
451
+
452
+ results = search_response.json()["result"]
453
+
454
+ if results is None:
455
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
456
+ return None
457
+ if isinstance(results, list):
458
+ if len(results) == 0:
459
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
460
+ return None
461
+
462
+ similarity = results[0]["score"]
463
+ payload = results[0]["payload"]
464
+ if not self._payload_matches_cache_key(payload=payload, key=key):
465
+ print_verbose("Qdrant semantic-cache hit did not match cache key scope")
466
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
467
+ return None
468
+
469
+ cached_prompt = payload["text"]
470
+
471
+ # check similarity, if more than self.similarity_threshold, return results
472
+ print_verbose(
473
+ f"semantic cache: similarity threshold: {self.similarity_threshold}, similarity: {similarity}, prompt: {prompt}, closest_cached_prompt: {cached_prompt}"
474
+ )
475
+
476
+ # update kwargs["metadata"] with similarity, don't rewrite the original metadata
477
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity
478
+
479
+ if similarity >= self.similarity_threshold:
480
+ # cache hit !
481
+ cached_value = payload["response"]
482
+ print_verbose(
483
+ f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}"
484
+ )
485
+ return self._get_cache_logic(cached_response=cached_value)
486
+ else:
487
+ # cache miss !
488
+ return None
489
+ pass
490
+
491
+ async def _collection_info(self):
492
+ return self.collection_info
493
+
494
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
495
+ tasks = []
496
+ for val in cache_list:
497
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
498
+ await asyncio.gather(*tasks)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cache.py ADDED
@@ -0,0 +1,1710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Redis Cache implementation
3
+
4
+ Has 4 primary methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache
8
+ - async_get_cache
9
+ """
10
+
11
+ import ast
12
+ import asyncio
13
+ import functools
14
+ import hashlib
15
+ import inspect
16
+ import json
17
+ import time
18
+ from datetime import timedelta
19
+ from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast
20
+
21
+ import litellm
22
+ from litellm._logging import print_verbose, verbose_logger
23
+ from litellm.constants import (
24
+ DEFAULT_REDIS_MAJOR_VERSION,
25
+ REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD,
26
+ REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT,
27
+ )
28
+ from litellm.litellm_core_utils.core_helpers import _get_parent_otel_span_from_kwargs
29
+ from litellm.litellm_core_utils.coroutine_checker import coroutine_checker
30
+ from litellm.types.caching import (
31
+ RedisPipelineIncrementOperation,
32
+ RedisPipelineLpopOperation,
33
+ RedisPipelineRpushOperation,
34
+ )
35
+ from litellm.types.services import ServiceTypes
36
+
37
+ from .base_cache import BaseCache
38
+
39
+ if TYPE_CHECKING:
40
+ from opentelemetry.trace import Span as _Span
41
+ from redis.asyncio import Redis, RedisCluster
42
+ from redis.asyncio.client import Pipeline
43
+ from redis.asyncio.cluster import ClusterPipeline
44
+
45
+ pipeline = Pipeline
46
+ cluster_pipeline = ClusterPipeline
47
+ async_redis_client = Redis
48
+ async_redis_cluster_client = RedisCluster
49
+ Span = Union[_Span, Any]
50
+ else:
51
+ pipeline = Any
52
+ cluster_pipeline = Any
53
+ async_redis_client = Any
54
+ async_redis_cluster_client = Any
55
+ Span = Any
56
+
57
+
58
+ def _get_call_stack_info(num_frames: int = 2) -> str:
59
+ """
60
+ Get the function names from the previous 1-2 functions in the call stack.
61
+
62
+ Args:
63
+ num_frames: Number of previous frames to include (default: 2)
64
+
65
+ Returns:
66
+ A string with format "current_function <- caller_function [<- grandparent_function]"
67
+ """
68
+ try:
69
+ current_frame = inspect.currentframe()
70
+ if current_frame is None:
71
+ return "unknown"
72
+
73
+ # Skip this function and the immediate caller (which sets call_type)
74
+ f_back = current_frame.f_back
75
+ if f_back is None:
76
+ return "unknown"
77
+ frame = f_back.f_back
78
+ if frame is None:
79
+ return "unknown"
80
+ function_names = []
81
+
82
+ for _ in range(num_frames):
83
+ if frame is None:
84
+ break
85
+ func_name = frame.f_code.co_name
86
+ function_names.append(func_name)
87
+ frame = frame.f_back
88
+
89
+ if not function_names:
90
+ return "unknown"
91
+
92
+ return " <- ".join(function_names)
93
+ except Exception:
94
+ return "unknown"
95
+
96
+
97
+ class RedisCircuitBreaker:
98
+ """
99
+ Tracks Redis health for a RedisCache instance.
100
+
101
+ States:
102
+ CLOSED - normal, Redis is called
103
+ OPEN - Redis is down, raise immediately (no network call)
104
+ HALF_OPEN - recovery probe: allow one request through
105
+
106
+ Transitions:
107
+ CLOSED -> OPEN after failure_threshold consecutive failures
108
+ OPEN -> HALF_OPEN after recovery_timeout seconds
109
+ HALF_OPEN -> CLOSED on success
110
+ HALF_OPEN -> OPEN on failure (resets timer)
111
+ """
112
+
113
+ CLOSED = "closed"
114
+ OPEN = "open"
115
+ HALF_OPEN = "half_open"
116
+
117
+ def __init__(self, failure_threshold: int, recovery_timeout: int) -> None:
118
+ self.failure_threshold = failure_threshold
119
+ self.recovery_timeout = recovery_timeout
120
+ self._failure_count = 0
121
+ self._opened_at: Optional[float] = None
122
+ self._state = self.CLOSED
123
+
124
+ def is_open(self) -> bool:
125
+ """Returns True if Redis calls should be skipped."""
126
+ if self._state == self.HALF_OPEN:
127
+ # Probe already in flight — fast-fail all concurrent requests.
128
+ # Only the one call that caused the OPEN→HALF_OPEN transition
129
+ # (which returned False) is the designated probe.
130
+ return True
131
+ if self._state == self.OPEN:
132
+ if time.time() - (self._opened_at or 0) > self.recovery_timeout:
133
+ self._state = self.HALF_OPEN
134
+ return False # this caller is the designated probe
135
+ return True
136
+ return False
137
+
138
+ def record_failure(self) -> None:
139
+ self._failure_count += 1
140
+ self._opened_at = time.time()
141
+ if self._failure_count >= self.failure_threshold:
142
+ if self._state != self.OPEN:
143
+ verbose_logger.warning(
144
+ "Redis circuit breaker OPENED after %d consecutive failures — "
145
+ "fast-failing Redis calls for %ds",
146
+ self._failure_count,
147
+ self.recovery_timeout,
148
+ )
149
+ self._state = self.OPEN
150
+
151
+ def record_success(self) -> None:
152
+ if self._state == self.HALF_OPEN:
153
+ verbose_logger.info("Redis circuit breaker CLOSED — Redis recovered")
154
+ self._failure_count = 0
155
+ self._state = self.CLOSED
156
+
157
+
158
+ def _redis_circuit_breaker_guard(method): # type: ignore
159
+ """
160
+ Decorator for RedisCache async methods.
161
+ Checks the circuit breaker before each call; records success/failure after.
162
+ Does not apply to ping/disconnect/test_connection (health/teardown must always run).
163
+ """
164
+
165
+ @functools.wraps(method)
166
+ async def wrapper(self, *args, **kwargs): # type: ignore
167
+ if self._circuit_breaker.is_open():
168
+ raise Exception(
169
+ f"Redis circuit breaker is open — skipping {method.__name__}"
170
+ )
171
+ try:
172
+ result = await method(self, *args, **kwargs)
173
+ self._circuit_breaker.record_success()
174
+ return result
175
+ except Exception:
176
+ self._circuit_breaker.record_failure()
177
+ raise
178
+
179
+ return wrapper
180
+
181
+
182
+ class RedisCache(BaseCache):
183
+ # if users don't provider one, use the default litellm cache
184
+
185
+ def __init__(
186
+ self,
187
+ host=None,
188
+ port=None,
189
+ password=None,
190
+ redis_flush_size: Optional[int] = 100,
191
+ namespace: Optional[str] = None,
192
+ startup_nodes: Optional[List] = None, # for redis-cluster
193
+ socket_timeout: Optional[float] = 5.0, # default 5 second timeout
194
+ **kwargs,
195
+ ):
196
+ from litellm._service_logger import ServiceLogging
197
+
198
+ from .._redis import get_redis_client, get_redis_connection_pool
199
+
200
+ redis_kwargs = {}
201
+ if host is not None:
202
+ redis_kwargs["host"] = host
203
+ if port is not None:
204
+ redis_kwargs["port"] = port
205
+ if password is not None:
206
+ redis_kwargs["password"] = password
207
+ if startup_nodes is not None:
208
+ redis_kwargs["startup_nodes"] = startup_nodes
209
+ if socket_timeout is not None:
210
+ redis_kwargs["socket_timeout"] = socket_timeout
211
+
212
+ ### HEALTH MONITORING OBJECT ###
213
+ if kwargs.get("service_logger_obj", None) is not None and isinstance(
214
+ kwargs["service_logger_obj"], ServiceLogging
215
+ ):
216
+ self.service_logger_obj = kwargs.pop("service_logger_obj")
217
+ else:
218
+ self.service_logger_obj = ServiceLogging()
219
+
220
+ redis_kwargs.update(kwargs)
221
+ self.redis_client = get_redis_client(**redis_kwargs)
222
+ self.redis_async_client: Optional[
223
+ Union[async_redis_client, async_redis_cluster_client]
224
+ ] = None
225
+ self.redis_kwargs = redis_kwargs
226
+ self.async_redis_conn_pool = get_redis_connection_pool(**redis_kwargs)
227
+
228
+ # redis namespaces
229
+ self.namespace = namespace
230
+ # for high traffic, we store the redis results in memory and then batch write to redis
231
+ self.redis_batch_writing_buffer: list = []
232
+ if redis_flush_size is None:
233
+ self.redis_flush_size: int = 100
234
+ else:
235
+ self.redis_flush_size = redis_flush_size
236
+ self.redis_version = "Unknown"
237
+ try:
238
+ if not coroutine_checker.is_async_callable(self.redis_client):
239
+ self.redis_version = self.redis_client.info()["redis_version"] # type: ignore
240
+ except Exception:
241
+ pass
242
+
243
+ self._circuit_breaker = RedisCircuitBreaker(
244
+ failure_threshold=REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD,
245
+ recovery_timeout=REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT,
246
+ )
247
+
248
+ self._setup_health_pings()
249
+
250
+ if litellm.default_redis_ttl is not None:
251
+ super().__init__(default_ttl=int(litellm.default_redis_ttl))
252
+ else:
253
+ super().__init__() # defaults to 60s
254
+
255
+ def _setup_health_pings(self):
256
+ """Setup async and sync health pings for Redis."""
257
+ # ASYNC HEALTH PING
258
+ try:
259
+ _ = asyncio.get_running_loop().create_task(self.ping())
260
+ except Exception as e:
261
+ if "no running event loop" in str(e):
262
+ verbose_logger.debug(
263
+ "Ignoring async redis ping. No running event loop."
264
+ )
265
+ else:
266
+ verbose_logger.error(
267
+ "Error connecting to Async Redis client - {}".format(str(e)),
268
+ extra={"error": str(e)},
269
+ )
270
+ self._handle_async_ping_error(e)
271
+
272
+ # SYNC HEALTH PING
273
+ try:
274
+ if hasattr(self.redis_client, "ping"):
275
+ self.redis_client.ping() # type: ignore
276
+ except Exception as e:
277
+ verbose_logger.error(
278
+ "Error connecting to Sync Redis client", extra={"error": str(e)}
279
+ )
280
+ self._handle_sync_ping_error(e)
281
+
282
+ def _handle_async_ping_error(self, e: Exception):
283
+ """Handle async ping error with service failure hook."""
284
+ try:
285
+ loop = asyncio.get_running_loop()
286
+ start_time = time.time()
287
+ end_time = start_time
288
+ loop.create_task(
289
+ self.service_logger_obj.async_service_failure_hook(
290
+ service=ServiceTypes.REDIS,
291
+ duration=end_time - start_time,
292
+ error=e,
293
+ call_type="redis_async_ping",
294
+ )
295
+ )
296
+ except Exception:
297
+ pass
298
+
299
+ def _handle_sync_ping_error(self, e: Exception):
300
+ """Handle sync ping error with service failure hook."""
301
+ try:
302
+ loop = asyncio.get_running_loop()
303
+ start_time = time.time()
304
+ end_time = start_time
305
+ loop.create_task(
306
+ self.service_logger_obj.async_service_failure_hook(
307
+ service=ServiceTypes.REDIS,
308
+ duration=end_time - start_time,
309
+ error=e,
310
+ call_type="redis_sync_ping",
311
+ )
312
+ )
313
+ except Exception:
314
+ pass
315
+
316
+ def _get_async_client_cache_key(self) -> str:
317
+ """
318
+ Generate a cache key for the async Redis client based on connection parameters.
319
+ This ensures different Redis configurations use different cached clients.
320
+ """
321
+ # Create a stable representation of redis_kwargs for hashing
322
+ # Sort keys to ensure consistent hash regardless of parameter order
323
+ sorted_kwargs = sorted(self.redis_kwargs.items())
324
+ kwargs_str = json.dumps(sorted_kwargs, sort_keys=True)
325
+ kwargs_hash = hashlib.sha256(kwargs_str.encode()).hexdigest()[:16]
326
+ return f"async-redis-client-{kwargs_hash}"
327
+
328
+ def init_async_client(
329
+ self,
330
+ ) -> Union[async_redis_client, async_redis_cluster_client]:
331
+ from litellm import in_memory_llm_clients_cache
332
+
333
+ from .._redis import get_redis_async_client, get_redis_connection_pool
334
+
335
+ cache_key = self._get_async_client_cache_key()
336
+ cached_client = in_memory_llm_clients_cache.get_cache(key=cache_key)
337
+ if cached_client is not None:
338
+ redis_async_client = cast(
339
+ Union[async_redis_client, async_redis_cluster_client], cached_client
340
+ )
341
+ else:
342
+ # Create new connection pool and client for current event loop
343
+ self.async_redis_conn_pool = get_redis_connection_pool(**self.redis_kwargs)
344
+ redis_async_client = get_redis_async_client(
345
+ connection_pool=self.async_redis_conn_pool, **self.redis_kwargs
346
+ )
347
+ in_memory_llm_clients_cache.set_cache(
348
+ key=cache_key, value=redis_async_client
349
+ )
350
+
351
+ self.redis_async_client = redis_async_client # type: ignore
352
+ return redis_async_client
353
+
354
+ def check_and_fix_namespace(self, key: str) -> str:
355
+ """
356
+ Make sure each key starts with the given namespace
357
+ """
358
+ if self.namespace is not None and not key.startswith(self.namespace):
359
+ key = self.namespace + ":" + key
360
+
361
+ return key
362
+
363
+ def _parse_redis_major_version(self) -> int:
364
+ """
365
+ Parse Redis version to extract the major version number.
366
+
367
+ Handles multiple version formats:
368
+ - Strings: "7.0.0", "6", "7.0.0-rc1", " 7.0.0 "
369
+ - Floats: 7.0 (e.g., from AWS ElastiCache Valkey)
370
+ - Integers: 7
371
+ - Malformed: "latest", "", "Unknown" (defaults to DEFAULT_REDIS_MAJOR_VERSION)
372
+
373
+ Returns:
374
+ int: The major version number (defaults to DEFAULT_REDIS_MAJOR_VERSION if unparseable)
375
+ """
376
+ if self.redis_version == "Unknown":
377
+ return DEFAULT_REDIS_MAJOR_VERSION
378
+
379
+ try:
380
+ version_str = str(self.redis_version).strip()
381
+ # Handle cases where there's no dot (e.g., "7" or 7)
382
+ if "." in version_str:
383
+ major_version = int(version_str.split(".")[0])
384
+ else:
385
+ # Direct integer or single-digit string
386
+ major_version = int(float(version_str))
387
+ return major_version
388
+ except (ValueError, AttributeError):
389
+ # Fallback for unparseable versions (e.g., "v7.0.0", "latest")
390
+ return DEFAULT_REDIS_MAJOR_VERSION
391
+
392
+ def set_cache(self, key, value, **kwargs):
393
+ ttl = self.get_ttl(**kwargs)
394
+ print_verbose(
395
+ f"Set Redis Cache: key: {key}\nValue {value}\nttl={ttl}, redis_version={self.redis_version}"
396
+ )
397
+ key = self.check_and_fix_namespace(key=key)
398
+ try:
399
+ start_time = time.time()
400
+ self.redis_client.set(name=key, value=str(value), ex=ttl)
401
+ end_time = time.time()
402
+ _duration = end_time - start_time
403
+ self.service_logger_obj.service_success_hook(
404
+ service=ServiceTypes.REDIS,
405
+ duration=_duration,
406
+ call_type=f"set_cache <- {_get_call_stack_info()}",
407
+ start_time=start_time,
408
+ end_time=end_time,
409
+ )
410
+ except Exception as e:
411
+ # NON blocking - notify users Redis is throwing an exception
412
+ print_verbose(
413
+ f"litellm.caching.caching: set() - Got exception from REDIS : {str(e)}"
414
+ )
415
+
416
+ def increment_cache(
417
+ self, key, value: int, ttl: Optional[float] = None, **kwargs
418
+ ) -> int:
419
+ _redis_client = self.redis_client
420
+ start_time = time.time()
421
+ set_ttl = self.get_ttl(ttl=ttl)
422
+ try:
423
+ start_time = time.time()
424
+ result: int = _redis_client.incr(name=key, amount=value) # type: ignore
425
+ end_time = time.time()
426
+ _duration = end_time - start_time
427
+ self.service_logger_obj.service_success_hook(
428
+ service=ServiceTypes.REDIS,
429
+ duration=_duration,
430
+ call_type=f"increment_cache <- {_get_call_stack_info()}",
431
+ start_time=start_time,
432
+ end_time=end_time,
433
+ )
434
+
435
+ if set_ttl is not None:
436
+ # check if key already has ttl, if not -> set ttl
437
+ start_time = time.time()
438
+ current_ttl = _redis_client.ttl(key)
439
+ end_time = time.time()
440
+ _duration = end_time - start_time
441
+ self.service_logger_obj.service_success_hook(
442
+ service=ServiceTypes.REDIS,
443
+ duration=_duration,
444
+ call_type=f"increment_cache_ttl <- {_get_call_stack_info()}",
445
+ start_time=start_time,
446
+ end_time=end_time,
447
+ )
448
+ if current_ttl == -1:
449
+ # Key has no expiration
450
+ start_time = time.time()
451
+ _redis_client.expire(key, set_ttl) # type: ignore
452
+ end_time = time.time()
453
+ _duration = end_time - start_time
454
+ self.service_logger_obj.service_success_hook(
455
+ service=ServiceTypes.REDIS,
456
+ duration=_duration,
457
+ call_type=f"increment_cache_expire <- {_get_call_stack_info()}",
458
+ start_time=start_time,
459
+ end_time=end_time,
460
+ )
461
+ return result
462
+ except Exception as e:
463
+ ## LOGGING ##
464
+ end_time = time.time()
465
+ _duration = end_time - start_time
466
+ verbose_logger.error(
467
+ "LiteLLM Redis Caching: increment_cache() - Got exception from REDIS %s, Writing value=%s",
468
+ str(e),
469
+ value,
470
+ )
471
+ raise e
472
+
473
+ @_redis_circuit_breaker_guard
474
+ async def async_scan_iter(self, pattern: str, count: int = 100) -> list:
475
+ start_time = time.time()
476
+ try:
477
+ keys = []
478
+ _redis_client = self.init_async_client()
479
+ if not hasattr(_redis_client, "scan_iter"):
480
+ verbose_logger.debug(
481
+ "Redis client does not support scan_iter, potentially using Redis Cluster. Returning empty list."
482
+ )
483
+ return []
484
+
485
+ async for key in _redis_client.scan_iter(match=pattern + "*", count=count): # type: ignore
486
+ keys.append(key)
487
+ if len(keys) >= count:
488
+ break
489
+
490
+ ## LOGGING ##
491
+ end_time = time.time()
492
+ _duration = end_time - start_time
493
+ asyncio.create_task(
494
+ self.service_logger_obj.async_service_success_hook(
495
+ service=ServiceTypes.REDIS,
496
+ duration=_duration,
497
+ call_type=f"async_scan_iter <- {_get_call_stack_info()}",
498
+ start_time=start_time,
499
+ end_time=end_time,
500
+ )
501
+ ) # DO NOT SLOW DOWN CALL B/C OF THIS
502
+ return keys
503
+ except Exception as e:
504
+ # NON blocking - notify users Redis is throwing an exception
505
+ ## LOGGING ##
506
+ end_time = time.time()
507
+ _duration = end_time - start_time
508
+ asyncio.create_task(
509
+ self.service_logger_obj.async_service_failure_hook(
510
+ service=ServiceTypes.REDIS,
511
+ duration=_duration,
512
+ error=e,
513
+ call_type=f"async_scan_iter <- {_get_call_stack_info()}",
514
+ start_time=start_time,
515
+ end_time=end_time,
516
+ )
517
+ )
518
+ raise e
519
+
520
+ def async_register_script(self, script: str) -> Any:
521
+ """
522
+ Register a Lua script with Redis asynchronously.
523
+ Works with both standalone Redis and Redis Cluster.
524
+
525
+ Args:
526
+ script (str): The Lua script to register
527
+
528
+ Returns:
529
+ Any: A script object that can be called with keys and args
530
+ """
531
+ try:
532
+ _redis_client = self.init_async_client()
533
+ # For standalone Redis
534
+ if hasattr(_redis_client, "register_script"):
535
+ return _redis_client.register_script(script) # type: ignore
536
+ # For Redis Cluster
537
+ elif hasattr(_redis_client, "script_load"):
538
+ # Load the script and get its SHA
539
+ script_sha = _redis_client.script_load(script) # type: ignore
540
+
541
+ # Return a callable that uses evalsha
542
+ async def script_callable(keys: List[str], args: List[Any]) -> Any:
543
+ return _redis_client.evalsha(script_sha, len(keys), *keys, *args) # type: ignore
544
+
545
+ return script_callable
546
+ except Exception as e:
547
+ verbose_logger.error(f"Error registering Redis script: {str(e)}")
548
+ raise e
549
+
550
+ @_redis_circuit_breaker_guard
551
+ async def async_set_cache(self, key, value, **kwargs):
552
+ from redis.asyncio import Redis
553
+
554
+ if key is None:
555
+ verbose_logger.debug(
556
+ "LiteLLM Redis Caching: async set() skipped — key is None, value=%r",
557
+ value,
558
+ )
559
+ return None
560
+
561
+ start_time = time.time()
562
+ try:
563
+ _redis_client: Redis = self.init_async_client() # type: ignore
564
+ except Exception as e:
565
+ end_time = time.time()
566
+ _duration = end_time - start_time
567
+ asyncio.create_task(
568
+ self.service_logger_obj.async_service_failure_hook(
569
+ service=ServiceTypes.REDIS,
570
+ duration=_duration,
571
+ error=e,
572
+ start_time=start_time,
573
+ end_time=end_time,
574
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
575
+ call_type=f"async_set_cache <- {_get_call_stack_info()}",
576
+ )
577
+ )
578
+ verbose_logger.error(
579
+ "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, key=%r, value=%r",
580
+ str(e),
581
+ key,
582
+ value,
583
+ )
584
+ raise e
585
+
586
+ key = self.check_and_fix_namespace(key=key)
587
+ ttl = self.get_ttl(**kwargs)
588
+ nx = kwargs.get("nx", False)
589
+ print_verbose(f"Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}")
590
+
591
+ try:
592
+ if not hasattr(_redis_client, "set"):
593
+ raise Exception("Redis client cannot set cache. Attribute not found.")
594
+ result = await _redis_client.set(
595
+ name=key,
596
+ value=json.dumps(value),
597
+ nx=nx,
598
+ ex=ttl,
599
+ )
600
+ print_verbose(
601
+ f"Successfully Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}"
602
+ )
603
+ end_time = time.time()
604
+ _duration = end_time - start_time
605
+ asyncio.create_task(
606
+ self.service_logger_obj.async_service_success_hook(
607
+ service=ServiceTypes.REDIS,
608
+ duration=_duration,
609
+ call_type=f"async_set_cache <- {_get_call_stack_info()}",
610
+ start_time=start_time,
611
+ end_time=end_time,
612
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
613
+ event_metadata={"key": key},
614
+ )
615
+ )
616
+ return result
617
+ except Exception as e:
618
+ end_time = time.time()
619
+ _duration = end_time - start_time
620
+ asyncio.create_task(
621
+ self.service_logger_obj.async_service_failure_hook(
622
+ service=ServiceTypes.REDIS,
623
+ duration=_duration,
624
+ error=e,
625
+ call_type=f"async_set_cache <- {_get_call_stack_info()}",
626
+ start_time=start_time,
627
+ end_time=end_time,
628
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
629
+ event_metadata={"key": key},
630
+ )
631
+ )
632
+ verbose_logger.error(
633
+ "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, Writing value=%s",
634
+ str(e),
635
+ value,
636
+ )
637
+
638
+ async def _pipeline_helper(
639
+ self,
640
+ pipe: Union[pipeline, cluster_pipeline],
641
+ cache_list: List[Tuple[Any, Any]],
642
+ ttl: Optional[float],
643
+ ) -> List:
644
+ """
645
+ Helper function for executing a pipeline of set operations on Redis
646
+ """
647
+ ttl = self.get_ttl(ttl=ttl)
648
+ # Iterate through each key-value pair in the cache_list and set them in the pipeline.
649
+ for cache_key, cache_value in cache_list:
650
+ cache_key = self.check_and_fix_namespace(key=cache_key)
651
+ print_verbose(
652
+ f"Set ASYNC Redis Cache PIPELINE: key: {cache_key}\nValue {cache_value}\nttl={ttl}"
653
+ )
654
+ json_cache_value = json.dumps(cache_value)
655
+ # Set the value with a TTL if it's provided.
656
+ _td: Optional[timedelta] = None
657
+ if ttl is not None:
658
+ _td = timedelta(seconds=ttl)
659
+ pipe.set( # type: ignore
660
+ name=cache_key,
661
+ value=json_cache_value,
662
+ ex=_td,
663
+ )
664
+ # Execute the pipeline and return the results.
665
+ results = await pipe.execute()
666
+ return results
667
+
668
+ @_redis_circuit_breaker_guard
669
+ async def async_set_cache_pipeline(
670
+ self, cache_list: List[Tuple[Any, Any]], ttl: Optional[float] = None, **kwargs
671
+ ):
672
+ """
673
+ Use Redis Pipelines for bulk write operations
674
+ """
675
+ # don't waste a network request if there's nothing to set
676
+ if len(cache_list) == 0:
677
+ return
678
+
679
+ _redis_client = self.init_async_client()
680
+ start_time = time.time()
681
+
682
+ print_verbose(
683
+ f"Set Async Redis Cache: key list: {cache_list}\nttl={ttl}, redis_version={self.redis_version}"
684
+ )
685
+ cache_value: Any = None
686
+ try:
687
+ async with _redis_client.pipeline(transaction=False) as pipe:
688
+ results = await self._pipeline_helper(pipe, cache_list, ttl)
689
+
690
+ print_verbose(f"pipeline results: {results}")
691
+ # Optionally, you could process 'results' to make sure that all set operations were successful.
692
+ ## LOGGING ##
693
+ end_time = time.time()
694
+ _duration = end_time - start_time
695
+ asyncio.create_task(
696
+ self.service_logger_obj.async_service_success_hook(
697
+ service=ServiceTypes.REDIS,
698
+ duration=_duration,
699
+ call_type=f"async_set_cache_pipeline <- {_get_call_stack_info()}",
700
+ start_time=start_time,
701
+ end_time=end_time,
702
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
703
+ )
704
+ )
705
+ return None
706
+ except Exception as e:
707
+ ## LOGGING ##
708
+ end_time = time.time()
709
+ _duration = end_time - start_time
710
+ asyncio.create_task(
711
+ self.service_logger_obj.async_service_failure_hook(
712
+ service=ServiceTypes.REDIS,
713
+ duration=_duration,
714
+ error=e,
715
+ call_type=f"async_set_cache_pipeline <- {_get_call_stack_info()}",
716
+ start_time=start_time,
717
+ end_time=end_time,
718
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
719
+ )
720
+ )
721
+
722
+ verbose_logger.error(
723
+ "LiteLLM Redis Caching: async set_cache_pipeline() - Got exception from REDIS %s, Writing value=%s",
724
+ str(e),
725
+ cache_value,
726
+ )
727
+
728
+ async def _set_cache_sadd_helper(
729
+ self,
730
+ redis_client: async_redis_client,
731
+ key: str,
732
+ value: List,
733
+ ttl: Optional[float],
734
+ ) -> None:
735
+ """Helper function for async_set_cache_sadd. Separated for testing."""
736
+ ttl = self.get_ttl(ttl=ttl)
737
+ try:
738
+ await redis_client.sadd(key, *value) # type: ignore
739
+ if ttl is not None:
740
+ _td = timedelta(seconds=ttl)
741
+ await redis_client.expire(key, _td)
742
+ except Exception:
743
+ raise
744
+
745
+ @_redis_circuit_breaker_guard
746
+ async def async_set_cache_sadd(
747
+ self, key, value: List, ttl: Optional[float], **kwargs
748
+ ):
749
+ from redis.asyncio import Redis
750
+
751
+ start_time = time.time()
752
+ try:
753
+ _redis_client: Redis = self.init_async_client() # type: ignore
754
+ except Exception as e:
755
+ end_time = time.time()
756
+ _duration = end_time - start_time
757
+ asyncio.create_task(
758
+ self.service_logger_obj.async_service_failure_hook(
759
+ service=ServiceTypes.REDIS,
760
+ duration=_duration,
761
+ error=e,
762
+ start_time=start_time,
763
+ end_time=end_time,
764
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
765
+ call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}",
766
+ )
767
+ )
768
+ # NON blocking - notify users Redis is throwing an exception
769
+ verbose_logger.error(
770
+ "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, Writing value=%s",
771
+ str(e),
772
+ value,
773
+ )
774
+ raise e
775
+
776
+ key = self.check_and_fix_namespace(key=key)
777
+ print_verbose(f"Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}")
778
+ try:
779
+ await self._set_cache_sadd_helper(
780
+ redis_client=_redis_client, key=key, value=value, ttl=ttl
781
+ )
782
+ print_verbose(
783
+ f"Successfully Set ASYNC Redis Cache SADD: key: {key}\nValue {value}\nttl={ttl}"
784
+ )
785
+ end_time = time.time()
786
+ _duration = end_time - start_time
787
+ asyncio.create_task(
788
+ self.service_logger_obj.async_service_success_hook(
789
+ service=ServiceTypes.REDIS,
790
+ duration=_duration,
791
+ call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}",
792
+ start_time=start_time,
793
+ end_time=end_time,
794
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
795
+ )
796
+ )
797
+ except Exception as e:
798
+ end_time = time.time()
799
+ _duration = end_time - start_time
800
+ asyncio.create_task(
801
+ self.service_logger_obj.async_service_failure_hook(
802
+ service=ServiceTypes.REDIS,
803
+ duration=_duration,
804
+ error=e,
805
+ call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}",
806
+ start_time=start_time,
807
+ end_time=end_time,
808
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
809
+ )
810
+ )
811
+ # NON blocking - notify users Redis is throwing an exception
812
+ verbose_logger.error(
813
+ "LiteLLM Redis Caching: async set_cache_sadd() - Got exception from REDIS %s, Writing value=%s",
814
+ str(e),
815
+ value,
816
+ )
817
+
818
+ @_redis_circuit_breaker_guard
819
+ async def batch_cache_write(self, key, value, **kwargs):
820
+ print_verbose(
821
+ f"in batch cache writing for redis buffer size={len(self.redis_batch_writing_buffer)}",
822
+ )
823
+ key = self.check_and_fix_namespace(key=key)
824
+ self.redis_batch_writing_buffer.append((key, value))
825
+ if len(self.redis_batch_writing_buffer) >= self.redis_flush_size:
826
+ await self.flush_cache_buffer() # logging done in here
827
+
828
+ @_redis_circuit_breaker_guard
829
+ async def async_increment(
830
+ self,
831
+ key,
832
+ value: float,
833
+ ttl: Optional[int] = None,
834
+ parent_otel_span: Optional[Span] = None,
835
+ refresh_ttl: bool = False,
836
+ ) -> float:
837
+ from redis.asyncio import Redis
838
+
839
+ _redis_client: Redis = self.init_async_client() # type: ignore
840
+ start_time = time.time()
841
+ _used_ttl = self.get_ttl(ttl=ttl)
842
+ key = self.check_and_fix_namespace(key=key)
843
+ try:
844
+ result = await _redis_client.incrbyfloat(name=key, amount=value)
845
+ if _used_ttl is not None:
846
+ if refresh_ttl:
847
+ await _redis_client.expire(key, _used_ttl)
848
+ else:
849
+ current_ttl = await _redis_client.ttl(key)
850
+ if current_ttl == -1:
851
+ await _redis_client.expire(key, _used_ttl)
852
+
853
+ ## LOGGING ##
854
+ end_time = time.time()
855
+ _duration = end_time - start_time
856
+
857
+ asyncio.create_task(
858
+ self.service_logger_obj.async_service_success_hook(
859
+ service=ServiceTypes.REDIS,
860
+ duration=_duration,
861
+ call_type=f"async_increment <- {_get_call_stack_info()}",
862
+ start_time=start_time,
863
+ end_time=end_time,
864
+ parent_otel_span=parent_otel_span,
865
+ )
866
+ )
867
+ return result
868
+ except Exception as e:
869
+ ## LOGGING ##
870
+ end_time = time.time()
871
+ _duration = end_time - start_time
872
+ asyncio.create_task(
873
+ self.service_logger_obj.async_service_failure_hook(
874
+ service=ServiceTypes.REDIS,
875
+ duration=_duration,
876
+ error=e,
877
+ call_type=f"async_increment <- {_get_call_stack_info()}",
878
+ start_time=start_time,
879
+ end_time=end_time,
880
+ parent_otel_span=parent_otel_span,
881
+ )
882
+ )
883
+ verbose_logger.error(
884
+ "LiteLLM Redis Caching: async async_increment() - Got exception from REDIS %s, Writing value=%s",
885
+ str(e),
886
+ value,
887
+ )
888
+ raise e
889
+
890
+ async def flush_cache_buffer(self):
891
+ print_verbose(
892
+ f"flushing to redis....reached size of buffer {len(self.redis_batch_writing_buffer)}"
893
+ )
894
+ await self.async_set_cache_pipeline(self.redis_batch_writing_buffer)
895
+ self.redis_batch_writing_buffer = []
896
+
897
+ def _get_cache_logic(self, cached_response: Any):
898
+ """
899
+ Common 'get_cache_logic' across sync + async redis client implementations
900
+ """
901
+ if cached_response is None:
902
+ return cached_response
903
+ # cached_response is in `b{} convert it to ModelResponse
904
+ cached_response = cached_response.decode("utf-8") # Convert bytes to string
905
+ try:
906
+ cached_response = json.loads(
907
+ cached_response
908
+ ) # Convert string to dictionary
909
+ except Exception:
910
+ cached_response = ast.literal_eval(cached_response)
911
+ return cached_response
912
+
913
+ def get_cache(self, key, parent_otel_span: Optional[Span] = None, **kwargs):
914
+ try:
915
+ key = self.check_and_fix_namespace(key=key)
916
+ print_verbose(f"Get Redis Cache: key: {key}")
917
+ start_time = time.time()
918
+ cached_response = self.redis_client.get(key)
919
+ end_time = time.time()
920
+ _duration = end_time - start_time
921
+ self.service_logger_obj.service_success_hook(
922
+ service=ServiceTypes.REDIS,
923
+ duration=_duration,
924
+ call_type=f"get_cache <- {_get_call_stack_info()}",
925
+ start_time=start_time,
926
+ end_time=end_time,
927
+ parent_otel_span=parent_otel_span,
928
+ )
929
+ print_verbose(
930
+ f"Got Redis Cache: key: {key}, cached_response {cached_response}"
931
+ )
932
+ return self._get_cache_logic(cached_response=cached_response)
933
+ except Exception as e:
934
+ # NON blocking - notify users Redis is throwing an exception
935
+ verbose_logger.error(
936
+ "litellm.caching.caching: get() - Got exception from REDIS: ", e
937
+ )
938
+
939
+ def _run_redis_mget_operation(self, keys: List[str]) -> List[Any]:
940
+ """
941
+ Wrapper to call `mget` on the redis client
942
+
943
+ We use a wrapper so RedisCluster can override this method
944
+ """
945
+ return self.redis_client.mget(keys=keys) # type: ignore
946
+
947
+ async def _async_run_redis_mget_operation(self, keys: List[str]) -> List[Any]:
948
+ """
949
+ Wrapper to call `mget` on the redis client
950
+
951
+ We use a wrapper so RedisCluster can override this method
952
+ """
953
+ async_redis_client = self.init_async_client()
954
+ return await async_redis_client.mget(keys=keys) # type: ignore
955
+
956
+ def batch_get_cache(
957
+ self,
958
+ key_list: Union[List[str], List[Optional[str]]],
959
+ parent_otel_span: Optional[Span] = None,
960
+ ) -> dict:
961
+ """
962
+ Use Redis for bulk read operations
963
+
964
+ Args:
965
+ key_list: List of keys to get from Redis
966
+ parent_otel_span: Optional parent OpenTelemetry span
967
+
968
+ Returns:
969
+ dict: A dictionary mapping keys to their cached values
970
+ """
971
+ key_value_dict = {}
972
+ _key_list = [key for key in key_list if key is not None]
973
+
974
+ try:
975
+ _keys = []
976
+ for cache_key in _key_list:
977
+ cache_key = self.check_and_fix_namespace(key=cache_key or "")
978
+ _keys.append(cache_key)
979
+ start_time = time.time()
980
+ results: List = self._run_redis_mget_operation(keys=_keys)
981
+ end_time = time.time()
982
+ _duration = end_time - start_time
983
+ self.service_logger_obj.service_success_hook(
984
+ service=ServiceTypes.REDIS,
985
+ duration=_duration,
986
+ call_type=f"batch_get_cache <- {_get_call_stack_info()}",
987
+ start_time=start_time,
988
+ end_time=end_time,
989
+ parent_otel_span=parent_otel_span,
990
+ )
991
+
992
+ # Associate the results back with their keys.
993
+ # 'results' is a list of values corresponding to the order of keys in '_key_list'.
994
+ key_value_dict = dict(zip(_key_list, results))
995
+
996
+ decoded_results = {}
997
+ for k, v in key_value_dict.items():
998
+ if isinstance(k, bytes):
999
+ k = k.decode("utf-8")
1000
+ v = self._get_cache_logic(v)
1001
+ decoded_results[k] = v
1002
+
1003
+ return decoded_results
1004
+ except Exception as e:
1005
+ verbose_logger.error(f"Error occurred in batch get cache - {str(e)}")
1006
+ return key_value_dict
1007
+
1008
+ @_redis_circuit_breaker_guard
1009
+ async def async_get_cache(
1010
+ self, key, parent_otel_span: Optional[Span] = None, **kwargs
1011
+ ):
1012
+ from redis.asyncio import Redis
1013
+
1014
+ _redis_client: Redis = self.init_async_client() # type: ignore
1015
+ key = self.check_and_fix_namespace(key=key)
1016
+ start_time = time.time()
1017
+
1018
+ try:
1019
+ print_verbose(f"Get Async Redis Cache: key: {key}")
1020
+ cached_response = await _redis_client.get(key)
1021
+ print_verbose(
1022
+ f"Got Async Redis Cache: key: {key}, cached_response {cached_response}"
1023
+ )
1024
+ response = self._get_cache_logic(cached_response=cached_response)
1025
+
1026
+ end_time = time.time()
1027
+ _duration = end_time - start_time
1028
+ asyncio.create_task(
1029
+ self.service_logger_obj.async_service_success_hook(
1030
+ service=ServiceTypes.REDIS,
1031
+ duration=_duration,
1032
+ call_type=f"async_get_cache <- {_get_call_stack_info()}",
1033
+ start_time=start_time,
1034
+ end_time=end_time,
1035
+ parent_otel_span=parent_otel_span,
1036
+ event_metadata={"key": key},
1037
+ )
1038
+ )
1039
+ return response
1040
+ except Exception as e:
1041
+ end_time = time.time()
1042
+ _duration = end_time - start_time
1043
+ asyncio.create_task(
1044
+ self.service_logger_obj.async_service_failure_hook(
1045
+ service=ServiceTypes.REDIS,
1046
+ duration=_duration,
1047
+ error=e,
1048
+ call_type=f"async_get_cache <- {_get_call_stack_info()}",
1049
+ start_time=start_time,
1050
+ end_time=end_time,
1051
+ parent_otel_span=parent_otel_span,
1052
+ event_metadata={"key": key},
1053
+ )
1054
+ )
1055
+ print_verbose(
1056
+ f"litellm.caching.caching: async get() - Got exception from REDIS: {str(e)}"
1057
+ )
1058
+
1059
+ @_redis_circuit_breaker_guard
1060
+ async def async_batch_get_cache(
1061
+ self,
1062
+ key_list: Union[List[str], List[Optional[str]]],
1063
+ parent_otel_span: Optional[Span] = None,
1064
+ ) -> dict:
1065
+ """
1066
+ Use Redis for bulk read operations
1067
+
1068
+ Args:
1069
+ key_list: List of keys to get from Redis
1070
+ parent_otel_span: Optional parent OpenTelemetry span
1071
+
1072
+ Returns:
1073
+ dict: A dictionary mapping keys to their cached values
1074
+
1075
+ `.mget` does not support None keys. This will filter out None keys.
1076
+ """
1077
+ # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `mget`
1078
+ key_value_dict = {}
1079
+ start_time = time.time()
1080
+ _key_list = [key for key in key_list if key is not None]
1081
+ try:
1082
+ _keys = []
1083
+ for cache_key in _key_list:
1084
+ cache_key = self.check_and_fix_namespace(key=cache_key)
1085
+ _keys.append(cache_key)
1086
+ results = await self._async_run_redis_mget_operation(keys=_keys)
1087
+ ## LOGGING ##
1088
+ end_time = time.time()
1089
+ _duration = end_time - start_time
1090
+ asyncio.create_task(
1091
+ self.service_logger_obj.async_service_success_hook(
1092
+ service=ServiceTypes.REDIS,
1093
+ duration=_duration,
1094
+ call_type=f"async_batch_get_cache <- {_get_call_stack_info()}",
1095
+ start_time=start_time,
1096
+ end_time=end_time,
1097
+ parent_otel_span=parent_otel_span,
1098
+ )
1099
+ )
1100
+
1101
+ # Associate the results back with their keys.
1102
+ # 'results' is a list of values corresponding to the order of keys in 'key_list'.
1103
+ key_value_dict = dict(zip(_key_list, results))
1104
+
1105
+ decoded_results = {}
1106
+ for k, v in key_value_dict.items():
1107
+ if isinstance(k, bytes):
1108
+ k = k.decode("utf-8")
1109
+ v = self._get_cache_logic(v)
1110
+ decoded_results[k] = v
1111
+
1112
+ return decoded_results
1113
+ except Exception as e:
1114
+ ## LOGGING ##
1115
+ end_time = time.time()
1116
+ _duration = end_time - start_time
1117
+ asyncio.create_task(
1118
+ self.service_logger_obj.async_service_failure_hook(
1119
+ service=ServiceTypes.REDIS,
1120
+ duration=_duration,
1121
+ error=e,
1122
+ call_type=f"async_batch_get_cache <- {_get_call_stack_info()}",
1123
+ start_time=start_time,
1124
+ end_time=end_time,
1125
+ parent_otel_span=parent_otel_span,
1126
+ )
1127
+ )
1128
+ verbose_logger.error(f"Error occurred in async batch get cache - {str(e)}")
1129
+ return key_value_dict
1130
+
1131
+ def sync_ping(self) -> bool:
1132
+ """
1133
+ Tests if the sync redis client is correctly setup.
1134
+ """
1135
+ print_verbose("Pinging Sync Redis Cache")
1136
+ start_time = time.time()
1137
+ try:
1138
+ response: bool = self.redis_client.ping() # type: ignore
1139
+ print_verbose(f"Redis Cache PING: {response}")
1140
+ ## LOGGING ##
1141
+ end_time = time.time()
1142
+ _duration = end_time - start_time
1143
+ self.service_logger_obj.service_success_hook(
1144
+ service=ServiceTypes.REDIS,
1145
+ duration=_duration,
1146
+ call_type=f"sync_ping <- {_get_call_stack_info()}",
1147
+ start_time=start_time,
1148
+ end_time=end_time,
1149
+ )
1150
+ return response
1151
+ except Exception as e:
1152
+ # NON blocking - notify users Redis is throwing an exception
1153
+ ## LOGGING ##
1154
+ end_time = time.time()
1155
+ _duration = end_time - start_time
1156
+ self.service_logger_obj.service_failure_hook(
1157
+ service=ServiceTypes.REDIS,
1158
+ duration=_duration,
1159
+ error=e,
1160
+ call_type=f"sync_ping <- {_get_call_stack_info()}",
1161
+ )
1162
+ verbose_logger.error(
1163
+ f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}"
1164
+ )
1165
+ raise e
1166
+
1167
+ async def ping(self) -> bool:
1168
+ # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `ping`
1169
+ _redis_client: Any = self.init_async_client()
1170
+ start_time = time.time()
1171
+ print_verbose("Pinging Async Redis Cache")
1172
+ try:
1173
+ response = await _redis_client.ping()
1174
+ ## LOGGING ##
1175
+ end_time = time.time()
1176
+ _duration = end_time - start_time
1177
+ asyncio.create_task(
1178
+ self.service_logger_obj.async_service_success_hook(
1179
+ service=ServiceTypes.REDIS,
1180
+ duration=_duration,
1181
+ call_type=f"async_ping <- {_get_call_stack_info()}",
1182
+ )
1183
+ )
1184
+ return response
1185
+ except Exception as e:
1186
+ # NON blocking - notify users Redis is throwing an exception
1187
+ ## LOGGING ##
1188
+ end_time = time.time()
1189
+ _duration = end_time - start_time
1190
+ asyncio.create_task(
1191
+ self.service_logger_obj.async_service_failure_hook(
1192
+ service=ServiceTypes.REDIS,
1193
+ duration=_duration,
1194
+ error=e,
1195
+ call_type=f"async_ping <- {_get_call_stack_info()}",
1196
+ )
1197
+ )
1198
+ verbose_logger.error(
1199
+ f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}"
1200
+ )
1201
+ raise e
1202
+
1203
+ @_redis_circuit_breaker_guard
1204
+ async def delete_cache_keys(self, keys):
1205
+ # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `delete`
1206
+ _redis_client: Any = self.init_async_client()
1207
+ # keys is a list, unpack it so it gets passed as individual elements to delete
1208
+ await _redis_client.delete(*keys)
1209
+
1210
+ def client_list(self) -> List:
1211
+ client_list: List = self.redis_client.client_list() # type: ignore
1212
+ return client_list
1213
+
1214
+ def info(self):
1215
+ info = self.redis_client.info()
1216
+ return info
1217
+
1218
+ def flush_cache(self):
1219
+ self.redis_client.flushall()
1220
+
1221
+ def flushall(self):
1222
+ self.redis_client.flushall()
1223
+
1224
+ async def disconnect(self):
1225
+ await self.async_redis_conn_pool.disconnect(inuse_connections=True)
1226
+ try:
1227
+ self.redis_client.close()
1228
+ except Exception as e:
1229
+ verbose_logger.debug("Error closing sync Redis client: %s", e)
1230
+
1231
+ async def test_connection(self) -> dict:
1232
+ """
1233
+ Test the Redis connection by creating a new client and pinging it.
1234
+
1235
+ This creates a fresh connection without using cached clients or connection pools
1236
+ to ensure the credentials are actually valid.
1237
+
1238
+ Returns:
1239
+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}
1240
+ """
1241
+ try:
1242
+ import redis.asyncio as redis_async
1243
+
1244
+ # Create a fresh Redis client with current settings
1245
+ redis_client = redis_async.Redis(**self.redis_kwargs)
1246
+
1247
+ # Test the connection
1248
+ ping_result = await redis_client.ping() # type: ignore[misc]
1249
+
1250
+ # Close the connection
1251
+ await redis_client.aclose() # type: ignore[attr-defined]
1252
+
1253
+ if ping_result:
1254
+ return {
1255
+ "status": "success",
1256
+ "message": "Redis connection test successful",
1257
+ }
1258
+ else:
1259
+ return {"status": "failed", "message": "Redis ping returned False"}
1260
+ except Exception as e:
1261
+ verbose_logger.error(f"Redis connection test failed: {str(e)}")
1262
+ return {
1263
+ "status": "failed",
1264
+ "message": f"Redis connection failed: {str(e)}",
1265
+ "error": str(e),
1266
+ }
1267
+
1268
+ @_redis_circuit_breaker_guard
1269
+ async def async_delete_cache(self, key: str):
1270
+ # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `delete`
1271
+ _redis_client: Any = self.init_async_client()
1272
+ # keys is str
1273
+ return await _redis_client.delete(key)
1274
+
1275
+ def delete_cache(self, key):
1276
+ self.redis_client.delete(key)
1277
+
1278
+ async def _pipeline_increment_helper(
1279
+ self,
1280
+ pipe: pipeline,
1281
+ increment_list: List[RedisPipelineIncrementOperation],
1282
+ ) -> Optional[List[float]]:
1283
+ """Helper function for pipeline increment operations"""
1284
+ # Iterate through each increment operation and add commands to pipeline
1285
+ for increment_op in increment_list:
1286
+ cache_key = self.check_and_fix_namespace(key=increment_op["key"])
1287
+ print_verbose(
1288
+ f"Increment ASYNC Redis Cache PIPELINE: key: {cache_key}\nValue {increment_op['increment_value']}\nttl={increment_op['ttl']}"
1289
+ )
1290
+ pipe.incrbyfloat(cache_key, increment_op["increment_value"])
1291
+ if increment_op["ttl"] is not None:
1292
+ _td = timedelta(seconds=increment_op["ttl"])
1293
+ pipe.expire(cache_key, _td)
1294
+ # Execute the pipeline and return results
1295
+ results = await pipe.execute()
1296
+ # only return float values
1297
+ verbose_logger.debug(
1298
+ f"Increment ASYNC Redis Cache PIPELINE: results: {results}"
1299
+ )
1300
+ return [r for r in results if isinstance(r, float)]
1301
+
1302
+ @_redis_circuit_breaker_guard
1303
+ async def async_increment_pipeline(
1304
+ self, increment_list: List[RedisPipelineIncrementOperation], **kwargs
1305
+ ) -> Optional[List[float]]:
1306
+ """
1307
+ Use Redis Pipelines for bulk increment operations
1308
+ Args:
1309
+ increment_list: List of RedisPipelineIncrementOperation dicts containing:
1310
+ - key: str
1311
+ - increment_value: float
1312
+ - ttl_seconds: int
1313
+ """
1314
+ # don't waste a network request if there's nothing to increment
1315
+ if len(increment_list) == 0:
1316
+ return None
1317
+
1318
+ from redis.asyncio import Redis
1319
+
1320
+ _redis_client: Redis = self.init_async_client() # type: ignore
1321
+ start_time = time.time()
1322
+
1323
+ print_verbose(
1324
+ f"Increment Async Redis Cache Pipeline: increment list: {increment_list}"
1325
+ )
1326
+
1327
+ try:
1328
+ async with _redis_client.pipeline(transaction=False) as pipe:
1329
+ results = await self._pipeline_increment_helper(pipe, increment_list)
1330
+
1331
+ ## LOGGING ##
1332
+ end_time = time.time()
1333
+ _duration = end_time - start_time
1334
+ asyncio.create_task(
1335
+ self.service_logger_obj.async_service_success_hook(
1336
+ service=ServiceTypes.REDIS,
1337
+ duration=_duration,
1338
+ call_type=f"async_increment_pipeline <- {_get_call_stack_info()}",
1339
+ start_time=start_time,
1340
+ end_time=end_time,
1341
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
1342
+ )
1343
+ )
1344
+ return results
1345
+ except Exception as e:
1346
+ ## LOGGING ##
1347
+ end_time = time.time()
1348
+ _duration = end_time - start_time
1349
+ asyncio.create_task(
1350
+ self.service_logger_obj.async_service_failure_hook(
1351
+ service=ServiceTypes.REDIS,
1352
+ duration=_duration,
1353
+ error=e,
1354
+ call_type=f"async_increment_pipeline <- {_get_call_stack_info()}",
1355
+ start_time=start_time,
1356
+ end_time=end_time,
1357
+ parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs),
1358
+ )
1359
+ )
1360
+ verbose_logger.error(
1361
+ "LiteLLM Redis Caching: async increment_pipeline() - Got exception from REDIS %s",
1362
+ str(e),
1363
+ )
1364
+ raise e
1365
+
1366
+ @_redis_circuit_breaker_guard
1367
+ async def async_get_ttl(self, key: str) -> Optional[int]:
1368
+ """
1369
+ Get the remaining TTL of a key in Redis
1370
+
1371
+ Args:
1372
+ key (str): The key to get TTL for
1373
+
1374
+ Returns:
1375
+ Optional[int]: The remaining TTL in seconds, or None if key doesn't exist
1376
+
1377
+ Redis ref: https://redis.io/docs/latest/commands/ttl/
1378
+ """
1379
+ try:
1380
+ # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `ttl`
1381
+ _redis_client: Any = self.init_async_client()
1382
+ ttl = await _redis_client.ttl(key)
1383
+ if ttl <= -1: # -1 means the key does not exist, -2 key does not exist
1384
+ return None
1385
+ return ttl
1386
+ except Exception as e:
1387
+ verbose_logger.debug(f"Redis TTL Error: {e}")
1388
+ return None
1389
+
1390
+ @_redis_circuit_breaker_guard
1391
+ async def async_rpush(
1392
+ self,
1393
+ key: str,
1394
+ values: List[Any],
1395
+ parent_otel_span: Optional[Span] = None,
1396
+ **kwargs,
1397
+ ) -> int:
1398
+ """
1399
+ Append one or multiple values to a list stored at key
1400
+
1401
+ Args:
1402
+ key: The Redis key of the list
1403
+ values: One or more values to append to the list
1404
+ parent_otel_span: Optional parent OpenTelemetry span
1405
+
1406
+ Returns:
1407
+ int: The length of the list after the push operation
1408
+ """
1409
+ _redis_client: Any = self.init_async_client()
1410
+ start_time = time.time()
1411
+ try:
1412
+ response = await _redis_client.rpush(key, *values)
1413
+ ## LOGGING ##
1414
+ end_time = time.time()
1415
+ _duration = end_time - start_time
1416
+ asyncio.create_task(
1417
+ self.service_logger_obj.async_service_success_hook(
1418
+ service=ServiceTypes.REDIS,
1419
+ duration=_duration,
1420
+ call_type=f"async_rpush <- {_get_call_stack_info()}",
1421
+ )
1422
+ )
1423
+ return response
1424
+ except Exception as e:
1425
+ # NON blocking - notify users Redis is throwing an exception
1426
+ ## LOGGING ##
1427
+ end_time = time.time()
1428
+ _duration = end_time - start_time
1429
+ asyncio.create_task(
1430
+ self.service_logger_obj.async_service_failure_hook(
1431
+ service=ServiceTypes.REDIS,
1432
+ duration=_duration,
1433
+ error=e,
1434
+ call_type=f"async_rpush <- {_get_call_stack_info()}",
1435
+ )
1436
+ )
1437
+ verbose_logger.error(
1438
+ f"LiteLLM Redis Cache RPUSH: - Got exception from REDIS : {str(e)}"
1439
+ )
1440
+ raise e
1441
+
1442
+ async def _pipeline_rpush_helper(
1443
+ self,
1444
+ pipe: pipeline,
1445
+ rpush_list: List[RedisPipelineRpushOperation],
1446
+ ) -> List[int]:
1447
+ """Helper function for pipeline rpush operations"""
1448
+ for rpush_op in rpush_list:
1449
+ pipe.rpush(rpush_op["key"], *rpush_op["values"])
1450
+ results = await pipe.execute()
1451
+ # Preserve positional correspondence — raise on per-command errors
1452
+ for r in results:
1453
+ if isinstance(r, Exception):
1454
+ raise r
1455
+ return results
1456
+
1457
+ @_redis_circuit_breaker_guard
1458
+ async def async_rpush_pipeline(
1459
+ self,
1460
+ rpush_list: List[RedisPipelineRpushOperation],
1461
+ ) -> List[int]:
1462
+ """
1463
+ Use Redis Pipelines for bulk RPUSH operations
1464
+
1465
+ Args:
1466
+ rpush_list: List of RedisPipelineRpushOperation dicts containing:
1467
+ - key: str
1468
+ - values: List[Any]
1469
+
1470
+ Returns:
1471
+ List[int]: List lengths after each push
1472
+ """
1473
+ if len(rpush_list) == 0:
1474
+ return []
1475
+
1476
+ _redis_client: Any = self.init_async_client()
1477
+ start_time = time.time()
1478
+
1479
+ try:
1480
+ async with _redis_client.pipeline(transaction=False) as pipe:
1481
+ results = await self._pipeline_rpush_helper(pipe, rpush_list)
1482
+
1483
+ ## LOGGING ##
1484
+ end_time = time.time()
1485
+ _duration = end_time - start_time
1486
+ asyncio.create_task(
1487
+ self.service_logger_obj.async_service_success_hook(
1488
+ service=ServiceTypes.REDIS,
1489
+ duration=_duration,
1490
+ call_type=f"async_rpush_pipeline <- {_get_call_stack_info()}",
1491
+ )
1492
+ )
1493
+ return results
1494
+ except Exception as e:
1495
+ ## LOGGING ##
1496
+ end_time = time.time()
1497
+ _duration = end_time - start_time
1498
+ asyncio.create_task(
1499
+ self.service_logger_obj.async_service_failure_hook(
1500
+ service=ServiceTypes.REDIS,
1501
+ duration=_duration,
1502
+ error=e,
1503
+ call_type=f"async_rpush_pipeline <- {_get_call_stack_info()}",
1504
+ )
1505
+ )
1506
+ verbose_logger.error(
1507
+ "LiteLLM Redis Caching: async_rpush_pipeline() - Got exception from REDIS %s",
1508
+ str(e),
1509
+ )
1510
+ raise e
1511
+
1512
+ async def handle_lpop_count_for_older_redis_versions(
1513
+ self, pipe: pipeline, key: str, count: int
1514
+ ) -> List[bytes]:
1515
+ result: List[bytes] = []
1516
+ for _ in range(count):
1517
+ pipe.lpop(key)
1518
+ results = await pipe.execute()
1519
+
1520
+ # Filter out None values and decode bytes
1521
+ for r in results:
1522
+ if r is not None:
1523
+ result.append(r)
1524
+
1525
+ return result
1526
+
1527
+ @_redis_circuit_breaker_guard
1528
+ async def async_lpop(
1529
+ self,
1530
+ key: str,
1531
+ count: Optional[int] = None,
1532
+ parent_otel_span: Optional[Span] = None,
1533
+ **kwargs,
1534
+ ) -> Union[Any, List[Any]]:
1535
+ _redis_client: Any = self.init_async_client()
1536
+ start_time = time.time()
1537
+ print_verbose(f"LPOP from Redis list: key: {key}, count: {count}")
1538
+ try:
1539
+ major_version = self._parse_redis_major_version()
1540
+
1541
+ if count is not None and major_version < 7:
1542
+ # For Redis < 7.0, use pipeline to execute multiple LPOP commands
1543
+ async with _redis_client.pipeline(transaction=False) as pipe:
1544
+ result = await self.handle_lpop_count_for_older_redis_versions(
1545
+ pipe, key, count
1546
+ )
1547
+ else:
1548
+ # For Redis >= 7.0 or when count is None, use native LPOP with count
1549
+ result = await _redis_client.lpop(key, count)
1550
+
1551
+ ## LOGGING ##
1552
+ end_time = time.time()
1553
+ _duration = end_time - start_time
1554
+ asyncio.create_task(
1555
+ self.service_logger_obj.async_service_success_hook(
1556
+ service=ServiceTypes.REDIS,
1557
+ duration=_duration,
1558
+ call_type=f"async_lpop <- {_get_call_stack_info()}",
1559
+ )
1560
+ )
1561
+
1562
+ # Handle result parsing if needed
1563
+ if isinstance(result, bytes):
1564
+ try:
1565
+ return result.decode("utf-8")
1566
+ except Exception:
1567
+ return result
1568
+ elif isinstance(result, list) and all(
1569
+ isinstance(item, bytes) for item in result
1570
+ ):
1571
+ try:
1572
+ return [item.decode("utf-8") for item in result]
1573
+ except Exception:
1574
+ return result
1575
+ return result
1576
+ except Exception as e:
1577
+ # NON blocking - notify users Redis is throwing an exception
1578
+ ## LOGGING ##
1579
+ end_time = time.time()
1580
+ _duration = end_time - start_time
1581
+ asyncio.create_task(
1582
+ self.service_logger_obj.async_service_failure_hook(
1583
+ service=ServiceTypes.REDIS,
1584
+ duration=_duration,
1585
+ error=e,
1586
+ call_type=f"async_lpop <- {_get_call_stack_info()}",
1587
+ )
1588
+ )
1589
+ verbose_logger.error(
1590
+ f"LiteLLM Redis Cache LPOP: - Got exception from REDIS : {str(e)}"
1591
+ )
1592
+ raise e
1593
+
1594
+ async def _pipeline_lpop_helper(
1595
+ self,
1596
+ pipe: pipeline,
1597
+ lpop_list: List[RedisPipelineLpopOperation],
1598
+ ) -> List[Optional[List[str]]]:
1599
+ """Helper function for pipeline lpop operations.
1600
+
1601
+ For Redis >= 7, queues one LPOP(key, count) per operation.
1602
+ For Redis < 7, queues `count` individual LPOP(key) commands per operation.
1603
+ """
1604
+ major_version = self._parse_redis_major_version()
1605
+
1606
+ if major_version >= 7:
1607
+ for lpop_op in lpop_list:
1608
+ pipe.lpop(lpop_op["key"], lpop_op["count"])
1609
+ raw_results = await pipe.execute()
1610
+ else:
1611
+ # For Redis < 7, LPOP doesn't support count param.
1612
+ # Issue `count` individual LPOP commands per key, all in one pipeline.
1613
+ counts: List[int] = []
1614
+ for lpop_op in lpop_list:
1615
+ count = lpop_op["count"] or 1
1616
+ counts.append(count)
1617
+ for _ in range(count):
1618
+ pipe.lpop(lpop_op["key"])
1619
+ flat_results = await pipe.execute()
1620
+
1621
+ # Re-group the flat results back into per-key lists
1622
+ raw_results = []
1623
+ offset = 0
1624
+ for count in counts:
1625
+ key_results = [
1626
+ r for r in flat_results[offset : offset + count] if r is not None
1627
+ ]
1628
+ raw_results.append(key_results if key_results else None)
1629
+ offset += count
1630
+
1631
+ # Raise on per-command errors (matches _pipeline_rpush_helper behavior)
1632
+ for r in raw_results:
1633
+ if isinstance(r, Exception):
1634
+ raise r
1635
+
1636
+ # Decode bytes -> str for each result set
1637
+ decoded_results: List[Optional[List[str]]] = []
1638
+ for r in raw_results:
1639
+ if r is None:
1640
+ decoded_results.append(None)
1641
+ elif isinstance(r, list):
1642
+ try:
1643
+ decoded_results.append(
1644
+ [
1645
+ item.decode("utf-8") if isinstance(item, bytes) else item
1646
+ for item in r
1647
+ if item is not None
1648
+ ]
1649
+ or None
1650
+ )
1651
+ except Exception:
1652
+ decoded_results.append(r) # type: ignore
1653
+ else:
1654
+ decoded_results.append(None)
1655
+ return decoded_results
1656
+
1657
+ @_redis_circuit_breaker_guard
1658
+ async def async_lpop_pipeline(
1659
+ self,
1660
+ lpop_list: List[RedisPipelineLpopOperation],
1661
+ ) -> List[Optional[List[str]]]:
1662
+ """
1663
+ Use Redis Pipelines for bulk LPOP operations
1664
+
1665
+ Args:
1666
+ lpop_list: List of RedisPipelineLpopOperation dicts containing:
1667
+ - key: str
1668
+ - count: Optional[int]
1669
+
1670
+ Returns:
1671
+ List[Optional[List[str]]]: Decoded results per key, None if key was empty
1672
+ """
1673
+ if len(lpop_list) == 0:
1674
+ return []
1675
+
1676
+ _redis_client: Any = self.init_async_client()
1677
+ start_time = time.time()
1678
+
1679
+ try:
1680
+ async with _redis_client.pipeline(transaction=False) as pipe:
1681
+ results = await self._pipeline_lpop_helper(pipe, lpop_list)
1682
+
1683
+ ## LOGGING ##
1684
+ end_time = time.time()
1685
+ _duration = end_time - start_time
1686
+ asyncio.create_task(
1687
+ self.service_logger_obj.async_service_success_hook(
1688
+ service=ServiceTypes.REDIS,
1689
+ duration=_duration,
1690
+ call_type=f"async_lpop_pipeline <- {_get_call_stack_info()}",
1691
+ )
1692
+ )
1693
+ return results
1694
+ except Exception as e:
1695
+ ## LOGGING ##
1696
+ end_time = time.time()
1697
+ _duration = end_time - start_time
1698
+ asyncio.create_task(
1699
+ self.service_logger_obj.async_service_failure_hook(
1700
+ service=ServiceTypes.REDIS,
1701
+ duration=_duration,
1702
+ error=e,
1703
+ call_type=f"async_lpop_pipeline <- {_get_call_stack_info()}",
1704
+ )
1705
+ )
1706
+ verbose_logger.error(
1707
+ "LiteLLM Redis Caching: async_lpop_pipeline() - Got exception from REDIS %s",
1708
+ str(e),
1709
+ )
1710
+ raise e
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cluster_cache.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Redis Cluster Cache implementation
3
+
4
+ Key differences:
5
+ - RedisClient NEEDs to be re-used across requests, adds 3000ms latency if it's re-created
6
+ """
7
+
8
+ from typing import TYPE_CHECKING, Any, List, Optional, Union
9
+
10
+ from litellm.caching.redis_cache import RedisCache
11
+
12
+ if TYPE_CHECKING:
13
+ from opentelemetry.trace import Span as _Span
14
+ from redis.asyncio import Redis, RedisCluster
15
+ from redis.asyncio.client import Pipeline
16
+
17
+ pipeline = Pipeline
18
+ async_redis_client = Redis
19
+ Span = Union[_Span, Any]
20
+ else:
21
+ pipeline = Any
22
+ async_redis_client = Any
23
+ Span = Any
24
+
25
+
26
+ class RedisClusterCache(RedisCache):
27
+ def __init__(self, *args, **kwargs):
28
+ super().__init__(*args, **kwargs)
29
+ self.redis_async_redis_cluster_client: Optional[RedisCluster] = None
30
+ self.redis_sync_redis_cluster_client: Optional[RedisCluster] = None
31
+
32
+ def init_async_client(self):
33
+ from redis.asyncio import RedisCluster
34
+
35
+ from .._redis import get_redis_async_client
36
+
37
+ if self.redis_async_redis_cluster_client:
38
+ return self.redis_async_redis_cluster_client
39
+
40
+ _redis_client = get_redis_async_client(
41
+ connection_pool=self.async_redis_conn_pool, **self.redis_kwargs
42
+ )
43
+ if isinstance(_redis_client, RedisCluster):
44
+ self.redis_async_redis_cluster_client = _redis_client
45
+
46
+ return _redis_client
47
+
48
+ def _run_redis_mget_operation(self, keys: List[str]) -> List[Any]:
49
+ """
50
+ Overrides `_run_redis_mget_operation` in redis_cache.py
51
+ """
52
+ return self.redis_client.mget_nonatomic(keys=keys) # type: ignore
53
+
54
+ async def _async_run_redis_mget_operation(self, keys: List[str]) -> List[Any]:
55
+ """
56
+ Overrides `_async_run_redis_mget_operation` in redis_cache.py
57
+ """
58
+ async_redis_cluster_client = self.init_async_client()
59
+ return await async_redis_cluster_client.mget_nonatomic(keys=keys) # type: ignore
60
+
61
+ async def test_connection(self) -> dict:
62
+ """
63
+ Test the Redis Cluster connection.
64
+
65
+ Returns:
66
+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}
67
+ """
68
+ try:
69
+ import redis.asyncio as redis_async
70
+ from redis.cluster import ClusterNode
71
+
72
+ # Create ClusterNode objects from startup_nodes
73
+ cluster_kwargs = self.redis_kwargs.copy()
74
+ startup_nodes = cluster_kwargs.pop("startup_nodes", [])
75
+
76
+ new_startup_nodes: List[ClusterNode] = []
77
+ for item in startup_nodes:
78
+ new_startup_nodes.append(ClusterNode(**item))
79
+
80
+ # Create a fresh Redis Cluster client with current settings
81
+ redis_client = redis_async.RedisCluster(
82
+ startup_nodes=new_startup_nodes, **cluster_kwargs # type: ignore
83
+ )
84
+
85
+ # Test the connection
86
+ ping_result = await redis_client.ping() # type: ignore[attr-defined, misc]
87
+
88
+ # Close the connection
89
+ await redis_client.aclose() # type: ignore[attr-defined]
90
+
91
+ if ping_result:
92
+ return {
93
+ "status": "success",
94
+ "message": "Redis Cluster connection test successful",
95
+ }
96
+ else:
97
+ return {
98
+ "status": "failed",
99
+ "message": "Redis Cluster ping returned False",
100
+ }
101
+ except Exception as e:
102
+ from litellm._logging import verbose_logger
103
+
104
+ verbose_logger.error(f"Redis Cluster connection test failed: {str(e)}")
105
+ return {
106
+ "status": "failed",
107
+ "message": f"Redis Cluster connection failed: {str(e)}",
108
+ "error": str(e),
109
+ }
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_semantic_cache.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Redis Semantic Cache implementation for LiteLLM
3
+
4
+ The RedisSemanticCache provides semantic caching functionality using Redis as a backend.
5
+ This cache stores responses based on the semantic similarity of prompts rather than
6
+ exact matching, allowing for more flexible caching of LLM responses.
7
+
8
+ This implementation uses RedisVL's SemanticCache to find semantically similar prompts
9
+ and their cached responses.
10
+ """
11
+
12
+ import ast
13
+ import asyncio
14
+ import json
15
+ import os
16
+ from typing import Any, Dict, List, Optional, Tuple, cast
17
+
18
+ import litellm
19
+ from litellm._logging import print_verbose
20
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
21
+ get_str_from_messages,
22
+ )
23
+ from litellm.types.utils import EmbeddingResponse
24
+
25
+ from .base_cache import BaseCache
26
+
27
+
28
+ class RedisSemanticCache(BaseCache):
29
+ """
30
+ Redis-backed semantic cache for LLM responses.
31
+
32
+ This cache uses vector similarity to find semantically similar prompts that have been
33
+ previously sent to the LLM, allowing for cache hits even when prompts are not identical
34
+ but carry similar meaning.
35
+ """
36
+
37
+ DEFAULT_REDIS_INDEX_NAME: str = "litellm_semantic_cache_index"
38
+ CACHE_KEY_FIELD_NAME: str = "litellm_cache_key"
39
+
40
+ def __init__(
41
+ self,
42
+ host: Optional[str] = None,
43
+ port: Optional[str] = None,
44
+ password: Optional[str] = None,
45
+ redis_url: Optional[str] = None,
46
+ similarity_threshold: Optional[float] = None,
47
+ embedding_model: str = "text-embedding-ada-002",
48
+ index_name: Optional[str] = None,
49
+ **kwargs,
50
+ ):
51
+ """
52
+ Initialize the Redis Semantic Cache.
53
+
54
+ Args:
55
+ host: Redis host address
56
+ port: Redis port
57
+ password: Redis password
58
+ redis_url: Full Redis URL (alternative to separate host/port/password)
59
+ similarity_threshold: Threshold for semantic similarity (0.0 to 1.0)
60
+ where 1.0 requires exact matches and 0.0 accepts any match
61
+ embedding_model: Model to use for generating embeddings
62
+ index_name: Name for the Redis index
63
+ ttl: Default time-to-live for cache entries in seconds
64
+ **kwargs: Additional arguments passed to the Redis client
65
+
66
+ Raises:
67
+ Exception: If similarity_threshold is not provided or required Redis
68
+ connection information is missing
69
+ """
70
+ from redisvl.extensions.llmcache import SemanticCache # type: ignore[import-not-found, import-untyped]
71
+ from redisvl.utils.vectorize import CustomTextVectorizer # type: ignore[import-not-found, import-untyped]
72
+
73
+ if index_name is None:
74
+ index_name = self.DEFAULT_REDIS_INDEX_NAME
75
+
76
+ print_verbose(f"Redis semantic-cache initializing index - {index_name}")
77
+
78
+ # Validate similarity threshold
79
+ if similarity_threshold is None:
80
+ raise ValueError("similarity_threshold must be provided, passed None")
81
+
82
+ # Store configuration
83
+ self.similarity_threshold = similarity_threshold
84
+
85
+ # Convert similarity threshold [0,1] to distance threshold [0,2]
86
+ # For cosine distance: 0 = most similar, 2 = least similar
87
+ # While similarity: 1 = most similar, 0 = least similar
88
+ self.distance_threshold = 1 - similarity_threshold
89
+ self.embedding_model = embedding_model
90
+
91
+ # Set up Redis connection
92
+ if redis_url is None:
93
+ try:
94
+ # Attempt to use provided parameters or fallback to environment variables
95
+ host = host or os.environ["REDIS_HOST"]
96
+ port = port or os.environ["REDIS_PORT"]
97
+ password = password or os.environ["REDIS_PASSWORD"]
98
+ except KeyError as e:
99
+ # Raise a more informative exception if any of the required keys are missing
100
+ missing_var = e.args[0]
101
+ raise ValueError(
102
+ f"Missing required Redis configuration: {missing_var}. "
103
+ f"Provide {missing_var} or redis_url."
104
+ ) from e
105
+
106
+ redis_url = f"redis://:{password}@{host}:{port}"
107
+
108
+ print_verbose(f"Redis semantic-cache redis_url: {redis_url}")
109
+
110
+ # Initialize the Redis vectorizer and cache
111
+ cache_vectorizer = CustomTextVectorizer(self._get_embedding)
112
+
113
+ self.llmcache = self._init_semantic_cache(
114
+ semantic_cache_cls=SemanticCache,
115
+ index_name=index_name,
116
+ redis_url=redis_url,
117
+ cache_vectorizer=cache_vectorizer,
118
+ )
119
+
120
+ @classmethod
121
+ def _cache_key_filterable_field(cls) -> Dict[str, str]:
122
+ return {
123
+ "name": cls.CACHE_KEY_FIELD_NAME,
124
+ "type": "tag",
125
+ }
126
+
127
+ def _init_semantic_cache(
128
+ self,
129
+ semantic_cache_cls: Any,
130
+ index_name: str,
131
+ redis_url: str,
132
+ cache_vectorizer: Any,
133
+ ) -> Any:
134
+ def _is_schema_mismatch(exc: ValueError) -> bool:
135
+ error_message = str(exc).lower()
136
+ return any(
137
+ phrase in error_message
138
+ for phrase in ("schema does not match", "index schema")
139
+ )
140
+
141
+ try:
142
+ return semantic_cache_cls(
143
+ name=index_name,
144
+ redis_url=redis_url,
145
+ vectorizer=cache_vectorizer,
146
+ distance_threshold=self.distance_threshold,
147
+ filterable_fields=[self._cache_key_filterable_field()],
148
+ overwrite=False,
149
+ )
150
+ except ValueError as exc:
151
+ if not _is_schema_mismatch(exc):
152
+ raise
153
+
154
+ isolated_index_name = f"{index_name}_isolated"
155
+ print_verbose(
156
+ "Redis semantic-cache existing index schema is not isolated; "
157
+ f"using isolated index - {isolated_index_name}"
158
+ )
159
+ try:
160
+ return semantic_cache_cls(
161
+ name=isolated_index_name,
162
+ redis_url=redis_url,
163
+ vectorizer=cache_vectorizer,
164
+ distance_threshold=self.distance_threshold,
165
+ filterable_fields=[self._cache_key_filterable_field()],
166
+ overwrite=False,
167
+ )
168
+ except ValueError as isolated_exc:
169
+ if not _is_schema_mismatch(isolated_exc):
170
+ raise
171
+
172
+ print_verbose(
173
+ "Redis semantic-cache isolated index schema is stale; "
174
+ f"recreating isolated index - {isolated_index_name}"
175
+ )
176
+ return semantic_cache_cls(
177
+ name=isolated_index_name,
178
+ redis_url=redis_url,
179
+ vectorizer=cache_vectorizer,
180
+ distance_threshold=self.distance_threshold,
181
+ filterable_fields=[self._cache_key_filterable_field()],
182
+ overwrite=True,
183
+ )
184
+
185
+ def _get_cache_filters(self, key: str) -> Dict[str, str]:
186
+ return {self.CACHE_KEY_FIELD_NAME: str(key)}
187
+
188
+ def _get_cache_key_filter_expression(self, key: str) -> Any:
189
+ from redisvl.query.filter import Tag # type: ignore[import-not-found, import-untyped]
190
+
191
+ return Tag(self.CACHE_KEY_FIELD_NAME) == str(key)
192
+
193
+ def _cache_hit_matches_key(self, cache_hit: Dict[str, Any], key: str) -> bool:
194
+ # Pre-isolation entries with no ``litellm_cache_key`` field cannot be
195
+ # safely reassigned to a caller's scope and are treated as misses.
196
+ cached_key = cache_hit.get(self.CACHE_KEY_FIELD_NAME)
197
+ if isinstance(cached_key, bytes):
198
+ cached_key = cached_key.decode("utf-8")
199
+ return cached_key is not None and str(cached_key) == str(key)
200
+
201
+ def _get_ttl(self, **kwargs) -> Optional[int]:
202
+ """
203
+ Get the TTL (time-to-live) value for cache entries.
204
+
205
+ Args:
206
+ **kwargs: Keyword arguments that may contain a custom TTL
207
+
208
+ Returns:
209
+ Optional[int]: The TTL value in seconds, or None if no TTL should be applied
210
+ """
211
+ ttl = kwargs.get("ttl")
212
+ if ttl is not None:
213
+ ttl = int(ttl)
214
+ return ttl
215
+
216
+ def _get_embedding(self, prompt: str) -> List[float]:
217
+ """
218
+ Generate an embedding vector for the given prompt using the configured embedding model.
219
+
220
+ Args:
221
+ prompt: The text to generate an embedding for
222
+
223
+ Returns:
224
+ List[float]: The embedding vector
225
+ """
226
+ # Create an embedding from prompt
227
+ embedding_response = cast(
228
+ EmbeddingResponse,
229
+ litellm.embedding(
230
+ model=self.embedding_model,
231
+ input=prompt,
232
+ cache={"no-store": True, "no-cache": True},
233
+ ),
234
+ )
235
+ embedding = embedding_response["data"][0]["embedding"]
236
+ return embedding
237
+
238
+ def _get_cache_logic(self, cached_response: Any) -> Any:
239
+ """
240
+ Process the cached response to prepare it for use.
241
+
242
+ Args:
243
+ cached_response: The raw cached response
244
+
245
+ Returns:
246
+ The processed cache response, or None if input was None
247
+ """
248
+ if cached_response is None:
249
+ return cached_response
250
+
251
+ # Convert bytes to string if needed
252
+ if isinstance(cached_response, bytes):
253
+ cached_response = cached_response.decode("utf-8")
254
+
255
+ # Convert string representation to Python object
256
+ try:
257
+ cached_response = json.loads(cached_response)
258
+ except json.JSONDecodeError:
259
+ try:
260
+ cached_response = ast.literal_eval(cached_response)
261
+ except (ValueError, SyntaxError) as e:
262
+ print_verbose(f"Error parsing cached response: {str(e)}")
263
+ return None
264
+
265
+ return cached_response
266
+
267
+ def set_cache(self, key: str, value: Any, **kwargs) -> None:
268
+ """
269
+ Store a value in the semantic cache.
270
+
271
+ Args:
272
+ key: The cache key used to isolate semantic cache entries
273
+ value: The response value to cache
274
+ **kwargs: Additional arguments including 'messages' for the prompt
275
+ and optional 'ttl' for time-to-live
276
+ """
277
+ print_verbose(f"Redis semantic-cache set_cache, kwargs: {kwargs}")
278
+
279
+ value_str: Optional[str] = None
280
+ try:
281
+ # Extract the prompt from messages
282
+ messages = kwargs.get("messages", [])
283
+ if not messages:
284
+ print_verbose("No messages provided for semantic caching")
285
+ return
286
+
287
+ prompt = get_str_from_messages(messages)
288
+ value_str = str(value)
289
+
290
+ store_kwargs: Dict[str, Any] = {
291
+ "filters": self._get_cache_filters(key),
292
+ }
293
+
294
+ # Get TTL and store in Redis semantic cache
295
+ ttl = self._get_ttl(**kwargs)
296
+ if ttl is not None:
297
+ store_kwargs["ttl"] = int(ttl)
298
+ self.llmcache.store(prompt, value_str, **store_kwargs)
299
+ except Exception as e:
300
+ print_verbose(
301
+ f"Error setting {value_str or value} in the Redis semantic cache: {str(e)}"
302
+ )
303
+
304
+ def get_cache(self, key: str, **kwargs) -> Any:
305
+ """
306
+ Retrieve a semantically similar cached response.
307
+
308
+ Args:
309
+ key: The cache key used to isolate semantic cache entries
310
+ **kwargs: Additional arguments including 'messages' for the prompt
311
+
312
+ Returns:
313
+ The cached response if a semantically similar prompt is found, else None
314
+ """
315
+ print_verbose(f"Redis semantic-cache get_cache, kwargs: {kwargs}")
316
+
317
+ try:
318
+ # Extract the prompt from messages
319
+ messages = kwargs.get("messages", [])
320
+ if not messages:
321
+ print_verbose("No messages provided for semantic cache lookup")
322
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
323
+ return None
324
+
325
+ prompt = get_str_from_messages(messages)
326
+ # Check the cache for semantically similar prompts in this exact
327
+ # LiteLLM cache-key scope.
328
+ check_kwargs: Dict[str, Any] = {
329
+ "prompt": prompt,
330
+ "filter_expression": self._get_cache_key_filter_expression(key),
331
+ }
332
+ results = self.llmcache.check(**check_kwargs)
333
+
334
+ # Return None if no similar prompts found
335
+ if not results:
336
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
337
+ return None
338
+
339
+ # Process the best matching result
340
+ cache_hit = results[0]
341
+ if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key):
342
+ print_verbose("Redis semantic-cache hit did not match cache key scope")
343
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
344
+ return None
345
+ vector_distance = float(cache_hit["vector_distance"])
346
+
347
+ # Convert vector distance back to similarity score
348
+ # For cosine distance: 0 = most similar, 2 = least similar
349
+ # While similarity: 1 = most similar, 0 = least similar
350
+ similarity = 1 - vector_distance
351
+
352
+ cached_prompt = cache_hit["prompt"]
353
+ cached_response = cache_hit["response"]
354
+
355
+ # update kwargs["metadata"] with similarity, don't rewrite the original metadata
356
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity
357
+
358
+ print_verbose(
359
+ f"Cache hit: similarity threshold: {self.similarity_threshold}, "
360
+ f"actual similarity: {similarity}, "
361
+ f"current prompt: {prompt}, "
362
+ f"cached prompt: {cached_prompt}"
363
+ )
364
+
365
+ return self._get_cache_logic(cached_response=cached_response)
366
+ except Exception as e:
367
+ print_verbose(f"Error retrieving from Redis semantic cache: {str(e)}")
368
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
369
+
370
+ async def _get_async_embedding(self, prompt: str, **kwargs) -> List[float]:
371
+ """
372
+ Asynchronously generate an embedding for the given prompt.
373
+
374
+ Args:
375
+ prompt: The text to generate an embedding for
376
+ **kwargs: Additional arguments that may contain metadata
377
+
378
+ Returns:
379
+ List[float]: The embedding vector
380
+ """
381
+ from litellm.proxy.proxy_server import llm_model_list, llm_router
382
+
383
+ # Route the embedding request through the proxy if appropriate
384
+ router_model_names = (
385
+ [m["model_name"] for m in llm_model_list]
386
+ if llm_model_list is not None
387
+ else []
388
+ )
389
+
390
+ try:
391
+ if llm_router is not None and self.embedding_model in router_model_names:
392
+ # Use the router for embedding generation
393
+ user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
394
+ embedding_response = await llm_router.aembedding(
395
+ model=self.embedding_model,
396
+ input=prompt,
397
+ cache={"no-store": True, "no-cache": True},
398
+ metadata={
399
+ "user_api_key": user_api_key,
400
+ "semantic-cache-embedding": True,
401
+ "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
402
+ },
403
+ )
404
+ else:
405
+ # Generate embedding directly
406
+ embedding_response = await litellm.aembedding(
407
+ model=self.embedding_model,
408
+ input=prompt,
409
+ cache={"no-store": True, "no-cache": True},
410
+ )
411
+
412
+ # Extract and return the embedding vector
413
+ return embedding_response["data"][0]["embedding"]
414
+ except Exception as e:
415
+ print_verbose(f"Error generating async embedding: {str(e)}")
416
+ raise ValueError(f"Failed to generate embedding: {str(e)}") from e
417
+
418
+ async def async_set_cache(self, key: str, value: Any, **kwargs) -> None:
419
+ """
420
+ Asynchronously store a value in the semantic cache.
421
+
422
+ Args:
423
+ key: The cache key used to isolate semantic cache entries
424
+ value: The response value to cache
425
+ **kwargs: Additional arguments including 'messages' for the prompt
426
+ and optional 'ttl' for time-to-live
427
+ """
428
+ print_verbose(f"Async Redis semantic-cache set_cache, kwargs: {kwargs}")
429
+
430
+ try:
431
+ # Extract the prompt from messages
432
+ messages = kwargs.get("messages", [])
433
+ if not messages:
434
+ print_verbose("No messages provided for semantic caching")
435
+ return
436
+
437
+ prompt = get_str_from_messages(messages)
438
+ value_str = str(value)
439
+
440
+ # Generate embedding for the value (response) to cache
441
+ prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
442
+
443
+ store_kwargs: Dict[str, Any] = {
444
+ "vector": prompt_embedding,
445
+ "filters": self._get_cache_filters(key),
446
+ }
447
+
448
+ # Get TTL and store in Redis semantic cache
449
+ ttl = self._get_ttl(**kwargs)
450
+ if ttl is not None:
451
+ store_kwargs["ttl"] = ttl
452
+ await self.llmcache.astore(
453
+ prompt,
454
+ value_str,
455
+ **store_kwargs,
456
+ )
457
+ except Exception as e:
458
+ print_verbose(f"Error in async_set_cache: {str(e)}")
459
+
460
+ async def async_get_cache(self, key: str, **kwargs) -> Any:
461
+ """
462
+ Asynchronously retrieve a semantically similar cached response.
463
+
464
+ Args:
465
+ key: The cache key used to isolate semantic cache entries
466
+ **kwargs: Additional arguments including 'messages' for the prompt
467
+
468
+ Returns:
469
+ The cached response if a semantically similar prompt is found, else None
470
+ """
471
+ print_verbose(f"Async Redis semantic-cache get_cache, kwargs: {kwargs}")
472
+
473
+ try:
474
+ # Extract the prompt from messages
475
+ messages = kwargs.get("messages", [])
476
+ if not messages:
477
+ print_verbose("No messages provided for semantic cache lookup")
478
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
479
+ return None
480
+
481
+ prompt = get_str_from_messages(messages)
482
+
483
+ # Generate embedding for the prompt
484
+ prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
485
+
486
+ # Check the cache for semantically similar prompts in this exact
487
+ # LiteLLM cache-key scope.
488
+ check_kwargs: Dict[str, Any] = {
489
+ "prompt": prompt,
490
+ "vector": prompt_embedding,
491
+ "filter_expression": self._get_cache_key_filter_expression(key),
492
+ }
493
+ results = await self.llmcache.acheck(**check_kwargs)
494
+
495
+ # handle results / cache hit
496
+ if not results:
497
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
498
+ return None
499
+
500
+ cache_hit = results[0]
501
+ if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key):
502
+ print_verbose("Redis semantic-cache hit did not match cache key scope")
503
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
504
+ return None
505
+ vector_distance = float(cache_hit["vector_distance"])
506
+
507
+ # Convert vector distance back to similarity
508
+ # For cosine distance: 0 = most similar, 2 = least similar
509
+ # While similarity: 1 = most similar, 0 = least similar
510
+ similarity = 1 - vector_distance
511
+
512
+ cached_prompt = cache_hit["prompt"]
513
+ cached_response = cache_hit["response"]
514
+
515
+ # update kwargs["metadata"] with similarity, don't rewrite the original metadata
516
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity
517
+
518
+ print_verbose(
519
+ f"Cache hit: similarity threshold: {self.similarity_threshold}, "
520
+ f"actual similarity: {similarity}, "
521
+ f"current prompt: {prompt}, "
522
+ f"cached prompt: {cached_prompt}"
523
+ )
524
+
525
+ return self._get_cache_logic(cached_response=cached_response)
526
+ except Exception as e:
527
+ print_verbose(f"Error in async_get_cache: {str(e)}")
528
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
529
+
530
+ async def _index_info(self) -> Dict[str, Any]:
531
+ """
532
+ Get information about the Redis index.
533
+
534
+ Returns:
535
+ Dict[str, Any]: Information about the Redis index
536
+ """
537
+ aindex = await self.llmcache._get_async_index()
538
+ return await aindex.info()
539
+
540
+ async def async_set_cache_pipeline(
541
+ self, cache_list: List[Tuple[str, Any]], **kwargs
542
+ ) -> None:
543
+ """
544
+ Asynchronously store multiple values in the semantic cache.
545
+
546
+ Args:
547
+ cache_list: List of (key, value) tuples to cache
548
+ **kwargs: Additional arguments
549
+ """
550
+ try:
551
+ tasks = []
552
+ for val in cache_list:
553
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
554
+ await asyncio.gather(*tasks)
555
+ except Exception as e:
556
+ print_verbose(f"Error in async_set_cache_pipeline: {str(e)}")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/s3_cache.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ S3 Cache implementation
3
+
4
+ Has 4 methods:
5
+ - set_cache
6
+ - get_cache
7
+ - async_set_cache (uses run_in_executor)
8
+ - async_get_cache (uses run_in_executor)
9
+ """
10
+
11
+ import ast
12
+ import asyncio
13
+ import json
14
+ from functools import partial
15
+ from typing import Optional
16
+ from datetime import datetime, timezone, timedelta
17
+
18
+ from litellm._logging import print_verbose, verbose_logger
19
+
20
+ from .base_cache import BaseCache
21
+
22
+
23
+ class S3Cache(BaseCache):
24
+ def __init__(
25
+ self,
26
+ s3_bucket_name,
27
+ s3_region_name=None,
28
+ s3_api_version=None,
29
+ s3_use_ssl: Optional[bool] = True,
30
+ s3_verify=None,
31
+ s3_endpoint_url=None,
32
+ s3_aws_access_key_id=None,
33
+ s3_aws_secret_access_key=None,
34
+ s3_aws_session_token=None,
35
+ s3_config=None,
36
+ s3_path=None,
37
+ **kwargs,
38
+ ):
39
+ import boto3
40
+
41
+ self.bucket_name = s3_bucket_name
42
+ self.key_prefix = s3_path.rstrip("/") + "/" if s3_path else ""
43
+ # Create an S3 client with custom endpoint URL
44
+
45
+ self.s3_client = boto3.client(
46
+ "s3",
47
+ region_name=s3_region_name,
48
+ endpoint_url=s3_endpoint_url,
49
+ api_version=s3_api_version,
50
+ use_ssl=s3_use_ssl,
51
+ verify=s3_verify,
52
+ aws_access_key_id=s3_aws_access_key_id,
53
+ aws_secret_access_key=s3_aws_secret_access_key,
54
+ aws_session_token=s3_aws_session_token,
55
+ config=s3_config,
56
+ **kwargs,
57
+ )
58
+
59
+ def _to_s3_key(self, key: str) -> str:
60
+ """Convert cache key to S3 key"""
61
+ return self.key_prefix + key.replace(":", "/")
62
+
63
+ def set_cache(self, key, value, **kwargs):
64
+ try:
65
+ print_verbose(f"LiteLLM SET Cache - S3. Key={key}. Value={value}")
66
+ ttl = kwargs.get("ttl", None)
67
+ # Convert value to JSON before storing in S3
68
+ serialized_value = json.dumps(value)
69
+ key = self._to_s3_key(key)
70
+
71
+ if ttl is not None:
72
+ cache_control = f"immutable, max-age={ttl}, s-maxage={ttl}"
73
+
74
+ # Calculate expiration time
75
+ expiration_time = datetime.now(timezone.utc) + timedelta(seconds=ttl)
76
+ # Upload the data to S3 with the calculated expiration time
77
+ self.s3_client.put_object(
78
+ Bucket=self.bucket_name,
79
+ Key=key,
80
+ Body=serialized_value,
81
+ Expires=expiration_time,
82
+ CacheControl=cache_control,
83
+ ContentType="application/json",
84
+ ContentLanguage="en",
85
+ ContentDisposition=f'inline; filename="{key}.json"',
86
+ )
87
+ else:
88
+ cache_control = "immutable, max-age=31536000, s-maxage=31536000"
89
+ # Upload the data to S3 without specifying Expires
90
+ self.s3_client.put_object(
91
+ Bucket=self.bucket_name,
92
+ Key=key,
93
+ Body=serialized_value,
94
+ CacheControl=cache_control,
95
+ ContentType="application/json",
96
+ ContentLanguage="en",
97
+ ContentDisposition=f'inline; filename="{key}.json"',
98
+ )
99
+ except Exception as e:
100
+ print_verbose(f"S3 Caching: set_cache() - Got exception from S3: {e}")
101
+
102
+ async def async_set_cache(self, key, value, **kwargs):
103
+ """
104
+ Asynchronously set cache using run_in_executor to avoid blocking the event loop.
105
+ Compatible with Python 3.8+.
106
+ """
107
+ try:
108
+ verbose_logger.debug(f"Set ASYNC S3 Cache: Key={key}. Value={value}")
109
+ loop = asyncio.get_event_loop()
110
+ func = partial(self.set_cache, key, value, **kwargs)
111
+ await loop.run_in_executor(None, func)
112
+ except Exception as e:
113
+ verbose_logger.error(
114
+ f"S3 Caching: async_set_cache() - Got exception from S3: {e}"
115
+ )
116
+
117
+ def get_cache(self, key, **kwargs):
118
+ import botocore
119
+
120
+ try:
121
+ key = self._to_s3_key(key)
122
+
123
+ print_verbose(f"Get S3 Cache: key: {key}")
124
+ # Download the data from S3
125
+ cached_response = self.s3_client.get_object(
126
+ Bucket=self.bucket_name, Key=key
127
+ )
128
+
129
+ if cached_response is not None:
130
+ if "Expires" in cached_response:
131
+ expires_time = cached_response["Expires"]
132
+ current_time = datetime.now(expires_time.tzinfo)
133
+
134
+ if current_time > expires_time:
135
+ return None
136
+
137
+ # cached_response is in `b{} convert it to ModelResponse
138
+ cached_response = (
139
+ cached_response["Body"].read().decode("utf-8")
140
+ ) # Convert bytes to string
141
+ try:
142
+ cached_response = json.loads(
143
+ cached_response
144
+ ) # Convert string to dictionary
145
+ except Exception:
146
+ cached_response = ast.literal_eval(cached_response)
147
+ if not isinstance(cached_response, dict):
148
+ cached_response = dict(cached_response)
149
+ verbose_logger.debug(
150
+ f"Got S3 Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}"
151
+ )
152
+
153
+ return cached_response
154
+ except botocore.exceptions.ClientError as e: # type: ignore
155
+ if e.response["Error"]["Code"] == "NoSuchKey":
156
+ verbose_logger.debug(
157
+ f"S3 Cache: The specified key '{key}' does not exist in the S3 bucket."
158
+ )
159
+ return None
160
+
161
+ except Exception as e:
162
+ verbose_logger.error(
163
+ f"S3 Caching: get_cache() - Got exception from S3: {e}"
164
+ )
165
+
166
+ async def async_get_cache(self, key, **kwargs):
167
+ """
168
+ Asynchronously get cache using run_in_executor to avoid blocking the event loop.
169
+ Compatible with Python 3.8+.
170
+ """
171
+ try:
172
+ verbose_logger.debug(f"Get ASYNC S3 Cache: key: {key}")
173
+ loop = asyncio.get_event_loop()
174
+ func = partial(self.get_cache, key, **kwargs)
175
+ result = await loop.run_in_executor(None, func)
176
+ return result
177
+ except Exception as e:
178
+ verbose_logger.error(
179
+ f"S3 Caching: async_get_cache() - Got exception from S3: {e}"
180
+ )
181
+ return None
182
+
183
+ def flush_cache(self):
184
+ pass
185
+
186
+ async def disconnect(self):
187
+ pass
188
+
189
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
190
+ tasks = []
191
+ for val in cache_list:
192
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
193
+ await asyncio.gather(*tasks)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Logic specific for `litellm.completion`.
2
+
3
+ Includes:
4
+ - Bridge for transforming completion requests to responses api requests
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .litellm_responses_transformation import responses_api_bridge
2
+
3
+ __all__ = ["responses_api_bridge"]