This prompt is designed for integration test engineers who are investigating a flaky test and have already narrowed the failure domain to an interaction with an external, third-party API. The core job-to-be-done is to move beyond a hunch and produce a defensible, structured attribution decision. You should use this prompt when you have collected structured evidence from both passing and failing test runs, including HTTP response payloads, status codes, latency distributions, and rate-limiting headers. The prompt acts as a rigorous analyst, cross-referencing this evidence to determine if the root cause is a dependency issue (e.g., a provider outage, a rate limit, a slow backend) or an application-level problem (e.g., a brittle assertion, a missing retry, a timeout misconfiguration).
Prompt
Third-Party API Flakiness Attribution Prompt

When to Use This Prompt
A systematic, evidence-based analysis for attributing integration test flakiness to third-party API dependencies versus application code.
This prompt is not a replacement for checking a provider's status page or running network diagnostics. Instead, it structures the evidence you already possess into a clear, repeatable analysis. For example, you might feed it a set of logs showing a 502 Bad Gateway from the provider alongside a spike in latency, and the prompt will guide the model to attribute the failure to the provider rather than your code. Conversely, if the evidence shows consistent 200 OK responses with a valid payload but your test fails on a strict schema assertion, the prompt will correctly attribute the flakiness to your application's validation logic. The ideal user is someone who needs to make a quick, evidence-backed decision on whether to mock the dependency, adjust timeouts and retries, or escalate the issue to the external provider's support team.
Do not use this prompt for initial flakiness discovery or for analyzing failures that are clearly unrelated to external API calls, such as unit test logic errors or database deadlocks. It is also unsuitable when you lack concrete API interaction logs from both passing and failing scenarios, as the analysis would be speculative. The output is an attribution, not a full root cause fix. After receiving the attribution, your next step should be to act on the recommendation: implement a mock for provider-side issues, adjust your application's resilience patterns for client-side timeout issues, or open a ticket with the provider if their SLA has been breached. Avoid using this prompt as a final sign-off without a human reviewing the evidence for high-severity or customer-impacting test failures.
Use Case Fit
Where the Third-Party API Flakiness Attribution Prompt works and where it does not. Use these cards to decide if this prompt fits your integration test workflow before wiring it into your CI pipeline.
Good Fit: Recurring 5xx and Timeout Patterns
Use when: integration tests fail intermittently with HTTP 502, 503, 504, or connection timeout errors that correlate with specific time windows or endpoints. Why it works: the prompt analyzes error code distributions, latency percentiles, and retry outcomes to attribute failures to upstream service degradation rather than application logic.
Bad Fit: Single Occurrence or First-Time Failures
Avoid when: you have only one failure instance with no historical pattern. Why it fails: the prompt requires multiple data points across runs to distinguish transient network blips from systemic third-party issues. A single failure lacks the statistical signal needed for confident attribution.
Required Inputs: Structured Failure Logs with Timing Data
What you need: HTTP status codes, response bodies (sanitized), request timestamps, latency measurements, retry counts, and rate-limit headers from at least 5-10 failing test runs. Guardrail: if your test harness does not capture response headers or precise timing, the prompt cannot distinguish API throttling from network issues.
Operational Risk: Masking Application Bugs as Third-Party Issues
What to watch: the prompt may attribute failures to the third party when the root cause is incorrect request construction, missing auth tokens, or malformed payloads from your application code. Guardrail: always run a parallel check that validates request correctness before accepting third-party attribution. Require human review when the confidence score is below 0.7.
Operational Risk: Rate Limit Misclassification
What to watch: HTTP 429 responses with Retry-After headers can be misread as service unavailability rather than client-side throttling. Guardrail: the prompt must explicitly check for rate-limit headers and separate throttling attribution from server-error attribution. If your tests lack retry-after header capture, add it before using this prompt.
Boundary: Not a Replacement for Service-Level Monitoring
What to watch: this prompt analyzes test-level failures, not production traffic patterns. It cannot replace APM dashboards, synthetic monitoring, or SLO-based alerting. Guardrail: use this prompt for root cause analysis of flaky integration tests only. Escalate to your observability stack for production third-party dependency health assessment.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for attributing test failures to third-party APIs versus application code.
This section provides the core prompt template for the Third-Party API Flakiness Attribution workflow. The prompt is designed to receive structured evidence from your test harness—including API response metadata, error codes, latency distributions, and rate-limiting signals—and produce an evidence-based attribution report. The template uses square-bracket placeholders that you must replace with real data from your test runs before sending the prompt to the model. Each placeholder corresponds to a specific input your integration test infrastructure should collect and format.
textYou are an integration test analyst specializing in third-party API dependency failures. Your task is to determine whether a flaky test failure is caused by the external API, the application code, or the test environment. ## INPUT DATA ### Test Context - Test name: [TEST_NAME] - Test suite: [TEST_SUITE] - Execution timestamp: [EXECUTION_TIMESTAMP] - CI run URL: [CI_RUN_URL] - Application version: [APP_VERSION] ### API Call Details - Endpoint: [API_ENDPOINT] - HTTP method: [HTTP_METHOD] - Request payload (sanitized): [REQUEST_PAYLOAD] - Response status code: [RESPONSE_STATUS_CODE] - Response body (sanitized, first 2000 chars): [RESPONSE_BODY] - Response headers (relevant): [RESPONSE_HEADERS] - Request duration (ms): [REQUEST_DURATION_MS] - Timeout configured (ms): [TIMEOUT_CONFIGURED_MS] - Retry count before failure: [RETRY_COUNT] ### Latency Distribution (last 10 calls to same endpoint) [LATENCY_DISTRIBUTION_TABLE] ### Rate Limiting Signals - Rate limit headers present: [RATE_LIMIT_HEADERS] - 429 responses in last 5 minutes: [RECENT_429_COUNT] - Retry-After header value: [RETRY_AFTER_VALUE] ### Application Error Context - Application error message: [APP_ERROR_MESSAGE] - Stack trace (first 1000 chars): [STACK_TRACE] - Error handling code path: [ERROR_HANDLING_PATH] ### Environment Context - Network zone: [NETWORK_ZONE] - DNS resolution time (ms): [DNS_RESOLUTION_MS] - TLS handshake time (ms): [TLS_HANDSHAKE_MS] - Proxy or gateway in path: [PROXY_DETAILS] ## OUTPUT SCHEMA Produce a JSON object with this exact structure: { "attribution": { "primary_category": "THIRD_PARTY_API" | "APPLICATION_CODE" | "TEST_ENVIRONMENT" | "NETWORK_INFRASTRUCTURE" | "INCONCLUSIVE", "confidence": 0.0-1.0, "secondary_categories": ["string"] }, "evidence": [ { "signal": "string (specific observation)", "strength": "STRONG" | "MODERATE" | "WEAK", "supports_category": "string", "explanation": "string (why this signal points to the category)" } ], "counter_evidence": [ { "signal": "string (observation that contradicts primary attribution)", "strength": "STRONG" | "MODERATE" | "WEAK", "explanation": "string" } ], "recommendations": { "immediate_action": "string (what to do right now for this test)", "mock_or_stub_strategy": "string (how to simulate this API in tests)", "code_changes": ["string (specific application code changes if applicable)"], "monitoring_improvements": ["string (observability gaps to close)"] }, "requires_human_review": true | false, "human_review_reason": "string (if requires_human_review is true)" } ## CONSTRAINTS - Do not attribute to THIRD_PARTY_API unless you have specific evidence from response codes, headers, latency patterns, or rate limiting signals. - Do not attribute to APPLICATION_CODE unless you see error handling gaps, missing retries, or incorrect timeout configuration in the application context. - If latency is high but the API eventually returns a valid response, consider whether the application timeout is too aggressive. - If the API returns 5xx errors, check whether the application has retry logic and whether retries were exhausted. - If rate limiting signals are present, attribute to THIRD_PARTY_API regardless of other factors. - If evidence is contradictory or insufficient, set primary_category to INCONCLUSIVE and confidence below 0.5. - Set requires_human_review to true for any attribution with confidence below 0.7 or when primary_category is INCONCLUSIVE. - Never recommend production code changes without flagging for human review. ## EXAMPLES ### Example 1: Clear Third-Party Failure Input: 503 status, no retry-after header, latency distribution shows all recent calls failing with 503, no application error handler gap. Output attribution: THIRD_PARTY_API, confidence 0.95. ### Example 2: Application Timeout Misconfiguration Input: 200 status but response time 4500ms, timeout configured at 3000ms, latency distribution shows consistent 4000-5000ms responses. Output attribution: APPLICATION_CODE, confidence 0.85, recommendation: increase timeout or add async pattern. ### Example 3: Rate Limiting Input: 429 status, Retry-After: 60, 12 rate-limited responses in last 5 minutes. Output attribution: THIRD_PARTY_API, confidence 0.98, recommendation: implement exponential backoff with jitter.
To adapt this template for your environment, replace each square-bracket placeholder with data collected from your test execution framework. The latency distribution table should be formatted as a markdown table with columns for timestamp, duration, status code, and any error codes. If a placeholder has no data available, replace it with N/A rather than leaving it empty—this prevents the model from hallucinating missing information. The output schema is designed to be machine-parseable so your test harness can automatically route attributions to the right team: third-party API issues go to the API integration owner, application code issues go to the development team, and environment issues go to platform engineering. Always run the output through a JSON schema validator before acting on the recommendations, and ensure human review is triggered when the requires_human_review field is true.
Prompt Variables
Required inputs for the Third-Party API Flakiness Attribution Prompt. Each placeholder must be populated with structured data to produce reliable attribution results.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[API_CALL_LOG] | Structured log of API requests and responses including timestamps, status codes, headers, and latency | JSON array of request/response pairs from API gateway logs | Must contain at least 20 call records. Validate each record has timestamp, status_code, latency_ms, and request_id fields. Reject if missing required fields. |
[ERROR_PATTERN_WINDOW] | Time window specification for analyzing error patterns and rate limiting signals | {"start": "2025-01-15T00:00:00Z", "end": "2025-01-15T23:59:59Z", "granularity": "5m"} | Start must precede end. Granularity must be one of 1m, 5m, 15m, 1h. Validate ISO 8601 format. Reject if window spans less than 1 hour. |
[RATE_LIMIT_HEADERS] | List of HTTP header names that indicate rate limiting from the third-party service | ["X-RateLimit-Remaining", "Retry-After", "X-RateLimit-Reset"] | Must be non-empty array of valid HTTP header name strings. Validate each header name matches RFC 7230 token format. Warn if common rate limit headers are missing from the list. |
[EXPECTED_LATENCY_PROFILE] | Baseline latency distribution for the third-party API under normal conditions | {"p50_ms": 120, "p95_ms": 350, "p99_ms": 800, "timeout_ms": 5000} | All latency values must be positive integers. p50 < p95 < p99 < timeout_ms must hold. Validate monotonic ordering. Reject if timeout exceeds 30000ms without explicit justification. |
[APPLICATION_ERROR_BUDGET] | Thresholds for acceptable error rates from application code versus third-party attribution | {"app_error_threshold_pct": 2.0, "third_party_attribution_confidence": 0.85} | Thresholds must be between 0 and 100 for percentages, 0 and 1 for confidence. Validate numeric ranges. Reject if confidence threshold below 0.7 without documented risk acceptance. |
[RETRY_CONFIGURATION] | Application retry policy settings for the third-party API calls | {"max_retries": 3, "backoff_strategy": "exponential", "base_delay_ms": 200, "retry_on_status": [429, 502, 503]} | max_retries must be non-negative integer. backoff_strategy must be one of fixed, linear, exponential. retry_on_status must be array of valid HTTP status codes. Validate strategy enum and status code ranges. |
[MOCK_STUB_CATALOG] | Available mock and stub configurations for the third-party service in test environment | {"available_mocks": ["success", "timeout", "rate_limited", "server_error"], "wiremock_mapping_path": "/mocks/payment-api/"} | available_mocks must be non-empty array. Validate each mock name maps to an existing configuration. Reject if catalog is empty when attribution recommends mocking. |
Implementation Harness Notes
How to wire the Third-Party API Flakiness Attribution Prompt into a test pipeline with validation, retries, and human review gates.
This prompt is designed to sit inside an automated flakiness triage pipeline, not as a one-off chat interaction. The typical integration point is a CI/CD post-execution hook or a dedicated flakiness analysis service that receives test failure artifacts (logs, HAR files, API response traces, timing data) and routes them to the LLM for attribution. The harness should collect all required inputs before calling the model: the failing test name, the full API interaction log including request/response pairs with headers and status codes, latency distributions across multiple runs, any rate-limit headers (X-RateLimit-Remaining, Retry-After), and the application's retry/timeout configuration. Missing or incomplete inputs are the most common cause of incorrect attributions, so the harness must validate input completeness before invoking the prompt.
Wire the prompt into an application function that constructs the [API_INTERACTION_LOG] placeholder from structured trace data rather than raw text dumps. Parse your observability exports (OpenTelemetry spans, HAR files, or API gateway logs) into a normalized JSON structure with fields for timestamp, method, url, request_headers, request_body, status_code, response_headers, response_body (truncated), and latency_ms. Feed this structured log into the prompt template along with the [TEST_NAME], [RETRY_CONFIG], and [ENVIRONMENT_CONTEXT] placeholders. After the model returns its attribution JSON, run a schema validator to confirm the output contains the required fields: attribution_target (one of third_party, application_code, network_infrastructure, unknown), confidence_score (0.0-1.0), evidence_summary, error_pattern_category, and mock_stub_recommendation. Reject and retry outputs that fail schema validation or produce confidence scores below your configured threshold (typically 0.7 for automated routing, lower for human-review queues).
For high-risk pipelines—such as release-blocking test suites or production canary analysis—route attributions with confidence_score < 0.85 or attribution_target == 'unknown' to a human review queue. Log every attribution decision with the full prompt input, model output, validator results, and reviewer action for auditability. Choose a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent) and set temperature=0 to minimize variance across repeated runs. Avoid using this prompt for real-time request path decisions; it is an offline analysis tool. The most common production failure mode is stale or truncated API logs that omit the rate-limit headers or response bodies needed for accurate attribution—build log completeness checks into your harness before calling the model.
Expected Output Contract
The model must return a structured JSON object. Use this contract to validate the response before routing it to downstream systems or human review queues.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
attribution_decision | enum string | Must be one of: 'third_party_api', 'application_code', 'environment', 'inconclusive'. No other values allowed. | |
confidence_score | float | Must be a number between 0.0 and 1.0 inclusive. Reject if outside range or non-numeric. | |
evidence_summary | array of objects | Array must contain 1-5 objects. Each object must have 'source' (string), 'observation' (string), and 'relevance' (enum: 'high', 'medium', 'low') fields. | |
api_error_patterns | array of objects | Each object must have 'error_code' (string), 'frequency' (integer), and 'timestamp_range' (object with 'start' and 'end' ISO 8601 strings). Null array not allowed; use empty array if no patterns found. | |
latency_analysis | object | Must contain 'p50_ms' (integer), 'p95_ms' (integer), 'p99_ms' (integer), and 'spike_timestamps' (array of ISO 8601 strings). All latency values must be non-negative integers. | |
rate_limiting_indicators | object | Must contain 'detected' (boolean), 'evidence' (array of strings), and 'retry_after_header_observed' (boolean or null). Null allowed for retry_after_header_observed only when detected is false. | |
mock_stub_recommendations | array of objects | Each object must have 'endpoint' (string matching URL pattern), 'failure_mode_to_simulate' (string), and 'implementation_notes' (string). Array may be empty if no recommendations applicable. | |
human_review_required | boolean | Must be true if confidence_score < 0.7 or attribution_decision is 'inconclusive'. Validation check: reject if human_review_required is false but confidence_score < 0.7. |
Common Failure Modes
When attributing flakiness to third-party APIs, these failure modes can mislead your root cause analysis. Each card identifies a specific breakdown and a concrete guardrail to keep your investigation on track.
Correlation Mistaken for Causation
What to watch: The prompt attributes a test failure to a third-party API simply because a 5xx error appeared in the same time window, ignoring a simultaneous application deployment that broke the request signature. Guardrail: Require the prompt to cross-reference API error timestamps with the deployment history and configuration change log before making an attribution claim.
Client-Side Error Misattribution
What to watch: A 4xx error from the third-party API is incorrectly classified as an external service flakiness event, when the root cause is a malformed request due to a recent code change. Guardrail: Add a pre-processing step that separates 4xx errors (client fault) from 5xx and timeout errors (potential server fault) and requires the prompt to analyze the request payload for schema validity before blaming the dependency.
Ignoring Local Network Proxies
What to watch: The prompt analyzes API response codes and latencies but fails to account for an internal proxy, service mesh, or API gateway that is introducing its own timeouts and retries, masking the true third-party behavior. Guardrail: Include network topology context (e.g., proxy logs, Via headers, egress IPs) in the prompt's input and instruct it to isolate the hop where the failure originated before attributing it to the final API endpoint.
Rate Limiting Misread as Unavailability
What to watch: A 429 Too Many Requests response is treated as a generic service disruption, leading to a false conclusion that the third-party API is unstable, when the application's retry storm is actually causing self-inflicted throttling. Guardrail: Instruct the prompt to treat 429 status codes as a distinct category, analyze the Retry-After header, and correlate the request rate with the API's documented rate limits before classifying the failure as external flakiness.
Mock Recommendation Without Contract Validation
What to watch: The prompt recommends replacing a flaky third-party API with a stub or mock, but the mock's behavior is based on a single observed failure mode and doesn't cover the full API contract, leading to false-positive test passes in the future. Guardrail: Require the prompt to output a contract-first stub specification that includes all response codes, headers, and edge cases from the API's OpenAPI spec, not just the error that triggered the investigation.
Single-Sample Overfitting
What to watch: The prompt receives only one failure log and confidently attributes the root cause to a specific third-party endpoint, ignoring that the same error pattern occurs across multiple unrelated tests and services, indicating a broader infrastructure issue. Guardrail: Design the prompt to request a minimum sample size of failures across different test suites and time windows, and instruct it to explicitly state its confidence level based on the breadth of evidence provided.
Evaluation Rubric
Criteria for evaluating the quality of the Third-Party API Flakiness Attribution Prompt output before integrating it into a production triage workflow.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Attribution Classification | Output assigns exactly one primary attribution label: 'third_party', 'application_code', or 'indeterminate'. | Output is missing the label, uses an undefined label, or assigns multiple conflicting labels. | Schema check: assert [OUTPUT_SCHEMA].attribution exists and value is in the defined enum. |
Evidence Completeness | For 'third_party' attribution, at least two distinct evidence types are cited (e.g., error code + latency spike). For 'indeterminate', a specific missing signal is named. | Attribution is 'third_party' but only one generic reason is given, or 'indeterminate' is chosen without naming the data gap. | LLM-as-judge: prompt a second model to count distinct evidence categories in the output's evidence array. |
Error Code Grounding | All cited HTTP error codes or API-specific error strings match the raw [INPUT_LOGS] provided. | The output references a 503 error, but the input logs only contain 504 and connection timeout errors. | Unit test: parse [INPUT_LOGS] for all status codes and assert the output's cited codes are a subset. |
Latency Analysis Precision | If latency is cited, the output includes a specific percentile (e.g., p95) and a comparison baseline from the logs, not just a qualitative 'slow' statement. | Output states 'the API was slow' without referencing a specific metric or threshold from the provided data. | Regex check: assert the output contains a numeric latency value and a percentile label when latency is mentioned in the evidence. |
Rate Limiting Signal Detection | If rate limiting is suspected, the output correctly identifies a 429 status code or a 'Retry-After' header from the logs. | Output blames rate limiting based on a generic timeout without citing a 429 or header evidence. | Keyword scan: if 'rate limit' is in the output, assert '429' or 'Retry-After' is also present in the evidence section. |
Mock/Stub Recommendation Quality | The recommendation specifies a concrete behavior to mock (e.g., 'mock the /payment endpoint to return a 200 with a 2-second delay') and is directly traceable to the failure evidence. | Recommendation is a generic 'mock the third-party service' without specifying the endpoint, response, or condition. | LLM-as-judge: evaluate if the recommendation includes an endpoint path and a specific response behavior tied to the failure. |
Confidence Score Calibration | A confidence score between 0.0 and 1.0 is provided. A score above 0.9 requires three or more distinct evidence points. | A confidence score of 0.95 is given with only one weak signal, or the score is missing entirely. | Schema check: assert 0.0 <= confidence <= 1.0. Logic check: if confidence > 0.9, assert length of evidence array >= 3. |
Abstention for Insufficient Data | When input logs contain fewer than 2 failure events, the output must classify as 'indeterminate' with a note requesting more data. | Output confidently attributes the failure to a third party based on a single timeout log line. | Unit test: provide a minimal input with one log line and assert the output's attribution is 'indeterminate'. |
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
Start with the base prompt and a single API dependency log file. Remove strict output schema requirements initially—accept a structured but unvalidated JSON block. Focus on getting correct attribution categories (third-party vs. application vs. network) before enforcing field-level precision.
Simplify the prompt:
- Drop
[OUTPUT_SCHEMA]and ask for a plain JSON object withattribution,evidence, andconfidencekeys. - Use a single
[API_LOG]input instead of separating logs, metrics, and config. - Skip mock/stub recommendations until attribution accuracy is confirmed.
Watch for
- Over-attribution to the third party when evidence is thin—the model may default to blaming the external service.
- Missing latency distribution analysis when only error codes are provided.
- Hallucinated rate limit signals when logs don't contain rate limit headers.

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