utils.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. import logging
  2. import os
  3. from typing import Optional, Union
  4. import requests
  5. import hashlib
  6. from concurrent.futures import ThreadPoolExecutor
  7. from huggingface_hub import snapshot_download
  8. from langchain.retrievers import ContextualCompressionRetriever, EnsembleRetriever
  9. from langchain_community.retrievers import BM25Retriever
  10. from langchain_core.documents import Document
  11. from open_webui.config import VECTOR_DB
  12. from open_webui.retrieval.vector.connector import VECTOR_DB_CLIENT
  13. from open_webui.models.users import UserModel
  14. from open_webui.models.files import Files
  15. from open_webui.retrieval.vector.main import GetResult
  16. from open_webui.env import (
  17. SRC_LOG_LEVELS,
  18. OFFLINE_MODE,
  19. ENABLE_FORWARD_USER_INFO_HEADERS,
  20. )
  21. from open_webui.config import (
  22. RAG_EMBEDDING_QUERY_PREFIX,
  23. RAG_EMBEDDING_CONTENT_PREFIX,
  24. RAG_EMBEDDING_PREFIX_FIELD_NAME,
  25. )
  26. log = logging.getLogger(__name__)
  27. log.setLevel(SRC_LOG_LEVELS["RAG"])
  28. from typing import Any
  29. from langchain_core.callbacks import CallbackManagerForRetrieverRun
  30. from langchain_core.retrievers import BaseRetriever
  31. class VectorSearchRetriever(BaseRetriever):
  32. collection_name: Any
  33. embedding_function: Any
  34. top_k: int
  35. def _get_relevant_documents(
  36. self,
  37. query: str,
  38. *,
  39. run_manager: CallbackManagerForRetrieverRun,
  40. ) -> list[Document]:
  41. result = VECTOR_DB_CLIENT.search(
  42. collection_name=self.collection_name,
  43. vectors=[self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)],
  44. limit=self.top_k,
  45. )
  46. ids = result.ids[0]
  47. metadatas = result.metadatas[0]
  48. documents = result.documents[0]
  49. results = []
  50. for idx in range(len(ids)):
  51. results.append(
  52. Document(
  53. metadata=metadatas[idx],
  54. page_content=documents[idx],
  55. )
  56. )
  57. return results
  58. def query_doc(
  59. collection_name: str, query_embedding: list[float], k: int, user: UserModel = None
  60. ):
  61. try:
  62. log.debug(f"query_doc:doc {collection_name}")
  63. result = VECTOR_DB_CLIENT.search(
  64. collection_name=collection_name,
  65. vectors=[query_embedding],
  66. limit=k,
  67. )
  68. if result:
  69. log.info(f"query_doc:result {result.ids} {result.metadatas}")
  70. return result
  71. except Exception as e:
  72. log.exception(f"Error querying doc {collection_name} with limit {k}: {e}")
  73. raise e
  74. def get_doc(collection_name: str, user: UserModel = None):
  75. try:
  76. log.debug(f"get_doc:doc {collection_name}")
  77. result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
  78. if result:
  79. log.info(f"query_doc:result {result.ids} {result.metadatas}")
  80. return result
  81. except Exception as e:
  82. log.exception(f"Error getting doc {collection_name}: {e}")
  83. raise e
  84. def query_doc_with_hybrid_search(
  85. collection_name: str,
  86. collection_result: GetResult,
  87. query: str,
  88. embedding_function,
  89. k: int,
  90. reranking_function,
  91. k_reranker: int,
  92. r: float,
  93. ) -> dict:
  94. try:
  95. log.debug(f"query_doc_with_hybrid_search:doc {collection_name}")
  96. bm25_retriever = BM25Retriever.from_texts(
  97. texts=collection_result.documents[0],
  98. metadatas=collection_result.metadatas[0],
  99. )
  100. bm25_retriever.k = k
  101. vector_search_retriever = VectorSearchRetriever(
  102. collection_name=collection_name,
  103. embedding_function=embedding_function,
  104. top_k=k,
  105. )
  106. ensemble_retriever = EnsembleRetriever(
  107. retrievers=[bm25_retriever, vector_search_retriever], weights=[0.5, 0.5]
  108. )
  109. compressor = RerankCompressor(
  110. embedding_function=embedding_function,
  111. top_n=k_reranker,
  112. reranking_function=reranking_function,
  113. r_score=r,
  114. )
  115. compression_retriever = ContextualCompressionRetriever(
  116. base_compressor=compressor, base_retriever=ensemble_retriever
  117. )
  118. result = compression_retriever.invoke(query)
  119. distances = [d.metadata.get("score") for d in result]
  120. documents = [d.page_content for d in result]
  121. metadatas = [d.metadata for d in result]
  122. # retrieve only min(k, k_reranker) items, sort and cut by distance if k < k_reranker
  123. if k < k_reranker:
  124. sorted_items = sorted(
  125. zip(distances, metadatas, documents), key=lambda x: x[0], reverse=True
  126. )
  127. sorted_items = sorted_items[:k]
  128. distances, documents, metadatas = map(list, zip(*sorted_items))
  129. result = {
  130. "distances": [distances],
  131. "documents": [documents],
  132. "metadatas": [metadatas],
  133. }
  134. log.info(
  135. "query_doc_with_hybrid_search:result "
  136. + f'{result["metadatas"]} {result["distances"]}'
  137. )
  138. return result
  139. except Exception as e:
  140. log.exception(f"Error querying doc {collection_name} with hybrid search: {e}")
  141. raise e
  142. def merge_get_results(get_results: list[dict]) -> dict:
  143. # Initialize lists to store combined data
  144. combined_documents = []
  145. combined_metadatas = []
  146. combined_ids = []
  147. for data in get_results:
  148. combined_documents.extend(data["documents"][0])
  149. combined_metadatas.extend(data["metadatas"][0])
  150. combined_ids.extend(data["ids"][0])
  151. # Create the output dictionary
  152. result = {
  153. "documents": [combined_documents],
  154. "metadatas": [combined_metadatas],
  155. "ids": [combined_ids],
  156. }
  157. return result
  158. def merge_and_sort_query_results(query_results: list[dict], k: int) -> dict:
  159. # Initialize lists to store combined data
  160. combined = dict() # To store documents with unique document hashes
  161. for data in query_results:
  162. distances = data["distances"][0]
  163. documents = data["documents"][0]
  164. metadatas = data["metadatas"][0]
  165. for distance, document, metadata in zip(distances, documents, metadatas):
  166. if isinstance(document, str):
  167. doc_hash = hashlib.md5(
  168. document.encode()
  169. ).hexdigest() # Compute a hash for uniqueness
  170. if doc_hash not in combined.keys():
  171. combined[doc_hash] = (distance, document, metadata)
  172. continue # if doc is new, no further comparison is needed
  173. # if doc is alredy in, but new distance is better, update
  174. if distance > combined[doc_hash][0]:
  175. combined[doc_hash] = (distance, document, metadata)
  176. combined = list(combined.values())
  177. # Sort the list based on distances
  178. combined.sort(key=lambda x: x[0], reverse=True)
  179. # Slice to keep only the top k elements
  180. sorted_distances, sorted_documents, sorted_metadatas = (
  181. zip(*combined[:k]) if combined else ([], [], [])
  182. )
  183. # Create and return the output dictionary
  184. return {
  185. "distances": [list(sorted_distances)],
  186. "documents": [list(sorted_documents)],
  187. "metadatas": [list(sorted_metadatas)],
  188. }
  189. def get_all_items_from_collections(collection_names: list[str]) -> dict:
  190. results = []
  191. for collection_name in collection_names:
  192. if collection_name:
  193. try:
  194. result = get_doc(collection_name=collection_name)
  195. if result is not None:
  196. results.append(result.model_dump())
  197. except Exception as e:
  198. log.exception(f"Error when querying the collection: {e}")
  199. else:
  200. pass
  201. return merge_get_results(results)
  202. def query_collection(
  203. collection_names: list[str],
  204. queries: list[str],
  205. embedding_function,
  206. k: int,
  207. ) -> dict:
  208. results = []
  209. for query in queries:
  210. log.debug(f"query_collection:query {query}")
  211. query_embedding = embedding_function(query, prefix=RAG_EMBEDDING_QUERY_PREFIX)
  212. for collection_name in collection_names:
  213. if collection_name:
  214. try:
  215. result = query_doc(
  216. collection_name=collection_name,
  217. k=k,
  218. query_embedding=query_embedding,
  219. )
  220. if result is not None:
  221. results.append(result.model_dump())
  222. except Exception as e:
  223. log.exception(f"Error when querying the collection: {e}")
  224. else:
  225. pass
  226. return merge_and_sort_query_results(results, k=k)
  227. def query_collection_with_hybrid_search(
  228. collection_names: list[str],
  229. queries: list[str],
  230. embedding_function,
  231. k: int,
  232. reranking_function,
  233. k_reranker: int,
  234. r: float,
  235. ) -> dict:
  236. results = []
  237. error = False
  238. # Fetch collection data once per collection sequentially
  239. # Avoid fetching the same data multiple times later
  240. collection_results = {}
  241. for collection_name in collection_names:
  242. try:
  243. log.debug(f"query_collection_with_hybrid_search:VECTOR_DB_CLIENT.get:collection {collection_name}")
  244. collection_results[collection_name] = VECTOR_DB_CLIENT.get(
  245. collection_name=collection_name
  246. )
  247. except Exception as e:
  248. log.exception(f"Failed to fetch collection {collection_name}: {e}")
  249. collection_results[collection_name] = None
  250. log.info(
  251. f"Starting hybrid search for {len(queries)} queries in {len(collection_names)} collections..."
  252. )
  253. def process_query(collection_name, query):
  254. try:
  255. result = query_doc_with_hybrid_search(
  256. collection_name=collection_name,
  257. collection_result=collection_results[collection_name],
  258. query=query,
  259. embedding_function=embedding_function,
  260. k=k,
  261. reranking_function=reranking_function,
  262. k_reranker=k_reranker,
  263. r=r,
  264. )
  265. return result, None
  266. except Exception as e:
  267. log.exception(f"Error when querying the collection with hybrid_search: {e}")
  268. return None, e
  269. # Prepare tasks for all collections and queries
  270. # Avoid running any tasks for collections that failed to fetch data (have assigned None)
  271. tasks = [
  272. (cn, q)
  273. for cn in collection_names
  274. if collection_results[cn] is not None
  275. for q in queries
  276. ]
  277. with ThreadPoolExecutor() as executor:
  278. future_results = [executor.submit(process_query, cn, q) for cn, q in tasks]
  279. task_results = [future.result() for future in future_results]
  280. for result, err in task_results:
  281. if err is not None:
  282. error = True
  283. elif result is not None:
  284. results.append(result)
  285. if error and not results:
  286. raise Exception(
  287. "Hybrid search failed for all collections. Using Non-hybrid search as fallback."
  288. )
  289. return merge_and_sort_query_results(results, k=k)
  290. def get_embedding_function(
  291. embedding_engine,
  292. embedding_model,
  293. embedding_function,
  294. url,
  295. key,
  296. embedding_batch_size,
  297. ):
  298. if embedding_engine == "":
  299. return lambda query, prefix=None, user=None: embedding_function.encode(
  300. query, **({"prompt": prefix} if prefix else {})
  301. ).tolist()
  302. elif embedding_engine in ["ollama", "openai"]:
  303. func = lambda query, prefix=None, user=None: generate_embeddings(
  304. engine=embedding_engine,
  305. model=embedding_model,
  306. text=query,
  307. prefix=prefix,
  308. url=url,
  309. key=key,
  310. user=user,
  311. )
  312. def generate_multiple(query, prefix, user, func):
  313. if isinstance(query, list):
  314. embeddings = []
  315. for i in range(0, len(query), embedding_batch_size):
  316. embeddings.extend(
  317. func(
  318. query[i : i + embedding_batch_size],
  319. prefix=prefix,
  320. user=user,
  321. )
  322. )
  323. return embeddings
  324. else:
  325. return func(query, prefix, user)
  326. return lambda query, prefix=None, user=None: generate_multiple(
  327. query, prefix, user, func
  328. )
  329. else:
  330. raise ValueError(f"Unknown embedding engine: {embedding_engine}")
  331. def get_sources_from_files(
  332. request,
  333. files,
  334. queries,
  335. embedding_function,
  336. k,
  337. reranking_function,
  338. k_reranker,
  339. r,
  340. hybrid_search,
  341. full_context=False,
  342. ):
  343. log.debug(
  344. f"files: {files} {queries} {embedding_function} {reranking_function} {full_context}"
  345. )
  346. extracted_collections = []
  347. relevant_contexts = []
  348. for file in files:
  349. context = None
  350. if file.get("docs"):
  351. # BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL
  352. context = {
  353. "documents": [[doc.get("content") for doc in file.get("docs")]],
  354. "metadatas": [[doc.get("metadata") for doc in file.get("docs")]],
  355. }
  356. elif file.get("context") == "full":
  357. # Manual Full Mode Toggle
  358. context = {
  359. "documents": [[file.get("file").get("data", {}).get("content")]],
  360. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  361. }
  362. elif (
  363. file.get("type") != "web_search"
  364. and request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
  365. ):
  366. # BYPASS_EMBEDDING_AND_RETRIEVAL
  367. if file.get("type") == "collection":
  368. file_ids = file.get("data", {}).get("file_ids", [])
  369. documents = []
  370. metadatas = []
  371. for file_id in file_ids:
  372. file_object = Files.get_file_by_id(file_id)
  373. if file_object:
  374. documents.append(file_object.data.get("content", ""))
  375. metadatas.append(
  376. {
  377. "file_id": file_id,
  378. "name": file_object.filename,
  379. "source": file_object.filename,
  380. }
  381. )
  382. context = {
  383. "documents": [documents],
  384. "metadatas": [metadatas],
  385. }
  386. elif file.get("id"):
  387. file_object = Files.get_file_by_id(file.get("id"))
  388. if file_object:
  389. context = {
  390. "documents": [[file_object.data.get("content", "")]],
  391. "metadatas": [
  392. [
  393. {
  394. "file_id": file.get("id"),
  395. "name": file_object.filename,
  396. "source": file_object.filename,
  397. }
  398. ]
  399. ],
  400. }
  401. elif file.get("file").get("data"):
  402. context = {
  403. "documents": [[file.get("file").get("data", {}).get("content")]],
  404. "metadatas": [
  405. [file.get("file").get("data", {}).get("metadata", {})]
  406. ],
  407. }
  408. else:
  409. collection_names = []
  410. if file.get("type") == "collection":
  411. if file.get("legacy"):
  412. collection_names = file.get("collection_names", [])
  413. else:
  414. collection_names.append(file["id"])
  415. elif file.get("collection_name"):
  416. collection_names.append(file["collection_name"])
  417. elif file.get("id"):
  418. if file.get("legacy"):
  419. collection_names.append(f"{file['id']}")
  420. else:
  421. collection_names.append(f"file-{file['id']}")
  422. collection_names = set(collection_names).difference(extracted_collections)
  423. if not collection_names:
  424. log.debug(f"skipping {file} as it has already been extracted")
  425. continue
  426. if full_context:
  427. try:
  428. context = get_all_items_from_collections(collection_names)
  429. except Exception as e:
  430. log.exception(e)
  431. else:
  432. try:
  433. context = None
  434. if file.get("type") == "text":
  435. context = file["content"]
  436. else:
  437. if hybrid_search:
  438. try:
  439. context = query_collection_with_hybrid_search(
  440. collection_names=collection_names,
  441. queries=queries,
  442. embedding_function=embedding_function,
  443. k=k,
  444. reranking_function=reranking_function,
  445. k_reranker=k_reranker,
  446. r=r,
  447. )
  448. except Exception as e:
  449. log.debug(
  450. "Error when using hybrid search, using"
  451. " non hybrid search as fallback."
  452. )
  453. if (not hybrid_search) or (context is None):
  454. context = query_collection(
  455. collection_names=collection_names,
  456. queries=queries,
  457. embedding_function=embedding_function,
  458. k=k,
  459. )
  460. except Exception as e:
  461. log.exception(e)
  462. extracted_collections.extend(collection_names)
  463. if context:
  464. if "data" in file:
  465. del file["data"]
  466. relevant_contexts.append({**context, "file": file})
  467. sources = []
  468. for context in relevant_contexts:
  469. try:
  470. if "documents" in context:
  471. if "metadatas" in context:
  472. source = {
  473. "source": context["file"],
  474. "document": context["documents"][0],
  475. "metadata": context["metadatas"][0],
  476. }
  477. if "distances" in context and context["distances"]:
  478. source["distances"] = context["distances"][0]
  479. sources.append(source)
  480. except Exception as e:
  481. log.exception(e)
  482. return sources
  483. def get_model_path(model: str, update_model: bool = False):
  484. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  485. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  486. local_files_only = not update_model
  487. if OFFLINE_MODE:
  488. local_files_only = True
  489. snapshot_kwargs = {
  490. "cache_dir": cache_dir,
  491. "local_files_only": local_files_only,
  492. }
  493. log.debug(f"model: {model}")
  494. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  495. # Inspiration from upstream sentence_transformers
  496. if (
  497. os.path.exists(model)
  498. or ("\\" in model or model.count("/") > 1)
  499. and local_files_only
  500. ):
  501. # If fully qualified path exists, return input, else set repo_id
  502. return model
  503. elif "/" not in model:
  504. # Set valid repo_id for model short-name
  505. model = "sentence-transformers" + "/" + model
  506. snapshot_kwargs["repo_id"] = model
  507. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  508. try:
  509. model_repo_path = snapshot_download(**snapshot_kwargs)
  510. log.debug(f"model_repo_path: {model_repo_path}")
  511. return model_repo_path
  512. except Exception as e:
  513. log.exception(f"Cannot determine model snapshot path: {e}")
  514. return model
  515. def generate_openai_batch_embeddings(
  516. model: str,
  517. texts: list[str],
  518. url: str = "https://api.openai.com/v1",
  519. key: str = "",
  520. prefix: str = None,
  521. user: UserModel = None,
  522. ) -> Optional[list[list[float]]]:
  523. try:
  524. log.debug(f"generate_openai_batch_embeddings:model {model} batch size: {len(texts)}")
  525. json_data = {"input": texts, "model": model}
  526. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  527. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  528. r = requests.post(
  529. f"{url}/embeddings",
  530. headers={
  531. "Content-Type": "application/json",
  532. "Authorization": f"Bearer {key}",
  533. **(
  534. {
  535. "X-OpenWebUI-User-Name": user.name,
  536. "X-OpenWebUI-User-Id": user.id,
  537. "X-OpenWebUI-User-Email": user.email,
  538. "X-OpenWebUI-User-Role": user.role,
  539. }
  540. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  541. else {}
  542. ),
  543. },
  544. json=json_data,
  545. )
  546. r.raise_for_status()
  547. data = r.json()
  548. if "data" in data:
  549. return [elem["embedding"] for elem in data["data"]]
  550. else:
  551. raise "Something went wrong :/"
  552. except Exception as e:
  553. log.exception(f"Error generating openai batch embeddings: {e}")
  554. return None
  555. def generate_ollama_batch_embeddings(
  556. model: str,
  557. texts: list[str],
  558. url: str,
  559. key: str = "",
  560. prefix: str = None,
  561. user: UserModel = None,
  562. ) -> Optional[list[list[float]]]:
  563. try:
  564. log.debug(f"generate_ollama_batch_embeddings:model {model} batch size: {len(texts)}")
  565. json_data = {"input": texts, "model": model}
  566. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  567. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  568. r = requests.post(
  569. f"{url}/api/embed",
  570. headers={
  571. "Content-Type": "application/json",
  572. "Authorization": f"Bearer {key}",
  573. **(
  574. {
  575. "X-OpenWebUI-User-Name": user.name,
  576. "X-OpenWebUI-User-Id": user.id,
  577. "X-OpenWebUI-User-Email": user.email,
  578. "X-OpenWebUI-User-Role": user.role,
  579. }
  580. if ENABLE_FORWARD_USER_INFO_HEADERS
  581. else {}
  582. ),
  583. },
  584. json=json_data,
  585. )
  586. r.raise_for_status()
  587. data = r.json()
  588. if "embeddings" in data:
  589. return data["embeddings"]
  590. else:
  591. raise "Something went wrong :/"
  592. except Exception as e:
  593. log.exception(f"Error generating ollama batch embeddings: {e}")
  594. return None
  595. def generate_embeddings(
  596. engine: str,
  597. model: str,
  598. text: Union[str, list[str]],
  599. prefix: Union[str, None] = None,
  600. **kwargs,
  601. ):
  602. url = kwargs.get("url", "")
  603. key = kwargs.get("key", "")
  604. user = kwargs.get("user")
  605. if prefix is not None and RAG_EMBEDDING_PREFIX_FIELD_NAME is None:
  606. if isinstance(text, list):
  607. text = [f"{prefix}{text_element}" for text_element in text]
  608. else:
  609. text = f"{prefix}{text}"
  610. if engine == "ollama":
  611. if isinstance(text, list):
  612. embeddings = generate_ollama_batch_embeddings(
  613. **{
  614. "model": model,
  615. "texts": text,
  616. "url": url,
  617. "key": key,
  618. "prefix": prefix,
  619. "user": user,
  620. }
  621. )
  622. else:
  623. embeddings = generate_ollama_batch_embeddings(
  624. **{
  625. "model": model,
  626. "texts": [text],
  627. "url": url,
  628. "key": key,
  629. "prefix": prefix,
  630. "user": user,
  631. }
  632. )
  633. return embeddings[0] if isinstance(text, str) else embeddings
  634. elif engine == "openai":
  635. if isinstance(text, list):
  636. embeddings = generate_openai_batch_embeddings(
  637. model, text, url, key, prefix, user
  638. )
  639. else:
  640. embeddings = generate_openai_batch_embeddings(
  641. model, [text], url, key, prefix, user
  642. )
  643. return embeddings[0] if isinstance(text, str) else embeddings
  644. import operator
  645. from typing import Optional, Sequence
  646. from langchain_core.callbacks import Callbacks
  647. from langchain_core.documents import BaseDocumentCompressor, Document
  648. class RerankCompressor(BaseDocumentCompressor):
  649. embedding_function: Any
  650. top_n: int
  651. reranking_function: Any
  652. r_score: float
  653. class Config:
  654. extra = "forbid"
  655. arbitrary_types_allowed = True
  656. def compress_documents(
  657. self,
  658. documents: Sequence[Document],
  659. query: str,
  660. callbacks: Optional[Callbacks] = None,
  661. ) -> Sequence[Document]:
  662. reranking = self.reranking_function is not None
  663. if reranking:
  664. scores = self.reranking_function.predict(
  665. [(query, doc.page_content) for doc in documents]
  666. )
  667. else:
  668. from sentence_transformers import util
  669. query_embedding = self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)
  670. document_embedding = self.embedding_function(
  671. [doc.page_content for doc in documents], RAG_EMBEDDING_CONTENT_PREFIX
  672. )
  673. scores = util.cos_sim(query_embedding, document_embedding)[0]
  674. docs_with_scores = list(zip(documents, scores.tolist()))
  675. if self.r_score:
  676. docs_with_scores = [
  677. (d, s) for d, s in docs_with_scores if s >= self.r_score
  678. ]
  679. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  680. final_results = []
  681. for doc, doc_score in result[: self.top_n]:
  682. metadata = doc.metadata
  683. metadata["score"] = doc_score
  684. doc = Document(
  685. page_content=doc.page_content,
  686. metadata=metadata,
  687. )
  688. final_results.append(doc)
  689. return final_results