Skip to main content
ClaudeWave
ES, Spanish
Skill227 estrellas del repoactualizado 2mo ago

context-ranking

Rank an existing set of context chunks by relevance, diversity, freshness, and utility. Use when retrieval has already produced candidates that must be scored or reranked; use context-retrieval when the source corpus still needs to be searched.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/context-ranking && cp -r /tmp/context-ranking/context-engineering/context-ranking ~/.claude/skills/context-ranking
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Context Ranking

Context ranking is the process of ordering retrieved text chunks so the most relevant, diverse, and useful information rises to the top. In any retrieval pipeline, the initial search returns a broad set of candidates -- many of which are only tangentially related to the query. Ranking transforms this unordered candidate set into a prioritized list, enabling downstream steps (context assembly, prompt construction) to select the best material and discard the rest. Effective ranking is the difference between a grounded, precise answer and a vague, off-topic one.

## Workflow

1. **Collect Candidate Chunks**: Gather the initial set of retrieved chunks from the search layer. This is typically the top-k results (k = 15-30) from a vector search, keyword search, or hybrid search. Each chunk arrives with a preliminary score (e.g., cosine similarity or BM25 score) and source metadata.

2. **Apply First-Stage Scoring**: Score each candidate with a fast, lightweight algorithm. BM25 is the standard choice for keyword relevance; cosine similarity between the query embedding and chunk embedding is the standard for semantic relevance. In hybrid pipelines, compute both scores and combine them using Reciprocal Rank Fusion (RRF) or a weighted linear combination. This stage is meant to be fast and run over all candidates.

3. **Rerank with a Cross-Encoder**: Pass the top candidates (typically 15-25) from the first stage through a cross-encoder reranker. Unlike bi-encoder embeddings that score query and document independently, a cross-encoder processes the query and chunk together with full attention, producing much more accurate relevance scores. Models like Cohere Rerank, `bge-reranker-v2-m3`, or ColBERTv2 are commonly used. This step is slower but dramatically improves precision.

4. **Apply Diversity Selection**: After reranking, the top results may cluster around a single subtopic, leaving other aspects of the query uncovered. Apply Maximal Marginal Relevance (MMR) or a similar diversity algorithm to penalize chunks that are too similar to already-selected chunks. This ensures the final ranked list covers the breadth of the query, not just its most obvious interpretation.

5. **Assign Final Scores and Rank**: Combine the reranker relevance score with the diversity penalty and any domain-specific boosting signals (e.g., recency boost, source authority weight) into a final composite score. Sort chunks by this composite score in descending order. The top-n chunks (n = 3-7) form the final ranked context to be injected into the prompt.

6. **Attach Metadata and Confidence**: Annotate each ranked chunk with its final score, source path, and a confidence tier (high / medium / low). This metadata helps the downstream prompt assembly step decide how to present the context and allows the model to calibrate its confidence when citing sources.

## Key Concepts

- **BM25**: A probabilistic keyword-matching algorithm based on term frequency, inverse document frequency, and document length normalization. Excels at matching exact terms and rare keywords. Fast and interpretable, but blind to synonyms and paraphrases. The standard first-stage ranker for keyword search.
- **Cosine Similarity**: Measures the angle between two embedding vectors. Values range from -1 to 1, with higher values indicating greater semantic similarity. The standard first-stage ranker for semantic search. Quality depends heavily on the embedding model used.
- **Cross-Encoder Reranking**: A transformer model that takes the concatenation of query and document as input and outputs a relevance score. Because it applies full cross-attention between query and document tokens, it captures fine-grained relevance that bi-encoders miss. Typically 5-20x slower than cosine similarity but produces significantly better ranking.
- **Maximal Marginal Relevance (MMR)**: An algorithm that iteratively selects chunks by balancing relevance to the query against redundancy with already-selected chunks. Controlled by a lambda parameter: lambda = 1.0 selects purely by relevance, lambda = 0.0 selects purely by diversity, and values around 0.5-0.7 balance both. Essential for multi-faceted queries.
- **Reciprocal Rank Fusion (RRF)**: A score-combining method used in hybrid search. For each chunk, compute 1/(k + rank) for each ranking source, then sum. This produces a fused ranking that is robust to score scale differences between BM25 and cosine similarity.

## Usage

Provide a query and a list of candidate text chunks (with optional preliminary scores and metadata). The skill scores, reranks, and diversifies the chunks, returning a ranked list with final scores and confidence tiers. Specify the desired number of output chunks (top-n) and an optional diversity parameter (MMR lambda).

## Examples

### Example 1: Ranking Code Search Results for a Debugging Query

**Query:** "Why does the WebSocket connection drop after 60 seconds of inactivity?"

**Candidate Chunks (from hybrid search, top-8):**

| # | Source | BM25 | Cosine | Content Summary |
|---|--------|------|--------|-----------------|
| 1 | `src/ws/server.ts:40-65` | 12.4 | 0.88 | WebSocket server config with `pingInterval: 30000` and `pingTimeout: 60000` |
| 2 | `src/ws/server.ts:80-95` | 8.1 | 0.82 | Connection cleanup handler that logs "connection timed out" |
| 3 | `docs/websocket.md:15-30` | 6.3 | 0.79 | Documentation: "Connections are kept alive via ping/pong. Default timeout is 60s." |
| 4 | `src/ws/client.ts:10-35` | 5.7 | 0.84 | Client-side WebSocket wrapper -- does not implement pong response handler |
| 5 | `nginx.conf:22-28` | 9.8 | 0.71 | Nginx proxy config: `proxy_read_timeout 60s` for WebSocket upstream |
| 6 | `CHANGELOG.md:44-50` | 3.2 | 0.55 | "v2.1: Fixed WebSocket reconnection logic" -- no timeout details |
| 7 | `src/ws/server.ts:100-120` | 4.5 | 0.76 | Rate limiting middleware for WebSocket messages |
| 8 | `package.json:15-20` | 2.1 | 0.45 | `"ws": "^8.14.0"` dependency entr
accessibility-testingSkill

Audit web interfaces against WCAG 2.1 AA/AAA standards, identify violations, and produce actionable remediation reports with code fixes. Use when the user requests accessibility testing or provides relevant inputs for this workflow.

agent-evaluationSkill

Design reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.

agent-observabilitySkill

Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.

agent-red-teamingSkill

Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.

analytics-reportingSkill

Generate comprehensive marketing analytics reports by collecting KPIs, analyzing trends, and delivering actionable insights with attribution modeling and funnel analysis. Use when the user requests analytics reporting or provides relevant inputs for this workflow.

api-designSkill

Design RESTful APIs with proper resource modeling, HTTP method semantics, status codes, pagination, versioning, and documentation. Use when the user requests api design or provides relevant inputs for this workflow.

api-integrationSkill

Integrate with external APIs using REST clients, webhook consumers, SDK wrappers, and polling patterns with proper authentication, error handling, and retry logic. Use when the user requests api integration or provides relevant inputs for this workflow.

budget-planningSkill

Create and manage budgets with variance analysis and departmental allocation. Use when the user requests budget planning or provides relevant inputs for this workflow.