|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from typing import Sequence |
| 4 | + |
| 5 | +from opentelemetry.sdk.trace import ReadableSpan |
| 6 | +from opentelemetry.sdk.trace.export import ( |
| 7 | + SpanExporter, |
| 8 | + SpanExportResult, |
| 9 | +) |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +class LlamaIndexAdapter(SpanExporter): |
| 14 | + """A simple wrapper for SpanExporters that allows for customization.""" |
| 15 | + |
| 16 | + # Mapping of old attribute names to new attribute names or (new name, function) |
| 17 | + ATTRIBUTE_MAPPING = { |
| 18 | + "input.value": ("input", lambda s: json.loads(s)), |
| 19 | + "output.value": ("output", lambda s: json.loads(s)), |
| 20 | + "llm.model_name": "model", |
| 21 | + } |
| 22 | + |
| 23 | + def __init__(self, wrapped_exporter: SpanExporter): |
| 24 | + """Initialize with the exporter to wrap. |
| 25 | + |
| 26 | + Args: |
| 27 | + wrapped_exporter: The underlying SpanExporter to wrap |
| 28 | + """ |
| 29 | + super().__init__() |
| 30 | + self.wrapped_exporter = wrapped_exporter |
| 31 | + |
| 32 | + def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: |
| 33 | + """Export spans, with a hook to transform them first.""" |
| 34 | + transformed_spans = [self.transform_span(span) for span in spans] |
| 35 | + return self.wrapped_exporter.export(transformed_spans) |
| 36 | + |
| 37 | + def transform_span(self, span: ReadableSpan) -> ReadableSpan: |
| 38 | + """Override this method to transform spans before export. |
| 39 | + |
| 40 | + Args: |
| 41 | + span: The original span to transform |
| 42 | + |
| 43 | + Returns: |
| 44 | + The transformed span |
| 45 | + """ |
| 46 | + for old_key, mapping in self.ATTRIBUTE_MAPPING.items(): |
| 47 | + if old_key in span.attributes: |
| 48 | + if isinstance(mapping, tuple): |
| 49 | + new_key, func = mapping |
| 50 | + try: |
| 51 | + span.attributes[new_key] = func(span.attributes[old_key]) |
| 52 | + except Exception: |
| 53 | + span.attributes[new_key] = span.attributes[old_key] |
| 54 | + else: |
| 55 | + new_key = mapping |
| 56 | + span.attributes[new_key] = span.attributes[old_key] |
| 57 | + del span.attributes[old_key] |
| 58 | + return span |
| 59 | + |
| 60 | + def force_flush(self, timeout_millis: int = 30000) -> bool: |
| 61 | + """Pass through to the wrapped exporter.""" |
| 62 | + return self.wrapped_exporter.force_flush(timeout_millis) |
| 63 | + |
| 64 | + def shutdown(self) -> None: |
| 65 | + """Pass through to the wrapped exporter.""" |
| 66 | + return self.wrapped_exporter.shutdown() |
0 commit comments