adikwok commited on
Commit
3cd807f
Β·
verified Β·
1 Parent(s): 2f78515

Update app.py

Browse files

chatbox enhanced style

Files changed (1) hide show
  1. app.py +58 -37
app.py CHANGED
@@ -14,14 +14,14 @@ print(f"πŸ”‘ API Key Found: {'Yes' if API_KEY else 'No'}")
14
  # In-memory chat history storage
15
  chat_history: List[Dict[str, str]] = []
16
 
17
- def groq_with_memory(message: str, topic: str = "general", summarize: bool = False, max_history: int = 10) -> str:
18
- """Groq API call with chat history and optional summarization"""
19
 
20
  if not API_KEY:
21
- return "❌ No API Key found"
22
 
23
  if not message.strip():
24
- return "❌ Empty message"
25
 
26
  try:
27
  headers = {
@@ -84,27 +84,34 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
84
  "topic": topic,
85
  "timestamp": datetime.now().isoformat()
86
  })
87
- return response_content
 
88
  else:
89
- return f"❌ No choices in response: {json.dumps(result, indent=2)}"
 
90
  else:
91
- return f"❌ HTTP {response.status_code}: {response.text}"
 
92
 
93
  except requests.exceptions.Timeout:
94
- return "❌ Request timeout (30s)"
95
  except requests.exceptions.ConnectionError:
96
- return "❌ Connection error - cannot reach Groq API"
97
  except json.JSONDecodeError:
98
- return f"❌ Invalid JSON response: {response.text}"
99
  except Exception as e:
100
- return f"❌ Unexpected error: {str(e)}"
 
 
 
 
101
 
102
  def clear_history():
103
  """Clear the chat history"""
104
  chat_history.clear()
105
- return "βœ… Chat history cleared"
106
 
107
- def view_history(topic: str = None):
108
  """View the chat history, optionally filtered by topic"""
109
  if not chat_history:
110
  return "❌ No chat history available"
@@ -122,7 +129,7 @@ def manual_curl_example():
122
 
123
  curl_cmd = f'''curl -X POST "{API_URL}" \\
124
  -H "Authorization: Bearer {API_KEY}" \\
125
- -H "Content-Type: application/json" \\
126
  -d '{{
127
  "model": "llama3-8b-8192",
128
  "messages": [
@@ -134,37 +141,51 @@ def manual_curl_example():
134
  return curl_cmd
135
 
136
  # Create Gradio interface
137
- with gr.Blocks(title="Groq Debug with Memory") as demo:
 
 
 
138
  gr.Markdown("# πŸ” Groq API Debug Tool with Memory")
139
 
140
  with gr.Tab("Chat with Memory"):
141
- gr.Markdown("Chat with Groq, maintain history, and summarize by topic")
142
 
143
- chat_input = gr.Textbox(
144
- label="Message",
145
- placeholder="Enter your message",
146
- value="Hello, how can you help me today?"
147
- )
148
- topic_input = gr.Textbox(
149
- label="Topic",
150
- placeholder="Enter topic (e.g., 'coding', 'general')",
151
- value="general"
152
- )
153
- summarize_checkbox = gr.Checkbox(
154
- label="Summarize conversation for this topic",
155
- value=False
156
- )
157
- chat_button = gr.Button("Send Message", variant="primary")
158
- chat_output = gr.Textbox(
159
- label="Response",
160
- lines=10,
161
- max_lines=20
162
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  chat_button.click(
165
  groq_with_memory,
166
  inputs=[chat_input, topic_input, summarize_checkbox],
167
- outputs=[chat_output]
 
 
 
 
168
  )
169
 
170
  with gr.Tab("View History"):
@@ -189,7 +210,7 @@ with gr.Blocks(title="Groq Debug with Memory") as demo:
189
  )
190
  clear_button.click(
191
  clear_history,
192
- outputs=[history_output]
193
  )
194
 
195
  with gr.Tab("Manual Test"):
 
14
  # In-memory chat history storage
15
  chat_history: List[Dict[str, str]] = []
16
 
17
+ def groq_with_memory(message: str, topic: str = "general", summarize: bool = False, max_history: int = 10) -> List[List[str]]:
18
+ """Groq API call with chat history and optional summarization, returning chatbot format"""
19
 
20
  if not API_KEY:
21
+ return [[None, "❌ No API Key found"]]
22
 
23
  if not message.strip():
24
+ return [[None, "❌ Empty message"]]
25
 
26
  try:
27
  headers = {
 
84
  "topic": topic,
85
  "timestamp": datetime.now().isoformat()
86
  })
87
+ # Return in chatbot format: [[user_message, assistant_response]]
88
+ return [[message.strip(), response_content]]
89
  else:
90
+ error_msg = f"❌ No choices in response: {json.dumps(result, indent=2)}"
91
+ return [[message.strip(), error_msg]]
92
  else:
93
+ error_msg = f"❌ HTTP {response.status_code}: {response.text}"
94
+ return [[message.strip(), error_msg]]
95
 
96
  except requests.exceptions.Timeout:
97
+ return [[message.strip(), "❌ Request timeout (30s)"]]
98
  except requests.exceptions.ConnectionError:
99
+ return [[message.strip(), "❌ Connection error - cannot reach Groq API"]]
100
  except json.JSONDecodeError:
101
+ return [[message.strip(), f"❌ Invalid JSON response: {response.text}"]]
102
  except Exception as e:
103
+ return [[message.strip(), f"❌ Unexpected error: {str(e)}"]]
104
+
105
+ def update_chatbot_display() -> List[List[str]]:
106
+ """Update the chatbot display with the entire chat history"""
107
+ return [[msg["content"], None] if msg["role"] == "user" else [None, msg["content"]] for msg in chat_history]
108
 
109
  def clear_history():
110
  """Clear the chat history"""
111
  chat_history.clear()
112
+ return [], "βœ… Chat history cleared"
113
 
114
+ def view_history(topic: str = None) -> str:
115
  """View the chat history, optionally filtered by topic"""
116
  if not chat_history:
117
  return "❌ No chat history available"
 
129
 
130
  curl_cmd = f'''curl -X POST "{API_URL}" \\
