File size: 2,513 Bytes
28d6d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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.")