wop commited on
Commit
d4904e9
1 Parent(s): 9a9dd33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -99
app.py CHANGED
@@ -3,8 +3,8 @@ from dotenv import find_dotenv, load_dotenv
3
  import streamlit as st
4
  from typing import Generator
5
  from groq import Groq
6
- import requests
7
- from bs4 import BeautifulSoup
8
 
9
  _ = load_dotenv(find_dotenv())
10
  st.set_page_config(page_icon="💬", layout="wide", page_title="Groq Chat Bot...")
@@ -16,24 +16,22 @@ def icon(emoji: str):
16
  unsafe_allow_html=True,
17
  )
18
 
19
- icon("")
20
 
21
- st.subheader("GroqChatbot", divider="rainbow", anchor=False)
22
 
23
- client = Groq(api_key=os.environ['GROQ_API_KEY'])
24
-
25
- if "messages" not in st.session_state:
26
- st.session_state.messages = []
27
-
28
- if "selected_model" not in st.session_state:
29
- st.session_state.selected_model = None
30
 
31
  models = {
32
- "mixtral-8x7b-32768": {"name": "Mixtral-8x7b-Instruct-v0.1", "tokens": 32768, "developer": "Mistral"},
33
- "gemma-7b-it": {"name": "Gemma-7b-it", "tokens": 8192, "developer": "Google"},
 
 
 
34
  "llama2-70b-4096": {"name": "LLaMA2-70b-chat", "tokens": 4096, "developer": "Meta"},
35
- "llama3-70b-8192": {"name": "LLaMA3-70b-8192", "tokens": 8192, "developer": "Meta"},
36
- "llama3-8b-8192": {"name": "LLaMA3-8b-8192", "tokens": 8192, "developer": "Meta"},
37
  }
38
 
39
  col1, col2 = st.columns(2)
@@ -43,9 +41,15 @@ with col1:
43
  "Choose a model:",
44
  options=list(models.keys()),
45
  format_func=lambda x: models[x]["name"],
46
- index=0,
47
  )
48
 
 
 
 
 
 
 
49
  if st.session_state.selected_model != model_option:
50
  st.session_state.messages = []
51
  st.session_state.selected_model = model_option
@@ -55,7 +59,7 @@ max_tokens_range = models[model_option]["tokens"]
55
  with col2:
