import os import sqlite3 import streamlit as st import google.generativeai as genai from dotenv import load_dotenv # Load environment variables from .env load_dotenv() # Set up the Google API key for Gemini api_key = os.getenv("GOOGLE_API_KEY") if api_key is None: st.error("GOOGLE_API_KEY not found in environment variables. Please check your .env file.") else: # Configure Google Generative AI API genai.configure(api_key=api_key) # Function to fetch all courses from the SQLite database def fetch_all_courses(): conn = sqlite3.connect('courses.db') cur = conn.cursor() cur.execute("SELECT title, description, price FROM courses") rows = cur.fetchall() conn.close() return rows # Function to generate a response using Google Generative AI based on user prompt and available courses def generate_response(prompt, courses): try: # Prepare a detailed context prompt for the LLM course_details = "\n".join( [f"Title: {course[0]}, Description: {course[1]}, Price: {course[2]}" for course in courses]) genai_prompt = f""" You are an expert assistant tasked with finding relevant courses based on user queries. Below are details of available courses: {course_details} Based on this information, respond to the user's query in the most relevant way: {prompt} """ # Generate a response using Google Generative AI model = genai.GenerativeModel('gemini-pro') response = model.generate_content([genai_prompt, prompt]) return response.text.strip() # Return the natural language response except Exception as e: st.error(f"Error generating a response: {e}") return None # Streamlit interface st.set_page_config(page_title="Smart Search for Courses") st.header("Find Relevant Courses on Analytics Vidhya") # User prompt input user_query = st.text_input("Enter your search query (e.g., 'Show me all free courses on machine learning'):") submit = st.button("Search") # Fetch all courses from the database courses = fetch_all_courses() # If user submits the query if submit and user_query: # Generate a response from Google Generative AI response = generate_response(user_query, courses) if response: st.subheader("Search Results:") st.write(response) else: st.write("Could not generate a response. Please try again.")