Schedule icon
Webhook icon
Request icon
Script icon
Docker icon
Set icon
If icon
SlackIncomingWebhook icon
Log icon

LangSmith & OpenTelemetry LLM Token Spend and Latency Outlier Gate

Audit LangSmith LLM run traces, compute p95 token spend and latency outliers, trip automated circuit breakers, and alert Slack via Kestra.

Categories
AICloud

Orchestrates hourly telemetry surveillance over LangSmith and OpenTelemetry LLM run traces, computing p95 and p99 token spend, prompt-to-completion ratios, and latency distributions across model endpoints. When hourly spend breaches financial quotas, latency exceeds SLA ceilings, or invocation error rates spike, the flow automatically trips a circuit breaker in Kestra's built-in KV store and dispatches an actionable Slack incident notification to engineering and FinOps teams.

How it works

  1. Dual Scheduling & Webhook Triggering: The flow triggers automatically on an hourly cadence via hourly_llm_gate (io.kestra.plugin.core.trigger.Schedule), or on demand via on_demand_gate (io.kestra.plugin.core.trigger.Webhook) secured by the LANGSMITH_WEBHOOK_KEY secret.
  2. Telemetry Extraction: fetch_llm_run_traces (io.kestra.plugin.core.http.Request) queries the LangSmith REST API or OpenTelemetry HTTP tracing endpoint for LLM runs executed over the trailing 60 minutes with allowFailed: true.
  3. Statistical Outlier Analysis: compute_llm_metrics_and_outliers (io.kestra.plugin.scripts.python.Script in python:3.12-slim) normalizes token counts, evaluates blended prompt/completion pricing, calculates p50/p90/p95/p99 latency percentiles, determines prompt-to-completion token ratios, and flags anomalous runs.
  4. KV Store Telemetry Record: store_metrics_in_kv (io.kestra.plugin.core.kv.Set) writes the aggregated telemetry payload into Kestra's internal KV store under langsmith_llm_telemetry_last_hour for downstream reporting.
  5. Circuit Breaker Branching: evaluate_circuit_breaker (io.kestra.plugin.core.flow.If) checks whether any threshold was violated. If tripped, set_circuit_open_kv marks langsmith_circuit_breaker_state as OPEN and alert_circuit_breaker_slack (io.kestra.plugin.slack.notifications.SlackIncomingWebhook) alerts the engineering channel. Otherwise, set_circuit_closed_kv maintains a CLOSED state and log_healthy_metrics (io.kestra.plugin.core.log.Log) records the clean audit pass.
  6. Pipeline Error Handling: The flow-level errors handler (notify_pipeline_failure) delivers an urgent Slack alert if an unexpected execution error occurs.

What you get

  • Automated Cost Protection: Stops runaway prompt loops and expensive model misuse before monthly cloud budgets are exhausted.
  • Latency SLA Enforcement: Identifies tail latency degradation (p95 and p99) before end-user applications experience timeouts.
  • Prompt-to-Completion Ratio Insights: Tracks prompt expansion and token inflation across conversational agent workflows.
  • Zero-External-Database KV State: Uses Kestra's built-in KV store to persist circuit breaker states and telemetry rollups without maintaining external Redis or DynamoDB instances.
  • Multi-Model Attribution: Normalizes telemetry across disparate LLM engines (e.g., GPT-4o, Claude 3.5 Sonnet, embedding models) in a unified schema.

Who it's for

  • AI Platform Engineers managing production LLM microservices, RAG architectures, and agentic workflows.
  • FinOps & Cloud Economics Teams seeking automated hourly budget circuit breakers on foundation model spend.
  • Site Reliability Engineers (SREs) enforcing latency service level agreements (SLAs) and error budgets across AI endpoints.

Why orchestrate this with Kestra

Monitoring high-volume LLM workloads requires combining HTTP API interactions, Python statistical computation, stateful KV persistence, and conditional incident routing. Hand-rolled cron scripts lack execution retry semantics, secret masking, and state persistence. Kestra orchestrates the entire audit declaratively: scheduling the checks, securely handling API tokens, isolating Python analytics in Docker containers, and storing state directly in Kestra KV store.

Prerequisites

  • A Kestra 2.0+ deployment with Docker task runner support.
  • A LangSmith account with API access or an OpenTelemetry HTTP endpoint collecting GenAI traces.
  • A Slack Incoming Webhook URL for incident notifications.

Secrets

  • LANGSMITH_API_KEY: API authentication key for querying the LangSmith REST API (https://api.smith.langchain.com).
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook URL to deliver circuit breaker alerts.
  • LANGSMITH_WEBHOOK_KEY: Secret key guarding the on-demand Webhook trigger endpoint.

Quick start

  1. Configure the LANGSMITH_API_KEY, SLACK_WEBHOOK_URL, and LANGSMITH_WEBHOOK_KEY secrets in your Kestra namespace.
  2. Import this blueprint into your Kestra instance under company.ai.
  3. Run the flow once with default inputs to verify endpoint connectivity, statistical metric computation, and KV store persistence.
  4. Enable the hourly_llm_gate schedule trigger to establish automated continuous hourly surveillance.

How to extend

  • Dynamic Model Fallback: Connect the OPEN circuit breaker state to an upstream proxy (e.g., LiteLLM or Cloudflare AI Gateway) via an HTTP request task to automatically downgrade traffic to smaller, faster models (e.g., gpt-4o-mini).
  • PagerDuty Incident Escalation: Add io.kestra.plugin.pagerduty.notifications.PagerDutyAlert in the then branch to page the on-call engineer during critical SLA outages.
  • Multi-Namespace Fleet Scanning: Use a ForEachItem loop to iterate over an array of LLM service endpoints and audit the entire organization's AI deployments concurrently.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.