zakerytclarke commited on
Commit
e115381
·
verified ·
1 Parent(s): 341437d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -58
app.py CHANGED
@@ -3,19 +3,27 @@ from teapotai import TeapotAI, TeapotAISettings
3
  import hashlib
4
  import os
5
  import requests
 
6
  from langsmith import traceable
7
 
 
 
 
 
 
 
 
 
 
8
  default_documents = []
9
 
10
  API_KEY = os.environ.get("brave_api_key")
11
 
 
12
  def brave_search(query, count=3):
13
  url = "https://api.search.brave.com/res/v1/web/search"
14
  headers = {"Accept": "application/json", "X-Subscription-Token": API_KEY}
15
- params = {
16
- "q": query,
17
- "count": count
18
- }
19
 
20
  response = requests.get(url, headers=headers, params=params)
21
 
@@ -28,92 +36,65 @@ def brave_search(query, count=3):
28
  return []
29
 
30
  @traceable
 
31
  def query_teapot(prompt, context, user_input, teapot_ai):
32
  response = teapot_ai.query(
33
  context=prompt+"\n"+context,
34
  query=user_input
35
  )
36
-
37
  return response
38
-
39
 
40
- # Function to handle the chat with TeapotAI
41
  def handle_chat(user_input, teapot_ai):
42
  results = brave_search(user_input)
43
-
44
- documents = []
45
- for i, (title, description, url) in enumerate(results, 1):
46
- documents.append(description.replace('<strong>','').replace('</strong>',''))
47
  print(documents)
48
 
49
- context="\n".join(documents)
50
  prompt = "You are Teapot, an open-source AI assistant optimized for low-end devices, providing short, accurate responses without hallucinating while excelling at information extraction and text summarization."
51
  response = query_teapot(prompt, context, user_input, teapot_ai)
52
 
53
- # response = teapot_ai.chat([
54
- # {
55
- # "role": "system",
56
- # "content": "You are Teapot, an open-source AI assistant optimized for running efficiently on low-end devices. You provide short, accurate responses without hallucinating and excel at extracting information and summarizing text."
57
- # },
58
- # {
59
- # "role": "user",
60
- # "content": user_input
61
- # }
62
- # ])
63
  return response
64
 
65
  def suggestion_button(suggestion_text, teapot_ai):
66
  if st.button(suggestion_text):
67
  handle_chat(suggestion_text, teapot_ai)
68
 
69
- # Function to hash documents
70
  def hash_documents(documents):
71
  return hashlib.sha256("\n".join(documents).encode("utf-8")).hexdigest()
72
 
73
- # Streamlit app
74
  def main():
75
  st.set_page_config(page_title="TeapotAI Chat", page_icon=":robot_face:", layout="wide")
76
-
77
- # Sidebar for document input
78
  st.sidebar.header("Document Input (for RAG)")
79
- user_documents = st.sidebar.text_area(
80
- "Enter documents, each on a new line",
81
- value="\n".join(default_documents)
82
- )
83
-
84
- # Parse the user input to get the documents (split by newline)
85
- documents = user_documents.split("\n")
86
 
87
- # Ensure non-empty documents
88
- documents = [doc for doc in documents if doc.strip()]
89
-
90
- # Check if documents have changed
91
  new_documents_hash = hash_documents(documents)
92
-
93
- # Load model if documents have changed, otherwise reuse the model from session_state
94
  if "documents_hash" not in st.session_state or st.session_state.documents_hash != new_documents_hash:
95
  with st.spinner('Loading Model and Embeddings...'):
 
96
  teapot_ai = TeapotAI(documents=documents or default_documents, settings=TeapotAISettings(rag_num_results=3))
 
 
97
 
98
- # Store the new hash and model in session state
99
  st.session_state.documents_hash = new_documents_hash
100
  st.session_state.teapot_ai = teapot_ai
101
  else:
102
- # Reuse the existing model
103
  teapot_ai = st.session_state.teapot_ai
104
-
105
- # Initialize session state and display the welcome message
106
  if "messages" not in st.session_state:
107
  st.session_state.messages = [{"role": "assistant", "content": "Hi, I am Teapot AI, how can I help you?"}]
108
 
109
- # Display previous messages from chat history
110
  for message in st.session_state.messages:
111
  with st.chat_message(message["role"]):
112
  st.markdown(message["content"])
113
-
114
- # Accept user input
115
  user_input = st.chat_input("Ask me anything")
116
-
117
  s1, s2, s3 = st.columns([1, 2, 3])
118
  with s1:
119
  suggestion_button("Tell me about the varieties of tea", teapot_ai)
@@ -123,26 +104,18 @@ def main():
123
  suggestion_button("Extract Google's stock price", teapot_ai)
124
 
125
  if user_input:
126
- # Display user message in chat message container
127
  with st.chat_message("user"):
128
  st.markdown(user_input)
129
-
130
- # Add user message to session state
131
  st.session_state.messages.append({"role": "user", "content": user_input})
132
  with st.spinner('Generating Response...'):