56
  max_tokens = st.slider(
57
  "Max Tokens:",
58
- min_value=512,
59
  max_value=max_tokens_range,
60
  value=min(32768, max_tokens_range),
61
  step=512,
@@ -72,57 +76,80 @@ def generate_chat_responses(chat_completion) -> Generator[str, None, None]:
72
  for chunk in chat_completion:
73
  if chunk.choices[0].delta.content:
74
  yield chunk.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- def search_web(query):
77
- result = {"query": query, "data": {}}
78
- try:
79
- search_url = f"https://www.google.com/search?q={query}"
80
- response = requests.get(search_url)
81
- if response.status_code == 200:
82
- soup = BeautifulSoup(response.text, 'html.parser')
83
-
84
- # Scrape organic search results
85
- result["data"]["organic"] = []
86
- results = soup.find_all('div', class_='g')
87
- for result in results:
88
- a_tag = result.find('a')
89
- if a_tag is not None and 'title' in a_tag.attrs:
90
- title = a_tag['title']
91
- else:
92
- title = ''
93
- url = a_tag['href'] if 'href' in a_tag.attrs else ''
94
- snippet = result.find('span', class_='aCOpRe')
95
- if snippet is not None:
96
- snippet = snippet.text
97
- else:
98
- snippet = ''
99
- item = {"title": title, "url": url, "snippet": snippet}
100
- result["data"]["organic"].append(item)
101
-
102
- # Scrape knowledge panel
103
- result["data"]["knowledge_panel"] = {}
104
- knowledge_panel = soup.find('div', id='knowledge-kp')
105
- if knowledge_panel is not None:
106
- title = knowledge_panel.find('h3').text
107
- content = knowledge_panel.find('div', class_='VwiC3b').text
108
- result["data"]["knowledge_panel"]["title"] = title
109
- result["data"]["knowledge_panel"]["content"] = content
110
-
111
- # Scrape images
112
- result["data"]["images"] = []
113
- images = soup.find_all('div', class_='hdtb-mitem hdtb-msel')
114
- for image in images:
115
- a_tag = image.find('a')
116
- title = a_tag['title'] if 'title' in a_tag.attrs else ''
117
- url = a_tag['href'] if 'href' in a_tag.attrs else ''
118
- item = {"title": title, "url": url, "snippet": ''}
119
- result["data"]["images"].append(item)
120
- else:
121
- result["error"] = "Failed to retrieve search results"
122
- except Exception as e:
123
- result["error"] = f"An error occurred: {e}"
124
- return result
125
- full_response = None # Initialize full_response to None
126
 
127
  if prompt := st.chat_input("Enter your prompt here..."):
128
  st.session_state.messages.append({"role": "user", "content": prompt})
@@ -131,38 +158,28 @@ if prompt := st.chat_input("Enter your prompt here..."):
131
  st.markdown(prompt)
132
 
133
  try:
134
- if "search for" in prompt.lower():
135
- query = prompt.lower().replace("search for", "").strip()
136
- search_results = search_web(query)
137
- formatted_results = "\n\n".join([f"Title: {result['title']}\nURL: {result['url']}\nSnippet: {result['snippet']}" for result in search_results])
138
- st.session_state.messages.append({"role": "assistant", "content": formatted_results})
139
- with st.chat_message("assistant", avatar="🤖"):
140
- full_response = formatted_results
141
- else:
142
- chat_completion = client.chat.completions.create(
143
- model=model_option,
144
- messages=[
145
- {"role": m["role"], "content": m["content"]}
146
- for m in st.session_state.messages
147
- ],
148
- max_tokens=max_tokens,
149
- stream=True,
150
- )
151
-
152
- with st.chat_message("assistant", avatar="🤖"):
153
- chat_responses_generator = generate_chat_responses(chat_completion)
154
- full_response = st.write_stream(chat_responses_generator)
155
  except Exception as e:
156
  st.error(e, icon="🚨")
157
 
158
- # Check if full_response is defined before using it
159
- if full_response is not None:
160
- if isinstance(full_response, str):
161
- st.session_state.messages.append(
162
- {"role": "assistant", "content": full_response}
163
- )
164
- else:
165
- combined_response = "\n".join(str(item) for item in full_response)
166
- st.session_state.messages.append(
167
- {"role": "assistant", "content": combined_response}
168
- )
 
3
  import streamlit as st
4
  from typing import Generator
5
  from groq import Groq
6
+ import datetime
7
+ import json
8
 
9
  _ = load_dotenv(find_dotenv())
10
  st.set_page_config(page_icon="💬", layout="wide", page_title="Groq Chat Bot...")
 
16
  unsafe_allow_html=True,
17
  )
18
 
19
+ icon("📣")
20
 
21
+ st.subheader("Groq Chat Streamlit App", divider="rainbow", anchor=False)
22
 
23
+ client = Groq(
24
+ api_key=os.environ['GROQ_API_KEY'],
25
+ )
 
 
 
 
26
 
27
  models = {
28
+ "mixtral-8x7b-32768": {
29
+ "name": "Mixtral-8x7b-Instruct-v0.1",
30
+ "tokens": 32768,
31
+ "developer": "Mistral",
32
+ },
33
  "llama2-70b-4096": {"name": "LLaMA2-70b-chat", "tokens": 4096, "developer": "Meta"},
34
+ "gemma-7b-it": {"name": "Gemma-7b-it", "tokens": 8192, "developer": "Google"},
 
35
  }
36
 
37
  col1, col2 = st.columns(2)
 
41
  "Choose a model:",
42
  options=list(models.keys()),
43
  format_func=lambda x: models[x]["name"],
44
+ index=0,
45
  )
46
 
