utils.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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(
  244. f"query_collection_with_hybrid_search:VECTOR_DB_CLIENT.get:collection {collection_name}"
  245. )
  246. collection_results[collection_name] = VECTOR_DB_CLIENT.get(
  247. collection_name=collection_name
  248. )
  249. except Exception as e:
  250. log.exception(f"Failed to fetch collection {collection_name}: {e}")
  251. collection_results[collection_name] = None
  252. log.info(
  253. f"Starting hybrid search for {len(queries)} queries in {len(collection_names)} collections..."
  254. )
  255. def process_query(collection_name, query):
  256. try:
  257. result = query_doc_with_hybrid_search(
  258. collection_name=collection_name,
  259. collection_result=collection_results[collection_name],
  260. query=query,
  261. embedding_function=embedding_function,
  262. k=k,
  263. reranking_function=reranking_function,
  264. k_reranker=k_reranker,
  265. r=r,
  266. )
  267. return result, None
  268. except Exception as e:
  269. log.exception(f"Error when querying the collection with hybrid_search: {e}")
  270. return None, e
  271. # Prepare tasks for all collections and queries
  272. # Avoid running any tasks for collections that failed to fetch data (have assigned None)
  273. tasks = [
  274. (cn, q)
  275. for cn in collection_names
  276. if collection_results[cn] is not None
  277. for q in queries
  278. ]
  279. with ThreadPoolExecutor() as executor:
  280. future_results = [executor.submit(process_query, cn, q) for cn, q in tasks]
  281. task_results = [future.result() for future in future_results]
  282. for result, err in task_results:
  283. if err is not None:
  284. error = True
  285. elif result is not None:
  286. results.append(result)
  287. if error and not results:
  288. raise Exception(
  289. "Hybrid search failed for all collections. Using Non-hybrid search as fallback."
  290. )
  291. return merge_and_sort_query_results(results, k=k)
  292. def get_embedding_function(
  293. embedding_engine,
  294. embedding_model,
  295. embedding_function,
  296. url,
  297. key,
  298. embedding_batch_size,
  299. ):
  300. if embedding_engine == "":
  301. return lambda query, prefix=None, user=None: embedding_function.encode(
  302. query, **({"prompt": prefix} if prefix else {})
  303. ).tolist()
  304. elif embedding_engine in ["ollama", "openai"]:
  305. func = lambda query, prefix=None, user=None: generate_embeddings(
  306. engine=embedding_engine,
  307. model=embedding_model,
  308. text=query,
  309. prefix=prefix,
  310. url=url,
  311. key=key,
  312. user=user,
  313. )
  314. def generate_multiple(query, prefix, user, func):
  315. if isinstance(query, list):
  316. embeddings = []
  317. for i in range(0, len(query), embedding_batch_size):
  318. embeddings.extend(
  319. func(
  320. query[i : i + embedding_batch_size],
  321. prefix=prefix,
  322. user=user,
  323. )
  324. )
  325. return embeddings
  326. else:
  327. return func(query, prefix, user)
  328. return lambda query, prefix=None, user=None: generate_multiple(
  329. query, prefix, user, func
  330. )
  331. else:
  332. raise ValueError(f"Unknown embedding engine: {embedding_engine}")
  333. def get_sources_from_files(
  334. request,
  335. files,
  336. queries,
  337. embedding_function,
  338. k,
  339. reranking_function,
  340. k_reranker,
  341. r,
  342. hybrid_search,
  343. full_context=False,
  344. ):
  345. log.debug(
  346. f"files: {files} {queries} {embedding_function} {reranking_function} {full_context}"
  347. )
  348. extracted_collections = []
  349. relevant_contexts = []
  350. for file in files:
  351. context = None
  352. if file.get("docs"):
  353. # BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL
  354. context = {
  355. "documents": [[doc.get("content") for doc in file.get("docs")]],
  356. "metadatas": [[doc.get("metadata") for doc in file.get("docs")]],
  357. }
  358. elif file.get("context") == "full":
  359. # Manual Full Mode Toggle
  360. context = {
  361. "documents": [[file.get("file").get("data", {}).get("content")]],
  362. "metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
  363. }
  364. elif (
  365. file.get("type") != "web_search"
  366. and request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
  367. ):
  368. # BYPASS_EMBEDDING_AND_RETRIEVAL
  369. if file.get("type") == "collection":
  370. file_ids = file.get("data", {}).get("file_ids", [])
  371. documents = []
  372. metadatas = []
  373. for file_id in file_ids:
  374. file_object = Files.get_file_by_id(file_id)
  375. if file_object:
  376. documents.append(file_object.data.get("content", ""))
  377. metadatas.append(
  378. {
  379. "file_id": file_id,
  380. "name": file_object.filename,
  381. "source": file_object.filename,
  382. }
  383. )
  384. context = {
  385. "documents": [documents],
  386. "metadatas": [metadatas],
  387. }
  388. elif file.get("id"):
  389. file_object = Files.get_file_by_id(file.get("id"))
  390. if file_object:
  391. context = {
  392. "documents": [[file_object.data.get("content", "")]],
  393. "metadatas": [
  394. [
  395. {
  396. "file_id": file.get("id"),
  397. "name": file_object.filename,
  398. "source": file_object.filename,
  399. }
  400. ]
  401. ],
  402. }
  403. elif file.get("file").get("data"):
  404. context = {
  405. "documents": [[file.get("file").get("data", {}).get("content")]],
  406. "metadatas": [
  407. [file.get("file").get("data", {}).get("metadata", {})]
  408. ],
  409. }
  410. else:
  411. collection_names = []
  412. if file.get("type") == "collection":
  413. if file.get("legacy"):
  414. collection_names = file.get("collection_names", [])
  415. else:
  416. collection_names.append(file["id"])
  417. elif file.get("collection_name"):
  418. collection_names.append(file["collection_name"])
  419. elif file.get("id"):
  420. if file.get("legacy"):
  421. collection_names.append(f"{file['id']}")
  422. else:
  423. collection_names.append(f"file-{file['id']}")
  424. collection_names = set(collection_names).difference(extracted_collections)
  425. if not collection_names:
  426. log.debug(f"skipping {file} as it has already been extracted")
  427. continue
  428. if full_context:
  429. try:
  430. context = get_all_items_from_collections(collection_names)
  431. except Exception as e:
  432. log.exception(e)
  433. else:
  434. try:
  435. context = None
  436. if file.get("type") == "text":
  437. context = file["content"]
  438. else:
  439. if hybrid_search:
  440. try:
  441. context = query_collection_with_hybrid_search(
  442. collection_names=collection_names,
  443. queries=queries,
  444. embedding_function=embedding_function,
  445. k=k,
  446. reranking_function=reranking_function,
  447. k_reranker=k_reranker,
  448. r=r,
  449. )
  450. except Exception as e:
  451. log.debug(
  452. "Error when using hybrid search, using"
  453. " non hybrid search as fallback."
  454. )
  455. if (not hybrid_search) or (context is None):
  456. context = query_collection(
  457. collection_names=collection_names,
  458. queries=queries,
  459. embedding_function=embedding_function,
  460. k=k,
  461. )
  462. except Exception as e:
  463. log.exception(e)
  464. extracted_collections.extend(collection_names)
  465. if context:
  466. if "data" in file:
  467. del file["data"]
  468. relevant_contexts.append({**context, "file": file})
  469. sources = []
  470. for context in relevant_contexts:
  471. try:
  472. if "documents" in context:
  473. if "metadatas" in context:
  474. source = {
  475. "source": context["file"],
  476. "document": context["documents"][0],
  477. "metadata": context["metadatas"][0],
  478. }
  479. if "distances" in context and context["distances"]:
  480. source["distances"] = context["distances"][0]
  481. sources.append(source)
  482. except Exception as e:
  483. log.exception(e)
  484. return sources
  485. def get_model_path(model: str, update_model: bool = False):
  486. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  487. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  488. local_files_only = not update_model
  489. if OFFLINE_MODE:
  490. local_files_only = True
  491. snapshot_kwargs = {
  492. "cache_dir": cache_dir,
  493. "local_files_only": local_files_only,
  494. }
  495. log.debug(f"model: {model}")
  496. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  497. # Inspiration from upstream sentence_transformers
  498. if (
  499. os.path.exists(model)
  500. or ("\\" in model or model.count("/") > 1)
  501. and local_files_only
  502. ):
  503. # If fully qualified path exists, return input, else set repo_id
  504. return model
  505. elif "/" not in model:
  506. # Set valid repo_id for model short-name
  507. model = "sentence-transformers" + "/" + model
  508. snapshot_kwargs["repo_id"] = model
  509. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  510. try:
  511. model_repo_path = snapshot_download(**snapshot_kwargs)
  512. log.debug(f"model_repo_path: {model_repo_path}")
  513. return model_repo_path
  514. except Exception as e:
  515. log.exception(f"Cannot determine model snapshot path: {e}")
  516. return model
  517. def generate_openai_batch_embeddings(
  518. model: str,
  519. texts: list[str],
  520. url: str = "https://api.openai.com/v1",
  521. key: str = "",
  522. prefix: str = None,
  523. user: UserModel = None,
  524. ) -> Optional[list[list[float]]]:
  525. try:
  526. log.debug(
  527. f"generate_openai_batch_embeddings:model {model} batch size: {len(texts)}"
  528. )
  529. json_data = {"input": texts, "model": model}
  530. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  531. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  532. r = requests.post(
  533. f"{url}/embeddings",
  534. headers={
  535. "Content-Type": "application/json",
  536. "Authorization": f"Bearer {key}",
  537. **(
  538. {
  539. "X-OpenWebUI-User-Name": user.name,
  540. "X-OpenWebUI-User-Id": user.id,
  541. "X-OpenWebUI-User-Email": user.email,
  542. "X-OpenWebUI-User-Role": user.role,
  543. }
  544. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  545. else {}
  546. ),
  547. },
  548. json=json_data,
  549. )
  550. r.raise_for_status()
  551. data = r.json()
  552. if "data" in data:
  553. return [elem["embedding"] for elem in data["data"]]
  554. else:
  555. raise "Something went wrong :/"
  556. except Exception as e:
  557. log.exception(f"Error generating openai batch embeddings: {e}")
  558. return None
  559. def generate_ollama_batch_embeddings(
  560. model: str,
  561. texts: list[str],
  562. url: str,
  563. key: str = "",
  564. prefix: str = None,
  565. user: UserModel = None,
  566. ) -> Optional[list[list[float]]]:
  567. try:
  568. log.debug(
  569. f"generate_ollama_batch_embeddings:model {model} batch size: {len(texts)}"
  570. )
  571. json_data = {"input": texts, "model": model}
  572. if isinstance(RAG_EMBEDDING_PREFIX_FIELD_NAME, str) and isinstance(prefix, str):
  573. json_data[RAG_EMBEDDING_PREFIX_FIELD_NAME] = prefix
  574. r = requests.post(
  575. f"{url}/api/embed",
  576. headers={
  577. "Content-Type": "application/json",
  578. "Authorization": f"Bearer {key}",
  579. **(
  580. {
  581. "X-OpenWebUI-User-Name": user.name,
  582. "X-OpenWebUI-User-Id": user.id,
  583. "X-OpenWebUI-User-Email": user.email,
  584. "X-OpenWebUI-User-Role": user.role,
  585. }
  586. if ENABLE_FORWARD_USER_INFO_HEADERS
  587. else {}
  588. ),
  589. },
  590. json=json_data,
  591. )
  592. r.raise_for_status()
  593. data = r.json()
  594. if "embeddings" in data:
  595. return data["embeddings"]
  596. else:
  597. raise "Something went wrong :/"
  598. except Exception as e:
  599. log.exception(f"Error generating ollama batch embeddings: {e}")
  600. return None
  601. def generate_embeddings(
  602. engine: str,
  603. model: str,
  604. text: Union[str, list[str]],
  605. prefix: Union[str, None] = None,
  606. **kwargs,
  607. ):
  608. url = kwargs.get("url", "")
  609. key = kwargs.get("key", "")
  610. user = kwargs.get("user")
  611. if prefix is not None and RAG_EMBEDDING_PREFIX_FIELD_NAME is None:
  612. if isinstance(text, list):
  613. text = [f"{prefix}{text_element}" for text_element in text]
  614. else:
  615. text = f"{prefix}{text}"
  616. if engine == "ollama":
  617. if isinstance(text, list):
  618. embeddings = generate_ollama_batch_embeddings(
  619. **{
  620. "model": model,
  621. "texts": text,
  622. "url": url,
  623. "key": key,
  624. "prefix": prefix,
  625. "user": user,
  626. }
  627. )
  628. else:
  629. embeddings = generate_ollama_batch_embeddings(
  630. **{
  631. "model": model,
  632. "texts": [text],
  633. "url": url,
  634. "key": key,
  635. "prefix": prefix,
  636. "user": user,
  637. }
  638. )
  639. return embeddings[0] if isinstance(text, str) else embeddings
  640. elif engine == "openai":
  641. if isinstance(text, list):
  642. embeddings = generate_openai_batch_embeddings(
  643. model, text, url, key, prefix, user
  644. )
  645. else:
  646. embeddings = generate_openai_batch_embeddings(
  647. model, [text], url, key, prefix, user
  648. )
  649. return embeddings[0] if isinstance(text, str) else embeddings
  650. import operator
  651. from typing import Optional, Sequence
  652. from langchain_core.callbacks import Callbacks
  653. from langchain_core.documents import BaseDocumentCompressor, Document
  654. class RerankCompressor(BaseDocumentCompressor):
  655. embedding_function: Any
  656. top_n: int
  657. reranking_function: Any
  658. r_score: float
  659. class Config:
  660. extra = "forbid"
  661. arbitrary_types_allowed = True
  662. def compress_documents(
  663. self,
  664. documents: Sequence[Document],
  665. query: str,
  666. callbacks: Optional[Callbacks] = None,
  667. ) -> Sequence[Document]:
  668. reranking = self.reranking_function is not None
  669. if reranking:
  670. scores = self.reranking_function.predict(
  671. [(query, doc.page_content) for doc in documents]
  672. )
  673. else:
  674. from sentence_transformers import util
  675. query_embedding = self.embedding_function(query, RAG_EMBEDDING_QUERY_PREFIX)
  676. document_embedding = self.embedding_function(
  677. [doc.page_content for doc in documents], RAG_EMBEDDING_CONTENT_PREFIX
  678. )
  679. scores = util.cos_sim(query_embedding, document_embedding)[0]
  680. docs_with_scores = list(zip(documents, scores.tolist()))
  681. if self.r_score:
  682. docs_with_scores = [
  683. (d, s) for d, s in docs_with_scores if s >= self.r_score
  684. ]
  685. result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
  686. final_results = []
  687. for doc, doc_score in result[: self.top_n]:
  688. metadata = doc.metadata
  689. metadata["score"] = doc_score
  690. doc = Document(
  691. page_content=doc.page_content,
  692. metadata=metadata,
  693. )
  694. final_results.append(doc)
  695. return final_results