Solarum Asteridion commited on
Commit
018f5ac
Β·
verified Β·
1 Parent(s): e6600f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -35
app.py CHANGED
@@ -3,6 +3,8 @@ import datetime
3
  import pytz
4
  import gradio as gr
5
  import logging
 
 
6
 
7
  # Configure logging
8
  logging.basicConfig(level=logging.INFO)
@@ -10,10 +12,24 @@ logger = logging.getLogger(__name__)
10
 
11
  # Initialize OpenAI client using secrets.toml
12
  client = openai.OpenAI(
13
- api_key='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', # Accessing the API key from secrets.toml
14
  base_url="https://api.groq.com/openai/v1",
15
  )
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def get_current_local_time(timezone_str='UTC'):
18
  try:
19
  timezone = pytz.timezone(timezone_str)
@@ -47,7 +63,7 @@ Make it a challenge to guess if you are an AI.
47
  * Be respectful and polite if the user is polite; be rough if the user is rough
48
  """
49
 
50
- def generate_response(user_message, conversation_history):
51
  current_time, now = get_current_local_time()
52
  current_date = now
53
 
@@ -62,7 +78,7 @@ def generate_response(user_message, conversation_history):
62
 
63
  try:
64
  response = client.chat.completions.create(
65
- model='llama-3.2-11b-text-preview',
66
  messages=messages,
67
  temperature=1,
68
  max_tokens=300, # Adjust as needed
@@ -74,11 +90,11 @@ def generate_response(user_message, conversation_history):
74
  logger.error(f"Error generating response: {e}")
75
  return "Sorry, I encountered an error while processing your request."
76
 
77
- def chatbot_interface(user_message, history):
78
  if history is None:
79
  history = []
80
 
81
- ai_response = generate_response(user_message, history)
82
  history.append({"role": "user", "content": user_message})
83
  history.append({"role": "assistant", "content": ai_response})
84
  logger.info("Chat history: %s", history) # Corrected logging
@@ -152,35 +168,42 @@ padding: 8px 16px;
152
  }
153
  """) as demo:
154
  gr.Markdown("<h1 style='text-align: center; color: #007BFF;'>πŸ€– Human-like Chatbot πŸ€–</h1>")
155
- with gr.Row():
156
- with gr.Column(scale=1):
157
- chatbot = gr.Chatbot(label="Chatbot", elem_id="chatbot", type="messages")
158
- with gr.Column(scale=1):
159
- with gr.Row():
160
- msg = gr.Textbox(
161
- placeholder="Type your message here...",
162
- show_label=False,
163
- container=False,
164
- elem_id="textbox"
165
- )
166
- send = gr.Button("➀", elem_id="send-button")
167
-
168
- def update_chat(user_message, history):
169
- if user_message.strip() == "":
170
- return history, history # Do not process empty messages
171
- history, updated_history = chatbot_interface(user_message, history)
172
- return history, updated_history, "" # Clear textbox
173
-
174
- send.click(
175
- update_chat,
176
- inputs=[msg, chatbot],
177
- outputs=[chatbot, chatbot, msg] # Added msg to outputs
178
- )
179
-
180
- msg.submit(
181
- update_chat,
182
- inputs=[msg, chatbot],
183
- outputs=[chatbot, chatbot, msg] # Added msg to outputs
184
- )
 
 
 
 
 
 
 
185
 
186
  demo.launch()
 
3
  import pytz
4
  import gradio as gr
5
  import logging
6
+ import requests
7
+ grqapi = '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'
8
 
9
  # Configure logging
10
  logging.basicConfig(level=logging.INFO)
 
12
 
13
  # Initialize OpenAI client using secrets.toml
14
  client = openai.OpenAI(
15
+ api_key=grqapi, # Accessing the API key from secrets.toml
16
  base_url="https://api.groq.com/openai/v1",
17
  )
18
 
19
+ def get_available_models():
20
+ url = "https://api.groq.com/openai/v1/models"
21
+ headers = {
22
+ "Authorization": f"Bearer {grqapi}",
23
+ "Content-Type": "application/json"
24
+ }
25
+ response = requests.get(url, headers=headers)
26
+ if response.status_code == 200:
27
+ models = [model["id"] for model in response.json()["data"]]
28
+ return models
29
+ else:
30
+ logger.error(f"Error fetching models: {response.status_code} - {response.text}")
31
+ return []
32
+
33
  def get_current_local_time(timezone_str='UTC'):
34
  try:
35
  timezone = pytz.timezone(timezone_str)
 
63
  * Be respectful and polite if the user is polite; be rough if the user is rough
64
  """
65
 
66
+ def generate_response(user_message, conversation_history, model_name):
67
  current_time, now = get_current_local_time()
68
  current_date = now
69
 
 
78
 
79
  try:
80
  response = client.chat.completions.create(
81
+ model=model_name,
82
  messages=messages,
83
  temperature=1,
84
  max_tokens=300, # Adjust as needed
 
90
  logger.error(f"Error generating response: {e}")
91
  return "Sorry, I encountered an error while processing your request."
92
 
93
+ def chatbot_interface(user_message, history, model_name):
94
  if history is None:
95
  history = []
96
 
97
+ ai_response = generate_response(user_message, history, model_name)
98
  history.append({"role": "user", "content": user_message})
99
  history.append({"role": "assistant", "content": ai_response})
100
  logger.info("Chat history: %s", history) # Corrected logging
 
168
  }
169
  """) as demo:
170
  gr.Markdown("<h1 style='text-align: center; color: #007BFF;'>πŸ€– Human-like Chatbot πŸ€–</h1>")
171
+
172
+ available_models = get_available_models()
173
+ if not available_models:
174
+ gr.Markdown("**Error: Could not fetch available models from the API.**")
175
+ else:
176
+ with gr.Row():
177
+ model_dropdown = gr.Dropdown(choices=available_models, label="Select Model", value=available_models[0])
178
+ with gr.Row():
179
+ with gr.Column(scale=1):
180
+ chatbot = gr.Chatbot(label="Chatbot", elem_id="chatbot", type="messages")
181
+ with gr.Column(scale=1):
182
+ with gr.Row():
183
+ msg = gr.Textbox(
184
+ placeholder="Type your message here...",
185
+ show_label=False,
186
+ container=False,
187
+ elem_id="textbox"
188
+ )
189
+ send = gr.Button("➀", elem_id="send-button")
190
+
191
+ def update_chat(user_message, history, model_name):
192
+ if user_message.strip() == "":
193
+ return history, history # Do not process empty messages
194
+ history, updated_history = chatbot_interface(user_message, history, model_name)
195
+ return history, updated_history, "" # Clear textbox
196
+
197
+ send.click(
198
+ update_chat,
199
+ inputs=[msg, chatbot, model_dropdown],
200
+ outputs=[chatbot, chatbot, msg] # Added msg to outputs
201
+ )
202
+
203
+ msg.submit(
204
+ update_chat,
205
+ inputs=[msg, chatbot, model_dropdown],
206
+ outputs=[chatbot, chatbot, msg] # Added msg to outputs
207
+ )
208
 
209
  demo.launch()