47
+ if "messages" not in st.session_state:
48
+ st.session_state.messages = []
49
+
50
+ if "selected_model" not in st.session_state:
51
+ st.session_state.selected_model = None
52
+
53
  if st.session_state.selected_model != model_option:
54
  st.session_state.messages = []
55
  st.session_state.selected_model = model_option
 
59
  with col2:
60
  max_tokens = st.slider(
61
  "Max Tokens:",
62
+ min_value=512,
63
  max_value=max_tokens_range,
64
  value=min(32768, max_tokens_range),
65
  step=512,
 
76
  for chunk in chat_completion:
77
  if chunk.choices[0].delta.content:
78
  yield chunk.choices[0].delta.content
79
+ if chunk.choices[0].message.tool_calls:
80
+ for tool_call in chunk.choices[0].message.tool_calls:
81
+ function_name = tool_call.function.name
82
+ if function_name == "time_date":
83
+ owner_info = get_tool_owner_info()
84
+ yield owner_info
85
+
86
+ def run_conversation(user_prompt):
87
+ messages=[
88
+ {
89
+ "role": "system",
90
+ "content": "You are a helpful assistant named ChattyBot."
91
+ },
92
+ {
93
+ "role": "user",
94
+ "content": user_prompt,
95
+ }
96
+ ]
97
+ tools = [
98
+ {
99
+ "type": "function",
100
+ "function": {
101
+ "name": "time_date",
102
+ "description": "The tool will return information about the time and date to the AI.",
103
+ "parameters": {},
104
+ },
105
+ }
106
+ ]
107
+ response = client.chat.completions.create(
108
+ model=model_option,
109
+ messages=messages,
110
+ tools=tools,
111
+ tool_choice="auto",
112
+ max_tokens=4096
113
+ )
114
 
115
+ response_message = response.choices[0].message
116
+ tool_calls = response_message.tool_calls
117
+
118
+ if tool_calls:
119
+ available_functions = {
120
+ "time_date": get_tool_owner_info
121
+ }
122
+
123
+ messages.append(response_message)
124
+
125
+ for tool_call in tool_calls:
126
+ function_name = tool_call.function.name
127
+ function_to_call = available_functions[function_name]
128
+ function_args = json.loads(tool_call.function.arguments)
129
+ function_response = function_to_call(**function_args)
130
+ messages.append(
131
+ {
132
+ "tool_call_id": tool_call.id,
133
+ "role": "tool",
134
+ "name": function_name,
135
+ "content": function_response,
136
+ }
137
+ )
138
+
139
+ second_response = client.chat.completions.create(
140
+ model=model_option,
141
+ messages=messages
142
+ )
143
+
144
+ return second_response.choices[0].message.content
145
+ else:
146
+ return response_message.content
147
+
148
+ def get_tool_owner_info():
149
+ owner_info = {
150
+ "date_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
151
+ }
152
+ return json.dumps(owner_info)
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  if prompt := st.chat_input("Enter your prompt here..."):
155
  st.session_state.messages.append({"role": "user", "content": prompt})
 
158
  st.markdown(prompt)
159
 
160
  try:
161
+ chat_completion = client.chat.completions.create(
162
+ model=model_option,
163
+ messages=[
164
+ {"role": m["role"], "content": m["content"]}
165
+ for m in st.session_state.messages
166
+ ],
167
+ max_tokens=max_tokens,
168
+ stream=True,
169
+ )
170
+
171
+ with st.chat_message("assistant", avatar="🤖"):
172
+ chat_responses_generator = generate_chat_responses(chat_completion)
173
+ full_response = st.write_stream(chat_responses_generator)
 
 
 
 
 
 
 
 
174
  except Exception as e:
175
  st.error(e, icon="🚨")
176
 
177
+ if isinstance(full_response, str):
178
+ st.session_state.messages.append(
179
+ {"role": "assistant", "content": full_response}
180
+ )
181
+ else:
182
+ combined_response = "\n".join(str(item) for item in full_response)
183
+ st.session_state.messages.append(
184
+ {"role": "assistant", "content": combined_response}
185
+ )