|
| 1 | +import logging |
| 2 | +from enum import Enum |
| 3 | +from os import getenv |
| 4 | +from pprint import pprint |
| 5 | +from typing import Annotated |
| 6 | + |
| 7 | +import typer |
| 8 | +from dotenv import load_dotenv |
| 9 | +from langchain_community.document_loaders.csv_loader import CSVLoader |
| 10 | +from langchain_community.vectorstores import FAISS, VectorStore |
| 11 | +from langchain_community.vectorstores.azuresearch import AzureSearch |
| 12 | +from langchain_core.documents import Document |
| 13 | +from langchain_openai import AzureOpenAIEmbeddings |
| 14 | + |
| 15 | +app = typer.Typer() |
| 16 | + |
| 17 | + |
| 18 | +class VectorStoreType(str, Enum): |
| 19 | + AzureAISearch = "azureaisearch" |
| 20 | + Faiss = "faiss" |
| 21 | + |
| 22 | + |
| 23 | +def get_log_level(debug: bool) -> int: |
| 24 | + return logging.DEBUG if debug else logging.INFO |
| 25 | + |
| 26 | + |
| 27 | +def setup_logging(debug: bool = False): |
| 28 | + logging.basicConfig( |
| 29 | + format="[%(asctime)s] %(levelname)7s from %(name)s in %(pathname)s:%(lineno)d: " "%(message)s", |
| 30 | + level=get_log_level(debug), |
| 31 | + force=True, |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +def get_embeddings(): |
| 36 | + return AzureOpenAIEmbeddings( |
| 37 | + api_key=getenv("AZURE_OPENAI_API_KEY"), |
| 38 | + api_version=getenv("AZURE_OPENAI_API_VERSION"), |
| 39 | + azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), |
| 40 | + model=getenv("AZURE_OPENAI_MODEL_EMBEDDING"), |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def get_local_vector_store_path(identifier: str): |
| 45 | + return f"./artifacts/vectorstore/{identifier}" |
| 46 | + |
| 47 | + |
| 48 | +def create_azure_search(index_name: str) -> AzureSearch: |
| 49 | + return AzureSearch( |
| 50 | + azure_search_endpoint=getenv("AZURE_AI_SEARCH_ENDPOINT"), |
| 51 | + azure_search_key=getenv("AZURE_AI_SEARCH_API_KEY"), |
| 52 | + index_name=index_name, |
| 53 | + embedding_function=get_embeddings().embed_query, |
| 54 | + additional_search_client_options={"retry_total": 4}, |
| 55 | + ) |
| 56 | + |
| 57 | + |
| 58 | +def get_vector_store( |
| 59 | + vector_store_type: VectorStoreType, |
| 60 | + identifier: str, |
| 61 | +) -> VectorStore: |
| 62 | + if vector_store_type == VectorStoreType.AzureAISearch: |
| 63 | + logging.info("Creating Azure AI Search vector store") |
| 64 | + return create_azure_search(identifier) |
| 65 | + elif vector_store_type == VectorStoreType.Faiss: |
| 66 | + logging.info("Creating Faiss vector store") |
| 67 | + return FAISS.load_local( |
| 68 | + folder_path=get_local_vector_store_path(identifier), |
| 69 | + embeddings=get_embeddings(), |
| 70 | + allow_dangerous_deserialization=True, |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +def _create_vector_store( |
| 75 | + vector_store_type: VectorStoreType, |
| 76 | + identifier: str, |
| 77 | + documents: list[Document], |
| 78 | +) -> VectorStore: |
| 79 | + if vector_store_type == VectorStoreType.AzureAISearch: |
| 80 | + logging.info("Creating Azure AI Search vector store") |
| 81 | + vector_store = create_azure_search(identifier) |
| 82 | + vector_store.add_documents(documents=documents) |
| 83 | + return |
| 84 | + elif vector_store_type == VectorStoreType.Faiss: |
| 85 | + logging.info("Creating Faiss vector store") |
| 86 | + vector_store: FAISS = FAISS.from_documents( |
| 87 | + documents=documents, |
| 88 | + embedding=get_embeddings(), |
| 89 | + ) |
| 90 | + vector_store.save_local(folder_path=get_local_vector_store_path(identifier)) |
| 91 | + return |
| 92 | + |
| 93 | + |
| 94 | +@app.command() |
| 95 | +def create_vector_store( |
| 96 | + input_csv_file_path: Annotated[str, typer.Option(help="Path to the input CSV file")] = "./data/contoso_rules.csv", |
| 97 | + identifier="contoso_rules", |
| 98 | + vector_store_type: Annotated[VectorStoreType, typer.Option(case_sensitive=False)] = VectorStoreType.Faiss, |
| 99 | + debug: Annotated[bool, typer.Option(help="Enable debug mode")] = False, |
| 100 | +): |
| 101 | + setup_logging(debug) |
| 102 | + |
| 103 | + # Load documents from CSV |
| 104 | + try: |
| 105 | + documents = CSVLoader(file_path=input_csv_file_path).load() |
| 106 | + except Exception as e: |
| 107 | + logging.error(f"Failed to load documents from CSV: {e}") |
| 108 | + return |
| 109 | + |
| 110 | + # Create vector store |
| 111 | + _create_vector_store( |
| 112 | + vector_store_type=vector_store_type, |
| 113 | + identifier=identifier, |
| 114 | + documents=documents, |
| 115 | + ) |
| 116 | + |
| 117 | + |
| 118 | +@app.command() |
| 119 | +def search( |
| 120 | + identifier="contoso_rules", |
| 121 | + vector_store_type: Annotated[VectorStoreType, typer.Option(case_sensitive=False)] = VectorStoreType.Faiss, |
| 122 | + query: Annotated[str, typer.Option(help="Query to search")] = "社内の機密情報は外部に漏らさないでください", |
| 123 | + debug: Annotated[bool, typer.Option(help="Enable debug mode")] = False, |
| 124 | +): |
| 125 | + setup_logging(debug) |
| 126 | + |
| 127 | + # Create vector store |
| 128 | + vector_store = get_vector_store( |
| 129 | + vector_store_type=vector_store_type, |
| 130 | + identifier=identifier, |
| 131 | + ) |
| 132 | + |
| 133 | + # Search |
| 134 | + result = vector_store.similarity_search_with_relevance_scores( |
| 135 | + query=query, |
| 136 | + k=5, |
| 137 | + score_threshold=0.5, |
| 138 | + ) |
| 139 | + pprint(result) |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + load_dotenv() |
| 144 | + app() |
0 commit comments