utils.py 27 KB

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