File size: 6,865 Bytes
d5ed529
771e8d7
0194c2e
a427753
3911511
 
0194c2e
3911511
6f5672c
d5ed529
7b6cfab
9ce34f7
2458bb6
d5ed529
 
0194c2e
 
 
 
 
 
 
89f1436
 
 
3911511
 
 
 
 
 
 
 
 
7b6cfab
 
 
 
3911511
e821217
d5ed529
834e5f8
 
e5fb7b0
89f1436
21a434f
3911511
e5fb7b0
7b6cfab
76eb72e
d5ed529
7b6cfab
76eb72e
 
 
7b6cfab
3911511
 
 
834e5f8
3911511
d5ed529
 
 
 
 
53233bd
7b6cfab
 
d5ed529
 
2458bb6
d5ed529
 
 
7b6cfab
d5ed529
 
 
7b6cfab
d5ed529
7b6cfab
d5ed529
 
89f1436
d5ed529
 
 
 
 
7b6cfab
d5ed529
e7577f6
89f1436
e5fb7b0
 
 
21a434f
d5ed529
9ce34f7
d5ed529
 
 
7b6cfab
d5ed529
 
 
 
89f1436
d5ed529
 
 
22ac629
d5ed529
3911511
 
 
 
fe9ddcf
3911511
 
d5ed529
3911511
 
 
 
 
d5ed529
89f1436
 
 
d5ed529
834e5f8
22ac629
3911511
89f1436
 
 
d5ed529
834e5f8
89f1436
9ce34f7
89f1436
d5ed529
89f1436
0194c2e
9ce34f7
 
 
 
 
0194c2e
3911511
 
7b6cfab
3911511
89f1436
9ce34f7
 
 
 
 
 
 
 
 
89f1436
 
 
 
e5fb7b0
f026aa7
89f1436
 
 
e5fb7b0
771e8d7
7b6cfab
d5ed529
4688654
7b6cfab
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
171
172
173
174
175
176
177
178
179
180
181
from PIL import Image
import sys
import uuid

import streamlit as st
from streamlit_pills import pills
from streamlit_feedback import streamlit_feedback

from vectara_agentic.agent import AgentStatusType

from agent import initialize_agent, get_agent_config, teaching_styles, languages
from utils import thumbs_feedback, escape_dollars_outside_latex, send_amplitude_data

initial_prompt = "How can I help you today?"

# Setup for HTTP API Calls to Amplitude Analytics
if 'device_id' not in st.session_state:
    st.session_state.device_id = str(uuid.uuid4())

if "feedback_key" not in st.session_state:
        st.session_state.feedback_key = 0

def toggle_logs():
    st.session_state.show_logs = not st.session_state.show_logs

def show_example_questions():        
    if len(st.session_state.example_messages) > 0 and st.session_state.first_turn:            
        selected_example = pills("Queries to Try:", st.session_state.example_messages, index=None)
        if selected_example:
            st.session_state.ex_prompt = selected_example
            st.session_state.first_turn = False
            return True
    return False

def update_func(status_type: AgentStatusType, msg: str):
    if status_type != AgentStatusType.AGENT_UPDATE:
        output = f"{status_type.value} - {msg}"
        st.session_state.log_messages.append(output)

