summaryrefslogtreecommitdiff
path: root/rag/ui.py
blob: 83a22e2bf54c3e952e5367aafddda524609a139e (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
import streamlit as st

from langchain_community.document_loaders.blob_loaders import Blob
from .rag import RAG

from .generator import get_generator
from .generator.prompt import Prompt

rag = RAG()

MODELS = ["ollama", "cohere"]


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

    if not files:
        return

    with st.spinner("Indexing documents..."):
        for file in files:
            source = file.name
            blob = Blob.from_data(file.read())
            rag.add_pdf(blob, source)


if __name__ == "__main__":
    ss = st.session_state
    st.header("RAG-UI")

    model = st.selectbox("Model", options=MODELS)

    upload_pdfs()

    with st.form(key="query"):
        query = st.text_area(
            "query",
            key="query",
            height=100,
            placeholder="Enter query here",
            help="",
            label_visibility="collapsed",
            disabled=False,
        )
        submit = st.form_submit_button("Generate")

    (b,) = st.columns(1)
    (result_column, context_column) = st.columns(2)

    if submit:
        if not query:
            st.stop()

        query = ss.get("query", "")
        with st.spinner("Searching for documents..."):
            documents = rag.retrieve(query)

        prompt = Prompt(query, documents)

        with context_column:
            st.markdown("### Context")
            for i, doc in enumerate(documents):
                st.markdown(f"### Document {i}")
                st.markdown(f"**Title: {doc.title}**")
                st.markdown(doc.text)
                st.markdown("---")

        with result_column:
            generator = get_generator(model)
            st.markdown("### Answer")
            st.write_stream(rag.generate(generator, prompt))