This prompt is designed for Site Reliability Engineers (SREs) and platform operators who need a consistent, evidence-based first pass at triaging a latency spike in a production tool. The core job-to-be-done is to augment an on-call workflow, not replace your observability stack. When a monitoring dashboard flags that a tool's p95 or p99 latency has crossed a threshold, this prompt takes a structured current latency distribution, a historical baseline, and any known seasonal patterns to produce a standardized anomaly assessment. The output includes a severity classification (e.g., 'Critical', 'Warning', 'Nominal') and a recommended investigation path, allowing the responder to quickly decide whether to escalate, continue observing, or dismiss the alert as a known pattern.
Prompt
Tool Response Latency Anomaly Detection Prompt

When to Use This Prompt
Defines the ideal scenario, required inputs, and boundaries for the Tool Response Latency Anomaly Detection Prompt.
Use this prompt when you have already extracted the necessary metrics from your observability platform (such as Datadog, Prometheus, or Grafana) and can format them as structured input. The prompt assumes you can provide a current distribution with key percentiles (p50, p75, p90, p95, p99), a matching historical baseline distribution for the same window, and a description of known seasonal patterns like daily peak traffic or a weekend lull. Do not use this prompt if you lack a reliable historical baseline, as the model will be forced to guess at normal behavior. It is also inappropriate for real-time, sub-second decision-making or as a replacement for a statistical anomaly detection system. Its value lies in producing a human-readable, reasoned summary that standardizes the triage step across your on-call team, reducing cognitive load during an incident.
Before wiring this into an automated pipeline, validate that your input distributions are complete and correctly aligned in time. A common failure mode is providing a baseline from a different time window (e.g., a Tuesday baseline for a Saturday spike), which will produce a false severity classification. After using this prompt, the next step is to follow the recommended investigation path, which may involve checking for recent deployments, infrastructure changes, or upstream dependency saturation. Avoid the temptation to treat the AI's severity classification as a definitive answer; it is a triage aid that must be confirmed with direct system interrogation.
Use Case Fit
This prompt is a diagnostic tool for SREs, not a real-time circuit breaker. It excels at structured analysis of latency distributions but requires careful integration to avoid adding noise to your incident response pipeline.
Good Fit: Scheduled Performance Reviews
Use when: You run weekly or daily batch jobs that analyze tool latency distributions against historical baselines. The prompt's strength is in structured anomaly assessment and severity classification, making it ideal for proactive performance reviews rather than reactive alerting. Guardrail: Schedule the prompt as a cron job that feeds results into a dashboard, not directly into your pager.
Bad Fit: Real-Time Alerting Pipelines
Avoid when: You need sub-second latency anomaly detection to trigger circuit breakers or load shedding. This prompt is designed for analytical depth, not speed. An LLM call adds unacceptable latency and cost for high-frequency, low-latency decision loops. Guardrail: Use streaming statistical models for real-time detection and reserve this prompt for post-hoc investigation of incidents those models flag.
Required Inputs: Historical Baselines Are Non-Negotiable
Risk: Running this prompt without a statistically significant historical baseline (e.g., p50/p95/p99 latency distributions over the past 4+ comparable time windows) produces plausible-sounding but ungrounded anomaly reports. Guardrail: The prompt harness must validate that baseline data is present and recent before execution. If the baseline is stale or missing, the system should return a BASELINE_UNAVAILABLE error instead of a guess.
Operational Risk: Baseline Drift and Seasonality
Risk: A static baseline will trigger false positives during organic growth (e.g., a 20% latency increase after a successful product launch) or miss anomalies during known low-traffic periods. Guardrail: The prompt harness must support seasonal baseline windows (e.g., 'compare against the same hour last Tuesday') and include a manual override for marking known baseline shifts to prevent alert fatigue.
Integration Point: Human-in-the-Loop for Severity Critical
Risk: An LLM-classified 'critical' severity anomaly might trigger an automated rollback or page an on-call engineer without human review, leading to unnecessary incidents. Guardrail: The output schema must include a requires_human_review boolean. Any assessment classified as critical or major should be routed to a review queue before any automated action is taken.
Cost Consideration: Token Usage vs. Value
Risk: Feeding raw, high-cardinality latency logs directly into the prompt context wastes tokens and can exceed context windows, leading to truncated analysis. Guardrail: Pre-process raw metrics into statistical summaries (histograms, percentiles, standard deviations) before injection. The prompt should receive aggregated data, not raw log streams, to keep the analysis cost-effective and focused.
Copy-Ready Prompt Template
A reusable system prompt for detecting latency anomalies in tool responses by comparing current distributions against historical baselines.
This prompt template is designed to be pasted into your agent's system or task prompt. It instructs the model to act as an SRE analyzing a stream of tool-call latency data. The model compares a provided current latency distribution against a historical baseline, classifies the severity of any deviation, and recommends a concrete investigation path. The prompt is structured to prevent the model from hallucinating metrics or jumping to conclusions without sufficient evidence.
textYou are an SRE analyzing tool response latency for anomalies. Your task is to compare the current latency distribution against the provided historical baseline and produce a structured assessment. ## INPUT DATA [CURRENT_LATENCY_DATA] [BASELINE_LATENCY_DATA] ## CONTEXT [TOOL_NAME]: The specific tool or endpoint being monitored. [TIME_WINDOW]: The period for the current data (e.g., 'last 5 minutes'). [BASELINE_WINDOW]: The period for the baseline data (e.g., 'same 5-minute window over the last 14 days'). [SEASONALITY_NOTES]: Any known seasonal patterns, such as daily peaks or deployment windows. ## CONSTRAINTS - Do not invent data points. If the provided data is insufficient for a high-confidence assessment, state that explicitly. - Distinguish between a genuine latency spike and a shift in workload volume. - Consider the [SEASONALITY_NOTES] before classifying an anomaly. - If the anomaly is classified as 'critical', the investigation path must include an immediate check for cascading failures in dependent services. ## OUTPUT_SCHEMA Return a single JSON object with the following keys: - `anomaly_detected` (boolean): Whether a statistically significant deviation exists. - `severity` (string): One of 'none', 'minor', 'major', 'critical'. - `p95_increase_percent` (number or null): The percentage increase in P95 latency compared to the baseline. - `key_evidence` (string): A concise summary of the data points that support the assessment. - `likely_causes` (array of strings): A ranked list of 1-3 probable causes (e.g., 'resource saturation', 'network blip', 'upstream dependency slowdown'). - `investigation_path` (array of strings): An ordered list of 2-5 concrete next steps for an on-call engineer. - `confidence` (string): One of 'low', 'medium', 'high', reflecting the certainty of the assessment given the data.
To adapt this template, replace the square-bracket placeholders with data from your monitoring stack. The [CURRENT_LATENCY_DATA] and [BASELINE_LATENCY_DATA] fields should be populated with pre-formatted statistical summaries (e.g., P50, P95, P99, mean, and sample count) rather than raw log streams. This prevents the model from performing error-prone arithmetic and keeps the context window focused on interpretation. Before deploying, run this prompt against a golden dataset of known anomalies and normal periods to calibrate the severity thresholds in your evaluation harness.
Prompt Variables
Validate these inputs before sending the prompt. Missing or malformed variables are the most common cause of silent misclassification in production latency anomaly detection.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_LATENCY_DISTRIBUTION] | Recent tool response latency samples for the evaluation window | p50=142ms, p95=890ms, p99=2100ms, count=5000 | Must include at least p50, p95, p99, and sample count. Reject if fewer than 100 samples or window under 60 seconds. |
[HISTORICAL_BASELINE] | Baseline latency distribution from a comparable historical window | p50=135ms, p95=420ms, p99=980ms, count=5000, window=2025-01-15T14:00Z | Must match the same day-of-week and hour-of-day pattern as [CURRENT_LATENCY_DISTRIBUTION]. Reject if baseline is older than 7 days without explicit override. |
[TOOL_NAME] | Identifier for the tool being evaluated | payment-gateway-api | Must match a registered tool name in the agent tool registry. Reject if tool name is not found in active tool catalog. |
[SEASONALITY_CONFIG] | Known seasonal patterns that affect baseline comparison | weekday_peak_14_16_utc, month_end_spike | Optional. Use null if no known patterns. If provided, each entry must reference a documented seasonality rule in the observability config. |
[DEGRADATION_THRESHOLDS] | Latency thresholds that trigger severity classification | p95_warning=2x_baseline, p99_critical=5x_baseline | Must define at least warning and critical levels. Thresholds must be expressed as multipliers of baseline or absolute ms values. Reject if thresholds are inverted. |
[ERROR_RATE_CONTEXT] | Concurrent error rate for the same tool during the evaluation window | error_rate=0.023, error_types=timeout,connection_refused | Optional but strongly recommended. Use null if unavailable. If provided, error_rate must be a float between 0.0 and 1.0. |
[DEPLOYMENT_CHANGE_LOG] | Recent deployments or config changes that could explain latency shifts | deploy:v2.4.1 at 2025-01-15T13:45Z, config:timeout_increase at 13:50Z | Optional. Use null if no changes. If provided, each entry must include a timestamp. Reject entries without timestamps. |
[EVALUATION_WINDOW] | Time range for the current latency samples | start=2025-01-15T14:00:00Z, end=2025-01-15T14:15:00Z | Must be an ISO 8601 interval. Window must be at least 60 seconds and no more than 1 hour. Reject if end is before start. |
Implementation Harness Notes
How to wire the latency anomaly detection prompt into an agent or scheduled monitoring job with guardrails, data fetching, and notification routing.
This prompt is designed to be called by an agent or a scheduled job when a monitoring alert fires for a specific tool endpoint. The calling system is responsible for gathering the required inputs before invoking the LLM. Do not pass raw alert payloads directly to the prompt; the agent must first query your time-series database (Prometheus, Datadog, Grafana, or equivalent) to fetch the [CURRENT_LATENCY_DISTRIBUTION] and [HISTORICAL_BASELINE] for the affected tool and time window. The prompt expects structured distribution data—percentiles, sample counts, and timestamps—not raw metric streams or dashboard screenshots.
Implement a pre-invocation guardrail: if the sample count in [CURRENT_LATENCY_DISTRIBUTION] is below 100, the agent should abort the LLM call entirely and instead log a LOW_SAMPLE_COUNT event with a request for more data. Low-sample assessments produce unreliable severity classifications and waste on-call attention. After the prompt returns, parse the structured output and route it based on the severity field. For critical or major classifications, the agent should automatically page the on-call engineer via your incident management tool (PagerDuty, Opsgenie) and attach the full assessment. For minor or cosmetic classifications, post the output as a non-urgent notification to your team's incident channel (Slack, Teams). Always include the [OBSERVABILITY_LINK] in every notification so the responder can jump directly to the source dashboard and verify the analysis independently.
Model choice matters here. Use a model with strong numerical reasoning and structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature=0 to maximize consistency across repeated assessments. Implement a retry with backoff only for transient API failures; do not retry on validation errors. Validate the output against the expected schema before routing—reject any response where severity is not one of the defined enum values or where p95_deviation_percent is missing. For high-severity production systems, consider running the same prompt against a second model as a consistency check before paging, but weigh the added latency against your incident response SLA. Log every invocation, including the input distributions, the model's raw output, and the routing decision, to enable post-incident review and prompt drift detection over time.
Expected Output Contract
Fields, types, and validation rules for the latency anomaly assessment response. Use this contract to parse, validate, and route the model's output in your application harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
anomaly_detected | boolean | Must be true or false. If true, severity and investigation_path are required. | |
severity | enum: critical | major | minor | cosmetic | true if anomaly_detected is true | Must match one of the four enum values. Reject any other string. |
current_latency_p99_ms | number | Must be a positive float or integer. Null not allowed. Compare against baseline_p99_ms for sanity. | |
baseline_p99_ms | number | Must be a positive float or integer. Null not allowed. If baseline is missing from input, field must still be populated with a derived or default value and flagged in evidence. | |
deviation_factor | number | Must be >= 1.0. Calculated as current_p99 / baseline_p99. Reject if < 1.0 when anomaly_detected is true. | |
investigation_path | string | true if anomaly_detected is true | Must be a non-empty string describing concrete next steps. Reject empty strings or generic placeholders like 'investigate further'. |
confidence_score | number | Must be a float between 0.0 and 1.0 inclusive. Values outside range trigger a retry or repair. | |
evidence_summary | string | Must contain at least one specific metric reference (e.g., 'p99 rose from 320ms to 890ms'). Reject summaries with no quantitative evidence. |
Common Failure Modes
Latency anomaly detection prompts fail in predictable ways when baseline data is stale, seasonal patterns are ignored, or the model overconfidently classifies noise as an incident. These cards cover the most common production failure modes and how to guard against them.
Baseline Drift Produces False Positives
What to watch: The prompt compares current latency against a static baseline that no longer represents normal behavior due to gradual infrastructure changes, traffic growth, or code deployments. The model flags normal evolution as anomalous. Guardrail: Require a rolling baseline window with a configurable lookback period, and include a baseline freshness check in the prompt that asks the model to assess whether the provided baseline is still representative before classifying anomalies.
Seasonal Patterns Mask Real Anomalies
What to watch: The prompt treats elevated latency during known peak hours, batch processing windows, or maintenance periods as anomalous when it is expected behavior. Real anomalies hiding inside seasonal patterns go undetected. Guardrail: Include a seasonal adjustment flag in the input schema that marks known high-load windows, and instruct the model to compare latency against the same seasonal window in prior periods rather than against a flat baseline.
Severity Inflation from Small Sample Sizes
What to watch: The model classifies a latency spike as critical when only a handful of slow requests exist in a low-traffic tool, mistaking statistical noise for a systemic issue. Guardrail: Add a minimum sample size threshold to the prompt constraints, and instruct the model to downgrade severity when the affected request count is below statistical significance. Require a confidence interval in the output rather than a point estimate.
Correlation Confusion Across Dependent Tools
What to watch: The prompt attributes latency to the wrong tool when multiple tools share a dependency. A slow database makes three downstream tools look anomalous simultaneously, and the prompt misidentifies the root cause. Guardrail: Include a tool dependency graph in the context and instruct the model to check whether latency spikes correlate across dependent tools before assigning root cause. Require the output to list correlated anomalies and flag potential common-cause scenarios.
Threshold Hardcoding Ignores Context
What to watch: The prompt uses fixed latency thresholds that are too aggressive for slow-but-acceptable tools and too lenient for latency-sensitive ones, producing both false alarms and missed detections. Guardrail: Provide per-tool latency SLOs and percentile targets in the input schema rather than global thresholds. Instruct the model to classify severity relative to each tool's specific SLO breach magnitude, not against an absolute number.
Investigation Path Is Too Generic to Act On
What to watch: The prompt produces a vague recommendation like 'investigate network latency' without specifying which tool, which endpoint, which time window, or which metrics to check first. On-call engineers waste time triangulating. Guardrail: Require the output to include a ranked investigation path with specific tool names, metric names, time ranges, and diagnostic queries. Add an eval check that rejects outputs missing concrete next steps.
Evaluation Rubric
Run these checks against a golden dataset of known latency scenarios to validate the anomaly detection prompt before deployment. Each criterion targets a specific failure mode observed in production latency analysis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Severity Classification Accuracy | Severity matches the labeled class in the golden dataset within one level (e.g., P2 predicted as P1 or P3 is acceptable; P4 predicted as P1 is not). | Severity misclassification by two or more levels on more than 10% of test cases. | Run prompt against 50 labeled latency scenarios with known severities. Compute confusion matrix and off-by-one accuracy. |
Baseline Drift Detection | Prompt correctly identifies when current latency distribution has shifted from the historical baseline by more than 2 standard deviations. | Failure to flag a known distribution shift in 3 consecutive test windows, or false-positive drift alerts on stable baselines. | Inject synthetic latency spikes into a stable baseline stream. Verify the prompt's drift flag activates within the expected window and deactivates when the spike ends. |
Seasonal Pattern Handling | Prompt acknowledges known seasonal patterns (e.g., weekday peaks, end-of-month load) and does not classify expected cyclical variation as anomalous. | Prompt flags a known seasonal peak as an anomaly in more than 1 out of 5 seasonal cycles. | Feed the prompt a 4-week latency history with labeled weekday/weekend and month-end patterns. Verify anomaly flags do not fire on expected cyclical increases. |
Evidence Grounding | Every anomaly claim includes a specific metric comparison (e.g., 'p99 latency increased from 450ms to 2100ms') and a timestamp range. | Anomaly description contains qualitative language without numeric evidence, or cites a metric not present in the input data. | Parse the output for each test case. Assert that every anomaly statement contains at least one numeric comparison and one time reference from the provided [LATENCY_DATA]. |
Investigation Path Actionability | Recommended investigation path includes at least one specific tool, query, or log source to check, not generic advice. | Investigation path contains only vague suggestions like 'check the database' or 'look at network' without specific commands or dashboards. | Review investigation path output against a checklist of required elements: specific tool name, query template, or dashboard link. Score pass if 80% of recommendations are actionable. |
Confidence Calibration | Prompt assigns confidence scores that correlate with actual correctness: high-confidence predictions are correct more than 85% of the time. | High-confidence predictions (above 0.8) are wrong more than 20% of the time, or low-confidence predictions are consistently correct, indicating miscalibration. | Bucket predictions by confidence score decile. Compute expected calibration error (ECE) across 100 test cases. ECE must be below 0.15. |
Multi-Tool Correlation Handling | When latency spikes correlate across multiple tools, the prompt identifies the likely root-cause tool rather than flagging all tools independently. | Prompt produces independent anomaly reports for 5 tools when a single upstream dependency caused all the latency, missing the correlation. | Inject a single root-cause latency event that cascades to 3 dependent tools. Verify the output identifies the root tool and notes the cascade relationship. |
Output Schema Compliance | Output strictly matches the [OUTPUT_SCHEMA] definition with all required fields present and correctly typed. | Missing required fields, extra fields not in schema, or type mismatches (e.g., string where number expected) in any test case. | Validate output against the JSON Schema definition programmatically. Run schema validation on all 50 test outputs. Require 100% schema compliance. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a structured output schema with required fields: anomaly_detected, severity, confidence, affected_percentiles, comparison_baseline, investigation_steps. Include explicit instructions for handling low-sample-size tools and seasonal adjustment. Wire the prompt into a pipeline that fetches live metrics for [CURRENT_DISTRIBUTION] and [HISTORICAL_BASELINE] before invoking the model.
codeYou are analyzing tool latency for [TOOL_NAME]. Current window: [TIME_WINDOW] Current distribution: [CURRENT_DISTRIBUTION] Historical baseline (same hour-of-week, 4-week rolling): [HISTORICAL_BASELINE] Sample count: [SAMPLE_COUNT] If sample count < 50, increase confidence threshold by 0.2. Return JSON per [OUTPUT_SCHEMA].
Watch for
- Baseline drift when deployment patterns change (new regions, larger payloads)
- Silent format drift in the JSON output as model versions change
- Missing eval cases for borderline severity (p95 at 1.9x vs 2.1x baseline)

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us