def launch_bot():
    def reset():
        st.session_state.messages = [{"role": "assistant", "content": initial_prompt, "avatar": "πŸ¦–"}]
        st.session_state.thinking_message = "Agent at work..."
        st.session_state.log_messages = []
        st.session_state.prompt = None
        st.session_state.ex_prompt = None
        st.session_state.first_turn = True
        st.session_state.show_logs = False
        st.session_state.agent = initialize_agent(cfg, update_func=update_func) # must reset agent to apply new settings

    if 'cfg' not in st.session_state:
        cfg = get_agent_config()
        st.session_state.style = cfg.style
        st.session_state.language = cfg.language
        st.session_state.student_age = cfg.student_age
        st.session_state.cfg = cfg
        st.session_state.ex_prompt = None
        example_messages = [example.strip() for example in cfg.examples.split(",")] if cfg.examples else []
        st.session_state.example_messages = [em for em in example_messages if len(em)>0]
        reset()

    cfg = st.session_state.cfg

    # left side content
    with st.sidebar:
        image = Image.open('Vectara-logo.png')
        st.image(image, width=175)
        st.markdown(f"## {cfg['demo_welcome']}")
        st.markdown(f"{cfg['demo_description']}")

        st.markdown("\n")
        cfg.style = st.selectbox('Teacher Style:', teaching_styles)
        if st.session_state.style != cfg.style:
            st.session_state.style = cfg.style
            reset()
            st.rerun()

        cfg.language = st.selectbox('Language:', languages.keys())
        if st.session_state.language != cfg.language:
            st.session_state.language = cfg.language
            reset()
            st.rerun()

        cfg.student_age = st.number_input(
            'Student age:',  min_value=13, max_value=99, value=cfg.student_age,
            step=1, format='%i'
        )
        if st.session_state.student_age != cfg.student_age:
            st.session_state.student_age = cfg.student_age
            reset()
            st.rerun()

        st.markdown("\n")
        bc1, _ = st.columns([1, 1])
        with bc1:
            if st.button('Start Over'):
                reset()
                st.rerun()

        st.divider()
        st.markdown(
            "## How this works?\n"
            "This app was built with [Vectara](https://vectara.com).\n\n"
            "It demonstrates the use of Agentic RAG functionality with Vectara"
        )

    if "messages" not in st.session_state.keys():
        reset()
    
    # Display chat messages
    for message in st.session_state.messages:
        with st.chat_message(message["role"], avatar=message["avatar"]):
            st.write(message["content"])

    example_container = st.empty()
    with example_container:
        if show_example_questions():
            example_container.empty()
            st.session_state.first_turn = False
            st.rerun()

    # User-provided prompt
    if st.session_state.ex_prompt:
        prompt = st.session_state.ex_prompt
    else:
        prompt = st.chat_input()
    if prompt:
        st.session_state.messages.append({"role": "user", "content": prompt, "avatar": 'πŸ§‘β€πŸ’»'})
        st.session_state.prompt = prompt  # Save the prompt in session state
        st.session_state.log_messages = []
        st.session_state.show_logs = False
        with st.chat_message("user", avatar='πŸ§‘β€πŸ’»'):
            print(f"Starting new question: {prompt}\n")
            st.write(prompt)
        st.session_state.ex_prompt = None
        
    # Generate a new response if last message is not from assistant
    if st.session_state.prompt:
        with st.chat_message("assistant", avatar='πŸ€–'):
            with st.spinner(st.session_state.thinking_message):
                res = st.session_state.agent.chat(st.session_state.prompt)
                res = escape_dollars_outside_latex(res)
            message = {"role": "assistant", "content": res, "avatar": 'πŸ€–'}
            st.session_state.messages.append(message)
            st.markdown(res)

        send_amplitude_data(
            user_query=st.session_state.messages[-2]["content"], 
            bot_response=st.session_state.messages[-1]["content"],
            demo_name=cfg['demo_name']
        )

        st.session_state.ex_prompt = None
        st.session_state.prompt = None
        st.session_state.first_turn = False
        st.rerun()

    # Record user feedback
    if (st.session_state.messages[-1]["role"] == "assistant") & (st.session_state.messages[-1]["content"] != "How can I help you today?"):
        streamlit_feedback(
            feedback_type="thumbs", on_submit = thumbs_feedback, key = st.session_state.feedback_key,
            kwargs = {"user_query": st.session_state.messages[-2]["content"],
                      "bot_response": st.session_state.messages[-1]["content"],
                      "demo_name": cfg["demo_name"]}
        )

    log_placeholder = st.empty()
    with log_placeholder.container():
        if st.session_state.show_logs:
            st.button("Hide Logs", on_click=toggle_logs)
            for msg in st.session_state.log_messages:
                st.text(msg)
        else:
            if len(st.session_state.log_messages) > 0:
                st.button("Show Logs", on_click=toggle_logs)

    sys.stdout.flush()

if __name__ == "__main__":
    st.set_page_config(page_title="Justice Harard Teching Assistant", layout="wide")
    launch_bot()