131
  -H "Authorization: Bearer {API_KEY}" \\
132
+ -H "Content-Type: "application/json" \\
133
  -d '{{
134
  "model": "llama3-8b-8192",
135
  "messages": [
 
141
  return curl_cmd
142
 
143
  # Create Gradio interface
144
+ with gr.Blocks(title="Grok Debug with Memory", css="""
145
+ .chatbot-container { max-height: 500px; overflow-y: auto; }
146
+ .input-container { position: sticky; bottom: 0; background: white; padding: 10px; }
147
+ """) as demo:
148
  gr.Markdown("# πŸ” Groq API Debug Tool with Memory")
149
 
150
  with gr.Tab("Chat with Memory"):
151
+ gr.Markdown("Chat with Grok, maintain history, and summarize by topic")
152
 
153
+ chatbot = gr.Chatbot(
154
+ label="Conversation",
155
+ container=True,
156
+ height=500,
157
+ elem_classes="chatbot-container"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  )
159
+ with gr.Row(elem_classes="input-container"):
160
+ chat_input = gr.Textbox(
161
+ label="Message",
162
+ placeholder="Enter your message",
163
+ value="Hello, how can you help me today?",
164
+ show_label=False,
165
+ container=False
166
+ )
167
+ topic_input = gr.Textbox(
168
+ label="Topic",
169
+ placeholder="Enter topic (e.g., 'coding', 'general')",
170
+ value="general",
171
+ show_label=False,
172
+ container=False,
173
+ scale=1
174
+ )
175
+ summarize_checkbox = gr.Checkbox(
176
+ label="Summarize",
177
+ value=False
178
+ )
179
+ chat_button = gr.Button("Send", variant="primary")
180
 
181
  chat_button.click(
182
  groq_with_memory,
183
  inputs=[chat_input, topic_input, summarize_checkbox],
184
+ outputs=[chatbot],
185
+ _js="() => { setTimeout(() => document.querySelector('.chatbot-container').scrollTop = document.querySelector('.chatbot-container').scrollHeight, 100); }"
186
+ ).then(
187
+ update_chatbot_display,
188
+ outputs=[chatbot]
189
  )
190
 
191
  with gr.Tab("View History"):
 
210
  )
211
  clear_button.click(
212
  clear_history,
213
+ outputs=[chatbot, history_output]
214
  )
215
 
216
  with gr.Tab("Manual Test"):