LangChain OpenTutorial
  • 🦜️🔗 The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • Low decay_rate
  • High decay_rate
  • Summary of the decay_rate
  • Testing with Virtual Time
  1. 10-Retriever

TimeWeightedVectorStoreRetriever

PreviousTimeWeightedVectorStoreRetrieverNextKiwi BM25 Retriever

Last updated 28 days ago

  • Author:

  • Peer Review :

  • Proofread :

  • This is a part of

Overview

TimeWeightedVectorStoreRetriever is a retriever that uses a combination of semantic similarity and a time decay.

By doing so, it considers both the " freshness " and " relevance " of the documents or data in its results.

The algorithm for scoring them is:

$\text{semantic_similarity} + (1.0 - \text{decay_rate})^{hours_passed}$

  • semantic_similarity indicates the semantic similarity between documents or data.

  • decay_rate represents the ratio at which the score decreases over time.

  • hours_passed is the number of hours elapsed since the object was last accessed.

The key feature of this approach is that it evaluates the “ freshness of information ” based on the last time the object was accessed.

In other words, objects that are accessed frequently maintain a higher score over time, increasing the likelihood that frequently used or important information will appear near the top of search results. This allows the retriever to provide dynamic results that account for both recency and relevance.

Importantly, in this context, decay_rate is determined by the time since the object was last accessed , not since it was created.

Hence, any objects that are accessed frequently remain "fresh."

Table of Contents

References


Environment Setup

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

%%capture --no-stderr
%pip install langchain-opentutorial
# Install required packages
from langchain_opentutorial import package

package.install(
    [
        "langchain",
        "langchain_core",
        "langchain_community",
        "langchain_openai",
        "faiss-cpu"
    ],
    verbose=False,
    upgrade=False,
)
# Set environment variables
from langchain_opentutorial import set_env

set_env(
    {
        "OPENAI_API_KEY": "",
        "LANGCHAIN_API_KEY": "",
        "LANGCHAIN_TRACING_V2": "true",
        "LANGCHAIN_ENDPOINT": "https://api.smith.langchain.com",
        "LANGCHAIN_PROJECT": "TimeWeightedVectorStoreRetriever",
    }
)
Environment variables have been set successfully.

You can alternatively set API keys such as OPENAI_API_KEY in a .env file and load them.

[Note] This is not necessary if you've already set the required API keys in previous steps.

# Load API keys from .env file
from dotenv import load_dotenv

load_dotenv(override=True)

Low decay_rate

  • A low decay_rate (In this example, we'll set it to an extreme value close to 0) means that memories are retained for a longer period .

  • A decay_rate of 0 means that memories are never forgotten , which makes this retriever equivalent to a vector lookup.

Let's first initialize the TimeWeightedVectorStoreRetriever with a very small decay_rate and k=1 (where k is the number of vectors to retrieve).

from datetime import datetime, timedelta

import faiss
from langchain.docstore import InMemoryDocstore
from langchain.retrievers import TimeWeightedVectorStoreRetriever
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings

# Define the embedding model.
embeddings_model = OpenAIEmbeddings(model="text-embedding-3-small")

# Initialize vector store empty.
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model, index, InMemoryDocstore({}), {})

# Initialize the time-weighted vector store retriever. (Here, we'll apply a very small decay_rate)
retriever = TimeWeightedVectorStoreRetriever(
    vectorstore=vectorstore, decay_rate=0.0000000000000000000000001, k=1
)

Let's add a simple example data.

# Calculate the date of yesterday
yesterday = datetime.now() - timedelta(days=1)

retriever.add_documents(
    # Add a document with yesterday's date in the metadata
    [
        Document(
            page_content="Please subscribe to LangChain Youtube.",
            metadata={"last_accessed_at": yesterday},
        )
    ]
)

# Add another document. No metadata is specified here.
retriever.add_documents(
    [Document(page_content="Will you subscribe to LangChain Youtube? Please!")]
)
['58449575-d54f-47dc-9a76-806eccb850f3']
# Invoke the retriever to search
retriever.invoke("LangChain Youtube")
[Document(metadata={'last_accessed_at': datetime.datetime(2025, 1, 7, 10, 19, 14, 305565), 'created_at': datetime.datetime(2025, 1, 7, 10, 19, 2, 632517), 'buffer_idx': 0}, page_content='Please subscribe to Langchain Youtube.')]
  • The document "Please subscribe to LangChain Youtube" appears first because it is the most salient .

  • Since the decay_rate is close to 0, the document is still considered recent .

