Spaces:
Running
Running
Download core/observability/tracing.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 6.94 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/tracing.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/observability/tracing.py
-
curl -L -o tracing.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/tracing.py
6.94 kB
| """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" | |
| 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() | |