File size: 4,754 Bytes
616f6b6
 
 
 
 
 
 
 
 
 
0895fb8
 
616f6b6
 
 
 
 
 
 
 
 
 
 
69eff5b
 
616f6b6
 
 
 
 
 
 
 
 
 
 
69eff5b
616f6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69eff5b
616f6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267bea3
 
 
a1bf6fe
e7a056e
267bea3
 
616f6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from time import sleep
import qdrant_client
from qdrant_client import models
from llama_index.core import ChatPromptTemplate
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.embeddings.fastembed import FastEmbedEmbedding
from llama_index.llms.groq import Groq
from dotenv import load_dotenv
import os
from PIL import Image


load_dotenv()


QDRANT_API_URL = os.getenv('QDRANT_API_URL')
QDRANT_API_KEY = os.getenv('QDRANT_API_KEY')
GROQ_API = os.getenv('GROQ_API')


@st.cache_resource
def initialize_models():
    embed_model = FastEmbedEmbedding(model_name=os.getenv('EMBEDDING_MODEL'))
    llm = Groq(model=os.getenv('LLM_MODEL'),
               api_key=GROQ_API)
    client = qdrant_client.QdrantClient(
        url=QDRANT_API_URL,
        api_key=QDRANT_API_KEY,
        prefer_grpc=True
    )
    return embed_model, llm, client


message_templates = [
    ChatMessage(
        content=os.getenv('CHAT_TEMPLATE'),
        role=MessageRole.SYSTEM),
    ChatMessage(
        content="""
        We have provided context information below.
        {context_str}
        ---------------------
        Given this information, please answer the question: {query}
        ---------------------
        If the question is not from the provided context, say `I don't know. Not enough information recieved.`
        """,
        role=MessageRole.USER,
    ),
]


def search(query, client, embed_model, k=5):
    collection_name = os.getenv('COLLECTION_NAME')
    query_embedding = embed_model.get_query_embedding(query)
    result = client.query_points(
        collection_name=collection_name,
        query=query_embedding,
        limit=k
    )
    return result


def pipeline(query, embed_model, llm, client):
    # R - Retriever
    relevant_documents = search(query, client, embed_model)
    context = [doc.payload['context'] for doc in relevant_documents.points]
    context = "\n".join(context)

    # A - Augment
    chat_template = ChatPromptTemplate(message_templates=message_templates)

    # G - Generate
    response = llm.complete(
        chat_template.format(
            context_str=context,
            query=query)
    )
    return response


def extract_thinking_and_answer(response_text):
    """Extract thinking process and final answer from response"""
    try:
        thinking = response_text[response_text.find(
            "<think>") + 7:response_text.find("</think>")].strip()
        answer = response_text[response_text.find("</think>") + 8:].strip()
        return thinking, answer
    except:
        return "", response_text


def main():
    im = Image.open("favicon.png")

    st.set_page_config(
        page_title="CorpCare Chatbot",
        page_icon=im
    )

    st.title("CorpCare Chatbot")
    # this will run only once, and be saved inside the cache
    embed_model, llm, client = initialize_models()

    if "messages" not in st.session_state:
        st.session_state.messages = []

    with st.sidebar:
        if st.button("Clear Chat"):
            st.session_state.messages = []
            st.rerun()

    # Display chat messages
    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            if message["role"] == "assistant":
                thinking, answer = extract_thinking_and_answer(
                    message["content"])
                with st.expander("Show thinking process"):
                    st.markdown(thinking)
                st.markdown(answer)
            else:
                st.markdown(message["content"])

    # Chat input
    if prompt := st.chat_input("Ask your question about the CC knowledge Repo..."):
        # Display user message
        st.chat_message("user").markdown(prompt)
        st.session_state.messages.append({"role": "user", "content": prompt})

        # Generate and display response
        with st.chat_message("assistant"):
            message_placeholder = st.empty()
            with st.spinner("Thinking..."):
                full_response = pipeline(prompt, embed_model, llm, client)
                thinking, answer = extract_thinking_and_answer(
                    full_response.text)

                with st.expander("Show thinking process"):
                    st.markdown(thinking)

                response = ""
                for chunk in answer.split():
                    response += chunk + " "
                    message_placeholder.markdown(response + "▌")
                    sleep(0.05)

                message_placeholder.markdown(answer)

        # Add assistant response to history
        st.session_state.messages.append(
            {"role": "assistant", "content": full_response.text})


if __name__ == "__main__":
    main()