High decay_rate

When a high decay_rate is used (e.g., 0.9999...), the recency score rapidly converges to 0.

If this value were set to 1, all objects would end up with a recency value of 0, resulting in the same outcome as a standard vector lookup.

Initialize the retriever using TimeWeightedVectorStoreRetriever , setting the decay_rate to 0.999 to adjust the time-based weight decay rate.

# Define the embedding model.
embeddings_model = OpenAIEmbeddings(model="text-embedding-3-small")

# Initialize vector store empty.
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model, index, InMemoryDocstore({}), {})

# Initialize the time-weighted vector store retriever.
retriever = TimeWeightedVectorStoreRetriever(
    vectorstore=vectorstore, decay_rate=0.999, k=1
)

Add new documents again.

# Calculate the date of yesterday
yesterday = datetime.now() - timedelta(days=1)
retriever.add_documents(
    [
        Document(
            page_content="Please subscribe to LangChain Youtube.",
            metadata={"last_accessed_at": yesterday},
        )
    ]
)
retriever.add_documents(
    [Document(page_content="Will you subscribe to LangChain Youtube? Please!")]
)
['68d6e6ce-8ab7-4c40-aaf9-1d852eedcb49']
# Invoke the retriever to search
retriever.invoke("LangChain Youtube")
[Document(metadata={'last_accessed_at': datetime.datetime(2025, 1, 7, 10, 29, 2, 687697), 'created_at': datetime.datetime(2025, 1, 7, 10, 28, 37, 213151), 'buffer_idx': 1}, page_content='Will you subscribe to Langchain Youtube? Please!')]

In this case, when you invoke the retriever, "Will you subscribe to LangChain Youtube? Please!" is returned first.

  • Because decay_rate is high (close to 1), older documents (like the one from yesterday) are nearly forgotten.

Summary of the decay_rate

  • when the decay_rate is set to a very small value, such as 0.000001:

    • The decay rate (i.e., the rate at which information is forgotten) is extremely low, so information is hardly forgotten.

    • As a result, there is almost no difference in time-based weights between more or less recently accessed information . In this case, similarity scores are given higher priority.

  • When the decay_rate is set close to 1, such as 0.999:

    • The decay rate is very high, so most of the recently unaccessed information is almost completely forgotten.

    • As a result, in such cases, higher scores are given to more recently accessed information.

Testing with Virtual Time

LangChain provides some utilities that allow you to test time-based components by mocking the current time.

  • The mock_now function is a utility function provided by LangChain, used to mock the current time.

[NOTE] Inside the with statement, all datetime.now calls return the mocked time . Once you exit the with block, it reverts back to the original time .

import datetime
from langchain_core.utils import mock_now

# Define a function that print current time
def print_current_time():
    now = datetime.datetime.now()
    print(f"now is: {now}\n")

# Print the current time
print("before mocking")
print_current_time()

# Set the current time to a specific point in time
with mock_now(datetime.datetime(2025, 1, 7, 00, 00)):
    print("with mocking")
    print_current_time()

# Print the new current time(without mock_now block)
print("without mock_now block")
print_current_time()
before mocking
    now is: 2025-01-07 14:06:37.961348
    
    with mocking
    now is: 2025-01-07 00:00:00
    
    without mock_now block
    now is: 2025-01-07 14:06:37.961571
    

By using the mock_now function, you can shift the current time and see how the search results change.

  • This helps you find an appropriate decay_rate for your use case.

[Note]

If you set the time too far in the past, an error might occur during decay_rate calculations.

# Example usage changing the current time for testing.
with mock_now(datetime.datetime(2025, 1, 7, 00, 00)):
    # Execute a search in this simulated timeline.
    print(retriever.invoke("Langchain Youtube"))
[Document(metadata={'last_accessed_at': MockDateTime(2025, 1, 7, 0, 0), 'created_at': datetime.datetime(2025, 1, 7, 10, 28, 37, 213151), 'buffer_idx': 1}, page_content='Will you subscribe to Langchain Youtube? Please!')]

Set up the environment. You may refer to for more details.

You can checkout the for more details.

Time-weighted vector store retriever
TimeWeightedVectorStoreRetriever
mock_now
Environment Setup
langchain-opentutorial
Overview
Environment Setup
Low decay_rate
High decay_rate
Summary of the decay_rate
Testing with Virtual time
Youngjun Cho
Juni Lee
LangChain Open Tutorial