query-transformations
БесплатноБез исполняемых скриптовНе проверенPre-retrieval query rewriting techniques. HyDE, multi-query, step-back, RAG-fusion with RRF, sub-query decomposition, query routing, and expansion. Full…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Query Transformations
When to Apply
| Technique | Recall Gain | Latency Cost | Best For |
|---|---|---|---|
| Multi-query | +10-20% | 1 LLM call | Ambiguous or short queries |
| HyDE | +5-15% | 1 LLM call | Specialized domains, terminology mismatch |
| Step-back | +5-10% | 1 LLM call | Detail-heavy questions |
| RAG-fusion | +15-25% | 1 LLM + N searches | General-purpose quality boost |
| Sub-query decomposition | +20-30% on multi-hop | 1 LLM + N retrievals | Multi-part questions |
| Query routing | Varies | 1 classifier call | Heterogeneous indexes |
| Expansion (synonyms) | +5% | Free-ish | Keyword-heavy domains |
Multi-Query Generation
Generate paraphrases; union the retrieved docs.
from langchain_anthropic import ChatAnthropic
from langchain.retrievers.multi_query import MultiQueryRetriever
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
retriever = MultiQueryRetriever.from_llm(
retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
llm=llm,
include_original=True,
)
docs = retriever.invoke("How do I configure SSO?")
Manual implementation:
from anthropic import Anthropic
client = Anthropic()
def multi_query(q: str, n: int = 3) -> list[str]:
prompt = f"""Generate {n} different paraphrases of this question for semantic search.
One per line. No numbering or explanation.
Question: {q}"""
msg = client.messages.create(
model="claude-sonnet-4-5-20250929", max_tokens=300,
messages=[{"role": "user", "content": prompt}],
)
return [q] + [l.strip() for l in msg.content[0].text.splitlines() if l.strip()]
HyDE (Hypothetical Document Embeddings)
Have the LLM hallucinate a candidate answer, then embed that answer for retrieval. Closes the query-document style gap.
from langchain_openai import OpenAIEmbeddings
from langchain_qdrant import QdrantVectorStore
from anthropic import Anthropic
client = Anthropic()
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
HYDE_PROMPT = """Write a passage that answers this question. The passage should be
written as if from a technical document. Do not mention that it is hypothetical.
Question: {q}
Passage:"""
def hyde_search(vstore: QdrantVectorStore, q: str, k: int = 5):
msg = client.messages.create(
model="claude-sonnet-4-5-20250929", max_tokens=400,
messages=[{"role": "user", "content": HYDE_PROMPT.format(q=q)}],
)
hypothetical = msg.content[0].text
vec = embeddings.embed_query(hypothetical)
return vstore.similarity_search_by_vector(vec, k=k)
Works best when queries are terse ("SSO config?") and docs are verbose.
Step-Back Prompting
Rewrite a specific question into a more general one, retrieve against both.
STEP_BACK_PROMPT = """Given a specific question, write a more general, higher-level
question whose answer would help answer the specific one.
Specific: {q}
General:"""
def step_back(q: str) -> str:
msg = client.messages.create(
model="claude-sonnet-4-5-20250929", max_tokens=100,
messages=[{"role": "user", "content": STEP_BACK_PROMPT.format(q=q)}],
)
return msg.content[0].text.strip()
def step_back_retrieve(retriever, q: str, k: int = 5):
general = step_back(q)
specific_docs = retriever.invoke(q)
general_docs = retriever.invoke(general)
seen, out = set(), []
for d in specific_docs + general_docs:
if d.page_content not in seen:
out.append(d); seen.add(d.page_content)
return out[:k]
Use when questions assume background knowledge the corpus discusses separately.
RAG-Fusion (RRF over multi-query)
Multi-query retrieval with Reciprocal Rank Fusion instead of set union.
from collections import defaultdict
def rrf(rank_lists: list[list[str]], k_constant: int = 60) -> list[tuple[str, float]]:
scores = defaultdict(float)
for ranks in rank_lists:
for rank, doc_id in enumerate(ranks):
scores[doc_id] += 1 / (k_constant + rank + 1)
return sorted(scores.items(), key=lambda x: x[1], reverse=True)
def rag_fusion(retriever, query: str, n_queries: int = 4, top_k: int = 5):
queries = multi_query(query, n=n_queries)
rank_lists = []
id_to_doc = {}
for q in queries:
docs = retriever.invoke(q)
ids = []
for d in docs:
key = d.metadata.get("id") or hash(d.page_content)
id_to_doc[key] = d
ids.append(key)
rank_lists.append(ids)
fused = rrf(rank_lists)[:top_k]
return [id_to_doc[doc_id] for doc_id, _ in fused]
RRF is scale-free — no score normalization needed. k_constant=60 is the published default.
Sub-Query Decomposition
Split multi-part questions into atomic retrieval sub-queries.
import json
DECOMPOSE_PROMPT = """Break this question into atomic sub-questions that each require
a single fact retrieval. Return a JSON array of strings. If the question is already
atom
Установить query-transformations в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл query-transformations?
Pre-retrieval query rewriting techniques. HyDE, multi-query, step-back, RAG-fusion with RRF, sub-query decomposition, query routing, and expansion. Full Python code per technique with LangChain and native Anthropic SDK. USE WHEN: user mentions "HyDE", "hypothetical document", "multi-query", "step-back prompting", "RAG-fusion", "query rewriting", "query decomposition", "query routing" DO NOT USE FOR: post-retrieval reranking - use `reranking`; sparse+dense fusion on retrieved docs - use `hybrid-search`; agent loops - use `agentic-rag`
Как установить скилл query-transformations?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл query-transformations запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic