Home / File/ vector_db.py — langchain Source File

vector_db.py — langchain Source File

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

Entity Profile

Dependency Diagram

graph LR
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e["vector_db.py"]
  0c635125_6987_b8b3_7ff7_d60249aecde7["warnings"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> 0c635125_6987_b8b3_7ff7_d60249aecde7
  8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3["typing"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> 8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3
  f3bc7443_c889_119d_0744_aacc3620d8d2["langchain_core.callbacks"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> f3bc7443_c889_119d_0744_aacc3620d8d2
  c554676d_b731_47b2_a98f_c1c2d537c0aa["langchain_core.documents"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> c554676d_b731_47b2_a98f_c1c2d537c0aa
  d55af636_303c_0eb6_faee_20d89bd952d5["langchain_core.vectorstores"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> d55af636_303c_0eb6_faee_20d89bd952d5
  6e58aaea_f08e_c099_3cc7_f9567bfb1ae7["pydantic"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> 6e58aaea_f08e_c099_3cc7_f9567bfb1ae7
  91721f45_4909_e489_8c1f_084f8bd87145["typing_extensions"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> 91721f45_4909_e489_8c1f_084f8bd87145
  2bdb44fe_f0bd_1fb7_7a70_02295a883921["langchain_classic.chains.combine_documents.stuff"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> 2bdb44fe_f0bd_1fb7_7a70_02295a883921
  a85812ae_1e45_eb7c_7e8b_9e227e93604a["langchain_classic.chains.qa_with_sources.base"]
  dbe941e0_6e65_a06f_11f1_ee39bd5dd14e --> a85812ae_1e45_eb7c_7e8b_9e227e93604a
  style dbe941e0_6e65_a06f_11f1_ee39bd5dd14e fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

"""Question-answering with sources over a vector database."""

import warnings
from typing import Any

from langchain_core.callbacks import (
    AsyncCallbackManagerForChainRun,
    CallbackManagerForChainRun,
)
from langchain_core.documents import Document
from langchain_core.vectorstores import VectorStore
from pydantic import Field, model_validator
from typing_extensions import override

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


class VectorDBQAWithSourcesChain(BaseQAWithSourcesChain):
    """Question-answering with sources over a vector database."""

    vectorstore: VectorStore = Field(exclude=True)
    """Vector Database to connect to."""
    k: int = 4
    """Number of results to return from store"""
    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"""
    search_kwargs: dict[str, Any] = Field(default_factory=dict)
    """Extra search args."""

    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]

    @override
    def _get_docs(
        self,
        inputs: dict[str, Any],
        *,
        run_manager: CallbackManagerForChainRun,
    ) -> list[Document]:
        question = inputs[self.question_key]
        docs = self.vectorstore.similarity_search(
            question,
            k=self.k,
            **self.search_kwargs,
        )
        return self._reduce_tokens_below_limit(docs)

    async def _aget_docs(
        self,
        inputs: dict[str, Any],
        *,
        run_manager: AsyncCallbackManagerForChainRun,
    ) -> list[Document]:
        msg = "VectorDBQAWithSourcesChain does not support async"
        raise NotImplementedError(msg)

    @model_validator(mode="before")
    @classmethod
    def _raise_deprecation(cls, values: dict) -> Any:
        warnings.warn(
            "`VectorDBQAWithSourcesChain` is deprecated - "
            "please use `from langchain_classic.chains import "
            "RetrievalQAWithSourcesChain`",
            stacklevel=5,
        )
        return values

    @property
    def _chain_type(self) -> str:
        return "vector_db_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.vectorstores
  • pydantic
  • typing
  • typing_extensions
  • warnings

Frequently Asked Questions

What does vector_db.py do?
vector_db.py is a source file in the langchain codebase, written in python. It belongs to the CoreAbstractions domain, RunnableInterface subdomain.
What does vector_db.py depend on?
vector_db.py imports 9 module(s): langchain_classic.chains.combine_documents.stuff, langchain_classic.chains.qa_with_sources.base, langchain_core.callbacks, langchain_core.documents, langchain_core.vectorstores, pydantic, typing, typing_extensions, and 1 more.
Where is vector_db.py in the architecture?
vector_db.py is located at libs/langchain/langchain_classic/chains/qa_with_sources/vector_db.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