veris-ai 1.0.0__py3-none-any.whl → 1.2.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.

Potentially problematic release.


This version of veris-ai might be problematic. Click here for more details.

veris_ai/__init__.py CHANGED
@@ -1,7 +1,42 @@
1
1
  """Veris AI Python SDK."""
2
2
 
3
+ from typing import Any
4
+
3
5
  __version__ = "0.1.0"
4
6
 
7
+ # Import lightweight modules that only use base dependencies
5
8
  from .tool_mock import veris
9
+ from .jaeger_interface import JaegerClient
10
+ from .models import ResponseExpectation
11
+
12
+ # Lazy import for modules with heavy dependencies
13
+ _instrument = None
14
+
15
+
16
+ def instrument(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401
17
+ """Lazy loader for the instrument function from braintrust_tracing.
18
+
19
+ This function requires the 'instrument' extra dependencies:
20
+ pip install veris-ai[instrument]
21
+ """
22
+ global _instrument # noqa: PLW0603
23
+ if _instrument is None:
24
+ try:
25
+ from .braintrust_tracing import instrument as _instrument_impl # noqa: PLC0415
26
+
27
+ _instrument = _instrument_impl
28
+ except ImportError as e:
29
+ error_msg = (
30
+ "The 'instrument' function requires additional dependencies. "
31
+ "Please install them with: pip install veris-ai[instrument]"
32
+ )
33
+ raise ImportError(error_msg) from e
34
+ return _instrument(*args, **kwargs)
35
+
6
36
 
7
- __all__ = ["veris"]
37
+ __all__ = [
38
+ "veris",
39
+ "JaegerClient",
40
+ "instrument",
41
+ "ResponseExpectation"
42
+ ]
@@ -0,0 +1,282 @@
1
+ """Non-invasive Braintrust + Jaeger (OTEL) instrumentation helper for the `openai-agents` SDK.
2
+
3
+ Typical usage
4
+ -------------
5
+ >>> from our_sdk import braintrust_tracing
6
+ >>> braintrust_tracing.instrument(service_name="openai-agent")
7
+
8
+ After calling :func:`instrument`, any later call to
9
+ ``agents.set_trace_processors([...])`` will be transparently patched so that:
10
+ • the list always contains a BraintrustTracingProcessor (for Braintrust UI)
11
+ • *and* an OpenTelemetry bridge processor that mirrors every span to the
12
+ global OTEL tracer provider (Jaeger by default).
13
+
14
+ Goal: deliver full OTEL compatibility while keeping the official Braintrust
15
+ SDK integration unchanged – **no code modifications required** besides the
16
+ single `instrument()` call.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ from typing import Any, cast
25
+
26
+ import wrapt # type: ignore[import-untyped, import-not-found]
27
+ from braintrust.wrappers.openai import (
28
+ BraintrustTracingProcessor, # type: ignore[import-untyped, import-not-found]
29
+ )
30
+ from opentelemetry import context as otel_context # type: ignore[import-untyped, import-not-found]
31
+ from opentelemetry import trace # type: ignore[import-untyped, import-not-found]
32
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
33
+ OTLPSpanExporter, # type: ignore[import-untyped, import-not-found]
34
+ )
35
+ from opentelemetry.sdk.resources import ( # type: ignore[import-untyped, import-not-found]
36
+ SERVICE_NAME,
37
+ Resource,
38
+ )
39
+ from opentelemetry.sdk.trace import TracerProvider # type: ignore[import-untyped, import-not-found]
40
+ from opentelemetry.sdk.trace.export import (
41
+ BatchSpanProcessor, # type: ignore[import-untyped, import-not-found]
42
+ )
43
+ from opentelemetry.trace import SpanKind # type: ignore[import-untyped, import-not-found]
44
+
45
+ from veris_ai.tool_mock import _session_id_context
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Optional import of *agents* – we fail lazily at runtime if missing.
49
+ # ---------------------------------------------------------------------------
50
+ try:
51
+ import agents # type: ignore[import-untyped] # noqa: TC002
52
+ from agents import TracingProcessor # type: ignore[import-untyped]
53
+
54
+ try:
55
+ from agents.tracing import get_trace_provider # type: ignore[import-untyped]
56
+ except ImportError:
57
+ # Fallback for newer versions that have GLOBAL_TRACE_PROVIDER instead
58
+ from agents.tracing import ( # type: ignore[import-untyped, attr-defined, import-not-found]
59
+ GLOBAL_TRACE_PROVIDER, # type: ignore[import-untyped, attr-defined, import-not-found]
60
+ )
61
+
62
+ get_trace_provider = lambda: GLOBAL_TRACE_PROVIDER # type: ignore[no-any-return] # noqa: E731
63
+ except ModuleNotFoundError as exc: # pragma: no cover
64
+ _IMPORT_ERR: ModuleNotFoundError | None = exc
65
+ TracingProcessor = object # type: ignore[assignment, misc]
66
+ get_trace_provider = None # type: ignore[assignment]
67
+ else:
68
+ _IMPORT_ERR = None
69
+
70
+ __all__ = ["instrument"]
71
+
72
+ logger = logging.getLogger(__name__)
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Internal helper – OTEL bridge processor
76
+ # ---------------------------------------------------------------------------
77
+
78
+
79
+ class AgentsOTELBridgeProcessor(TracingProcessor): # type: ignore[misc]
80
+ """Mirrors every Agents span into a dedicated OTEL tracer provider."""
81
+
82
+ def __init__(
83
+ self,
84
+ braintrust_processor: BraintrustTracingProcessor,
85
+ *,
86
+ service_name: str, # noqa: ARG002
87
+ tracer_provider: trace.TracerProvider,
88
+ ) -> None: # noqa: D401,E501
89
+ self._braintrust = braintrust_processor
90
+ self._tracer = tracer_provider.get_tracer(__name__)
91
+ self._otel_spans: dict[str, trace.Span] = {}
92
+ self._provider = tracer_provider
93
+
94
+ # ----------------------------- utils ---------------------------------
95
+ @staticmethod
96
+ def _flatten(prefix: str, obj: Any, out: dict[str, Any]) -> None: # noqa: PLR0911, ANN401
97
+ """Flatten complex objects into OTEL-compatible primitives."""
98
+ if isinstance(obj, dict):
99
+ for k, v in obj.items():
100
+ AgentsOTELBridgeProcessor._flatten(f"{prefix}.{k}" if prefix else str(k), v, out)
101
+ elif isinstance(obj, str | int | float | bool) or obj is None:
102
+ out[prefix] = obj
103
+ elif isinstance(obj, list | tuple):
104
+ try:
105
+ if all(isinstance(i, str | int | float | bool) or i is None for i in obj):
106
+ out[prefix] = list(obj)
107
+ else:
108
+ out[prefix] = json.dumps(obj, default=str)
109
+ except Exception: # pragma: no cover – defensive
110
+ out[prefix] = json.dumps(obj, default=str)
111
+ else:
112
+ out[prefix] = str(obj)
113
+
114
+ def _log_data_attributes(self, span_obj: agents.tracing.Span) -> dict[str, Any]: # type: ignore[name-defined]
115
+ data = self._braintrust._log_data(span_obj) # pyright: ignore[reportPrivateUsage] # noqa: SLF001
116
+ flat: dict[str, Any] = {}
117
+ self._flatten("bt", data, flat)
118
+
119
+ # Add session_id if available
120
+ session_id = _session_id_context.get()
121
+ if session_id:
122
+ flat["veris.session_id"] = session_id
123
+
124
+ return {k: v for k, v in flat.items() if v is not None}
125
+
126
+ # --------------------- Agents lifecycle hooks ------------------------
127
+ def on_trace_start(self, trace_obj: Any) -> None: # noqa: ANN401, D102
128
+ # Get session_id at trace start
129
+ session_id = _session_id_context.get()
130
+ attributes = {"veris.session_id": session_id} if session_id else {}
131
+
132
+ otel_span = self._tracer.start_span(
133
+ name=trace_obj.name or "agent-trace",
134
+ kind=SpanKind.INTERNAL,
135
+ attributes=attributes,
136
+ )
137
+ self._otel_spans[trace_obj.trace_id] = otel_span
138
+ logger.info(f"VERIS AI BraintrustTracingProcessor: on_trace_start: {trace_obj.trace_id}")
139
+
140
+ def on_trace_end(self, trace_obj: Any) -> None: # noqa: ANN401, D102
141
+ span = self._otel_spans.pop(trace_obj.trace_id, None)
142
+ if span:
143
+ span.end()
144
+
145
+ def on_span_start(self, span: Any) -> None: # noqa: ANN401, D102
146
+ parent_otel = (
147
+ self._otel_spans.get(span.parent_id)
148
+ if span.parent_id
149
+ else self._otel_spans.get(span.trace_id)
150
+ )
151
+ parent_ctx = (
152
+ trace.set_span_in_context(parent_otel) if parent_otel else otel_context.get_current()
153
+ )
154
+
155
+ # Get session_id at span start
156
+ session_id = _session_id_context.get()
157
+ attributes = {"veris.session_id": session_id} if session_id else {}
158
+
159
+ child = self._tracer.start_span(
160
+ name=span.span_data.__class__.__name__,
161
+ context=parent_ctx,
162
+ kind=SpanKind.INTERNAL,
163
+ attributes=attributes,
164
+ )
165
+ self._otel_spans[span.span_id] = child
166
+ logger.info(f"VERIS AI BraintrustTracingProcessor: on_span_start: {span.span_id}")
167
+
168
+ def on_span_end(self, span: Any) -> None: # noqa: ANN401, D102
169
+ child = self._otel_spans.pop(span.span_id, None)
170
+ logger.info(f"VERIS AI BraintrustTracingProcessor: on_span_end: {span.span_id}")
171
+ if child:
172
+ for k, v in self._log_data_attributes(span).items():
173
+ try:
174
+ child.set_attribute(k, v)
175
+ except Exception: # pragma: no cover – bad value type # noqa: S112
176
+ continue
177
+ child.end()
178
+
179
+ # --------------------- house-keeping ---------------------------------
180
+ def shutdown(self) -> None: # noqa: D401
181
+ provider = cast("TracerProvider", self._provider)
182
+ provider.shutdown() # type: ignore[attr-defined]
183
+
184
+ def force_flush(self) -> None: # noqa: D401
185
+ provider = cast("TracerProvider", self._provider)
186
+ provider.force_flush() # type: ignore[attr-defined]
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Public entry point
191
+ # ---------------------------------------------------------------------------
192
+
193
+ _PATCHED: bool = False # ensure idempotent patching
194
+
195
+
196
+ def instrument(
197
+ *,
198
+ service_name: str | None = None,
199
+ otlp_endpoint: str | None = None,
200
+ ) -> None:
201
+ """Bootstrap Braintrust + OTEL instrumentation and patch Agents SDK.
202
+
203
+ Invoke once at any point before `set_trace_processors` is called.
204
+ """
205
+ global _PATCHED # noqa: PLW0603
206
+ if _PATCHED:
207
+ return # already done
208
+
209
+ if _IMPORT_ERR is not None or get_trace_provider is None: # pragma: no cover
210
+ error_msg = "The `agents` package is required but not installed"
211
+ raise RuntimeError(error_msg) from _IMPORT_ERR
212
+
213
+ # ------------------ 0. Validate inputs -----------------------------
214
+ # Resolve service name ─ explicit argument → env var → error
215
+ if not service_name or not str(service_name).strip():
216
+ service_name = os.getenv("VERIS_SERVICE_NAME")
217
+
218
+ if not service_name or not str(service_name).strip():
219
+ error_msg = (
220
+ "`service_name` must be provided either as an argument or via the "
221
+ "VERIS_SERVICE_NAME environment variable"
222
+ )
223
+ raise ValueError(error_msg)
224
+
225
+ # Resolve OTLP endpoint ─ explicit argument → env var → error
226
+ if not otlp_endpoint or not str(otlp_endpoint).strip():
227
+ otlp_endpoint = os.getenv("VERIS_OTLP_ENDPOINT")
228
+
229
+ if not otlp_endpoint or not str(otlp_endpoint).strip():
230
+ error_msg = (
231
+ "`otlp_endpoint` must be provided either as an argument or via the "
232
+ "VERIS_OTLP_ENDPOINT environment variable"
233
+ )
234
+ raise ValueError(error_msg)
235
+
236
+ logger.info(f"service_name: {service_name}")
237
+ logger.info(f"otlp_endpoint: {otlp_endpoint}")
238
+
239
+ # ------------------ 1. Configure OTEL provider ---------------------
240
+ # We create our own provider instance and do NOT set it globally.
241
+ # This avoids conflicts with any other OTEL setup in the application.
242
+ otel_provider = TracerProvider(resource=Resource.create({SERVICE_NAME: service_name}))
243
+ otel_provider.add_span_processor(
244
+ BatchSpanProcessor(OTLPSpanExporter(endpoint=otlp_endpoint, insecure=True)),
245
+ )
246
+
247
+ # ------------------ 2. Define wrapper for patching -------------------
248
+ def _wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any) -> Any: # noqa: ANN401, ARG001
249
+ """This function wraps `TraceProvider.set_processors`."""
250
+ processors = args[0] if args else []
251
+
252
+ # Find the user's Braintrust processor to pass to our bridge.
253
+ bt_processor = next(
254
+ (p for p in processors if isinstance(p, BraintrustTracingProcessor)), None
255
+ )
256
+
257
+ # If no Braintrust processor is present, our bridge is useless.
258
+ # Also, if a bridge is already there, don't add another one.
259
+ has_bridge = any(isinstance(p, AgentsOTELBridgeProcessor) for p in processors)
260
+ if not bt_processor or has_bridge:
261
+ return wrapped(*args, **kwargs)
262
+
263
+ # Create the bridge and add it to the list of processors.
264
+ bridge = AgentsOTELBridgeProcessor(
265
+ bt_processor,
266
+ service_name=service_name,
267
+ tracer_provider=otel_provider,
268
+ )
269
+ new_processors = list(processors) + [bridge]
270
+
271
+ # Call the original function with the augmented list.
272
+ new_args = (new_processors,) + args[1:]
273
+ logger.info(f"VERIS AI BraintrustTracingProcessor: {new_args}")
274
+ return wrapped(*new_args, **kwargs)
275
+
276
+ # ------------------ 3. Patch the provider instance -------------------
277
+ # This is more robust than patching the function, as it's independent
278
+ # of how the user imports `set_trace_processors`.
279
+ provider_instance = get_trace_provider()
280
+ wrapt.wrap_function_wrapper(provider_instance, "set_processors", _wrapper)
281
+
282
+ _PATCHED = True
@@ -0,0 +1,137 @@
1
+ # Jaeger Interface
2
+
3
+ This sub-package ships a **thin synchronous wrapper** around the
4
+ [Jaeger Query Service](https://www.jaegertracing.io/docs/) HTTP API so
5
+ that you can **search for and retrieve traces** directly from Python
6
+ with minimal boilerplate. It also provides **client-side span filtering**
7
+ capabilities for more granular control over the returned data.
8
+
9
+ > The client relies on `requests` (already included in the SDK's
10
+ > dependencies) and uses *pydantic* for full type-safety.
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ `veris-ai` already lists both `requests` and `pydantic` as hard
17
+ requirements, so **no additional dependencies are required**.
18
+
19
+ ```bash
20
+ pip install veris-ai
21
+ ```
22
+
23
+ ---
24
+
25
+ ## Quick-start
26
+
27
+ ```python
28
+ from veris_ai.jaeger_interface import JaegerClient
29
+ import json
30
+ from veris_ai.jaeger_interface.models import Trace
31
+ # Replace with the URL of your Jaeger Query Service instance
32
+ client = JaegerClient("http://localhost:16686")
33
+
34
+ # --- 1. Search traces --------------------------------------------------
35
+ resp = client.search(
36
+ service="veris-agent",
37
+ limit=10,
38
+ # operation="CustomSpanData",
39
+ tags={"veris.session_id":"088b5aaf-84bd-4768-9a62-5e981222a9f2"},
40
+ span_tags={"bt.metadata.model":"gpt-4.1-2025-04-14"}
41
+ )
42
+
43
+ # save to json
44
+ with open("resp.json", "w") as f:
45
+ f.write(resp.model_dump_json(indent=2))
46
+
47
+ # Guard clause
48
+ if not resp or not resp.data:
49
+ print("No data found")
50
+ exit(1)
51
+
52
+ # Print trace ids
53
+ for trace in resp.data:
54
+ if isinstance(trace, Trace):
55
+ print("TRACE ID:", trace.traceID, len(trace.spans), "spans")
56
+
57
+ # --- 2. Retrieve a specific trace -------------------------------------
58
+ if isinstance(resp.data, list):
59
+ trace_id = resp.data[0].traceID
60
+ else:
61
+ trace_id = resp.data.traceID
62
+
63
+ detailed = client.get_trace(trace_id)
64
+ # save detailed to json
65
+ with open("detailed.json", "w") as f:
66
+ f.write(detailed.model_dump_json(indent=2))
67
+ ```
68
+
69
+ ---
70
+
71
+ ## API Reference
72
+
73
+ ### `JaegerClient`
74
+
75
+ | Method | Description |
76
+ | -------- | ----------- |
77
+ | `search(service, *, limit=None, tags=None, operation=None, span_tags=None, **kwargs) -> SearchResponse` | Search for traces with optional span-level filtering. |
78
+ | `get_trace(trace_id: str) -> GetTraceResponse` | Fetch a single trace by ID (wrapper around `/api/traces/{id}`). |
79
+
80
+ ### `search()` Parameters
81
+
82
+ The `search()` method now uses a flattened parameter structure:
83
+
84
+ | Parameter | Type | Description |
85
+ | --------- | ---- | ----------- |
86
+ | `service` | `str` | Service name to search for. Optional - if not provided, searches across all services. |
87
+ | `limit` | `int` | Maximum number of traces to return. |
88
+ | `tags` | `Dict[str, Any]` | Trace-level tag filters (AND logic). A trace must have a span matching ALL tags. |
89
+ | `operation` | `str` | Filter by operation name. |
90
+ | `span_tags` | `Dict[str, Any]` | Span-level tag filters (OR logic). Returns only spans matching ANY of these tags. |
91
+ | `span_operations` | `List[str]` | Span-level operation name filters (OR logic). Returns only spans matching ANY of these operations. |
92
+ | `**kwargs` | `Any` | Additional parameters passed directly to Jaeger API. |
93
+
94
+ ### Filter Logic
95
+
96
+ The interface provides two levels of filtering:
97
+
98
+ 1. **Trace-level filtering** (`tags` parameter):
99
+ - Sent directly to Jaeger API
100
+ - Uses AND logic: all tag key-value pairs must match on a single span
101
+ - Efficient server-side filtering
102
+
103
+ 2. **Span-level filtering** (`span_tags` parameter):
104
+ - Applied client-side after retrieving traces
105
+ - Uses OR logic: spans matching ANY of the provided tags are included
106
+ - Traces with no matching spans are excluded from results
107
+ - Useful for finding spans with specific characteristics across different traces
108
+
109
+ ### Example: Combining Filters
110
+
111
+ ```python
112
+ # Find traces in service that have errors, then filter to show only
113
+ # spans with specific HTTP status codes or database errors
114
+ traces = client.search(
115
+ service="my-api",
116
+ tags={"error": "true"}, # Trace must contain an error
117
+ span_tags={
118
+ "http.status_code": 500,
119
+ "http.status_code": 503,
120
+ "db.error": "connection_timeout"
121
+ } # Show only spans with these specific errors
122
+ )
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Compatibility
128
+
129
+ The implementation targets **Jaeger v1.x** REST endpoints. For clusters
130
+ backed by **OpenSearch** storage the same endpoints apply. Should you
131
+ need API v3 support feel free to open an issue or contribution—thanks!
132
+
133
+ ---
134
+
135
+ ## License
136
+
137
+ This package is released under the **MIT license**.
@@ -0,0 +1,39 @@
1
+ """Jaeger interface for searching and retrieving traces.
2
+
3
+ This sub-package provides a thin synchronous wrapper around the Jaeger
4
+ Query Service HTTP API with client-side span filtering capabilities.
5
+
6
+ Typical usage example::
7
+
8
+ from veris_ai.jaeger_interface import JaegerClient
9
+
10
+ client = JaegerClient("http://localhost:16686")
11
+
12
+ # Search traces with trace-level filters
13
+ traces = client.search(
14
+ service="veris-agent",
15
+ limit=20,
16
+ tags={"error": "true"} # AND logic at trace level
17
+ )
18
+
19
+ # Search with span-level filtering
20
+ traces_filtered = client.search(
21
+ service="veris-agent",
22
+ limit=20,
23
+ span_tags={
24
+ "http.status_code": 404,
25
+ "db.error": "timeout"
26
+ } # OR logic: spans with either tag are included
27
+ )
28
+
29
+ # Get a specific trace
30
+ trace = client.get_trace(traces.data[0].traceID)
31
+
32
+ The implementation uses *requests* under the hood and all public functions
33
+ are fully typed using *pydantic* models so that IDEs can provide proper
34
+ autocomplete and type checking.
35
+ """
36
+
37
+ from .client import JaegerClient as JaegerClient # noqa: F401
38
+
39
+ __all__ = ["JaegerClient"]