*   [](/v0.2/)
*   [How-to guides](/v0.2/docs/how_to/)
*   How to use a time-weighted vector store retriever

On this page

How to use a time-weighted vector store retriever
=================================================

This retriever uses a combination of semantic similarity and a time decay.

The algorithm for scoring them is:

    semantic_similarity + (1.0 - decay_rate) ^ hours_passed

Notably, `hours_passed` refers to the hours passed since the object in the retriever **was last accessed**, not since it was created. This means that frequently accessed objects remain "fresh".

    from datetime import datetime, timedeltaimport faissfrom langchain.retrievers import TimeWeightedVectorStoreRetrieverfrom langchain_community.docstore import InMemoryDocstorefrom langchain_community.vectorstores import FAISSfrom langchain_core.documents import Documentfrom langchain_openai import OpenAIEmbeddings

**API Reference:**[TimeWeightedVectorStoreRetriever](https://api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html) | [InMemoryDocstore](https://api.python.langchain.com/en/latest/docstore/langchain_community.docstore.in_memory.InMemoryDocstore.html) | [FAISS](https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.faiss.FAISS.html) | [Document](https://api.python.langchain.com/en/latest/documents/langchain_core.documents.base.Document.html) | [OpenAIEmbeddings](https://api.python.langchain.com/en/latest/embeddings/langchain_openai.embeddings.base.OpenAIEmbeddings.html)

Low decay rate[​](#low-decay-rate "Direct link to Low decay rate")
------------------------------------------------------------------

A low `decay rate` (in this, to be extreme, we will set it close to 0) means memories will be "remembered" for longer. A `decay rate` of 0 means memories never be forgotten, making this retriever equivalent to the vector lookup.

    # Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model, index, InMemoryDocstore({}), {})retriever = TimeWeightedVectorStoreRetriever(    vectorstore=vectorstore, decay_rate=0.0000000000000000000000001, k=1)

    yesterday = datetime.now() - timedelta(days=1)retriever.add_documents(    [Document(page_content="hello world", metadata={"last_accessed_at": yesterday})])retriever.add_documents([Document(page_content="hello foo")])

    ['c3dcf671-3c0a-4273-9334-c4a913076bfa']

    # "Hello World" is returned first because it is most salient, and the decay rate is close to 0., meaning it's still recent enoughretriever.get_relevant_documents("hello world")

    [Document(page_content='hello world', metadata={'last_accessed_at': datetime.datetime(2023, 12, 27, 15, 30, 18, 457125), 'created_at': datetime.datetime(2023, 12, 27, 15, 30, 8, 442662), 'buffer_idx': 0})]

High decay rate[​](#high-decay-rate "Direct link to High decay rate")
---------------------------------------------------------------------

With a high `decay rate` (e.g., several 9's), the `recency score` quickly goes to 0! If you set this all the way to 1, `recency` is 0 for all objects, once again making this equivalent to a vector lookup.

    # Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model, index, InMemoryDocstore({}), {})retriever = TimeWeightedVectorStoreRetriever(    vectorstore=vectorstore, decay_rate=0.999, k=1)

    yesterday = datetime.now() - timedelta(days=1)retriever.add_documents(    [Document(page_content="hello world", metadata={"last_accessed_at": yesterday})])retriever.add_documents([Document(page_content="hello foo")])

    ['eb1c4c86-01a8-40e3-8393-9a927295a950']

    # "Hello Foo" is returned first because "hello world" is mostly forgottenretriever.get_relevant_documents("hello world")

    [Document(page_content='hello foo', metadata={'last_accessed_at': datetime.datetime(2023, 12, 27, 15, 30, 50, 57185), 'created_at': datetime.datetime(2023, 12, 27, 15, 30, 44, 720490), 'buffer_idx': 1})]

Virtual time[​](#virtual-time "Direct link to Virtual time")
------------------------------------------------------------

Using some utils in LangChain, you can mock out the time component.

    import datetimefrom langchain_core.utils import mock_now

**API Reference:**[mock\_now](https://api.python.langchain.com/en/latest/utils/langchain_core.utils.utils.mock_now.html)

    # Notice the last access time is that date timewith mock_now(datetime.datetime(2024, 2, 3, 10, 11)):    print(retriever.get_relevant_documents("hello world"))

    [Document(page_content='hello world', metadata={'last_accessed_at': MockDateTime(2024, 2, 3, 10, 11), 'created_at': datetime.datetime(2023, 12, 27, 15, 30, 44, 532941), 'buffer_idx': 0})]

[Edit this page](https://github.com/langchain-ai/langchain/edit/master/docs/docs/how_to/time_weighted_vectorstore.ipynb)

* * *

#### Was this page helpful?

  

#### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchain/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

How to stream responses from an LLM

](/v0.2/docs/how_to/streaming_llm/)[

Next

How to use a model to call tools

](/v0.2/docs/how_to/tool_calling/)

*   [Low decay rate](#low-decay-rate)
*   [High decay rate](#high-decay-rate)
*   [Virtual time](#virtual-time)