langchain/libs/community/langchain_community/document_compressors/rankllm_rerank.py
Eugene Yurtsev bf5193bb99
community[patch]: Upgrade pydantic extra (#25185)
Upgrade to using a literal for specifying the extra which is the
recommended approach in pydantic 2.

This works correctly also in pydantic v1.

```python
from pydantic.v1 import BaseModel

class Foo(BaseModel, extra="forbid"):
    x: int

Foo(x=5, y=1)
```

And 


```python
from pydantic.v1 import BaseModel

class Foo(BaseModel):
    x: int

    class Config:
      extra = "forbid"

Foo(x=5, y=1)
```


## Enum -> literal using grit pattern:

```
engine marzano(0.1)
language python
or {
    `extra=Extra.allow` => `extra="allow"`,
    `extra=Extra.forbid` => `extra="forbid"`,
    `extra=Extra.ignore` => `extra="ignore"`
}
```

Resorted attributes in config and removed doc-string in case we will
need to deal with going back and forth between pydantic v1 and v2 during
the 0.3 release. (This will reduce merge conflicts.)


## Sort attributes in Config:

```
engine marzano(0.1)
language python


function sort($values) js {
    return $values.text.split(',').sort().join("\n");
}


class_definition($name, $body) as $C where {
    $name <: `Config`,
    $body <: block($statements),
    $values = [],
    $statements <: some bubble($values) assignment() as $A where {
        $values += $A
    },
    $body => sort($values),
}

```
2024-08-08 17:20:39 +00:00

123 lines
4.0 KiB
Python

from __future__ import annotations
from copy import deepcopy
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
from langchain.retrievers.document_compressors.base import BaseDocumentCompressor
from langchain_core.callbacks.manager import Callbacks
from langchain_core.documents import Document
from langchain_core.pydantic_v1 import Field, PrivateAttr, root_validator
from langchain_core.utils import get_from_dict_or_env
if TYPE_CHECKING:
from rank_llm.data import Candidate, Query, Request
else:
# Avoid pydantic annotation issues when actually instantiating
# while keeping this import optional
try:
from rank_llm.data import Candidate, Query, Request
except ImportError:
pass
class RankLLMRerank(BaseDocumentCompressor):
"""Document compressor using Flashrank interface."""
client: Any = None
"""RankLLM client to use for compressing documents"""
top_n: int = Field(default=3)
"""Top N documents to return."""
model: str = Field(default="zephyr")
"""Name of model to use for reranking."""
step_size: int = Field(default=10)
"""Step size for moving sliding window."""
gpt_model: str = Field(default="gpt-3.5-turbo")
"""OpenAI model name."""
_retriever: Any = PrivateAttr()
class Config:
arbitrary_types_allowed = True
extra = "forbid"
@root_validator(pre=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validate python package exists in environment."""
if not values.get("client"):
client_name = values.get("model", "zephyr")
try:
model_enum = ModelType(client_name.lower())
except ValueError:
raise ValueError(
"Unsupported model type. Please use 'vicuna', 'zephyr', or 'gpt'."
)
try:
if model_enum == ModelType.VICUNA:
from rank_llm.rerank.vicuna_reranker import VicunaReranker
values["client"] = VicunaReranker()
elif model_enum == ModelType.ZEPHYR:
from rank_llm.rerank.zephyr_reranker import ZephyrReranker
values["client"] = ZephyrReranker()
elif model_enum == ModelType.GPT:
from rank_llm.rerank.rank_gpt import SafeOpenai
from rank_llm.rerank.reranker import Reranker
openai_api_key = get_from_dict_or_env(
values, "open_api_key", "OPENAI_API_KEY"
)
agent = SafeOpenai(
model=values["gpt_model"],
context_size=4096,
keys=openai_api_key,
)
values["client"] = Reranker(agent)
except ImportError:
raise ImportError(
"Could not import rank_llm python package. "
"Please install it with `pip install rank_llm`."
)
return values
def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = None,
) -> Sequence[Document]:
request = Request(
query=Query(text=query, qid=1),
candidates=[
Candidate(doc={"text": doc.page_content}, docid=index, score=1)
for index, doc in enumerate(documents)
],
)
rerank_results = self.client.rerank(
request,
rank_end=len(documents),
window_size=min(20, len(documents)),
step=10,
)
final_results = []
for res in rerank_results.candidates:
doc = documents[int(res.docid)]
doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
final_results.append(doc_copy)
return final_results[: self.top_n]
class ModelType(Enum):
VICUNA = "vicuna"
ZEPHYR = "zephyr"
GPT = "gpt"