import logging
from pathlib import Path
from typing import Any, Dict
import gradio as gr
from ragsystemspeed import (
load_documents,
split_documents,
create_embeddings,
save_vector_store,
load_vector_store,
query_vector_store,
setup_logger,
)
from llmengine import get_llm_response
# Set up logging
logger = setup_logger()
def load_or_create_vector_store(
txt_output_dir: Path, index_path: Path, metadata_path: Path
) -> Any:
"""
Loads an existing vector store if available; otherwise, creates a new one.
Args:
txt_output_dir (Path): Path to the directory containing text files.
index_path (Path): Path to the index file.
metadata_path (Path): Path to the metadata file.
Returns:
Any: The loaded or newly created vector store.
"""
try:
if index_path.exists() and metadata_path.exists():
# Load existing vector store
vector_store = load_vector_store(index_path, metadata_path)
logger.info("Loaded existing vector store.")
else:
# Create new vector store
documents = load_documents(txt_output_dir)
if not documents:
logger.error(
"No documents found to process. Please check the input directory and file patterns."
)
raise FileNotFoundError(
"No documents found in the specified directory."
)
split_docs = split_documents(documents)
if not split_docs:
logger.error(
"No split documents created. Please check the text splitter configuration."
)
raise ValueError(
"No split documents were created from the documents."
)
logger.info(
f"Loaded {len(documents)} documents and split into {len(split_docs)} chunks"
)
vector_store = create_embeddings(split_docs)
# Save the vector store
save_vector_store(vector_store, index_path, metadata_path)
logger.info("Created and saved new vector store.")
return vector_store
except Exception as e:
logger.error(f"Error in load_or_create_vector_store: {str(e)}")
raise
def process_query(user_query: str, vector_store: Any, top_k: int = 5) -> Dict[str, Any]:
"""
Processes the user query by querying the vector store and getting an LLM response.
Args:
user_query (str): The user's query.
vector_store (Any): The vector store object.
top_k (int): The number of top results to return.
Returns:
Dict[str, Any]: A dictionary containing the results and LLM response.
"""
try:
# Query the vector store to get relevant documents
results = query_vector_store(vector_store, user_query, k=top_k)
except Exception as e:
logger.error(f"Error querying vector store: {str(e)}")
results = []
try:
# Generate LLM response
response = get_llm_response(model="gpt-4o-mini", prompt=user_query)
except Exception as e:
logger.error(f"Error getting LLM response: {str(e)}")
response = "Error generating response from the language model."
return {"results": results, "response": response}
def gradio_interface(user_query: str) -> Any:
"""
Gradio interface function to process user query and return results.
Args:
user_query (str): The user's query.
Returns:
Any: The outputs to be displayed by Gradio.
"""
try:
output = process_query(user_query, vector_store)
response = output["response"]
results = output["results"]
# Format results
formatted_results = ""
for i, result in enumerate(results, 1):
content = result.get("content", "")
metadata = result.get("metadata", {})
formatted_results += (
f"<div class='result-item'>"
f"<h4>Result {i}:</h4>"
f"<div class='content'><strong>Content:</strong><br>{content}</div>"
f"<div class='metadata'><strong>Metadata:</strong><br>{metadata}</div>"
f"</div>"
)
return response, formatted_results
except Exception as e:
logger.error(f"Error in Gradio interface: {str(e)}")
return "An error occurred while processing your query.", "No results available."
def main():
"""
Main function to load vector store and launch Gradio interface.
"""
# Define paths
txt_output_dir = Path(r"E:\LLMS\Fine-tuning\output1") # Update with your directory
index_path = Path("faiss_index")
metadata_path = Path("faiss_index_metadata")
# Load or create vector store
global vector_store
vector_store = load_or_create_vector_store(
txt_output_dir=txt_output_dir,
index_path=index_path,
metadata_path=metadata_path,
)
# Define custom CSS
css = """
/* Custom CSS styles */
#title {
font-size: 32px;
font-weight: bold;
text-align: center;
color: #333;
margin-bottom: 20px;
}
#description {
font-size: 18px;
text-align: center;
color: #666;
margin-bottom: 30px;
}
#query-textbox {
border: 2px solid #333;
padding: 10px;
font-size: 18px;
color: #333;
width: 100%;
}
#response-box {
border: 2px solid #007ACC;
padding: 15px;
font-size: 16px;
background-color: #f0f8ff;
color: #333;
width: 100%;
height: 200px;
}
#results-box {
border: 2px solid #28a745;
padding: 15px;
font-size: 16px;
background-color: #e9ffe9;
color: #333;
width: 100%;
height: 400px;
overflow-y: auto;
}
#submit-button {
background-color: #007ACC;
color: #fff;
font-size: 18px;
padding: 10px 20px;
width: 100%;
}
.result-item {
margin-bottom: 20px;
}
.result-item h4 {
margin: 0 0 10px;
color: #007ACC;
}
.content, .metadata {
margin-bottom: 10px;
}
"""
# Build Gradio interface
with gr.Blocks(css=css) as demo:
gr.HTML("<div id='title'>Advanced Gradio Interface</div>")
gr.HTML(
"<div id='description'>Enter your query below to receive a response, relevant content, and metadata.</div>"
)
with gr.Row():
user_query = gr.Textbox(
lines=2,
placeholder="Enter your query here...",
elem_id="query-textbox",
label="Your Query",
)
submit_btn = gr.Button("Submit", elem_id="submit-button")
with gr.Row():
response = gr.HTML(elem_id="response-box")
with gr.Row():
results = gr.HTML(elem_id="results-box")
submit_btn.click(
fn=gradio_interface, inputs=user_query, outputs=[response, results]
)
# Launch Gradio app
demo.launch()
if __name__ == "__main__":
main()
Explanation:
-
PEP-8 Compliance: The code strictly adheres to PEP-8 standards, ensuring proper indentation, spacing, and naming conventions for readability and maintainability.
-
Type Hints and Imports: The typing module is used to provide type hints, enhancing code clarity. Relevant modules are imported, and the standard Path class from pathlib is utilized.
-
Error Handling: Comprehensive error handling is implemented using try-except blocks, logging errors, and providing meaningful messages without exposing sensitive information.
-
Functions and Modularity: The code is modular, with clear function definitions (load_or_create_vector_store, process_query, gradio_interface, main) each responsible for specific tasks.
-
Scalability and Efficiency: The code checks if a vector store exists to avoid unnecessary computations, enhancing performance when dealing with large datasets.
-
Gradio Interface:
- An advanced interface is created using Gradio's
Blocks, allowing for flexible layout and customization.
- Custom CSS is provided to style elements like the title, description, query input, response, and results, incorporating coloring and styling per requirements.
- Proper buttons, labels, and placeholders enhance user experience.
-
Displaying Metadata and Responses:
- The query and AI response are displayed with appropriate styling.
- Relevant content and metadata are formatted and presented in a scrollable area to handle extensive data.
-
Global Variables and State Management:
- The
vector_store is defined as a global variable to make it accessible within the Gradio interface function, ensuring consistency across user interactions.
-
Logging: A logger is set up for debugging and tracking, which is essential for monitoring the application's behavior in production environments.
Notes:
- Replace
E:\LLMS\Fine-tuning\output1 with the actual path to your text files.
- Ensure that the modules
ragsystemspeed and llmengine are installed and properly configured, as they are assumed to provide the necessary backend functionality.
- The custom CSS can be further refined to meet specific design requirements.
- The use of
gr.HTML components allows for rich text formatting, including the display of HTML content within the Gradio interface.
Usage:
- Run the script in an environment where Gradio and the required backend modules are installed.
- The Gradio app will launch in a web browser, presenting the advanced interface.
- Enter a query in the provided textbox and click "Submit" to receive the AI-generated response along with relevant content and metadata.
Dependencies:
- Python 3.7 or higher
- Gradio library (
pip install gradio)
- Custom modules
ragsystemspeed and llmengine with their dependencies
Security Considerations:
- All exceptions are caught and logged without exposing stack traces or sensitive information to the end-user.
- User inputs are not executed directly, mitigating potential code injection risks.
Conclusion:
This code provides an advanced, scalable, and user-friendly interface that meets the specified requirements. It is designed for maintainability and efficiency, making it suitable for deployment in applications that require robust AI interaction and data retrieval functionalities.