Spaces:
Running

File size: 6,936 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""OpenTelemetry tracing with GenAI semantic-convention attributes (Phase 15).



Spans:



* ``invoke_agent workpilot`` - one per run invocation (start, resume, crash-continue), with

  ``workpilot.tenant_id`` / ``workpilot.run_id`` / ``workpilot.thread_id`` and

  ``gen_ai.conversation.id`` (= thread id; Langfuse groups it as the session);

* ``chat <model>`` - every LLM call (``gen_ai.operation.name=chat``,

  ``gen_ai.provider.name``, ``gen_ai.request.model``, ``gen_ai.response.model``,

  ``gen_ai.usage.input_tokens`` / ``output_tokens``, ``gen_ai.output.type=json``,

  ``workpilot.cost_usd``);

* ``execute_tool <tool>`` - every gateway call (``gen_ai.tool.name``) with the gateway

  decision: ``workpilot.gateway.decision``, ``.tier``, ``.policy_rules`` (Cedar ``@id``s),

  ``.approval_id``, ``.reason`` and ``.replayed``.



Export: OTLP/HTTP to ``WP_OTEL_EXPORTER_ENDPOINT`` or, if only Langfuse is configured, to

Langfuse's OTLP endpoint (Langfuse ingests OTLP and understands ``gen_ai.*``). With neither,

``setup_tracing`` installs nothing and every span is a cheap no-op.



Privacy: prompts, completions and tool arguments are never recorded. String attributes pass

through ``redact_text`` (CNIC, phones, IBAN, email, cards) and are capped; secrets never

reach a span because they never reach the code paths that create spans (the gateway injects

credentials only into the handler's context).



Tests call ``use_provider(TracerProvider)`` with an in-memory exporter; production calls

``setup_tracing()`` once per process (API lifespan, worker).

"""

from __future__ import annotations

import base64
import logging
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from typing import Any

from opentelemetry import trace
from opentelemetry.trace import Span, Status, StatusCode, Tracer

from core.privacy.redact import redact_text

log = logging.getLogger(__name__)

TRACER_NAME = "workpilot"
MAX_ATTR_CHARS = 500

_provider: Any = None  # an SDK TracerProvider once configured


def use_provider(provider: Any) -> None:
    """Route WorkPilot spans to ``provider`` (tests: in-memory exporter). None: no-op."""
    global _provider
    _provider = provider


def tracer() -> Tracer:
    if _provider is not None:
        return _provider.get_tracer(TRACER_NAME)
    return trace.get_tracer(TRACER_NAME)


def otlp_target(settings: Any) -> tuple[str, dict[str, str]] | None:
    """(endpoint, headers) for the OTLP/HTTP exporter, or None when unconfigured."""
    headers = dict(settings.otel_exporter_headers or {})
    if settings.otel_exporter_endpoint:
        return str(settings.otel_exporter_endpoint), headers
    if settings.langfuse_host and settings.langfuse_public_key and settings.langfuse_secret_key:
        pair = f"{settings.langfuse_public_key}:{settings.langfuse_secret_key.get_secret_value()}"
        headers["Authorization"] = "Basic " + base64.b64encode(pair.encode()).decode()
        return f"{settings.langfuse_host.rstrip('/')}/api/public/otel/v1/traces", headers
    return None


def setup_tracing(settings: Any = None, exporter: Any = None) -> bool:
    """Install a batching OTLP exporter if configured (or ``exporter`` if given). Returns

    whether tracing is active. Idempotent per process."""
    if _provider is not None:
        return True
    if settings is None:
        from core.config import get_settings

        settings = get_settings()
    if exporter is None:
        target = otlp_target(settings)
        if target is None:
            return False
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

        exporter = OTLPSpanExporter(endpoint=target[0], headers=target[1])
    from opentelemetry.sdk.resources import Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor

    provider = TracerProvider(
        resource=Resource.create({"service.name": settings.otel_service_name})
    )
    provider.add_span_processor(BatchSpanProcessor(exporter))
    use_provider(provider)
    log.info("OpenTelemetry tracing enabled")
    return True


def shutdown_tracing() -> None:
    global _provider
    if _provider is not None and hasattr(_provider, "shutdown"):
        _provider.shutdown()
    _provider = None


def clean(value: Any) -> Any:
    """Attribute-safe value: primitives as-is, strings redacted and capped, sequences of

    primitives kept, anything else stringified."""
    if isinstance(value, bool | int | float):
        return value
    if isinstance(value, str):
        return redact_text(value)[:MAX_ATTR_CHARS]
    if isinstance(value, list | tuple):
        return [clean(v) if isinstance(v, str) else str(v) for v in value][:50]
    return redact_text(str(value))[:MAX_ATTR_CHARS]


def set_attrs(span: Span, attrs: Mapping[str, Any]) -> None:
    for k, v in attrs.items():
        if v is not None:
            span.set_attribute(k, clean(v))


def provider_of(model: str) -> str:
    return model.split(":", 1)[0] if ":" in model else "unknown"


@contextmanager
def span(name: str, attrs: Mapping[str, Any] | None = None) -> Iterator[Span]:
    with tracer().start_as_current_span(name) as sp:
        set_attrs(sp, attrs or {})
        try:
            yield sp
        except BaseException as exc:
            if sp.is_recording():
                sp.set_status(Status(StatusCode.ERROR, type(exc).__name__))
                sp.set_attribute("error.type", type(exc).__name__)
            raise


def run_span(tenant_id: Any, run_id: Any, thread_id: str, operation: str) -> Any:
    return span(
        "invoke_agent workpilot",
        {
            "gen_ai.operation.name": "invoke_agent",
            "gen_ai.agent.name": "workpilot",
            "gen_ai.conversation.id": thread_id,
            "workpilot.tenant_id": str(tenant_id),
            "workpilot.run_id": str(run_id),
            "workpilot.thread_id": thread_id,
            "workpilot.run.operation": operation,
        },
    )


def llm_span(model: str, schema: str, tier: str | None = None) -> Any:
    return span(
        f"chat {model}",
        {
            "gen_ai.operation.name": "chat",
            "gen_ai.provider.name": provider_of(model),
            "gen_ai.request.model": model,
            "gen_ai.request.temperature": 0,
            "gen_ai.output.type": "json",
            "workpilot.llm.schema": schema,
            "workpilot.llm.tier": tier,
        },
    )


def tool_span(tool: str, attrs: Mapping[str, Any]) -> Any:
    return span(
        f"execute_tool {tool}",
        {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool, **attrs},
    )


def current_span() -> Span:
    return trace.get_current_span()