|
| 1 | +import functools |
| 2 | +import inspect |
| 3 | +import os |
| 4 | +from contextlib import contextmanager |
| 5 | +from typing import Any, Callable, Dict, Optional |
| 6 | + |
| 7 | + |
| 8 | +_TRACER = None |
| 9 | +_SETUP_ATTEMPTED = False |
| 10 | + |
| 11 | + |
| 12 | +def _otel_enabled() -> bool: |
| 13 | + value = os.getenv("SWARMS_OTEL_ENABLED", "").lower() |
| 14 | + return value in {"1", "true", "yes", "on"} or bool( |
| 15 | + os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT") |
| 16 | + ) |
| 17 | + |
| 18 | + |
| 19 | +def _safe_value(value: Any) -> Any: |
| 20 | + if value is None or isinstance(value, (bool, int, float, str)): |
| 21 | + return value |
| 22 | + if isinstance(value, (list, tuple, set)): |
| 23 | + return len(value) |
| 24 | + if isinstance(value, dict): |
| 25 | + return len(value) |
| 26 | + return str(value) |
| 27 | + |
| 28 | + |
| 29 | +def _object_attributes(obj: Any) -> Dict[str, Any]: |
| 30 | + attrs: Dict[str, Any] = { |
| 31 | + "swarms.component": obj.__class__.__name__, |
| 32 | + } |
| 33 | + |
| 34 | + for source_attr, otel_attr in ( |
| 35 | + ("id", "swarms.id"), |
| 36 | + ("name", "swarms.name"), |
| 37 | + ("agent_name", "swarms.agent_name"), |
| 38 | + ("swarm_type", "swarms.swarm_type"), |
| 39 | + ("output_type", "swarms.output_type"), |
| 40 | + ): |
| 41 | + value = getattr(obj, source_attr, None) |
| 42 | + if value is not None: |
| 43 | + attrs[otel_attr] = _safe_value(value) |
| 44 | + |
| 45 | + agents = getattr(obj, "agents", None) |
| 46 | + if agents is not None: |
| 47 | + try: |
| 48 | + attrs["swarms.agents.count"] = len(agents) |
| 49 | + except TypeError: |
| 50 | + pass |
| 51 | + |
| 52 | + return attrs |
| 53 | + |
| 54 | + |
| 55 | +def setup_otel() -> Optional[Any]: |
| 56 | + global _TRACER, _SETUP_ATTEMPTED |
| 57 | + |
| 58 | + if _TRACER is not None: |
| 59 | + return _TRACER |
| 60 | + if _SETUP_ATTEMPTED or not _otel_enabled(): |
| 61 | + return None |
| 62 | + |
| 63 | + _SETUP_ATTEMPTED = True |
| 64 | + |
| 65 | + try: |
| 66 | + from opentelemetry import trace |
| 67 | + from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( |
| 68 | + OTLPSpanExporter, |
| 69 | + ) |
| 70 | + from opentelemetry.sdk.resources import Resource |
| 71 | + from opentelemetry.sdk.trace import TracerProvider |
| 72 | + from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 73 | + except Exception: |
| 74 | + return None |
| 75 | + |
| 76 | + resource = Resource.create( |
| 77 | + { |
| 78 | + "service.name": os.getenv( |
| 79 | + "SWARMS_OTEL_SERVICE_NAME", "swarms" |
| 80 | + ) |
| 81 | + } |
| 82 | + ) |
| 83 | + provider = TracerProvider(resource=resource) |
| 84 | + provider.add_span_processor( |
| 85 | + BatchSpanProcessor( |
| 86 | + OTLPSpanExporter( |
| 87 | + endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT") |
| 88 | + ) |
| 89 | + ) |
| 90 | + ) |
| 91 | + trace.set_tracer_provider(provider) |
| 92 | + _TRACER = trace.get_tracer("swarms") |
| 93 | + return _TRACER |
| 94 | + |
| 95 | + |
| 96 | +@contextmanager |
| 97 | +def otel_span(name: str, attributes: Optional[Dict[str, Any]] = None): |
| 98 | + tracer = setup_otel() |
| 99 | + if tracer is None: |
| 100 | + yield None |
| 101 | + return |
| 102 | + |
| 103 | + try: |
| 104 | + from opentelemetry.trace import Status, StatusCode |
| 105 | + except Exception: |
| 106 | + yield None |
| 107 | + return |
| 108 | + |
| 109 | + safe_attrs = { |
| 110 | + key: _safe_value(value) |
| 111 | + for key, value in (attributes or {}).items() |
| 112 | + if value is not None |
| 113 | + } |
| 114 | + |
| 115 | + with tracer.start_as_current_span(name) as span: |
| 116 | + for key, value in safe_attrs.items(): |
| 117 | + span.set_attribute(key, value) |
| 118 | + try: |
| 119 | + yield span |
| 120 | + except Exception as exc: |
| 121 | + span.record_exception(exc) |
| 122 | + span.set_status(Status(StatusCode.ERROR, str(exc))) |
| 123 | + raise |
| 124 | + |
| 125 | + |
| 126 | +def trace_method( |
| 127 | + span_name: str, |
| 128 | + attributes_factory: Optional[ |
| 129 | + Callable[[Any, tuple, dict], Dict[str, Any]] |
| 130 | + ] = None, |
| 131 | +): |
| 132 | + def decorator(func): |
| 133 | + if inspect.iscoroutinefunction(func): |
| 134 | + |
| 135 | + @functools.wraps(func) |
| 136 | + async def async_wrapper(self, *args, **kwargs): |
| 137 | + attributes = _object_attributes(self) |
| 138 | + if attributes_factory is not None: |
| 139 | + attributes.update( |
| 140 | + attributes_factory(self, args, kwargs) |
| 141 | + ) |
| 142 | + with otel_span(span_name, attributes): |
| 143 | + return await func(self, *args, **kwargs) |
| 144 | + |
| 145 | + return async_wrapper |
| 146 | + |
| 147 | + @functools.wraps(func) |
| 148 | + def wrapper(self, *args, **kwargs): |
| 149 | + attributes = _object_attributes(self) |
| 150 | + if attributes_factory is not None: |
| 151 | + attributes.update(attributes_factory(self, args, kwargs)) |
| 152 | + with otel_span(span_name, attributes): |
| 153 | + return func(self, *args, **kwargs) |
| 154 | + |
| 155 | + return wrapper |
| 156 | + |
| 157 | + return decorator |
0 commit comments