coolhand 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coolhand/__init__.py +108 -0
- coolhand/client.py +248 -0
- coolhand/interceptor.py +259 -0
- coolhand/types.py +31 -0
- coolhand/version.py +3 -0
- coolhand-0.1.0.dist-info/METADATA +97 -0
- coolhand-0.1.0.dist-info/RECORD +9 -0
- coolhand-0.1.0.dist-info/WHEEL +4 -0
- coolhand-0.1.0.dist-info/licenses/LICENSE +201 -0
coolhand/__init__.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Coolhand Python SDK - Automatic monitoring for LLM API calls.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
import coolhand # Auto-initializes and starts monitoring
|
|
6
|
+
|
|
7
|
+
# Or configure manually:
|
|
8
|
+
coolhand.Coolhand(api_key="your-key", debug=True)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .version import __version__
|
|
12
|
+
from .types import Config, RequestData, ResponseData
|
|
13
|
+
from .client import CoolhandClient, get_instance, set_instance, initialize
|
|
14
|
+
from . import interceptor
|
|
15
|
+
|
|
16
|
+
import atexit
|
|
17
|
+
import logging
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Coolhand(CoolhandClient):
|
|
23
|
+
"""Main Coolhand class - monitors LLM API calls automatically."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, config=None, **kwargs):
|
|
26
|
+
super().__init__(config, **kwargs)
|
|
27
|
+
|
|
28
|
+
# Set as global instance
|
|
29
|
+
set_instance(self)
|
|
30
|
+
|
|
31
|
+
# Start monitoring
|
|
32
|
+
self.start_monitoring()
|
|
33
|
+
|
|
34
|
+
# Cleanup on exit
|
|
35
|
+
atexit.register(self.shutdown)
|
|
36
|
+
|
|
37
|
+
logger.info(f"Coolhand initialized (session: {self.session_id})")
|
|
38
|
+
|
|
39
|
+
def start_monitoring(self):
|
|
40
|
+
"""Start HTTP monitoring."""
|
|
41
|
+
interceptor.set_handler(self.log_interaction)
|
|
42
|
+
interceptor.patch()
|
|
43
|
+
logger.info("HTTP monitoring started")
|
|
44
|
+
|
|
45
|
+
def stop_monitoring(self):
|
|
46
|
+
"""Stop HTTP monitoring."""
|
|
47
|
+
interceptor.unpatch()
|
|
48
|
+
logger.info("HTTP monitoring stopped")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# Module-level convenience functions
|
|
52
|
+
def status() -> dict:
|
|
53
|
+
"""Get status of global instance."""
|
|
54
|
+
instance = get_instance()
|
|
55
|
+
if instance:
|
|
56
|
+
return instance.get_stats()
|
|
57
|
+
return {"error": "Not initialized"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def start_monitoring():
|
|
61
|
+
"""Start monitoring on global instance."""
|
|
62
|
+
instance = get_instance()
|
|
63
|
+
if instance and hasattr(instance, 'start_monitoring'):
|
|
64
|
+
instance.start_monitoring()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def stop_monitoring():
|
|
68
|
+
"""Stop monitoring on global instance."""
|
|
69
|
+
instance = get_instance()
|
|
70
|
+
if instance and hasattr(instance, 'stop_monitoring'):
|
|
71
|
+
instance.stop_monitoring()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def shutdown():
|
|
75
|
+
"""Shutdown global instance."""
|
|
76
|
+
instance = get_instance()
|
|
77
|
+
if instance:
|
|
78
|
+
instance.shutdown()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_global_instance():
|
|
82
|
+
"""Get global instance (for compatibility)."""
|
|
83
|
+
return get_instance()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# Auto-initialize on import
|
|
87
|
+
try:
|
|
88
|
+
if get_instance() is None:
|
|
89
|
+
_instance = Coolhand()
|
|
90
|
+
logger.info("Coolhand auto-initialized with global monitoring enabled")
|
|
91
|
+
except Exception as e:
|
|
92
|
+
logger.debug(f"Auto-initialization skipped: {e}")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
'__version__',
|
|
97
|
+
'Coolhand',
|
|
98
|
+
'Config',
|
|
99
|
+
'RequestData',
|
|
100
|
+
'ResponseData',
|
|
101
|
+
'initialize',
|
|
102
|
+
'get_instance',
|
|
103
|
+
'get_global_instance',
|
|
104
|
+
'status',
|
|
105
|
+
'start_monitoring',
|
|
106
|
+
'stop_monitoring',
|
|
107
|
+
'shutdown',
|
|
108
|
+
]
|
coolhand/client.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Coolhand client for submitting API interactions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any, Dict, List, Optional, Union
|
|
10
|
+
from urllib.error import HTTPError, URLError
|
|
11
|
+
from urllib.request import Request, urlopen
|
|
12
|
+
|
|
13
|
+
from .types import Config, RequestData, ResponseData
|
|
14
|
+
from .version import __version__
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
# Sensitive headers to mask
|
|
19
|
+
SENSITIVE_HEADERS = ['authorization', 'api-key', 'x-api-key', 'openai-api-key', 'anthropic-api-key']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
BASE_URL = 'https://coolhandlabs.com'
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _get_default_config() -> Config:
|
|
26
|
+
"""Get default configuration from environment."""
|
|
27
|
+
return {
|
|
28
|
+
'api_key': os.getenv('COOLHAND_API_KEY', 'demo-key'),
|
|
29
|
+
'silent': os.getenv('COOLHAND_SILENT', 'true').lower() == 'true',
|
|
30
|
+
'auto_submit': True,
|
|
31
|
+
'session_id': f"session_{int(time.time() * 1000)}",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mask_value(value: str) -> str:
|
|
36
|
+
"""Mask a sensitive value, keeping first/last 4 chars."""
|
|
37
|
+
if len(value) <= 8:
|
|
38
|
+
return '*' * len(value)
|
|
39
|
+
return f"{value[:4]}{'*' * (len(value) - 8)}{value[-4:]}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _sanitize_headers(headers: Dict[str, str]) -> Dict[str, str]:
|
|
43
|
+
"""Sanitize sensitive headers."""
|
|
44
|
+
result = {}
|
|
45
|
+
for key, value in headers.items():
|
|
46
|
+
if any(s in key.lower() for s in SENSITIVE_HEADERS):
|
|
47
|
+
result[key] = _mask_value(str(value))
|
|
48
|
+
else:
|
|
49
|
+
result[key] = value
|
|
50
|
+
return result
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse_body(body: Optional[Union[str, bytes, Dict]]) -> Optional[Union[str, Dict]]:
|
|
54
|
+
"""Parse body to JSON object if possible, otherwise return as string."""
|
|
55
|
+
if body is None:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
# Already a dict
|
|
59
|
+
if isinstance(body, dict):
|
|
60
|
+
return body
|
|
61
|
+
|
|
62
|
+
# Convert bytes to string
|
|
63
|
+
if isinstance(body, bytes):
|
|
64
|
+
try:
|
|
65
|
+
body = body.decode('utf-8')
|
|
66
|
+
except:
|
|
67
|
+
return str(body)
|
|
68
|
+
|
|
69
|
+
# Try to parse as JSON
|
|
70
|
+
if isinstance(body, str):
|
|
71
|
+
try:
|
|
72
|
+
return json.loads(body)
|
|
73
|
+
except:
|
|
74
|
+
return body
|
|
75
|
+
|
|
76
|
+
return str(body)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _to_iso8601(timestamp: float) -> str:
|
|
80
|
+
"""Convert Unix timestamp to ISO 8601 string."""
|
|
81
|
+
return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class CoolhandClient:
|
|
85
|
+
"""Simple client for submitting interactions to Coolhand."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, config: Optional[Config] = None, **kwargs):
|
|
88
|
+
"""Initialize the client."""
|
|
89
|
+
self.config = _get_default_config()
|
|
90
|
+
if config:
|
|
91
|
+
self.config.update(config)
|
|
92
|
+
self.config.update(kwargs)
|
|
93
|
+
|
|
94
|
+
self._queue: List[Dict[str, Any]] = []
|
|
95
|
+
self._interaction_count = 0
|
|
96
|
+
|
|
97
|
+
if not self.config.get('silent'):
|
|
98
|
+
logging.basicConfig(level=logging.INFO)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def session_id(self) -> str:
|
|
102
|
+
return self.config.get('session_id', '')
|
|
103
|
+
|
|
104
|
+
def log_interaction(
|
|
105
|
+
self,
|
|
106
|
+
request: RequestData,
|
|
107
|
+
response: Optional[ResponseData] = None,
|
|
108
|
+
error: Optional[str] = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
"""Log an API interaction in flat format matching Ruby/Node SDKs."""
|
|
111
|
+
self._interaction_count += 1
|
|
112
|
+
|
|
113
|
+
# Get timestamps
|
|
114
|
+
req_timestamp = request.get('timestamp', time.time())
|
|
115
|
+
res_timestamp = response.get('timestamp', time.time()) if response else time.time()
|
|
116
|
+
duration_seconds = response.get('duration', 0.0) if response else 0.0
|
|
117
|
+
|
|
118
|
+
# Build flat interaction data (matching Ruby/Node format)
|
|
119
|
+
interaction = {
|
|
120
|
+
'id': str(uuid.uuid4()),
|
|
121
|
+
'timestamp': _to_iso8601(req_timestamp),
|
|
122
|
+
'method': request.get('method', '').lower(),
|
|
123
|
+
'url': request.get('url', ''),
|
|
124
|
+
'headers': _sanitize_headers(request.get('headers', {})),
|
|
125
|
+
'request_body': _parse_body(request.get('body')),
|
|
126
|
+
'response_headers': _sanitize_headers(response.get('headers', {})) if response else {},
|
|
127
|
+
'response_body': _parse_body(response.get('body')) if response else None,
|
|
128
|
+
'status_code': response.get('status_code', 0) if response else 0,
|
|
129
|
+
'duration_ms': round(duration_seconds * 1000, 2),
|
|
130
|
+
'completed_at': _to_iso8601(res_timestamp),
|
|
131
|
+
'is_streaming': response.get('is_streaming', False) if response else False,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
# Debug output when not silent
|
|
135
|
+
if not self.config.get('silent'):
|
|
136
|
+
url = request.get('url', 'unknown')
|
|
137
|
+
method = request.get('method', 'unknown')
|
|
138
|
+
status = response.get('status_code') if response else 'error'
|
|
139
|
+
logger.info(f"Captured: {method} {url} -> {status}")
|
|
140
|
+
|
|
141
|
+
self._queue.append(interaction)
|
|
142
|
+
|
|
143
|
+
# Auto-submit if enabled
|
|
144
|
+
if self.config.get('auto_submit') and len(self._queue) >= 1:
|
|
145
|
+
self.flush()
|
|
146
|
+
|
|
147
|
+
def flush(self) -> bool:
|
|
148
|
+
"""Submit queued interactions to Coolhand API."""
|
|
149
|
+
if not self._queue:
|
|
150
|
+
return True
|
|
151
|
+
|
|
152
|
+
api_key = self.config.get('api_key')
|
|
153
|
+
if not api_key or api_key == 'demo-key':
|
|
154
|
+
logger.debug("No API key configured, skipping submission")
|
|
155
|
+
self._queue.clear()
|
|
156
|
+
return True
|
|
157
|
+
|
|
158
|
+
success_count = 0
|
|
159
|
+
|
|
160
|
+
for interaction in self._queue:
|
|
161
|
+
try:
|
|
162
|
+
payload = {
|
|
163
|
+
'llm_request_log': {
|
|
164
|
+
'raw_request': interaction,
|
|
165
|
+
'collector': f'coolhand-python-{__version__}-auto-monitor',
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
request = Request(
|
|
170
|
+
url=f"{BASE_URL}/api/v2/llm_request_logs",
|
|
171
|
+
data=json.dumps(payload, default=str).encode('utf-8'),
|
|
172
|
+
headers={
|
|
173
|
+
'X-API-Key': api_key,
|
|
174
|
+
'Content-Type': 'application/json',
|
|
175
|
+
'User-Agent': f'coolhand-python/{__version__}',
|
|
176
|
+
},
|
|
177
|
+
method='POST',
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
with urlopen(request, timeout=10) as resp:
|
|
181
|
+
if resp.status == 200 or resp.status == 201:
|
|
182
|
+
success_count += 1
|
|
183
|
+
|
|
184
|
+
except (HTTPError, URLError) as e:
|
|
185
|
+
logger.warning(f"Failed to submit interaction: {e}")
|
|
186
|
+
except Exception as e:
|
|
187
|
+
logger.warning(f"Unexpected error submitting interaction: {e}")
|
|
188
|
+
|
|
189
|
+
if success_count > 0:
|
|
190
|
+
logger.info(f"Successfully submitted {success_count}/{len(self._queue)} interactions to Coolhand")
|
|
191
|
+
|
|
192
|
+
self._queue.clear()
|
|
193
|
+
return success_count == len(self._queue)
|
|
194
|
+
|
|
195
|
+
def get_stats(self) -> Dict[str, Any]:
|
|
196
|
+
"""Get client statistics."""
|
|
197
|
+
# Check if httpx is patched
|
|
198
|
+
patched_libs = []
|
|
199
|
+
try:
|
|
200
|
+
from . import interceptor
|
|
201
|
+
if interceptor.is_patched():
|
|
202
|
+
patched_libs = ['httpx.Client.send', 'httpx.AsyncClient.send']
|
|
203
|
+
except:
|
|
204
|
+
pass
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
'config': {
|
|
208
|
+
'has_api_key': bool(self.config.get('api_key')),
|
|
209
|
+
},
|
|
210
|
+
'monitoring': {
|
|
211
|
+
'enabled': True,
|
|
212
|
+
'patched_libraries': patched_libs,
|
|
213
|
+
},
|
|
214
|
+
'logging': {
|
|
215
|
+
'session_id': self.session_id,
|
|
216
|
+
'interaction_count': self._interaction_count,
|
|
217
|
+
'queue_size': len(self._queue),
|
|
218
|
+
},
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
def shutdown(self) -> None:
|
|
222
|
+
"""Flush and cleanup."""
|
|
223
|
+
logger.info("Shutting down Coolhand...")
|
|
224
|
+
self.flush()
|
|
225
|
+
logger.info("Coolhand shutdown complete")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# Global instance
|
|
229
|
+
_instance: Optional[CoolhandClient] = None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def get_instance() -> Optional[CoolhandClient]:
|
|
233
|
+
"""Get the global client instance."""
|
|
234
|
+
return _instance
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def set_instance(instance: CoolhandClient) -> None:
|
|
238
|
+
"""Set the global client instance."""
|
|
239
|
+
global _instance
|
|
240
|
+
_instance = instance
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def initialize(config: Optional[Config] = None, **kwargs) -> CoolhandClient:
|
|
244
|
+
"""Initialize the global client."""
|
|
245
|
+
global _instance
|
|
246
|
+
if _instance is None:
|
|
247
|
+
_instance = CoolhandClient(config, **kwargs)
|
|
248
|
+
return _instance
|
coolhand/interceptor.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""HTTP interceptor for capturing API calls - patches httpx only."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Callable, Optional
|
|
6
|
+
from urllib.parse import urlparse
|
|
7
|
+
|
|
8
|
+
from .types import RequestData, ResponseData
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
# State
|
|
13
|
+
_patched = False
|
|
14
|
+
_original_send: Optional[Callable] = None
|
|
15
|
+
_original_async_send: Optional[Callable] = None
|
|
16
|
+
_handler: Optional[Callable[[RequestData, Optional[ResponseData], Optional[str]], None]] = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Known LLM API domains to monitor
|
|
20
|
+
LLM_API_DOMAINS = [
|
|
21
|
+
'api.openai.com',
|
|
22
|
+
'api.anthropic.com',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _is_localhost(url: str) -> bool:
|
|
27
|
+
"""Check if URL is localhost."""
|
|
28
|
+
try:
|
|
29
|
+
host = urlparse(url).netloc.lower()
|
|
30
|
+
return any(p in host for p in ['localhost', '127.0.0.1', '0.0.0.0', '::1'])
|
|
31
|
+
except:
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _is_llm_api(url: str) -> bool:
|
|
36
|
+
"""Check if URL is a known LLM API endpoint."""
|
|
37
|
+
try:
|
|
38
|
+
host = urlparse(url).netloc.lower()
|
|
39
|
+
return any(domain in host for domain in LLM_API_DOMAINS)
|
|
40
|
+
except:
|
|
41
|
+
return False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_streaming_content_type(content_type: str) -> bool:
|
|
45
|
+
"""Check if content type indicates streaming."""
|
|
46
|
+
return 'text/event-stream' in content_type or 'application/x-ndjson' in content_type
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _read_response_body(response: Any) -> Any:
|
|
50
|
+
"""Safely read response body."""
|
|
51
|
+
try:
|
|
52
|
+
content_type = response.headers.get('content-type', '')
|
|
53
|
+
if _is_streaming_content_type(content_type):
|
|
54
|
+
return '[streaming]'
|
|
55
|
+
|
|
56
|
+
if hasattr(response, '_content') and response._content:
|
|
57
|
+
return response._content
|
|
58
|
+
if hasattr(response, 'content'):
|
|
59
|
+
return response.content
|
|
60
|
+
except:
|
|
61
|
+
pass
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_handler(handler: Callable[[RequestData, Optional[ResponseData], Optional[str]], None]) -> None:
|
|
66
|
+
"""Set the handler for captured requests."""
|
|
67
|
+
global _handler
|
|
68
|
+
_handler = handler
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def patch() -> bool:
|
|
72
|
+
"""Patch httpx to intercept requests."""
|
|
73
|
+
global _patched, _original_send, _original_async_send
|
|
74
|
+
|
|
75
|
+
if _patched:
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
import httpx
|
|
80
|
+
except ImportError:
|
|
81
|
+
logger.debug("httpx not available")
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
# Save originals
|
|
85
|
+
_original_send = httpx.Client.send
|
|
86
|
+
_original_async_send = httpx.AsyncClient.send
|
|
87
|
+
|
|
88
|
+
def patched_send(self, request, **kwargs):
|
|
89
|
+
"""Patched sync send."""
|
|
90
|
+
url = str(request.url)
|
|
91
|
+
|
|
92
|
+
# Only capture LLM API requests
|
|
93
|
+
if not _is_llm_api(url) or _is_localhost(url) or not _handler:
|
|
94
|
+
return _original_send(self, request, **kwargs)
|
|
95
|
+
|
|
96
|
+
start = time.time()
|
|
97
|
+
req_data: RequestData = {
|
|
98
|
+
'method': request.method,
|
|
99
|
+
'url': url,
|
|
100
|
+
'headers': dict(request.headers),
|
|
101
|
+
'body': request.content.decode('utf-8') if request.content else None,
|
|
102
|
+
'timestamp': start,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
response = _original_send(self, request, **kwargs)
|
|
107
|
+
duration = time.time() - start
|
|
108
|
+
|
|
109
|
+
res_data: ResponseData = {
|
|
110
|
+
'status_code': response.status_code,
|
|
111
|
+
'headers': dict(response.headers),
|
|
112
|
+
'body': _read_response_body(response),
|
|
113
|
+
'timestamp': time.time(),
|
|
114
|
+
'duration': duration,
|
|
115
|
+
'is_streaming': False,
|
|
116
|
+
}
|
|
117
|
+
_handler(req_data, res_data, None)
|
|
118
|
+
return response
|
|
119
|
+
|
|
120
|
+
except Exception as e:
|
|
121
|
+
_handler(req_data, None, str(e))
|
|
122
|
+
raise
|
|
123
|
+
|
|
124
|
+
async def patched_async_send(self, request, **kwargs):
|
|
125
|
+
"""Patched async send."""
|
|
126
|
+
url = str(request.url)
|
|
127
|
+
|
|
128
|
+
# Only capture LLM API requests
|
|
129
|
+
if not _is_llm_api(url) or _is_localhost(url) or not _handler:
|
|
130
|
+
return await _original_async_send(self, request, **kwargs)
|
|
131
|
+
|
|
132
|
+
start = time.time()
|
|
133
|
+
req_data: RequestData = {
|
|
134
|
+
'method': request.method,
|
|
135
|
+
'url': url,
|
|
136
|
+
'headers': dict(request.headers),
|
|
137
|
+
'body': request.content.decode('utf-8') if request.content else None,
|
|
138
|
+
'timestamp': start,
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
response = await _original_async_send(self, request, **kwargs)
|
|
143
|
+
duration = time.time() - start
|
|
144
|
+
|
|
145
|
+
# Check for streaming response
|
|
146
|
+
content_type = response.headers.get('content-type', '')
|
|
147
|
+
is_streaming = _is_streaming_content_type(content_type)
|
|
148
|
+
|
|
149
|
+
if is_streaming:
|
|
150
|
+
# Wrap streaming methods to capture content
|
|
151
|
+
captured_chunks = []
|
|
152
|
+
content_sent = [False] # Use list to allow mutation in closures
|
|
153
|
+
|
|
154
|
+
def send_captured():
|
|
155
|
+
if not content_sent[0] and captured_chunks:
|
|
156
|
+
content_sent[0] = True
|
|
157
|
+
res_data: ResponseData = {
|
|
158
|
+
'status_code': response.status_code,
|
|
159
|
+
'headers': dict(response.headers),
|
|
160
|
+
'body': ''.join(captured_chunks),
|
|
161
|
+
'timestamp': time.time(),
|
|
162
|
+
'duration': time.time() - start,
|
|
163
|
+
'is_streaming': True,
|
|
164
|
+
}
|
|
165
|
+
_handler(req_data, res_data, None)
|
|
166
|
+
|
|
167
|
+
# Wrap aiter_bytes
|
|
168
|
+
if hasattr(response, 'aiter_bytes'):
|
|
169
|
+
orig_aiter_bytes = response.aiter_bytes
|
|
170
|
+
async def capturing_aiter_bytes(chunk_size=1024):
|
|
171
|
+
async for chunk in orig_aiter_bytes(chunk_size):
|
|
172
|
+
if chunk:
|
|
173
|
+
captured_chunks.append(chunk.decode('utf-8', errors='replace'))
|
|
174
|
+
yield chunk
|
|
175
|
+
send_captured()
|
|
176
|
+
response.aiter_bytes = capturing_aiter_bytes
|
|
177
|
+
|
|
178
|
+
# Wrap aiter_lines (used by OpenAI for SSE)
|
|
179
|
+
if hasattr(response, 'aiter_lines'):
|
|
180
|
+
orig_aiter_lines = response.aiter_lines
|
|
181
|
+
async def capturing_aiter_lines():
|
|
182
|
+
async for line in orig_aiter_lines():
|
|
183
|
+
if line:
|
|
184
|
+
captured_chunks.append(line + '\n')
|
|
185
|
+
yield line
|
|
186
|
+
send_captured()
|
|
187
|
+
response.aiter_lines = capturing_aiter_lines
|
|
188
|
+
|
|
189
|
+
# Wrap aiter_text
|
|
190
|
+
if hasattr(response, 'aiter_text'):
|
|
191
|
+
orig_aiter_text = response.aiter_text
|
|
192
|
+
async def capturing_aiter_text():
|
|
193
|
+
async for text in orig_aiter_text():
|
|
194
|
+
if text:
|
|
195
|
+
captured_chunks.append(text)
|
|
196
|
+
yield text
|
|
197
|
+
send_captured()
|
|
198
|
+
response.aiter_text = capturing_aiter_text
|
|
199
|
+
|
|
200
|
+
# Wrap aiter_raw (lowest level)
|
|
201
|
+
if hasattr(response, 'aiter_raw'):
|
|
202
|
+
orig_aiter_raw = response.aiter_raw
|
|
203
|
+
async def capturing_aiter_raw(chunk_size=1024):
|
|
204
|
+
async for chunk in orig_aiter_raw(chunk_size):
|
|
205
|
+
if chunk:
|
|
206
|
+
captured_chunks.append(chunk.decode('utf-8', errors='replace'))
|
|
207
|
+
yield chunk
|
|
208
|
+
send_captured()
|
|
209
|
+
response.aiter_raw = capturing_aiter_raw
|
|
210
|
+
else:
|
|
211
|
+
# Non-streaming: send immediately
|
|
212
|
+
res_data: ResponseData = {
|
|
213
|
+
'status_code': response.status_code,
|
|
214
|
+
'headers': dict(response.headers),
|
|
215
|
+
'body': _read_response_body(response),
|
|
216
|
+
'timestamp': time.time(),
|
|
217
|
+
'duration': duration,
|
|
218
|
+
'is_streaming': False,
|
|
219
|
+
}
|
|
220
|
+
_handler(req_data, res_data, None)
|
|
221
|
+
|
|
222
|
+
return response
|
|
223
|
+
|
|
224
|
+
except Exception as e:
|
|
225
|
+
_handler(req_data, None, str(e))
|
|
226
|
+
raise
|
|
227
|
+
|
|
228
|
+
# Apply patches
|
|
229
|
+
httpx.Client.send = patched_send
|
|
230
|
+
httpx.AsyncClient.send = patched_async_send
|
|
231
|
+
_patched = True
|
|
232
|
+
|
|
233
|
+
logger.info("Global HTTP monitoring enabled")
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def unpatch() -> None:
|
|
238
|
+
"""Restore original httpx methods."""
|
|
239
|
+
global _patched, _original_send, _original_async_send
|
|
240
|
+
|
|
241
|
+
if not _patched:
|
|
242
|
+
return
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
import httpx
|
|
246
|
+
if _original_send:
|
|
247
|
+
httpx.Client.send = _original_send
|
|
248
|
+
if _original_async_send:
|
|
249
|
+
httpx.AsyncClient.send = _original_async_send
|
|
250
|
+
except ImportError:
|
|
251
|
+
pass
|
|
252
|
+
|
|
253
|
+
_patched = False
|
|
254
|
+
logger.info("Global HTTP monitoring disabled")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def is_patched() -> bool:
|
|
258
|
+
"""Check if httpx is patched."""
|
|
259
|
+
return _patched
|
coolhand/types.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Minimal type definitions for Coolhand."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Optional, Union
|
|
4
|
+
from typing_extensions import TypedDict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class RequestData(TypedDict, total=False):
|
|
8
|
+
"""HTTP request data."""
|
|
9
|
+
method: str
|
|
10
|
+
url: str
|
|
11
|
+
headers: Dict[str, str]
|
|
12
|
+
body: Optional[Union[str, bytes, Dict[str, Any]]]
|
|
13
|
+
timestamp: float
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ResponseData(TypedDict, total=False):
|
|
17
|
+
"""HTTP response data."""
|
|
18
|
+
status_code: int
|
|
19
|
+
headers: Dict[str, str]
|
|
20
|
+
body: Optional[Union[str, bytes, Dict[str, Any]]]
|
|
21
|
+
timestamp: float
|
|
22
|
+
duration: float
|
|
23
|
+
is_streaming: bool
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Config(TypedDict, total=False):
|
|
27
|
+
"""Coolhand configuration."""
|
|
28
|
+
api_key: Optional[str]
|
|
29
|
+
silent: bool
|
|
30
|
+
auto_submit: bool
|
|
31
|
+
session_id: Optional[str]
|
coolhand/version.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: coolhand
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python SDK for monitoring and analyzing AI API interactions with LLM services
|
|
5
|
+
Project-URL: Homepage, https://github.com/Coolhand-Labs/coolhand-python
|
|
6
|
+
Project-URL: Repository, https://github.com/Coolhand-Labs/coolhand-python.git
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/Coolhand-Labs/coolhand-python/issues
|
|
8
|
+
Author-email: Michael Carroll <team@coolhandlabs.com>
|
|
9
|
+
Maintainer-email: Michael Carroll <team@coolhandlabs.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai,analytics,anthropic,api,claude,gpt,llm,monitoring,openai
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Requires-Python: >=3.7
|
|
28
|
+
Requires-Dist: typing-extensions>=3.7.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: black>=23.0.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: flake8>=6.0.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: isort>=5.12.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
34
|
+
Requires-Dist: pre-commit>=3.0.0; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
37
|
+
Provides-Extra: test
|
|
38
|
+
Requires-Dist: httpx>=0.20.0; extra == 'test'
|
|
39
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
|
|
40
|
+
Requires-Dist: pytest>=7.0.0; extra == 'test'
|
|
41
|
+
Requires-Dist: requests>=2.25.0; extra == 'test'
|
|
42
|
+
Description-Content-Type: text/markdown
|
|
43
|
+
|
|
44
|
+
# Coolhand Python
|
|
45
|
+
|
|
46
|
+
Automatic monitoring for LLM API calls in Python applications.
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install coolhand
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quick Start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import coolhand # Auto-initializes and starts monitoring
|
|
58
|
+
|
|
59
|
+
# All LLM API calls are now automatically captured
|
|
60
|
+
from openai import OpenAI
|
|
61
|
+
client = OpenAI()
|
|
62
|
+
response = client.chat.completions.create(
|
|
63
|
+
model="gpt-4",
|
|
64
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Manual Configuration
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from coolhand import Coolhand
|
|
72
|
+
|
|
73
|
+
coolhand_client = Coolhand(
|
|
74
|
+
api_key='your-api-key',
|
|
75
|
+
silent=False, # Enable verbose logging
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Environment Variables
|
|
80
|
+
|
|
81
|
+
- `COOLHAND_API_KEY`: Your Coolhand API key
|
|
82
|
+
- `COOLHAND_SILENT`: Set to `false` for verbose logging
|
|
83
|
+
|
|
84
|
+
## Supported LLM APIs
|
|
85
|
+
|
|
86
|
+
Automatically captures requests to:
|
|
87
|
+
- OpenAI (api.openai.com)
|
|
88
|
+
- Anthropic (api.anthropic.com)
|
|
89
|
+
|
|
90
|
+
## Requirements
|
|
91
|
+
|
|
92
|
+
- Python 3.7+
|
|
93
|
+
- httpx (for HTTP client patching)
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
Apache-2.0
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
coolhand/__init__.py,sha256=iknzCrG-pcElgAEr2Ah25kU7f5e564HdSF0BZ58G-0g,2633
|
|
2
|
+
coolhand/client.py,sha256=mDHEJ-678VUCV7hVSSwPW3eCdnqyb4wVTbGLiRnblsw,8141
|
|
3
|
+
coolhand/interceptor.py,sha256=ptH-m4eBK8ESyTCiU7t-rndBO-OwdhwaKbxOxm_w4dE,8819
|
|
4
|
+
coolhand/types.py,sha256=p5aR0np7ljCxT9lNvGWjRvXZ9C3yROoaXKxWXpzDTOI,757
|
|
5
|
+
coolhand/version.py,sha256=Cebtgautio9TrP1ozvgCQOcnfAW9u-o66hIxoZ68FkM,73
|
|
6
|
+
coolhand-0.1.0.dist-info/METADATA,sha256=soaMZYG_djbPtfq-1zyRZP3OCPJfsciqUxfM5Gkm1Zg,2944
|
|
7
|
+
coolhand-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
8
|
+
coolhand-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
9
|
+
coolhand-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|