|
| 1 | +""" |
| 2 | +Cost Enrichment Span Processor. |
| 3 | +
|
| 4 | +This processor enriches spans with cost information by calculating costs from token usage. |
| 5 | +It runs early in the processing chain so that downstream processors and exporters can |
| 6 | +access pre-calculated costs from span attributes. |
| 7 | +""" |
| 8 | + |
| 9 | +import logging |
| 10 | + |
| 11 | +from opentelemetry.context import Context |
| 12 | +from opentelemetry.sdk.trace import ReadableSpan |
| 13 | +from opentelemetry.sdk.trace.export import SpanProcessor |
| 14 | + |
| 15 | +from alphatrion.utils.pricing import calculate_cost |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class CostEnrichmentProcessor(SpanProcessor): |
| 21 | + """ |
| 22 | + Span processor that enriches spans with cost information. |
| 23 | +
|
| 24 | + This processor checks if cost attributes are already present in a span. |
| 25 | + If not, it calculates costs from token usage and adds them to the span's |
| 26 | + attributes dictionary. This ensures all downstream processors and exporters |
| 27 | + have access to consistent cost data. |
| 28 | + """ |
| 29 | + |
| 30 | + def on_start(self, span: ReadableSpan, parent_context: Context | None = None): |
| 31 | + """Called when a span is started. No-op for this processor.""" |
| 32 | + pass |
| 33 | + |
| 34 | + def on_end(self, span: ReadableSpan): |
| 35 | + """ |
| 36 | + Called when a span ends. Calculate and add cost attributes if missing. |
| 37 | +
|
| 38 | + Args: |
| 39 | + span: The completed span |
| 40 | + """ |
| 41 | + try: |
| 42 | + # Only process spans with attributes |
| 43 | + if not span.attributes: |
| 44 | + return |
| 45 | + |
| 46 | + # Check if costs are already present |
| 47 | + if "alphatrion.cost.total_tokens" in span.attributes: |
| 48 | + # Costs already calculated (e.g., in claude.py) |
| 49 | + return |
| 50 | + |
| 51 | + # Check if this is an LLM span with token usage |
| 52 | + if "gen_ai.usage.input_tokens" not in span.attributes: |
| 53 | + # Not an LLM span, skip |
| 54 | + return |
| 55 | + |
| 56 | + # Extract token usage |
| 57 | + attributes = span.attributes |
| 58 | + provider = determine_provider(str(attributes.get("gen_ai.openai.api_base"))) |
| 59 | + model = str( |
| 60 | + attributes.get("gen_ai.request.model") |
| 61 | + or attributes.get("gen_ai.response.model", "") |
| 62 | + ) |
| 63 | + input_tokens = int(attributes.get("gen_ai.usage.input_tokens", 0)) |
| 64 | + output_tokens = int(attributes.get("gen_ai.usage.output_tokens", 0)) |
| 65 | + cache_creation_input_tokens = int( |
| 66 | + attributes.get("gen_ai.usage.cache_creation_input_tokens", 0) |
| 67 | + ) |
| 68 | + cache_read_input_tokens = int( |
| 69 | + attributes.get("gen_ai.usage.cache_read_input_tokens", 0) |
| 70 | + ) |
| 71 | + |
| 72 | + # Calculate costs |
| 73 | + cost_result = calculate_cost( |
| 74 | + provider=provider, |
| 75 | + model=model, |
| 76 | + input_tokens=input_tokens, |
| 77 | + output_tokens=output_tokens, |
| 78 | + cache_creation_input_tokens=cache_creation_input_tokens, |
| 79 | + cache_read_input_tokens=cache_read_input_tokens, |
| 80 | + ) |
| 81 | + |
| 82 | + # Add cost attributes to span |
| 83 | + # Note: We can't modify ReadableSpan.attributes directly after span ends, |
| 84 | + # but we can modify the underlying _attributes dict that will be read |
| 85 | + # by exporters. This is a bit of a hack but it's the only way to enrich |
| 86 | + # spans post-creation without modifying OpenTelemetry internals. |
| 87 | + if hasattr(span, "_attributes"): |
| 88 | + span._attributes["alphatrion.cost.total_tokens"] = str( |
| 89 | + cost_result["total_cost"] |
| 90 | + ) |
| 91 | + span._attributes["alphatrion.cost.input_tokens"] = str( |
| 92 | + cost_result["input_cost"] |
| 93 | + ) |
| 94 | + span._attributes["alphatrion.cost.output_tokens"] = str( |
| 95 | + cost_result["output_cost"] |
| 96 | + ) |
| 97 | + span._attributes["alphatrion.cost.cache_creation_input_tokens"] = str( |
| 98 | + cost_result["cache_creation_input_cost"] |
| 99 | + ) |
| 100 | + span._attributes["alphatrion.cost.cache_read_input_tokens"] = str( |
| 101 | + cost_result["cache_read_input_cost"] |
| 102 | + ) |
| 103 | + logger.debug( |
| 104 | + f"Enriched span {span.name} with cost: ${cost_result['total_cost']:.6f}" |
| 105 | + ) |
| 106 | + |
| 107 | + except Exception as e: |
| 108 | + logger.warning(f"Failed to enrich span with cost: {e}", exc_info=True) |
| 109 | + |
| 110 | + def shutdown(self): |
| 111 | + """Shutdown the processor.""" |
| 112 | + logger.info("CostEnrichmentProcessor shut down successfully") |
| 113 | + |
| 114 | + def force_flush(self, timeout_millis: int = 30000) -> bool: |
| 115 | + """ |
| 116 | + Force flush (no-op for this processor). |
| 117 | +
|
| 118 | + Args: |
| 119 | + timeout_millis: Timeout in milliseconds |
| 120 | +
|
| 121 | + Returns: |
| 122 | + True always |
| 123 | + """ |
| 124 | + return True |
| 125 | + |
| 126 | + |
| 127 | +def determine_provider(api_base: str) -> str: |
| 128 | + """Determine provider from API base URL. |
| 129 | +
|
| 130 | + Args: |
| 131 | + api_base: API base URL (e.g., "https://api.anthropic.com") |
| 132 | +
|
| 133 | + Returns: |
| 134 | + Provider name (e.g., "anthropic", "openai", "deepinfra", or "unknown") |
| 135 | + """ |
| 136 | + api_base = api_base.lower() |
| 137 | + if "anthropic" in api_base: |
| 138 | + return "anthropic" |
| 139 | + elif "deepinfra" in api_base: |
| 140 | + return "deepinfra" |
| 141 | + elif "openai" in api_base: |
| 142 | + return "openai" |
| 143 | + else: |
| 144 | + return "unknown" |
0 commit comments