133
- # Get the answer from TeapotAI using chat functionality
134
  response = handle_chat(user_input, teapot_ai)
135
-
136
- # Display assistant response in chat message container
137
  with st.chat_message("assistant"):
138
  st.markdown(response)
139
-
140
- # Add assistant response to session state
141
  st.session_state.messages.append({"role": "assistant", "content": response})
142
  st.markdown("### Suggested Questions")
143
 
144
-
145
-
146
- # Run the app
147
  if __name__ == "__main__":
148
  main()
 
3
  import hashlib
4
  import os
5
  import requests
6
+ import time
7
  from langsmith import traceable
8
 
9
+ def log_time(func):
10
+ def wrapper(*args, **kwargs):
11
+ start_time = time.time()
12
+ result = func(*args, **kwargs)
13
+ end_time = time.time()
14
+ print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
15
+ return result
16
+ return wrapper
17
+
18
  default_documents = []
19
 
20
  API_KEY = os.environ.get("brave_api_key")
21
 
22
+ @log_time
23
  def brave_search(query, count=3):
24
  url = "https://api.search.brave.com/res/v1/web/search"
25
  headers = {"Accept": "application/json", "X-Subscription-Token": API_KEY}
26
+ params = {"q": query, "count": count}
 
 
 
27
 
28
  response = requests.get(url, headers=headers, params=params)
29
 
 
36
  return []
37
 
38
  @traceable
39
+ @log_time
40
  def query_teapot(prompt, context, user_input, teapot_ai):
41
  response = teapot_ai.query(
42
  context=prompt+"\n"+context,
43
  query=user_input
44
  )
 
45
  return response
 
46
 
47
+ @log_time
48
  def handle_chat(user_input, teapot_ai):
49
  results = brave_search(user_input)
50
+
51
+ documents = [desc.replace('<strong>','').replace('</strong>','') for _, desc, _ in results]
 
 
52
  print(documents)
53
 
54
+ context = "\n".join(documents)
55
  prompt = "You are Teapot, an open-source AI assistant optimized for low-end devices, providing short, accurate responses without hallucinating while excelling at information extraction and text summarization."
56
  response = query_teapot(prompt, context, user_input, teapot_ai)
57
 
 
 
 
 
 
 
 
 
 
 
58
  return response
59
 
60
  def suggestion_button(suggestion_text, teapot_ai):
61
  if st.button(suggestion_text):
62
  handle_chat(suggestion_text, teapot_ai)
63
 
64
+ @log_time
65
  def hash_documents(documents):
66
  return hashlib.sha256("\n".join(documents).encode("utf-8")).hexdigest()
67
 
 
68
  def main():
69
  st.set_page_config(page_title="TeapotAI Chat", page_icon=":robot_face:", layout="wide")
70
+
 
71
  st.sidebar.header("Document Input (for RAG)")
72
+ user_documents = st.sidebar.text_area("Enter documents, each on a new line", value="\n".join(default_documents))
 
 
 
 
 
 
73
 
74
+ documents = [doc.strip() for doc in user_documents.split("\n") if doc.strip()]
 
 
 
75
  new_documents_hash = hash_documents(documents)
76
+
 
77
  if "documents_hash" not in st.session_state or st.session_state.documents_hash != new_documents_hash:
78
  with st.spinner('Loading Model and Embeddings...'):
79
+ start_time = time.time()
80
  teapot_ai = TeapotAI(documents=documents or default_documents, settings=TeapotAISettings(rag_num_results=3))
81
+ end_time = time.time()
82
+ print(f"Model loaded in {end_time - start_time:.4f} seconds")
83
 
 
84
  st.session_state.documents_hash = new_documents_hash
85
  st.session_state.teapot_ai = teapot_ai
86
  else:
 
87
  teapot_ai = st.session_state.teapot_ai
88
+
 
89
  if "messages" not in st.session_state:
90
  st.session_state.messages = [{"role": "assistant", "content": "Hi, I am Teapot AI, how can I help you?"}]
91
 
 
92
  for message in st.session_state.messages:
93
  with st.chat_message(message["role"]):
94
  st.markdown(message["content"])
95
+
 
96
  user_input = st.chat_input("Ask me anything")
97
+
98
  s1, s2, s3 = st.columns([1, 2, 3])
99
  with s1:
100
  suggestion_button("Tell me about the varieties of tea", teapot_ai)
 
104
  suggestion_button("Extract Google's stock price", teapot_ai)
105
 
106
  if user_input:
 
107
  with st.chat_message("user"):
108
  st.markdown(user_input)
109
+
 
110
  st.session_state.messages.append({"role": "user", "content": user_input})
111
  with st.spinner('Generating Response...'):
 
112
  response = handle_chat(user_input, teapot_ai)
113
+
 
114
  with st.chat_message("assistant"):
115
  st.markdown(response)
116
+
 
117
  st.session_state.messages.append({"role": "assistant", "content": response})
118
  st.markdown("### Suggested Questions")
119
 
 
 
 
120
  if __name__ == "__main__":
121
  main()