self-querying-retriever
LangChain SelfQueryRetriever pattern. LLM infers structured metadata filters from natural language ("books by Asimov after 2000" -> filter author=Asimov AND year>2000). Metadata schema declaration, comparators and operators, LlamaIndex AutoRetriever equivalent, combining with hybrid search, evaluation of filter correctness. USE WHEN: user mentions "self-querying retriever", "SelfQueryRetriever", "auto retriever", "metadata filter from query", "NL to filter", "AutoRetriever" DO NOT USE FOR: text-to-SQL on tables - use `tabular-rag`; plain query rewriting - use `query-transformations`; hybrid search - use `hybrid-search`
What this skill does
# Self-Querying Retriever
## The Pattern
User types natural language. The LLM produces a structured `(search_string, filter)` tuple that the retriever executes against a vector store with metadata filtering.
```
"books by Asimov after 2000"
|
v
{ query: "books", filter: AND(eq(author, "Asimov"), gt(year, 2000)) }
```
Separating semantic query from symbolic filter is the key. Semantic similarity cannot express `year > 2000`; metadata filters cannot express "books about first contact". Together they work.
## Core Flow
```
[NL query] -> [Structured query LLM] -> {query, filter} -> [vector store + metadata filter] -> docs
^
|
metadata schema description
```
## LangChain 0.3+ SelfQueryRetriever
```python
from langchain.chains.query_constructor.schema import AttributeInfo
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_anthropic import ChatAnthropic
from langchain_core.documents import Document
docs = [
Document(page_content="Foundation is a 1951 novel about...",
metadata={"title": "Foundation", "author": "Isaac Asimov",
"year": 1951, "genre": "science fiction", "rating": 4.4}),
Document(page_content="The Gods Themselves explores...",
metadata={"title": "The Gods Themselves", "author": "Isaac Asimov",
"year": 1972, "genre": "science fiction", "rating": 4.1}),
Document(page_content="Prelude to Foundation is set before...",
metadata={"title": "Prelude to Foundation", "author": "Isaac Asimov",
"year": 1988, "genre": "science fiction", "rating": 4.0}),
Document(page_content="Forward the Foundation...",
metadata={"title": "Forward the Foundation", "author": "Isaac Asimov",
"year": 1993, "genre": "science fiction", "rating": 4.2}),
]
vstore = Chroma.from_documents(docs, OpenAIEmbeddings(model="text-embedding-3-small"))
metadata_field_info = [
AttributeInfo(name="title", description="Book title", type="string"),
AttributeInfo(name="author", description="Author full name", type="string"),
AttributeInfo(name="year", description="Publication year", type="integer"),
AttributeInfo(name="genre",
description="Genre: 'science fiction', 'fantasy', 'mystery', 'non-fiction'",
type="string"),
AttributeInfo(name="rating",
description="Average reader rating 1.0-5.0", type="float"),
]
document_content_description = "Summary of a novel"
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
retriever = SelfQueryRetriever.from_llm(
llm=llm,
vectorstore=vstore,
document_contents=document_content_description,
metadata_field_info=metadata_field_info,
enable_limit=True, # "top 3 books..." populates `k`
use_original_query=False, # pass the rewritten semantic query
verbose=True,
)
docs = retriever.invoke("Asimov novels after 1970 rated above 4")
```
The LLM emits a structured query that the translator converts to Chroma's filter syntax:
```python
{
"query": "novels",
"filter": {
"$and": [
{"author": {"$eq": "Isaac Asimov"}},
{"year": {"$gt": 1970}},
{"rating": {"$gt": 4}},
]
},
"limit": 4
}
```
## Supported Comparators and Operators
Built-in (availability varies per backend):
| Comparator | Semantics | Ex |
|---|---|---|
| `eq` | equal | `author == "Asimov"` |
| `ne` | not equal | `genre != "fantasy"` |
| `gt` `gte` | greater than (or equal) | `year > 2000` |
| `lt` `lte` | less than (or equal) | `rating <= 3` |
| `contain` | substring match | `title contains "Foundation"` |
| `in` `nin` | (not) in set | `genre in ["sci-fi","fantasy"]` |
| `like` | regex/wildcard (backend) | `title like "Forward*"` |
Operators: `and`, `or`, `not`.
Pinecone, Weaviate, Qdrant, pgvector, Elasticsearch, Milvus, Chroma, and MongoDB each have a translator class in `langchain.retrievers.self_query.*`.
## Qdrant Example (production vector DB)
```python
from langchain_qdrant import QdrantVectorStore
vstore = QdrantVectorStore.from_documents(
docs, OpenAIEmbeddings(), url="http://localhost:6333", collection_name="books"
)
retriever = SelfQueryRetriever.from_llm(
llm=llm,
vectorstore=vstore,
document_contents=document_content_description,
metadata_field_info=metadata_field_info,
)
```
The Qdrant translator maps to native `must`/`should`/`must_not` clauses with `range`, `match`, `match_any`.
## Custom Prompt for Better Filter Inference
The default prompt is good but domain-specific hints pay off on narrow schemas.
```python
from langchain.chains.query_constructor.base import (
StructuredQueryOutputParser, get_query_constructor_prompt,
)
from langchain.retrievers.self_query.chroma import ChromaTranslator
examples = [
(
"top 5 highly rated sci-fi from the 80s",
{
"query": "science fiction novels",
"filter": 'and(eq("genre","science fiction"),gte("year",1980),lte("year",1989),gte("rating",4))',
"limit": 5,
},
),
(
"anything by Asimov except Foundation",
{
"query": "novels",
"filter": 'and(eq("author","Isaac Asimov"),ne("title","Foundation"))',
},
),
]
prompt = get_query_constructor_prompt(
document_contents=document_content_description,
attribute_info=metadata_field_info,
examples=examples,
)
output_parser = StructuredQueryOutputParser.from_components()
query_constructor = prompt | llm | output_parser
retriever = SelfQueryRetriever(
query_constructor=query_constructor,
vectorstore=vstore,
structured_query_translator=ChromaTranslator(),
)
```
Include 3-5 domain-specific examples. Test-time accuracy improves 10-30% vs the default prompt on non-trivial schemas.
## LlamaIndex AutoRetriever
```python
from llama_index.core.retrievers import VectorIndexAutoRetriever
from llama_index.core.vector_stores.types import MetadataInfo, VectorStoreInfo
from llama_index.llms.anthropic import Anthropic
vector_store_info = VectorStoreInfo(
content_info="summary of a novel",
metadata_info=[
MetadataInfo(name="author", type="str", description="Author full name"),
MetadataInfo(name="year", type="int", description="Publication year"),
MetadataInfo(name="genre", type="str",
description="One of science fiction, fantasy, mystery, non-fiction"),
MetadataInfo(name="rating", type="float", description="Rating 1.0-5.0"),
],
)
retriever = VectorIndexAutoRetriever(
index,
vector_store_info=vector_store_info,
llm=Anthropic(model="claude-sonnet-4-5-20250929"),
similarity_top_k=10,
empty_query_top_k=10, # if the LLM produces empty semantic query
verbose=True,
)
nodes = retriever.retrieve("Asimov novels after 1970 rated above 4")
```
## Combining with Hybrid Search
Self-query produces `(query, filter)`. Pass the filter to both the dense retriever and the BM25 retriever; BM25 handles filter via post-filtering since most implementations have no native metadata filter.
```python
from langchain_community.retrievers import BM25Retriever
from langchain.retrievers import EnsembleRetriever
def self_query_hybrid(nl_query: str):
structured = query_constructor.invoke({"query": nl_query})
filter_fn = make_python_filter(structured.filter)
filtered_docs = [d for d in all_docs if filter_fn(d.metadata)]
if not filtered_docs:
return []
bm25 = BM25Retriever.from_documents(filtered_docs); bm25.k = 20
dense = vstore.as_retriever(search_kwargs={"k": 20, "filter": structured.filter})
hybrid = EnsembleRetriever(retrievers=[bm25, dense], weights=[0.4, 0.6])
return hybrid.invoke(structured.query)
```
#Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.