Home / File/ retrieval.py — langchain Source File

retrieval.py — langchain Source File

Architecture documentation for retrieval.py, a python file in the langchain codebase. 7 imports, 0 dependents.

Entity Profile

Dependency Diagram

graph LR
  ca2a1c18_a172_918a_8246_6b8844d7c4d0["retrieval.py"]
  8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3["typing"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> 8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3
  f3bc7443_c889_119d_0744_aacc3620d8d2["langchain_core.callbacks"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> f3bc7443_c889_119d_0744_aacc3620d8d2
  c554676d_b731_47b2_a98f_c1c2d537c0aa["langchain_core.documents"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> c554676d_b731_47b2_a98f_c1c2d537c0aa
  38bc5323_3713_7377_32f8_091293bea54b["langchain_core.retrievers"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> 38bc5323_3713_7377_32f8_091293bea54b
  6e58aaea_f08e_c099_3cc7_f9567bfb1ae7["pydantic"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> 6e58aaea_f08e_c099_3cc7_f9567bfb1ae7
  2bdb44fe_f0bd_1fb7_7a70_02295a883921["langchain_classic.chains.combine_documents.stuff"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> 2bdb44fe_f0bd_1fb7_7a70_02295a883921
  a85812ae_1e45_eb7c_7e8b_9e227e93604a["langchain_classic.chains.qa_with_sources.base"]
  ca2a1c18_a172_918a_8246_6b8844d7c4d0 --> a85812ae_1e45_eb7c_7e8b_9e227e93604a
  style ca2a1c18_a172_918a_8246_6b8844d7c4d0 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

"""Question-answering with sources over an index."""

from typing import Any

from langchain_core.callbacks import (
    AsyncCallbackManagerForChainRun,
    CallbackManagerForChainRun,
)
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from pydantic import Field

from langchain_classic.chains.combine_documents.stuff import StuffDocumentsChain
from langchain_classic.chains.qa_with_sources.base import BaseQAWithSourcesChain


class RetrievalQAWithSourcesChain(BaseQAWithSourcesChain):
    """Question-answering with sources over an index."""

    retriever: BaseRetriever = Field(exclude=True)
    """Index to connect to."""
    reduce_k_below_max_tokens: bool = False
    """Reduce the number of results to return from store based on tokens limit"""
    max_tokens_limit: int = 3375
    """Restrict the docs to return from store based on tokens,
    enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true"""

    def _reduce_tokens_below_limit(self, docs: list[Document]) -> list[Document]:
        num_docs = len(docs)

        if self.reduce_k_below_max_tokens and isinstance(
            self.combine_documents_chain,
            StuffDocumentsChain,
        ):
            tokens = [
                self.combine_documents_chain.llm_chain._get_num_tokens(doc.page_content)  # noqa: SLF001
                for doc in docs
            ]
            token_count = sum(tokens[:num_docs])
            while token_count > self.max_tokens_limit:
                num_docs -= 1
                token_count -= tokens[num_docs]

        return docs[:num_docs]

    def _get_docs(
        self,
        inputs: dict[str, Any],
        *,
        run_manager: CallbackManagerForChainRun,
    ) -> list[Document]:
        question = inputs[self.question_key]
        docs = self.retriever.invoke(
            question,
            config={"callbacks": run_manager.get_child()},
        )
        return self._reduce_tokens_below_limit(docs)

    async def _aget_docs(
        self,
        inputs: dict[str, Any],
        *,
        run_manager: AsyncCallbackManagerForChainRun,
    ) -> list[Document]:
        question = inputs[self.question_key]
        docs = await self.retriever.ainvoke(
            question,
            config={"callbacks": run_manager.get_child()},
        )
        return self._reduce_tokens_below_limit(docs)

    @property
    def _chain_type(self) -> str:
        """Return the chain type."""
        return "retrieval_qa_with_sources_chain"

Subdomains

Dependencies

  • langchain_classic.chains.combine_documents.stuff
  • langchain_classic.chains.qa_with_sources.base
  • langchain_core.callbacks
  • langchain_core.documents
  • langchain_core.retrievers
  • pydantic
  • typing

Frequently Asked Questions

What does retrieval.py do?
retrieval.py is a source file in the langchain codebase, written in python. It belongs to the CoreAbstractions domain, RunnableInterface subdomain.
What does retrieval.py depend on?
retrieval.py imports 7 module(s): langchain_classic.chains.combine_documents.stuff, langchain_classic.chains.qa_with_sources.base, langchain_core.callbacks, langchain_core.documents, langchain_core.retrievers, pydantic, typing.
Where is retrieval.py in the architecture?
retrieval.py is located at libs/langchain/langchain_classic/chains/qa_with_sources/retrieval.py (domain: CoreAbstractions, subdomain: RunnableInterface, directory: libs/langchain/langchain_classic/chains/qa_with_sources).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free