summaryrefslogtreecommitdiff
path: root/rag/ui.py
blob: 23c44f9bb0d1404b92cc7bff9dfb3c4dd85b911f (plain)
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
166
167
168
169
170
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List

import streamlit as st
from dotenv import load_dotenv
from langchain_community.document_loaders.blob_loaders import Blob
from loguru import logger as log

from rag.generator import MODELS, get_generator
from rag.generator.prompt import Prompt
from rag.retriever.retriever import Retriever
from rag.retriever.vector import Document


class Cohere(Enum):
    USER = "USER"
    BOT = "CHATBOT"


class Ollama(Enum):
    USER = "user"
    BOT = "assistant"


@dataclass
class Message:
    role: str
    message: str

    def as_dict(self, client: str) -> Dict[str, str]:
        if client == "cohere":
            return {"role": self.role, "message": self.message}
        else:
            return {"role": self.role, "content": self.message}


def set_chat_users():
    log.debug("Setting user and bot value")
    ss = st.session_state
    if ss.generator == "cohere":
        ss.user = Cohere.USER.value
        ss.bot = Cohere.BOT.value
    else:
        ss.user = Ollama.USER.value
        ss.bot = Ollama.BOT.value


def clear_generator_messages():
    log.debug("Clearing generator chat history")
    st.session_state.generator_messages = []


@st.cache_resource
def load_retriever():
    log.debug("Loading retriever model")
    st.session_state.retriever = Retriever()


@st.cache_resource
def load_generator(client: str):
    log.debug("Loading generator model")
    st.session_state.generator = get_generator(client)
    set_chat_users()
    clear_generator_messages()


@st.cache_data(show_spinner=False)
def upload(files):
    retriever = st.session_state.retriever
    with st.spinner("Uploading documents..."):
        for file in files:
            source = file.name
            blob = Blob.from_data(file.read())
            retriever.add_pdf(blob=blob, source=source)


def display_context(documents: List[Document]):
    with st.popover("See Context"):
        for i, doc in enumerate(documents):
            st.markdown(f"### Document {i}")
            st.markdown(f"**Title: {doc.title}**")
            st.markdown(doc.text)
            st.markdown("---")


def display_chat():
    ss = st.session_state
    for msg in ss.chat:
        if isinstance(msg, list):
            display_context(msg)
        else:
            st.chat_message(msg.role).write(msg.message)


def generate_chat(query: str):
    ss = st.session_state

    with st.chat_message(ss.user):
        st.write(query)

    retriever = ss.retriever
    generator = ss.generator

    documents = retriever.retrieve(query, limit=5)
    prompt = Prompt(query, documents)

    with st.chat_message(ss.bot):
        history = [m.as_dict(ss.client) for m in ss.generator_messages]
        response = st.write_stream(generator.chat(prompt, history))

    display_context(documents)
    store_chat(query, response, documents)


def store_chat(query: str, response: str, documents: List[Document]):
    log.debug("Storing chat")
    ss = st.session_state
    query = Message(role=ss.user, message=query)
    response = Message(role=ss.bot, message=response)
    ss.chat.append(query)
    ss.chat.append(response)
    ss.generator_messages.append(response)
    ss.chat.append(documents)


def sidebar():
    with st.sidebar:
        st.header("Grouding")
        st.markdown(
            (
                "These files will be uploaded to the knowledge base and used "
                "as groudning if they are relevant to the question."
            )
        )

        files = st.file_uploader(
            "Choose pdfs to add to the knowledge base",
            type="pdf",
            accept_multiple_files=True,
        )

        upload(files)

        st.header("Generative Model")
        st.markdown("Select the model that will be used for generating the answer.")
        st.selectbox("Generative Model", key="client", options=MODELS)
        load_generator(st.session_state.client)


def page():
    ss = st.session_state
    if "generator_messages" not in st.session_state:
        ss.generator_messages = []
    if "chat" not in st.session_state:
        ss.chat = []

    display_chat()

    query = st.chat_input("Enter query here")
    if query:
        generate_chat(query)


if __name__ == "__main__":
    load_dotenv()
    st.title("Retrieval Augmented Generation")
    load_retriever()
    sidebar()
    page()