File size: 7,110 Bytes
96dad0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2f1a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from langchain.embeddings import OpenAIEmbeddings
from langchain.llms import OpenAI
import streamlit as st
import time
import logging
import os
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationalRetrievalChain
from langchain.prompts import PromptTemplate

from app.settings import load_env_variables
from app.logger import setup_logger
from data.vector_db import load_vector_db, save_vector_db
from data.embeddings import get_openai_embeddings

print("Starting src/app/main.py")

try:
    # Load environment variables and setup logging
    print("Loading environment variables and setting up logging")
    openai_api_key = load_env_variables()
    setup_logger()
    print("Environment variables loaded and logging set up")

    st.set_page_config(page_title="LawGPT")
    print("Streamlit page config set")

    col1, col2, col3 = st.columns([1, 4, 1])
    with col2:
        try:
            st.image("assets/Black Bold Initial AI Business Logo.jpg")
            print("Logo image loaded successfully")
        except Exception as e:
            print(f"Error loading logo image: {str(e)}")

    print("Applying custom CSS")
    st.markdown("""
        <style>
        .stApp, .ea3mdgi6{ background-color:#000000; }
        div.stButton > button:first-child { background-color: #ffd0d0; }
        div.stButton > button:active { background-color: #ff6262; }
        div[data-testid="stStatusWidget"] div button { display: none; }
        .reportview-container { margin-top: -2em; }
        #MainMenu {visibility: hidden;}
        .stDeployButton {display:none;}
        footer {visibility: hidden;}
        #stDecoration {display:none;}
        button[title="View fullscreen"]{ visibility: hidden;}
        button:first-child{ background-color : transparent !important; }
        </style>
    """, unsafe_allow_html=True)

    def reset_conversation():
        print("Resetting conversation")
        st.session_state.messages = []
        st.session_state.memory.clear()
        print("Conversation reset complete")

    print("Initializing session state")
    if "messages" not in st.session_state:
        st.session_state["messages"] = []
    if "memory" not in st.session_state:
        st.session_state["memory"] = ConversationBufferWindowMemory(k=2, memory_key="chat_history", return_messages=True)
    print("Session state initialized")

    print("Setting up OpenAI embeddings")
    try:
        embeddings = get_openai_embeddings(openai_api_key)
        print("OpenAI embeddings set up successfully")
    except Exception as e:
        print(f"Error setting up OpenAI embeddings: {str(e)}")
        raise

    # Placeholder data for creating the vector database
    data = [
        "Example legal text 1",
        "Example legal text 2",
        "Example legal text 3",
        # Add more data as needed
    ]

    print("Loading vector database")
    try:
        db_path = "./ipc_vector_db/vectordb"
        vector_db = load_vector_db(db_path, embeddings, data)
        db_retriever = vector_db.as_retriever(search_type="similarity", search_kwargs={"k": 4})
        print("Vector database loaded successfully")
    except Exception as e:
        print(f"Error loading vector database: {str(e)}")
        raise

    print("Setting up prompt template")
    prompt_template = """
    This is a chat template and As a legal chat bot specializing in Indian Penal Code queries, your primary objective is to provide accurate and concise information based on the user's questions. Do not generate your own questions and answers. You will adhere strictly to the instructions provided, offering relevant context from the knowledge base while avoiding unnecessary details. Your responses will be brief, to the point, and in compliance with the established format. If a question falls outside the given context, you will refrain from utilizing the chat history and instead rely on your own knowledge base to generate an appropriate response. You will prioritize the user's query and refrain from posing additional questions. The aim is to deliver professional, precise, and contextually relevant information pertaining to the Indian Penal Code.
    CONTEXT: {context}
    CHAT HISTORY: {chat_history}
    QUESTION: {question}
    ANSWER:
    """
    prompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question', 'chat_history'])

    print("Setting up OpenAI LLM")
    try:
        llm = OpenAI(model_name="text-davinci-003", temperature=0.5, max_tokens=1024, openai_api_key=os.getenv("OPENAI_API_KEY"))
        print("OpenAI LLM set up successfully")
    except Exception as e:
        print(f"Error setting up OpenAI LLM: {str(e)}")
        raise

    print("Setting up ConversationalRetrievalChain")
    try:
        qa = ConversationalRetrievalChain.from_llm(
            llm=llm,
            memory=ConversationBufferWindowMemory(k=2, memory_key="chat_history", return_messages=True),
            retriever=db_retriever,
            combine_docs_chain_kwargs={'prompt': prompt}
        )
        print("ConversationalRetrievalChain set up successfully")
    except Exception as e:
        print(f"Error setting up ConversationalRetrievalChain: {str(e)}")
        raise

    print("Displaying chat messages")
    for message in st.session_state.get("messages", []):
        with st.chat_message(message.get("role")):
            st.write(message.get("content"))

    input_prompt = st.chat_input("Say something")

    if input_prompt:
        print(f"Received input: {input_prompt}")
        with st.chat_message("user"):
            st.write(input_prompt)

        st.session_state.messages.append({"role": "user", "content": input_prompt})

        with st.chat_message("assistant"):
            with st.spinner("Thinking πŸ’‘..."):
                try:
                    print("Invoking ConversationalRetrievalChain")
                    result = qa.invoke(input=input_prompt)
                    print("ConversationalRetrievalChain invoked successfully")

                    message_placeholder = st.empty()
                    full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
                    for chunk in result["answer"]:
                        full_response += chunk
                        time.sleep(0.02)
                        message_placeholder.markdown(full_response + " β–Œ")
                    print("Response displayed successfully")
                except Exception as e:
                    print(f"Error generating or displaying response: {str(e)}")
                    st.error("An error occurred while processing your request. Please try again.")

            st.button('Reset All Chat πŸ—‘οΈ', on_click=reset_conversation)

        st.session_state.messages.append({"role": "assistant", "content": result["answer"]})

except Exception as e:
    print(f"Unhandled exception in main.py: {str(e)}")
    logging.exception("Unhandled exception in main.py")
    st.error("An unexpected error occurred. Please try again later.")

print("End of src/app/main.py")