netra-sdk 0.1.28__tar.gz → 0.1.30__tar.gz
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.
Potentially problematic release.
This version of netra-sdk might be problematic. Click here for more details.
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/PKG-INFO +1 -1
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/__init__.py +89 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/config.py +11 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/decorators.py +27 -2
- netra_sdk-0.1.30/netra/processors/__init__.py +4 -0
- netra_sdk-0.1.30/netra/processors/instrumentation_span_processor.py +102 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/session_manager.py +88 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/span_wrapper.py +14 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/tracer.py +3 -2
- netra_sdk-0.1.30/netra/version.py +1 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/pyproject.toml +1 -1
- netra_sdk-0.1.28/netra/processors/__init__.py +0 -3
- netra_sdk-0.1.28/netra/version.py +0 -1
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/LICENCE +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/README.md +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/anonymizer/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/anonymizer/anonymizer.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/anonymizer/base.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/anonymizer/fp_anonymizer.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/exceptions/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/exceptions/injection.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/exceptions/pii.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/input_scanner.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/aiohttp/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/aiohttp/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/cohere/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/cohere/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/fastapi/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/fastapi/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/google_genai/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/google_genai/config.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/google_genai/utils.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/google_genai/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/httpx/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/httpx/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/instruments.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/mistralai/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/mistralai/config.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/mistralai/utils.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/mistralai/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/openai/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/openai/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/openai/wrappers.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/pydantic_ai/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/pydantic_ai/utils.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/pydantic_ai/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/pydantic_ai/wrappers.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/weaviate/__init__.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/instrumentation/weaviate/version.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/pii.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/processors/session_span_processor.py +0 -0
- {netra_sdk-0.1.28 → netra_sdk-0.1.30}/netra/scanner.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: netra-sdk
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.30
|
|
4
4
|
Summary: A Python SDK for AI application observability that provides OpenTelemetry-based monitoring, tracing, and PII protection for LLM and vector database applications. Enables easy instrumentation, session tracking, and privacy-focused data collection for AI systems in production environments.
|
|
5
5
|
License: Apache-2.0
|
|
6
6
|
Keywords: netra,tracing,observability,sdk,ai,llm,vector,database
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
+
import atexit
|
|
1
2
|
import logging
|
|
2
3
|
import threading
|
|
3
4
|
from typing import Any, Dict, Optional, Set
|
|
4
5
|
|
|
6
|
+
from opentelemetry import context as context_api
|
|
7
|
+
from opentelemetry import trace
|
|
8
|
+
from opentelemetry.trace import SpanKind
|
|
9
|
+
|
|
5
10
|
from netra.instrumentation.instruments import InstrumentSet, NetraInstruments
|
|
6
11
|
|
|
7
12
|
from .config import Config
|
|
@@ -27,6 +32,8 @@ class Netra:
|
|
|
27
32
|
_initialized = False
|
|
28
33
|
# Use RLock so the thread that already owns the lock can re-acquire it safely
|
|
29
34
|
_init_lock = threading.RLock()
|
|
35
|
+
_root_span = None
|
|
36
|
+
_root_ctx_token = None
|
|
30
37
|
|
|
31
38
|
@classmethod
|
|
32
39
|
def is_initialized(cls) -> bool:
|
|
@@ -46,6 +53,7 @@ class Netra:
|
|
|
46
53
|
disable_batch: Optional[bool] = None,
|
|
47
54
|
trace_content: Optional[bool] = None,
|
|
48
55
|
debug_mode: Optional[bool] = None,
|
|
56
|
+
enable_root_span: Optional[bool] = None,
|
|
49
57
|
resource_attributes: Optional[Dict[str, Any]] = None,
|
|
50
58
|
environment: Optional[str] = None,
|
|
51
59
|
instruments: Optional[Set[NetraInstruments]] = None,
|
|
@@ -66,6 +74,7 @@ class Netra:
|
|
|
66
74
|
disable_batch=disable_batch,
|
|
67
75
|
trace_content=trace_content,
|
|
68
76
|
debug_mode=debug_mode,
|
|
77
|
+
enable_root_span=enable_root_span,
|
|
69
78
|
resource_attributes=resource_attributes,
|
|
70
79
|
environment=environment,
|
|
71
80
|
)
|
|
@@ -106,6 +115,61 @@ class Netra:
|
|
|
106
115
|
cls._initialized = True
|
|
107
116
|
logger.info("Netra successfully initialized.")
|
|
108
117
|
|
|
118
|
+
# Create and attach a long-lived root span if enabled
|
|
119
|
+
if cfg.enable_root_span:
|
|
120
|
+
tracer = trace.get_tracer("netra.root.span")
|
|
121
|
+
root_name = f"{Config.LIBRARY_NAME}.root.span"
|
|
122
|
+
root_span = tracer.start_span(root_name, kind=SpanKind.INTERNAL)
|
|
123
|
+
# Add useful attributes
|
|
124
|
+
if cfg.app_name:
|
|
125
|
+
root_span.set_attribute("service.name", cfg.app_name)
|
|
126
|
+
root_span.set_attribute("netra.environment", cfg.environment)
|
|
127
|
+
root_span.set_attribute("netra.library.version", Config.LIBRARY_VERSION)
|
|
128
|
+
|
|
129
|
+
# Attach span to current context so subsequent spans become its children
|
|
130
|
+
ctx = trace.set_span_in_context(root_span)
|
|
131
|
+
token = context_api.attach(ctx)
|
|
132
|
+
|
|
133
|
+
# Save for potential shutdown/cleanup and session tracking
|
|
134
|
+
cls._root_span = root_span
|
|
135
|
+
cls._root_ctx_token = token
|
|
136
|
+
try:
|
|
137
|
+
SessionManager.set_current_span(root_span)
|
|
138
|
+
except Exception:
|
|
139
|
+
pass
|
|
140
|
+
logger.info("Netra root span created and attached to context.")
|
|
141
|
+
|
|
142
|
+
# Ensure cleanup at process exit
|
|
143
|
+
atexit.register(cls.shutdown)
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
def shutdown(cls) -> None:
|
|
147
|
+
"""Optional cleanup to end the root span and detach context."""
|
|
148
|
+
with cls._init_lock:
|
|
149
|
+
if cls._root_ctx_token is not None:
|
|
150
|
+
try:
|
|
151
|
+
context_api.detach(cls._root_ctx_token)
|
|
152
|
+
except Exception:
|
|
153
|
+
pass
|
|
154
|
+
finally:
|
|
155
|
+
cls._root_ctx_token = None
|
|
156
|
+
if cls._root_span is not None:
|
|
157
|
+
try:
|
|
158
|
+
cls._root_span.end()
|
|
159
|
+
except Exception:
|
|
160
|
+
pass
|
|
161
|
+
finally:
|
|
162
|
+
cls._root_span = None
|
|
163
|
+
# Try to flush and shutdown the tracer provider to ensure export
|
|
164
|
+
try:
|
|
165
|
+
provider = trace.get_tracer_provider()
|
|
166
|
+
if hasattr(provider, "force_flush"):
|
|
167
|
+
provider.force_flush()
|
|
168
|
+
if hasattr(provider, "shutdown"):
|
|
169
|
+
provider.shutdown()
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
172
|
+
|
|
109
173
|
@classmethod
|
|
110
174
|
def set_session_id(cls, session_id: str) -> None:
|
|
111
175
|
"""
|
|
@@ -191,5 +255,30 @@ class Netra:
|
|
|
191
255
|
"""
|
|
192
256
|
return SpanWrapper(name, attributes, module_name)
|
|
193
257
|
|
|
258
|
+
@classmethod
|
|
259
|
+
def set_input(cls, value: Any, span_name: Optional[str] = None) -> None:
|
|
260
|
+
"""
|
|
261
|
+
Set custom attribute `netra.span.input` on a target span.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
value: Input payload to record (string or JSON-serializable object)
|
|
265
|
+
span_name: Optional. When provided, sets the attribute on the span registered
|
|
266
|
+
with this name. Otherwise sets on the active span.
|
|
267
|
+
"""
|
|
268
|
+
SessionManager.set_attribute_on_target_span(f"{Config.LIBRARY_NAME}.span.input", value, span_name)
|
|
269
|
+
|
|
270
|
+
@classmethod
|
|
271
|
+
def set_output(cls, value: Any, span_name: Optional[str] = None) -> None:
|
|
272
|
+
"""
|
|
273
|
+
Set custom attribute `netra.span.output` on a target span.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
value: Output payload to record (string or JSON-serializable object)
|
|
277
|
+
span_name: Optional. When provided, sets the attribute on the span registered
|
|
278
|
+
with this name. Otherwise sets on the active span.
|
|
279
|
+
"""
|
|
280
|
+
if value:
|
|
281
|
+
SessionManager.set_attribute_on_target_span(f"{Config.LIBRARY_NAME}.span.output", value, span_name)
|
|
282
|
+
|
|
194
283
|
|
|
195
284
|
__all__ = ["Netra", "UsageModel", "ActionModel"]
|
|
@@ -17,6 +17,7 @@ class Config:
|
|
|
17
17
|
- disable_batch: Whether to disable batch span processor (bool)
|
|
18
18
|
- trace_content: Whether to capture prompt/completion content (bool)
|
|
19
19
|
- debug_mode: Whether to enable SDK logging; default False (bool)
|
|
20
|
+
- enable_root_span: Whether to create a process root span; default False (bool)
|
|
20
21
|
- resource_attributes: Custom resource attributes dict (e.g., {'env': 'prod', 'version': '1.0.0'})
|
|
21
22
|
"""
|
|
22
23
|
|
|
@@ -24,6 +25,8 @@ class Config:
|
|
|
24
25
|
SDK_NAME = "netra"
|
|
25
26
|
LIBRARY_NAME = "netra"
|
|
26
27
|
LIBRARY_VERSION = __version__
|
|
28
|
+
# Maximum length for any attribute value (strings and bytes). Processors should honor this.
|
|
29
|
+
ATTRIBUTE_MAX_LEN = 1000
|
|
27
30
|
|
|
28
31
|
def __init__(
|
|
29
32
|
self,
|
|
@@ -32,6 +35,7 @@ class Config:
|
|
|
32
35
|
disable_batch: Optional[bool] = None,
|
|
33
36
|
trace_content: Optional[bool] = None,
|
|
34
37
|
debug_mode: Optional[bool] = None,
|
|
38
|
+
enable_root_span: Optional[bool] = None,
|
|
35
39
|
resource_attributes: Optional[Dict[str, Any]] = None,
|
|
36
40
|
environment: Optional[str] = None,
|
|
37
41
|
):
|
|
@@ -106,6 +110,13 @@ class Config:
|
|
|
106
110
|
else:
|
|
107
111
|
self.environment = os.getenv("NETRA_ENV", "local")
|
|
108
112
|
|
|
113
|
+
# Enable a long-lived root span for the process? Default False.
|
|
114
|
+
if enable_root_span is not None:
|
|
115
|
+
self.enable_root_span = enable_root_span
|
|
116
|
+
else:
|
|
117
|
+
env_root = os.getenv("NETRA_ENABLE_ROOT_SPAN")
|
|
118
|
+
self.enable_root_span = True if (env_root is not None and env_root.lower() in ("1", "true")) else False
|
|
119
|
+
|
|
109
120
|
# Resource attributes: param override, else parse JSON from env, else empty dict
|
|
110
121
|
if resource_attributes is not None:
|
|
111
122
|
self.resource_attributes = resource_attributes
|
|
@@ -7,6 +7,7 @@ Decorators can be applied to both functions and classes.
|
|
|
7
7
|
import functools
|
|
8
8
|
import inspect
|
|
9
9
|
import json
|
|
10
|
+
import logging
|
|
10
11
|
from typing import Any, Awaitable, Callable, Dict, Optional, ParamSpec, Tuple, TypeVar, Union, cast
|
|
11
12
|
|
|
12
13
|
from opentelemetry import trace
|
|
@@ -14,6 +15,8 @@ from opentelemetry import trace
|
|
|
14
15
|
from .config import Config
|
|
15
16
|
from .session_manager import SessionManager
|
|
16
17
|
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
17
20
|
P = ParamSpec("P")
|
|
18
21
|
R = TypeVar("R")
|
|
19
22
|
|
|
@@ -84,6 +87,13 @@ def _create_function_wrapper(func: Callable[P, R], entity_type: str, name: Optio
|
|
|
84
87
|
|
|
85
88
|
tracer = trace.get_tracer(module_name)
|
|
86
89
|
with tracer.start_as_current_span(span_name) as span:
|
|
90
|
+
# Register the span by name for cross-context attribute setting
|
|
91
|
+
try:
|
|
92
|
+
SessionManager.register_span(span_name, span)
|
|
93
|
+
SessionManager.set_current_span(span)
|
|
94
|
+
except Exception:
|
|
95
|
+
logger.exception("Failed to register span '%s' with SessionManager", span_name)
|
|
96
|
+
|
|
87
97
|
_add_span_attributes(span, func, args, kwargs, entity_type)
|
|
88
98
|
try:
|
|
89
99
|
result = await cast(Awaitable[Any], func(*args, **kwargs))
|
|
@@ -93,7 +103,11 @@ def _create_function_wrapper(func: Callable[P, R], entity_type: str, name: Optio
|
|
|
93
103
|
span.set_attribute(f"{Config.LIBRARY_NAME}.entity.error", str(e))
|
|
94
104
|
raise
|
|
95
105
|
finally:
|
|
96
|
-
#
|
|
106
|
+
# Unregister and pop entity from stack after function call is done
|
|
107
|
+
try:
|
|
108
|
+
SessionManager.unregister_span(span_name, span)
|
|
109
|
+
except Exception:
|
|
110
|
+
logger.exception("Failed to unregister span '%s' from SessionManager", span_name)
|
|
97
111
|
SessionManager.pop_entity(entity_type)
|
|
98
112
|
|
|
99
113
|
return cast(Callable[P, R], async_wrapper)
|
|
@@ -107,6 +121,13 @@ def _create_function_wrapper(func: Callable[P, R], entity_type: str, name: Optio
|
|
|
107
121
|
|
|
108
122
|
tracer = trace.get_tracer(module_name)
|
|
109
123
|
with tracer.start_as_current_span(span_name) as span:
|
|
124
|
+
# Register the span by name for cross-context attribute setting
|
|
125
|
+
try:
|
|
126
|
+
SessionManager.register_span(span_name, span)
|
|
127
|
+
SessionManager.set_current_span(span)
|
|
128
|
+
except Exception:
|
|
129
|
+
logger.exception("Failed to register span '%s' with SessionManager", span_name)
|
|
130
|
+
|
|
110
131
|
_add_span_attributes(span, func, args, kwargs, entity_type)
|
|
111
132
|
try:
|
|
112
133
|
result = func(*args, **kwargs)
|
|
@@ -116,7 +137,11 @@ def _create_function_wrapper(func: Callable[P, R], entity_type: str, name: Optio
|
|
|
116
137
|
span.set_attribute(f"{Config.LIBRARY_NAME}.entity.error", str(e))
|
|
117
138
|
raise
|
|
118
139
|
finally:
|
|
119
|
-
#
|
|
140
|
+
# Unregister and pop entity from stack after function call is done
|
|
141
|
+
try:
|
|
142
|
+
SessionManager.unregister_span(span_name, span)
|
|
143
|
+
except Exception:
|
|
144
|
+
logger.exception("Failed to unregister span '%s' from SessionManager", span_name)
|
|
120
145
|
SessionManager.pop_entity(entity_type)
|
|
121
146
|
|
|
122
147
|
return cast(Callable[P, R], sync_wrapper)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Callable, Optional
|
|
3
|
+
|
|
4
|
+
from opentelemetry import context as otel_context
|
|
5
|
+
from opentelemetry import trace
|
|
6
|
+
from opentelemetry.sdk.trace import SpanProcessor
|
|
7
|
+
|
|
8
|
+
from netra.config import Config
|
|
9
|
+
from netra.instrumentation.instruments import InstrumentSet
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
ALLOWED_INSTRUMENTATION_NAMES = {member.value for member in InstrumentSet} # type: ignore[attr-defined]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InstrumentationSpanProcessor(SpanProcessor): # type: ignore[misc]
|
|
18
|
+
"""Span processor to record this span's instrumentation name and wrap set_attribute.
|
|
19
|
+
|
|
20
|
+
- Records raw instrumentation scope name for the span
|
|
21
|
+
- Wraps span.set_attribute to truncate string values to max 1000 chars (also inside simple lists/dicts of strings)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
super().__init__()
|
|
26
|
+
|
|
27
|
+
def _detect_raw_instrumentation_name(self, span: trace.Span) -> Optional[str]:
|
|
28
|
+
"""Detect the raw instrumentation name for the span."""
|
|
29
|
+
scope = getattr(span, "instrumentation_info", None)
|
|
30
|
+
if scope is not None:
|
|
31
|
+
name = getattr(scope, "name", None)
|
|
32
|
+
if isinstance(name, str) and name:
|
|
33
|
+
# Normalize common pattern like 'opentelemetry.instrumentation.httpx' -> 'httpx'
|
|
34
|
+
try:
|
|
35
|
+
base = name.rsplit(".", 1)[-1].strip()
|
|
36
|
+
if base:
|
|
37
|
+
return base
|
|
38
|
+
except Exception:
|
|
39
|
+
pass
|
|
40
|
+
return name
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
def _truncate_value(self, value: Any) -> Any:
|
|
44
|
+
"""Truncate string values to max 1000 chars (also inside simple lists/dicts of strings)."""
|
|
45
|
+
try:
|
|
46
|
+
if isinstance(value, str):
|
|
47
|
+
return value if len(value) <= Config.ATTRIBUTE_MAX_LEN else value[: Config.ATTRIBUTE_MAX_LEN]
|
|
48
|
+
if isinstance(value, (bytes, bytearray)):
|
|
49
|
+
return value[: Config.ATTRIBUTE_MAX_LEN]
|
|
50
|
+
if isinstance(value, list):
|
|
51
|
+
# Shallow truncate strings inside lists
|
|
52
|
+
return [self._truncate_value(v) if isinstance(v, (str, bytes, bytearray)) else v for v in value]
|
|
53
|
+
if isinstance(value, dict):
|
|
54
|
+
# Shallow truncate strings inside dicts
|
|
55
|
+
return {
|
|
56
|
+
k: self._truncate_value(v) if isinstance(v, (str, bytes, bytearray)) else v
|
|
57
|
+
for k, v in value.items()
|
|
58
|
+
}
|
|
59
|
+
except Exception:
|
|
60
|
+
return value
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
def on_start(self, span: trace.Span, parent_context: Optional[otel_context.Context] = None) -> None:
|
|
64
|
+
"""Start span and wrap set_attribute."""
|
|
65
|
+
try:
|
|
66
|
+
# Wrap set_attribute first so subsequent sets are also processed
|
|
67
|
+
original_set_attribute: Callable[[str, Any], None] = span.set_attribute
|
|
68
|
+
|
|
69
|
+
def wrapped_set_attribute(key: str, value: Any) -> None:
|
|
70
|
+
try:
|
|
71
|
+
# Truncate value(s)
|
|
72
|
+
truncated = self._truncate_value(value)
|
|
73
|
+
# Forward to original
|
|
74
|
+
original_set_attribute(key, truncated)
|
|
75
|
+
# Special rule: if model key set, mark span as llm
|
|
76
|
+
if key == "gen_ai.request.model":
|
|
77
|
+
original_set_attribute(f"{Config.LIBRARY_NAME}.span.type", "llm")
|
|
78
|
+
except Exception:
|
|
79
|
+
# Best-effort; never break span
|
|
80
|
+
try:
|
|
81
|
+
original_set_attribute(key, value)
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
# Monkey patch for this span's lifetime
|
|
86
|
+
setattr(span, "set_attribute", wrapped_set_attribute)
|
|
87
|
+
|
|
88
|
+
# Set this span's instrumentation name
|
|
89
|
+
name = self._detect_raw_instrumentation_name(span)
|
|
90
|
+
if name and any(allowed in name for allowed in ALLOWED_INSTRUMENTATION_NAMES):
|
|
91
|
+
span.set_attribute(f"{Config.LIBRARY_NAME}.instrumentation.name", name)
|
|
92
|
+
except Exception:
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
def on_end(self, span: trace.Span) -> None:
|
|
96
|
+
"""End span."""
|
|
97
|
+
|
|
98
|
+
def force_flush(self, timeout_millis: int = 30000) -> None:
|
|
99
|
+
"""Force flush span."""
|
|
100
|
+
|
|
101
|
+
def shutdown(self) -> None:
|
|
102
|
+
pass
|
|
@@ -28,6 +28,9 @@ class SessionManager:
|
|
|
28
28
|
_agent_stack: List[str] = []
|
|
29
29
|
_span_stack: List[str] = []
|
|
30
30
|
|
|
31
|
+
# Span registry: name -> stack of spans (most-recent last)
|
|
32
|
+
_spans_by_name: Dict[str, List[trace.Span]] = {}
|
|
33
|
+
|
|
31
34
|
@classmethod
|
|
32
35
|
def set_current_span(cls, span: Optional[trace.Span]) -> None:
|
|
33
36
|
"""
|
|
@@ -48,6 +51,49 @@ class SessionManager:
|
|
|
48
51
|
"""
|
|
49
52
|
return cls._current_span
|
|
50
53
|
|
|
54
|
+
@classmethod
|
|
55
|
+
def register_span(cls, name: str, span: trace.Span) -> None:
|
|
56
|
+
"""
|
|
57
|
+
Register a span under a given name. Supports nested spans with the same name via a stack.
|
|
58
|
+
"""
|
|
59
|
+
try:
|
|
60
|
+
stack = cls._spans_by_name.get(name)
|
|
61
|
+
if stack is None:
|
|
62
|
+
cls._spans_by_name[name] = [span]
|
|
63
|
+
else:
|
|
64
|
+
stack.append(span)
|
|
65
|
+
except Exception:
|
|
66
|
+
logger.exception("Failed to register span '%s'", name)
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def unregister_span(cls, name: str, span: trace.Span) -> None:
|
|
70
|
+
"""
|
|
71
|
+
Unregister a span for a given name. Safe if not present.
|
|
72
|
+
"""
|
|
73
|
+
try:
|
|
74
|
+
stack = cls._spans_by_name.get(name)
|
|
75
|
+
if not stack:
|
|
76
|
+
return
|
|
77
|
+
# Remove the last matching instance (normal case)
|
|
78
|
+
for i in range(len(stack) - 1, -1, -1):
|
|
79
|
+
if stack[i] is span:
|
|
80
|
+
stack.pop(i)
|
|
81
|
+
break
|
|
82
|
+
if not stack:
|
|
83
|
+
cls._spans_by_name.pop(name, None)
|
|
84
|
+
except Exception:
|
|
85
|
+
logger.exception("Failed to unregister span '%s'", name)
|
|
86
|
+
|
|
87
|
+
@classmethod
|
|
88
|
+
def get_span_by_name(cls, name: str) -> Optional[trace.Span]:
|
|
89
|
+
"""
|
|
90
|
+
Get the most recently registered span with the given name.
|
|
91
|
+
"""
|
|
92
|
+
stack = cls._spans_by_name.get(name)
|
|
93
|
+
if stack:
|
|
94
|
+
return stack[-1]
|
|
95
|
+
return None
|
|
96
|
+
|
|
51
97
|
@classmethod
|
|
52
98
|
def push_entity(cls, entity_type: str, entity_name: str) -> None:
|
|
53
99
|
"""
|
|
@@ -190,3 +236,45 @@ class SessionManager:
|
|
|
190
236
|
span.add_event(name=name, attributes=attributes, timestamp=timestamp_ns)
|
|
191
237
|
except Exception as e:
|
|
192
238
|
logger.exception(f"Failed to add custom event: {name} - {e}")
|
|
239
|
+
|
|
240
|
+
@classmethod
|
|
241
|
+
def set_attribute_on_target_span(cls, attr_key: str, attr_value: Any, span_name: Optional[str] = None) -> None:
|
|
242
|
+
"""
|
|
243
|
+
Best-effort setter to annotate the active span with the provided attribute.
|
|
244
|
+
|
|
245
|
+
If span_name is provided, we look up that span via SessionManager's registry and set
|
|
246
|
+
the attribute on that span explicitly. Otherwise, we annotate the active span.
|
|
247
|
+
We first try the OpenTelemetry current span; if that's invalid, we fall back to
|
|
248
|
+
the SDK-managed current span from `SessionManager`.
|
|
249
|
+
"""
|
|
250
|
+
try:
|
|
251
|
+
# Convert attribute value to a JSON-safe string representation
|
|
252
|
+
try:
|
|
253
|
+
if isinstance(attr_value, str):
|
|
254
|
+
attr_str = attr_value
|
|
255
|
+
else:
|
|
256
|
+
import json
|
|
257
|
+
|
|
258
|
+
attr_str = json.dumps(attr_value)
|
|
259
|
+
except Exception:
|
|
260
|
+
attr_str = str(attr_value)
|
|
261
|
+
|
|
262
|
+
# If a target span name is provided, use the registry for explicit lookup
|
|
263
|
+
if span_name is not None:
|
|
264
|
+
target = cls.get_span_by_name(span_name)
|
|
265
|
+
if target is None:
|
|
266
|
+
logger.debug("No span found with name '%s' to set attribute %s", span_name, attr_key)
|
|
267
|
+
return
|
|
268
|
+
target.set_attribute(attr_key, attr_str)
|
|
269
|
+
return
|
|
270
|
+
|
|
271
|
+
# Otherwise annotate the active span
|
|
272
|
+
current_span = trace.get_current_span()
|
|
273
|
+
has_valid_current = getattr(current_span, "is_recording", None) is not None and current_span.is_recording()
|
|
274
|
+
candidate = current_span if has_valid_current else cls.get_current_span()
|
|
275
|
+
if candidate is None:
|
|
276
|
+
logger.debug("No active span found to set attribute %s", attr_key)
|
|
277
|
+
return
|
|
278
|
+
candidate.set_attribute(attr_key, attr_str)
|
|
279
|
+
except Exception as e:
|
|
280
|
+
logger.exception("Failed setting attribute %s: %s", attr_key, e)
|
|
@@ -11,6 +11,7 @@ from opentelemetry.trace.propagation import set_span_in_context
|
|
|
11
11
|
from pydantic import BaseModel
|
|
12
12
|
|
|
13
13
|
from netra.config import Config
|
|
14
|
+
from netra.session_manager import SessionManager
|
|
14
15
|
|
|
15
16
|
# Configure logging
|
|
16
17
|
logging.basicConfig(level=logging.INFO)
|
|
@@ -84,6 +85,14 @@ class SpanWrapper:
|
|
|
84
85
|
ctx = set_span_in_context(self.span)
|
|
85
86
|
self.context_token = context_api.attach(ctx)
|
|
86
87
|
|
|
88
|
+
# Register with SessionManager for name-based lookup
|
|
89
|
+
try:
|
|
90
|
+
SessionManager.register_span(self.name, self.span)
|
|
91
|
+
# Optionally set as current span for SDK consumers that rely on it
|
|
92
|
+
SessionManager.set_current_span(self.span)
|
|
93
|
+
except Exception:
|
|
94
|
+
logger.exception("Failed to register span '%s' with SessionManager", self.name)
|
|
95
|
+
|
|
87
96
|
logger.info(f"Started span wrapper: {self.name}")
|
|
88
97
|
return self
|
|
89
98
|
|
|
@@ -120,6 +129,11 @@ class SpanWrapper:
|
|
|
120
129
|
|
|
121
130
|
# End OpenTelemetry span and detach context
|
|
122
131
|
if self.span:
|
|
132
|
+
# Unregister from SessionManager before ending span
|
|
133
|
+
try:
|
|
134
|
+
SessionManager.unregister_span(self.name, self.span)
|
|
135
|
+
except Exception:
|
|
136
|
+
logger.exception("Failed to unregister span '%s' from SessionManager", self.name)
|
|
123
137
|
self.span.end()
|
|
124
138
|
if self.context_token:
|
|
125
139
|
context_api.detach(self.context_token)
|
|
@@ -65,9 +65,10 @@ class Tracer:
|
|
|
65
65
|
endpoint=self._format_endpoint(self.cfg.otlp_endpoint),
|
|
66
66
|
headers=self.cfg.headers,
|
|
67
67
|
)
|
|
68
|
-
# Add span processors
|
|
69
|
-
from netra.processors import SessionSpanProcessor
|
|
68
|
+
# Add span processors: first instrumentation wrapper, then session processor
|
|
69
|
+
from netra.processors import InstrumentationSpanProcessor, SessionSpanProcessor
|
|
70
70
|
|
|
71
|
+
provider.add_span_processor(InstrumentationSpanProcessor())
|
|
71
72
|
provider.add_span_processor(SessionSpanProcessor())
|
|
72
73
|
|
|
73
74
|
# Install appropriate span processor
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.30"
|
|
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "netra-sdk"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.30"
|
|
8
8
|
description = "A Python SDK for AI application observability that provides OpenTelemetry-based monitoring, tracing, and PII protection for LLM and vector database applications. Enables easy instrumentation, session tracking, and privacy-focused data collection for AI systems in production environments."
|
|
9
9
|
authors = [
|
|
10
10
|
{name = "Sooraj Thomas",email = "sooraj@keyvalue.systems"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.1.28"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|