time-aware-retrieval
БесплатноБез исполняемых скриптовНе проверенTemporal awareness in RAG. Recency bias weighting, exponential decay scoring, time-range filtering, LLM-based date extraction ("last quarter", "yesterday")…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Time-Aware Retrieval
Why It Matters
"What is our refund policy?" should return the current policy, not the 2019 version. Pure semantic similarity often prefers older verbose documents that match more query terms. Time awareness corrects this.
Two failure modes to prevent:
- Stale wins: old doc ranks above newer authoritative doc because it's more verbose.
- Fresh-but-wrong: auto-generated recent doc outranks the authoritative but older source of truth.
Approaches
| Approach | Needs | Strength | Weakness |
|---|---|---|---|
| Hard time filter | Date in query | Exact scoping | Fails for vague time |
| Recency decay | Timestamp metadata | Smooth, always applies | Can bury important old docs |
| LLM date extraction | LLM call | Handles "last quarter" | Latency + cost |
| Temporal KG | Entities with time edges | Multi-step time reasoning | Complex to build |
| Authority + recency blend | Authority score | Balances fresh vs canonical | Authority signal is hard |
Timestamp Metadata
Every chunk needs at least:
created_at— original publication time.updated_at— last content-significant edit.valid_from,valid_to— if the fact has explicit validity.
from pydantic import BaseModel
from datetime import datetime
class ChunkMetadata(BaseModel):
chunk_id: str
doc_id: str
created_at: datetime
updated_at: datetime
valid_from: datetime | None = None
valid_to: datetime | None = None
source_authority: float = 0.5 # 0-1; 1.0 = official/canonical
Exponential Decay Scoring
import math
from datetime import datetime
HALF_LIFE_DAYS = 180
def recency_weight(updated_at: datetime, now: datetime | None = None) -> float:
now = now or datetime.utcnow()
age_days = (now - updated_at).total_seconds() / 86400
return 0.5 ** (age_days / HALF_LIFE_DAYS)
def blended_score(semantic_score: float, meta: ChunkMetadata, alpha: float = 0.8) -> float:
return alpha * semantic_score + (1 - alpha) * recency_weight(meta.updated_at)
Half-life by domain:
- News: 7-30 days
- Software docs: 180 days
- Legal / regulations: 5-10 years
- Medical guidelines: 3-5 years
- Internal wiki: 365 days
Tune with the eval set; do not guess.
Authority-Weighted Recency
Pure recency punishes canonical sources (e.g., the constitution). Blend with authority.
def time_authority_score(semantic: float, meta: ChunkMetadata,
w_sem: float = 0.6, w_rec: float = 0.2, w_auth: float = 0.2) -> float:
return (w_sem * semantic
+ w_rec * recency_weight(meta.updated_at)
+ w_auth * meta.source_authority)
Chunks from /legal/policies/ get source_authority=1.0; chunks from community posts get 0.3.
LLM Date Extraction
from pydantic import BaseModel, Field
from typing import Literal
from datetime import datetime, timedelta
from langchain_anthropic import ChatAnthropic
class DateRange(BaseModel):
has_time_filter: bool
start: datetime | None = Field(None, description="ISO 8601 start")
end: datetime | None = Field(None, description="ISO 8601 end")
relative_hint: Literal["strict", "soft"] | None = Field(
"soft", description="strict = only these dates; soft = prefer these dates"
)
llm = ChatAnthropic(model="claude-haiku-4-5-20250929", temperature=0).with_structured_output(DateRange)
def extract_time(query: str, today: datetime) -> DateRange:
return llm.invoke(
f"Today is {today.isoformat()}. Extract any time filter from the query. "
f"Return has_time_filter=false if no time reference.\n\nQuery: {query}"
)
Examples:
- "refund policy" ->
has_time_filter=False - "revenue last quarter" ->
has_time_filter=True, start/end of Q3 2025 - "what changed since January" ->
has_time_filter=True, start=2025-01-01, end=today,soft
Soft hints feed the recency decay; strict hints become hard filters.
Query Pipeline
def time_aware_retrieve(query: str, top_k: int = 10):
now = datetime.utcnow()
dr = extract_time(query, now)
candidates = vstore.similarity_search(query, k=100,
filter=build_filter(dr) if dr.has_time_filter and dr.relative_hint == "strict" else None)
scored = []
for d in candidates:
meta = ChunkMetadata(**d.metadata)
base_score = d.metadata["score"]
score = time_authority_score(base_score, meta)
if dr.has_time_filter and dr.relative_hint == "soft":
in_range = (dr.start or datetime.min) <= meta.updated_at <= (dr.end or datetime.max)
score *= 1.2 if in_range else 0.9
scored.append((d, score))
scored.sort(key=lambda x: -x[1])
return [d for d, _ in scored[:top_k]]
def build_filter(dr: DateRange) -> dict:
f = {}
if dr.start: f["updated_at"] = {"$gte": dr.start.isoformat()}
if dr.end: f.setdefault("updated_at", {})["$lte"] = dr.end.isoformat()
return f
Valid-From / Valid-To (versioned facts)
Установить time-aware-retrieval в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл time-aware-retrieval?
Temporal awareness in RAG. Recency bias weighting, exponential decay scoring, time-range filtering, LLM-based date extraction ("last quarter", "yesterday"), temporal knowledge graphs, freshness vs authority tradeoff, event-based retrieval, timestamp metadata, differential reindexing of old vs fresh docs. USE WHEN: user mentions "time-aware RAG", "recency bias", "temporal retrieval", "freshness", "date filter", "temporal knowledge graph", "exponential decay" DO NOT USE FOR: static metadata filters generally - use `self-querying-retriever`; CDC for ingestion - use `cdc-streaming-ingestion`; evaluation of time-sensitive answers - use `rag-evaluation`
Как установить скилл time-aware-retrieval?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл time-aware-retrieval запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic