umer70112254 commited on
Commit
b2951df
·
1 Parent(s): b4adc7f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ import asyncio
3
+
4
+ # Create a new event loop
5
+ loop = asyncio.new_event_loop()
6
+
7
+ # Set the event loop as the current event loop
8
+ asyncio.set_event_loop(loop)
9
+
10
+ from llama_index import (
11
+ VectorStoreIndex,
12
+ ServiceContext,
13
+ download_loader,
14
+ )
15
+ from llama_index.llama_pack.base import BaseLlamaPack
16
+ from llama_index.llms import OpenAI
17
+
18
+
19
+ class StreamlitChatPack(BaseLlamaPack):
20
+ """Streamlit chatbot pack."""
21
+
22
+ def __init__(
23
+ self,
24
+ wikipedia_page: str = "Snowflake Inc.",
25
+ run_from_main: bool = False,
26
+ **kwargs: Any,
27
+ ) -> None:
28
+ """Init params."""
29
+ if not run_from_main:
30
+ raise ValueError(
31
+ "Please run this llama-pack directly with "
32
+ "`streamlit run [download_dir]/streamlit_chatbot/base.py`"
33
+ )
34
+
35
+ self.wikipedia_page = wikipedia_page
36
+
37
+ def get_modules(self) -> Dict[str, Any]:
38
+ """Get modules."""
39
+ return {}
40
+
41
+ def run(self, *args: Any, **kwargs: Any) -> Any:
42
+ """Run the pipeline."""
43
+ import streamlit as st
44
+ from streamlit_pills import pills
45
+
46
+ st.set_page_config(
47
+ page_title=f"Chat with {self.wikipedia_page}'s Wikipedia page, powered by LlamaIndex",
48
+ page_icon="🦙",
49
+ layout="centered",
50
+ initial_sidebar_state="auto",
51
+ menu_items=None,
52
+ )
53
+
54
+ if "messages" not in st.session_state: # Initialize the chat messages history
55
+ st.session_state["messages"] = [
56
+ {"role": "assistant", "content": "Ask me a question about Snowflake!"}
57
+ ]
58
+
59
+ st.title(
60
+ f"Chat with {self.wikipedia_page}'s Wikipedia page, powered by LlamaIndex 💬🦙"
61
+ )
62
+ st.info(
63
+ "This example is powered by the **[Llama Hub Wikipedia Loader](https://llamahub.ai/l/wikipedia)**. Use any of [Llama Hub's many loaders](https://llamahub.ai/) to retrieve and chat with your data via a Streamlit app.",
64
+ icon="ℹ️",
65
+ )
66
+
67
+ def add_to_message_history(role, content):
68
+ message = {"role": role, "content": str(content)}
69
+ st.session_state["messages"].append(
70
+ message
71
+ ) # Add response to message history
72
+
73
+ @st.cache_resource
74
+ def load_index_data():
75
+ WikipediaReader = download_loader(
76
+ "WikipediaReader", custom_path="local_dir"
77
+ )
78
+ loader = WikipediaReader()
79
+ docs = loader.load_data(pages=[self.wikipedia_page])
80
+ service_context = ServiceContext.from_defaults(
81
+ llm=OpenAI(model="gpt-3.5-turbo", temperature=0.5)
82
+ )
83
+ index = VectorStoreIndex.from_documents(
84
+ docs, service_context=service_context
85
+ )
86
+ return index
87
+
88
+ index = load_index_data()
89
+
90
+ selected = pills(
91
+ "Choose a question to get started or write your own below.",
92
+ [
93
+ "What is Snowflake?",
94
+ "What company did Snowflake announce they would acquire in October 2023?",
95
+ "What company did Snowflake acquire in March 2022?",
96
+ "When did Snowflake IPO?",
97
+ ],
98
+ clearable=True,
99
+ index=None,
100
+ )
101
+
102
+ if "chat_engine" not in st.session_state: # Initialize the query engine
103
+ st.session_state["chat_engine"] = index.as_chat_engine(
104
+ chat_mode="context", verbose=True
105
+ )
106
+
107
+ for message in st.session_state["messages"]: # Display the prior chat messages
108
+ with st.chat_message(message["role"]):
109
+ st.write(message["content"])
110
+
111
+ # To avoid duplicated display of answered pill questions each rerun
112
+ if selected and selected not in st.session_state.get(
113
+ "displayed_pill_questions", set()
114
+ ):
115
+ st.session_state.setdefault("displayed_pill_questions", set()).add(selected)
116
+ with st.chat_message("user"):
117
+ st.write(selected)
118
+ with st.chat_message("assistant"):
119
+ response = st.session_state["chat_engine"].stream_chat(selected)
120
+ response_str = ""
121
+ response_container = st.empty()
122
+ for token in response.response_gen:
123
+ response_str += token
124
+ response_container.write(response_str)
125
+ add_to_message_history("user", selected)
126
+ add_to_message_history("assistant", response)
127
+
128
+ if prompt := st.chat_input(
129
+ "Your question"
130
+ ): # Prompt for user input and save to chat history
131
+ add_to_message_history("user", prompt)
132
+
133
+ # Display the new question immediately after it is entered
134
+ with st.chat_message("user"):
135
+ st.write(prompt)
136
+
137
+ # If last message is not from assistant, generate a new response
138
+ # if st.session_state["messages"][-1]["role"] != "assistant":
139
+ with st.chat_message("assistant"):
140
+ response = st.session_state["chat_engine"].stream_chat(prompt)
141
+ response_str = ""
142
+ response_container = st.empty()
143
+ for token in response.response_gen:
144
+ response_str += token
145
+ response_container.write(response_str)
146
+ # st.write(response.response)
147
+ add_to_message_history("assistant", response.response)
148
+
149
+ # Save the state of the generator
150
+ st.session_state["response_gen"] = response.response_gen
151
+
152
+
153
+ if __name__ == "__main__":
154
+ StreamlitChatPack(run_from_main=True).run()