Skip to content

Commit

Permalink
Merge pull request #23 from hubkrieb/main
Browse files Browse the repository at this point in the history
Add LangChain Integration
  • Loading branch information
bclavie authored Sep 23, 2024
2 parents 34fb0cf + cd1ee7c commit b5d698c
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 2 deletions.
17 changes: 15 additions & 2 deletions byaldi/RAGModel.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
from pathlib import Path
from typing import Dict, List, Optional, Union
from typing import Any, Dict, List, Optional, Union

from PIL import Image

from byaldi.colpali import ColPaliModel

from byaldi.objects import Result

# Optional langchain integration
try:
from byaldi.integrations import ByaldiLangChainRetriever
except ImportError:
pass


class RAGMultiModalModel:
"""
Expand Down Expand Up @@ -50,7 +57,10 @@ def from_pretrained(
"""
instance = cls()
instance.model = ColPaliModel.from_pretrained(
pretrained_model_name_or_path, index_root=index_root, device=device, verbose=verbose
pretrained_model_name_or_path,
index_root=index_root,
device=device,
verbose=verbose,
)
return instance

Expand Down Expand Up @@ -165,3 +175,6 @@ def search(

def get_doc_ids_to_file_names(self):
return self.model.get_doc_ids_to_file_names()

def as_langchain_retriever(self, **kwargs: Any):
return ByaldiLangChainRetriever(model=self, kwargs=kwargs)
8 changes: 8 additions & 0 deletions byaldi/integrations/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
_all__ = []

try:
from byaldi.integrations._langchain import ByaldiLangChainRetriever

_all__.append("ByaldiLangChainRetriever")
except ImportError:
pass
21 changes: 21 additions & 0 deletions byaldi/integrations/_langchain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import Any, List

from langchain_core.callbacks.manager import CallbackManagerForRetrieverRun
from langchain_core.retrievers import BaseRetriever

from byaldi.objects import Result


class ByaldiLangChainRetriever(BaseRetriever):
model: Any
kwargs: dict = {}

def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun, # noqa
) -> List[Result]:
"""Get documents relevant to a query."""
docs = self.model.search(query, **self.kwargs)
return docs
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ dependencies = [
[project.optional-dependencies]
dev = ["pytest>=7.4.0", "ruff>=0.1.9"]
server = ["uvicorn", "fastapi"]
langchain = ["langchain-core"]

[project.urls]
"Homepage" = "https://github.com/answerdotai/byaldi"
Expand Down

0 comments on commit b5d698c

Please sign in to comment.