This prompt is built for developer-platform and DX engineering teams who need to rank API documentation passages by their actual utility for a developer trying to solve a specific task. The job-to-be-done is not generic relevance ranking—it is evidence selection that accounts for endpoint specificity, version accuracy, example completeness, and deprecation status. Use this prompt when your retrieval system returns multiple candidate passages from API docs, SDK references, changelogs, or migration guides, and you need a scored, ordered set of references before generating an answer or showing results to a user. The ideal user is an AI engineer integrating this into a RAG pipeline for a developer-facing copilot, documentation search, or support bot.
Prompt
API Documentation Evidence Ranking Prompt

When to Use This Prompt
Define the job, ideal user, required inputs, and boundaries for the API Documentation Evidence Ranking Prompt.
Do not use this prompt when the input is a single, obviously correct passage, or when the query is a general conceptual question that doesn't require endpoint-level precision. This prompt is also inappropriate for ranking non-technical content, marketing pages, or community forum threads where authority and versioning rules differ. The prompt assumes your retrieval step has already produced candidate passages with metadata including source URL, last-updated timestamp, and deprecation status. If you lack this metadata, the prompt's ranking logic will degrade because it relies on version freshness and deprecation signals as primary ranking factors. You must also provide the user's SDK language or framework context, because an example in the wrong language is worse than no example at all.
Before wiring this into production, define your failure boundaries. The prompt will rank passages, but it cannot verify that the code examples actually compile or that the documented behavior matches the live API. Your harness must include a post-ranking validation step: execute or lint code examples where feasible, check for broken links, and flag passages where the authentication method described doesn't match the user's configured auth context. The prompt outputs a structured ranking with reasoning, which makes it auditable, but the reasoning itself can contain errors—plan for spot-checking ranked outputs against human developer judgment during eval. If your use case involves safety-critical API calls (billing, provisioning, data deletion), add a human-review gate before any ranked documentation is used to generate executable code or configuration.
Use Case Fit
Where this prompt works, where it fails, and the operational risks to manage before putting it into production.
Good Fit: Structured API Reference Docs
Use when: ranking passages from OpenAPI specs, SDK references, or endpoint documentation with clear version tags, parameter tables, and example blocks. The prompt excels at detecting endpoint specificity and example completeness. Guardrail: pre-parse the documentation into endpoint-scoped chunks before ranking to avoid cross-endpoint confusion.
Bad Fit: Unstructured Developer Forums
Avoid when: ranking community forum threads, GitHub issue comments, or Stack Overflow answers as primary evidence. The prompt's authority scoring relies on structured metadata (version, deprecation status) that informal sources lack. Guardrail: route forum content through a separate source-trustworthiness assessment prompt before mixing with official docs.
Required Inputs: Version Context Is Mandatory
Risk: without the user's target API version, the prompt cannot detect version mismatches and will rank outdated passages equally with current ones. Guardrail: always inject [TARGET_VERSION] and [DEPRECATION_POLICY] into the prompt context. If the user's version is unknown, refuse to rank and request clarification.
Operational Risk: Broken Example Validation
Risk: the prompt ranks passages by example completeness but does not execute or validate the code examples. A highly-ranked passage may contain syntactically correct but semantically broken examples. Guardrail: add a post-ranking harness step that extracts code blocks and runs them against a sandbox or linter before surfacing to users.
Operational Risk: Missing Authentication Context
Risk: the prompt may rank passages that assume a specific auth method (OAuth, API key, bearer token) without knowing the user's configured auth context, leading to irrelevant top results. Guardrail: inject [AUTH_METHOD] and [AUTH_SCOPE] into the prompt and add an eval check that flags top-ranked passages whose auth assumptions conflict with the user's context.
Operational Risk: Deprecation Drift Over Time
Risk: documentation changes after the prompt was last run. A passage ranked as authoritative yesterday may reference a deprecated endpoint today. Guardrail: implement a time-based cache invalidation policy and re-rank whenever the source documentation's last-modified timestamp changes. Log deprecation status in the output for audit.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for ranking API documentation passages by endpoint specificity, version accuracy, example completeness, and deprecation status.
This prompt template is designed to be copied directly into your application or evaluation harness. It accepts a set of retrieved API documentation passages, a developer query, and optional context about the user's environment, then produces a ranked evidence set with explicit scores and reasoning. Every placeholder is enclosed in square brackets so you can substitute values programmatically before sending the request to the model.
textYou are an API documentation evidence ranker. Your job is to score and rank retrieved documentation passages by how well they answer a developer's query, using strict criteria for endpoint specificity, version accuracy, example completeness, and deprecation status. ## INPUT Developer query: [QUERY] User's SDK version: [SDK_VERSION] User's authentication method: [AUTH_METHOD] Current date: [CURRENT_DATE] Retrieved passages: [RETRIEVED_PASSAGES] ## RANKING CRITERIA For each passage, assign a score from 0 to 10 on each of the following dimensions, then compute a weighted total: 1. **Endpoint specificity (weight 0.30):** Does the passage reference a specific endpoint, method, or resource path that matches the query? Generic overviews score lower than endpoint-specific documentation. 2. **Version accuracy (weight 0.25):** Does the passage match the user's SDK version or explicitly state which versions it applies to? Passages for deprecated versions or incompatible major versions score lower. If version is unstated, score 5. 3. **Example completeness (weight 0.25):** Does the passage include a complete, runnable code example with proper authentication, request shape, and response handling? Partial examples score lower. Missing authentication context in the example reduces the score by at least 3 points. 4. **Deprecation status (weight 0.20):** Is the endpoint or feature described as deprecated, sunset, or replaced? Deprecated content scores 0 on this dimension. Active endpoints score 10. Passages with deprecation warnings but no migration path score 3. ## OUTPUT FORMAT Return a JSON object with this exact schema: { "ranked_passages": [ { "passage_id": "string", "weighted_score": number, "dimension_scores": { "endpoint_specificity": number, "version_accuracy": number, "example_completeness": number, "deprecation_status": number }, "reasoning": "string explaining the scores in 1-2 sentences", "flags": ["string"] } ], "query_coverage_assessment": "string describing whether the retrieved set adequately covers the query", "missing_information": ["string"] } ## FLAGS Use these flags where applicable: "deprecated_endpoint", "version_mismatch", "missing_auth_context", "broken_example", "generic_overview", "no_code_example", "incomplete_response_handling", "superseded_by_newer_endpoint" ## CONSTRAINTS - Do not invent endpoints, parameters, or examples not present in the retrieved passages. - If no passage scores above 6.0 weighted, set query_coverage_assessment to "insufficient" and list specific gaps in missing_information. - If a passage contains a code example that would fail due to missing authentication, flag it as "missing_auth_context" and score example_completeness no higher than 4. - Rank passages in descending order of weighted_score. - If two passages describe the same endpoint but different versions, prefer the one matching [SDK_VERSION].
To adapt this template, replace each square-bracket placeholder with values from your retrieval pipeline and user context. The [RETRIEVED_PASSAGES] placeholder should contain pre-formatted passages with unique IDs, source URLs, and full text. If your retrieval system returns passages without version metadata, adjust the version accuracy scoring logic or set a default score. For production use, add a [RISK_LEVEL] parameter that triggers human review when the top-ranked passage scores below a threshold or carries deprecation flags. Always validate the output JSON against the schema before surfacing results to users, and log any passages that receive conflicting scores across dimensions for later eval review.
Prompt Variables
Required inputs for the API Documentation Evidence Ranking Prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to programmatically verify the input before incurring inference cost.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[API_DOC_PASSAGES] | Array of retrieved API documentation passages to rank. Each passage must include the full text and a source identifier. | [{"source_id": "ref-v3-post-users", "text": "POST /users creates a new user. Requires Bearer token. Returns 201 with user object.", "section": "Endpoints"}] | Schema check: array of objects with required keys source_id (string), text (string), section (string). Reject if array is empty or any passage text is fewer than 20 characters. |
[API_QUERY] | The developer's question or task that triggered the retrieval. Used to score passage relevance to the specific need. | "How do I create a user account via the REST API and what auth header is required?" | String length check: minimum 10 characters, maximum 2000 characters. Reject if only punctuation or whitespace. Null not allowed. |
[API_VERSION] | The API version the developer is targeting. Critical for deprecation-aware ranking and version mismatch detection. | "v3" | Must match a known version pattern from the API's version registry (e.g., semver or date-based). Reject if version string is not found in the configured version list. Null allowed only if the API is unversioned. |
[AUTH_CONTEXT] | The authentication method and scope available to the developer. Used to rank passages by whether the developer can actually use the described endpoint. | {"method": "Bearer token", "scopes": ["users:write", "users:read"]} | Schema check: object with required keys method (string) and scopes (array of strings). Reject if method is empty string. Null allowed when auth context is unknown; prompt must then flag auth-required passages as uncertain. |
[DEPRECATION_POLICY] | The deprecation window and sunset rules for the API. Used to weight deprecated endpoints lower and flag imminent removals. | {"deprecation_window_days": 90, "sunset_header": "Sunset", "current_policy_url": "https://api.example.com/deprecation"} | Schema check: object with required key deprecation_window_days (integer >= 0). Reject if negative. Null allowed; prompt must then treat all deprecation signals as advisory without timeline context. |
[OUTPUT_SCHEMA] | The expected structure of the ranked evidence output. Defines the fields the prompt must return for each ranked passage. | {"fields": ["rank", "source_id", "relevance_score", "version_match", "deprecation_status", "example_completeness", "auth_requirement_met", "reasoning"]} | Schema check: object with required key fields (array of strings, minimum 1 element). Each field name must be a valid identifier. Reject if fields array contains duplicates or empty strings. |
[RANKING_WEIGHTS] | Configurable weights for each scoring dimension. Allows tuning the ranking algorithm without changing the prompt text. | {"endpoint_specificity": 0.35, "version_accuracy": 0.25, "example_completeness": 0.25, "deprecation_penalty": 0.15} | Schema check: object with numeric values that sum to 1.0 (tolerance ±0.01). All values must be between 0 and 1. Reject if weights sum outside tolerance or any weight is negative. Null allowed; prompt uses default equal weights. |
Common Failure Modes
When ranking API documentation evidence, these failures degrade trust and break downstream tooling. Each card pairs a common failure with a concrete guardrail you can implement before production.
Version Mismatch Blindness
What to watch: The prompt ranks a passage highly because it matches the endpoint name, but the passage describes v1 while the user's context or SDK targets v2. The model treats version numbers as incidental text rather than a ranking constraint. Guardrail: Include an explicit [API_VERSION] placeholder in the prompt and add a validator that compares the ranked passage's detected version against the requested version, demoting or flagging mismatches before the output is consumed.
Broken Example Propagation
What to watch: The prompt ranks a code example as high-quality evidence, but the example contains a syntax error, uses a deprecated method, or references an undefined variable. Downstream code generation or documentation tooling then replicates the broken example. Guardrail: Add a post-ranking validation step that attempts to parse or statically analyze extracted code examples. Flag any passage where the example fails validation and either remove it or append a warning to the ranked output.
Missing Authentication Context
What to watch: The prompt scores a passage as authoritative because it describes the endpoint in detail, but the passage omits required authentication headers, scopes, or token formats. The ranked evidence set looks complete but produces non-functional integration instructions. Guardrail: Include [AUTH_REQUIREMENTS] as a required input field and add an eval check that verifies each top-ranked passage references authentication context. Demote passages that describe endpoints without mentioning auth when the endpoint is known to require it.
Deprecation Status Ignored
What to watch: The prompt ranks a passage as the best evidence because it is the most detailed or frequently referenced, but the endpoint or parameter described is deprecated. The model does not automatically weight deprecation notices above content richness. Guardrail: Add a [DEPRECATION_POLICY] constraint to the prompt that instructs the model to check for deprecation banners, sunset dates, or removal notices. Implement a post-processing rule that caps the maximum rank of any passage flagged as deprecated, regardless of its relevance score.
Generic Passage Over-Scoring
What to watch: The prompt assigns high scores to overview or conceptual passages that mention the endpoint but lack parameter-level specificity, request/response schemas, or error codes. The ranked set looks relevant but fails to answer implementation questions. Guardrail: Define specificity criteria in the prompt's [CONSTRAINTS] section, such as requiring explicit field names, data types, or status codes for a passage to qualify as high-evidence. Add an eval that measures the presence of structured API details in top-ranked passages and flags sets dominated by conceptual prose.
Conflicting Endpoint Behavior
What to watch: Two highly-ranked passages describe different behavior for the same endpoint—one from a changelog, one from the reference docs, or one from a community wiki. The prompt ranks both highly without surfacing the conflict, producing an evidence set that appears consistent but is contradictory. Guardrail: Add a conflict-detection instruction to the prompt that asks the model to compare top-ranked passages for behavioral contradictions. Include a conflicts field in the output schema. Run a post-ranking eval that checks for unresolved contradictions and either resolves them by source authority or surfaces them explicitly.
Evaluation Rubric
Criteria for testing the API Documentation Evidence Ranking Prompt before shipping. Run these checks against a golden set of API doc passages with known endpoint status, version accuracy, and example validity.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Endpoint specificity ranking | Passages referencing exact endpoint paths and methods rank above generic overview passages | Generic SDK overview outranks a specific POST /v2/users/{id} reference | Golden set with 5 passages of varying specificity; verify rank order matches expected specificity hierarchy |
Deprecation status detection | Deprecated endpoints are flagged and demoted below active equivalents | Deprecated endpoint ranks above its active replacement or no deprecation flag appears | Include a passage with a deprecation notice banner; assert output contains deprecation=true and rank is lower than the replacement endpoint passage |
Version accuracy scoring | Passages matching the user's target API version score higher than mismatched versions | A v1 passage outranks a v3 passage when [TARGET_VERSION] is v3 | Set [TARGET_VERSION] to v3; provide v1, v2, and v3 passages; assert v3 passage has highest version_accuracy score |
Example completeness validation | Passages with complete, runnable examples score higher than those with partial or placeholder examples | A passage with a curl example missing auth headers outranks one with a full request and expected response | Include one passage with a full request/response pair and one with a truncated example; assert the full example receives a higher example_completeness score |
Authentication context awareness | Passages that include required auth method and scopes score higher than those omitting auth context | A passage describing an endpoint without mentioning OAuth scopes outranks one specifying required scopes | Provide two passages for the same endpoint, one with auth scopes documented and one without; assert the auth-aware passage ranks higher |
Broken example detection | Passages containing syntax errors, invalid JSON, or unresolvable references are flagged | A passage with a malformed JSON body example receives no broken_example flag | Include a passage with a JSON example missing a closing brace; assert broken_example=true in output and rank is penalized |
Cross-reference consistency | Passages that link to other documented endpoints without contradiction score higher than those with broken or circular references | A passage referencing a non-existent endpoint ID receives no cross_reference_warning | Include a passage with a see-also link to a fake endpoint; assert cross_reference_warning=true and a lower consistency score |
Confidence calibration | The model expresses lower confidence when evidence is sparse, outdated, or contradictory | High confidence score assigned when only one deprecated passage is provided for an endpoint | Provide a single deprecated passage for an endpoint; assert confidence_score < 0.6 or equivalent low-confidence signal in output |
Implementation Harness Notes
How to wire the API Documentation Evidence Ranking Prompt into a production application with validation, retries, and failure handling.
The API Documentation Evidence Ranking Prompt is designed to sit between your retrieval pipeline and the final answer generation or developer-facing display layer. It accepts a set of retrieved API doc passages and a developer query, then returns a scored, ranked, and annotated evidence set. The harness must enforce strict input validation before the prompt is assembled: each passage must include a source identifier (URL, file path, or doc section anchor), a retrieval timestamp, and the raw text. If your retriever cannot provide these fields, add a pre-processing step that attaches them before calling the ranking prompt. Missing source identifiers are the most common cause of downstream citation failures.
The output contract is a JSON array of ranked passages, each with a score (0.0 to 1.0), a rank integer, a rationale string explaining the score, and a set of boolean flags: endpoint_specific, version_accurate, example_complete, deprecation_aware, and auth_context_present. Your harness must validate this schema on every response. If the model returns malformed JSON, missing required fields, or scores outside the expected range, implement a retry loop with a maximum of three attempts. On the second and third retries, append the validation error message to the prompt as a [PREVIOUS_ERROR] context block. After three failures, log the raw response, flag the passage set for human review, and fall back to a simpler recency-based ranking heuristic.
Model choice matters for this workflow. Use a model with strong structured output capabilities and a context window large enough to hold your maximum passage set plus the prompt instructions. For most API doc corpora, 8K to 32K tokens is sufficient. If you are ranking more than 20 passages, consider batching them into groups of 10-15 and running a merge-rank step afterward. Enable structured output mode (JSON mode or function calling with a strict schema) rather than relying on free-text parsing. This reduces repair-loop frequency by an order of magnitude in production.
The most dangerous failure mode is the model assigning high scores to passages that contain broken code examples or missing authentication context. Your eval harness must include a set of seeded negative examples: passages with syntax errors in code samples, passages that omit required auth headers, passages from deprecated API versions, and passages that describe endpoints removed three versions ago. Run these through the prompt weekly and assert that no negative example scores above 0.3. If any does, your prompt needs hardening—add stronger negative constraints or few-shot examples that demonstrate low-scoring these patterns.
Logging and observability are critical because evidence ranking directly shapes the answers your developer users see. Log every ranking call with: the query, the number of input passages, the top three ranked passage IDs and scores, the model version, the latency, and whether validation passed on the first attempt. Set an alert if the first-attempt validation failure rate exceeds 10% over a rolling hour. For high-stakes API documentation surfaces—such as billing endpoints, authentication flows, or data deletion operations—route ranked outputs through a human review queue before they influence generated answers or code suggestions. The prompt is a ranking tool, not a correctness guarantee.
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 small set of API docs. Remove strict output schema requirements initially. Use a simple relevance score (1-5) instead of the full multi-factor ranking. Focus on getting the model to identify endpoint definitions and code examples correctly.
Prompt snippet
codeScore each API doc passage for relevance to [QUERY] on a 1-5 scale. Consider: endpoint match, example presence, version mention. Return: passage_id, score, brief_reason
Watch for
- Model confusing endpoint references with general descriptions
- Missing version-awareness in scoring
- Over-scoring passages that mention the endpoint name but lack usable details

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