|
| 1 | +# Copyright (C) 2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import os |
| 5 | +import time |
| 6 | + |
| 7 | +from langchain.text_splitter import RecursiveCharacterTextSplitter |
| 8 | +from langchain_community.document_loaders import AsyncHtmlLoader |
| 9 | +from langchain_community.document_transformers import Html2TextTransformer |
| 10 | +from langchain_community.utilities import GoogleSearchAPIWrapper |
| 11 | +from langchain_community.vectorstores import Chroma |
| 12 | +from langchain_huggingface import HuggingFaceEndpointEmbeddings |
| 13 | + |
| 14 | +from comps import ( |
| 15 | + CustomLogger, |
| 16 | + EmbedDoc, |
| 17 | + OpeaComponent, |
| 18 | + OpeaComponentRegistry, |
| 19 | + SearchedDoc, |
| 20 | + ServiceType, |
| 21 | + TextDoc, |
| 22 | + statistics_dict, |
| 23 | +) |
| 24 | + |
| 25 | +logger = CustomLogger("opea_google_search") |
| 26 | +logflag = os.getenv("LOGFLAG", False) |
| 27 | + |
| 28 | + |
| 29 | +@OpeaComponentRegistry.register("OPEA_GOOGLE_SEARCH") |
| 30 | +class OpeaGoogleSearch(OpeaComponent): |
| 31 | + """A specialized Web Retrieval component derived from OpeaComponent for Google web retriever services.""" |
| 32 | + |
| 33 | + def __init__(self, name: str, description: str, config: dict = None): |
| 34 | + self.google_api_key = os.environ.get("GOOGLE_API_KEY") |
| 35 | + self.google_cse_id = os.environ.get("GOOGLE_CSE_ID") |
| 36 | + self.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=50) |
| 37 | + # Create vectorstore |
| 38 | + self.tei_embedding_endpoint = os.getenv("TEI_EMBEDDING_ENDPOINT") |
| 39 | + health_status = self.check_health() |
| 40 | + if not health_status: |
| 41 | + logger.error("OpeaGoogleSearch health check failed.") |
| 42 | + |
| 43 | + super().__init__(name, ServiceType.WEB_RETRIEVER.name.lower(), description, config) |
| 44 | + |
| 45 | + def get_urls(self, query, num_search_result=1): |
| 46 | + result = self.search.results(query, num_search_result) |
| 47 | + return result |
| 48 | + |
| 49 | + def dump_docs(self, docs): |
| 50 | + batch_size = 32 |
| 51 | + for i in range(0, len(docs), batch_size): |
| 52 | + self.vector_db.add_documents(docs[i : i + batch_size]) |
| 53 | + |
| 54 | + def retrieve_htmls(self, all_urls): |
| 55 | + loader = AsyncHtmlLoader(all_urls, ignore_load_errors=True, trust_env=True) |
| 56 | + docs = loader.load() |
| 57 | + return docs |
| 58 | + |
| 59 | + def parse_htmls(self, docs): |
| 60 | + if logflag: |
| 61 | + logger.info("Indexing new urls...") |
| 62 | + |
| 63 | + html2text = Html2TextTransformer() |
| 64 | + docs = list(html2text.transform_documents(docs)) |
| 65 | + docs = self.text_splitter.split_documents(docs) |
| 66 | + |
| 67 | + return docs |
| 68 | + |
| 69 | + async def invoke(self, input: EmbedDoc) -> SearchedDoc: |
| 70 | + """Involve the Google search service to retrieve the documents related to the prompt.""" |
| 71 | + # Read the uploaded file |
| 72 | + if logflag: |
| 73 | + logger.info(input) |
| 74 | + start = time.time() |
| 75 | + query = input.text |
| 76 | + embedding = input.embedding |
| 77 | + |
| 78 | + # Google Search the results, parse the htmls |
| 79 | + search_results = self.get_urls(query=query, num_search_result=input.k) |
| 80 | + urls_to_look = [] |
| 81 | + for res in search_results: |
| 82 | + if res.get("link", None): |
| 83 | + urls_to_look.append(res["link"]) |
| 84 | + urls = list(set(urls_to_look)) |
| 85 | + if logflag: |
| 86 | + logger.info(f"urls: {urls}") |
| 87 | + docs = self.retrieve_htmls(urls) |
| 88 | + docs = self.parse_htmls(docs) |
| 89 | + if logflag: |
| 90 | + logger.info(docs) |
| 91 | + # Remove duplicated docs |
| 92 | + unique_documents_dict = {(doc.page_content, tuple(sorted(doc.metadata.items()))): doc for doc in docs} |
| 93 | + unique_documents = list(unique_documents_dict.values()) |
| 94 | + statistics_dict["opea_service@search"].append_latency(time.time() - start, None) |
| 95 | + |
| 96 | + # dump to vector_db |
| 97 | + self.dump_docs(unique_documents) |
| 98 | + |
| 99 | + # Do the retrieval |
| 100 | + search_res = await self.vector_db.asimilarity_search_by_vector(embedding=embedding, k=input.k) |
| 101 | + |
| 102 | + searched_docs = [] |
| 103 | + |
| 104 | + for r in search_res: |
| 105 | + # include the metadata into the retrieved docs content |
| 106 | + description_str = f"\n description: {r.metadata['description']} \n" if "description" in r.metadata else "" |
| 107 | + title_str = f"\n title: {r.metadata['title']} \n" if "title" in r.metadata else "" |
| 108 | + source_str = f"\n source: {r.metadata['source']} \n" if "source" in r.metadata else "" |
| 109 | + text_with_meta = f"{r.page_content} {description_str} {title_str} {source_str}" |
| 110 | + searched_docs.append(TextDoc(text=text_with_meta)) |
| 111 | + |
| 112 | + result = SearchedDoc(retrieved_docs=searched_docs, initial_query=query) |
| 113 | + statistics_dict["opea_service@web_retriever"].append_latency(time.time() - start, None) |
| 114 | + |
| 115 | + # For Now history is banned |
| 116 | + if self.vector_db.get()["ids"]: |
| 117 | + self.vector_db.delete(self.vector_db.get()["ids"]) |
| 118 | + if logflag: |
| 119 | + logger.info(result) |
| 120 | + return result |
| 121 | + |
| 122 | + def check_health(self) -> bool: |
| 123 | + """Checks the health of the embedding service. |
| 124 | +
|
| 125 | + Returns: |
| 126 | + bool: True if the service is reachable and healthy, False otherwise. |
| 127 | + """ |
| 128 | + try: |
| 129 | + self.search = GoogleSearchAPIWrapper( |
| 130 | + google_api_key=self.google_api_key, google_cse_id=self.google_cse_id, k=10 |
| 131 | + ) |
| 132 | + # vectordb_persistent_directory = os.getenv("VECTORDB_PERSISTENT_DIR", "/home/user/chroma_db_oai") |
| 133 | + self.vector_db = Chroma( |
| 134 | + embedding_function=HuggingFaceEndpointEmbeddings(model=self.tei_embedding_endpoint), |
| 135 | + # persist_directory=vectordb_persistent_directory |
| 136 | + ) |
| 137 | + except Exception as e: |
| 138 | + logger.error(e) |
| 139 | + return False |
| 140 | + return True |
0 commit comments