adikwok commited on
Commit
e2bed42
Β·
verified Β·
1 Parent(s): c5fe00a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -42
app.py CHANGED
@@ -1,3 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
  import gradio as gr
3
  import requests
@@ -9,7 +22,6 @@ from datetime import datetime
9
  # Groq API Configuration
10
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
  API_KEY = os.getenv("GROQ_API_KEY")
12
-
13
  print(f"πŸ”‘ API Key Found: {'Yes' if API_KEY else 'No'}")
14
 
15
  # In-memory chat history storage
@@ -18,19 +30,18 @@ chat_history: List[Dict[str, str]] = []
18
  def groq_with_memory(message: str, topic: str = "general", summarize: bool = False, max_history: int = 10) -> str:
19
  """Groq API call with chat history and optional summarization"""
20
 
21
- if not API_KEY:
22
- return "❌ No API Key found"
23
-
24
  if not message.strip():
25
  return "❌ Empty message"
26
 
27
  try:
 
 
 
28
  headers = {
29
  "Authorization": f"Bearer {API_KEY}",
30
  "Content-Type": "application/json"
31
  }
32
 
33
- # Add current message to history with timestamp and topic
34
  chat_history.append({
35
  "role": "user",
36
  "content": message.strip(),
@@ -38,10 +49,7 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
38
  "timestamp": datetime.now().isoformat()
39
  })
40
 
41
- # Limit history to max_history messages
42
  recent_history = chat_history[-max_history:]
43
-
44
- # Prepare messages for API call
45
  messages = [{"role": msg["role"], "content": msg["content"]} for msg in recent_history]
46
 
47
  if summarize:
@@ -50,7 +58,7 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
50
  messages.append({"role": "user", "content": summary_prompt})
51
 
52
  payload = {
53
- "model": "llama-3.3-70b-versatile",
54
  "messages": messages,
55
  "max_tokens": 5000,
56
  "temperature": 0.7
@@ -71,17 +79,15 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
71
  return response_content
72
  return f"❌ No choices in response: {result}"
73
  return f"❌ HTTP {response.status_code}: {response.text}"
74
-
75
  except Exception as e:
76
  return f"❌ Error: {str(e)}"
77
 
78
  def clear_history():
79
- """Clear the chat history"""
80
  chat_history.clear()
81
- return "βœ… Chat history cleared"
82
 
83
  def view_history(topic: str = None):
84
- """View chat history with optional topic filter"""
85
  if not chat_history:
86
  return "❌ No chat history available"
87
 
@@ -92,7 +98,6 @@ def view_history(topic: str = None):
92
  )
93
 
94
  def manual_curl_example():
95
- """Generate example curl command"""
96
  if not API_KEY:
97
  return "❌ No API key available"
98
  return f"""curl -X POST "{API_URL}" \\
@@ -101,41 +106,36 @@ def manual_curl_example():
101
  -d '{{"model": "llama3-8b-8192", "messages": [{{"role": "user", "content": "Hello"}}]}}'
102
  """
103
 
104
- def process_message(message: str, topic: str, summarize: bool):
105
- """Process message and clear input"""
 
 
 
 
106
  response = groq_with_memory(message, topic, summarize)
107
- return response, ""
 
 
108
 
109
  # Gradio Interface
110
- with gr.Blocks(title="Groq Chat Debugger") as demo:
111
- gr.Markdown("## πŸ’¬ Groq API Chat Interface")
112
 
113
  with gr.Tab("Chat"):
 
 
 
 
 
 
114
  with gr.Row():
115
- with gr.Column():
116
- msg_input = gr.Textbox(
117
- label="Your Message",
118
- value="",
119
- placeholder="Tulis di sini..."
120
- )
121
- topic_input = gr.Textbox(
122
- label="Topic",
123
- value="general"
124
- )
125
- summarize_cb = gr.Checkbox(label="Summarize conversation")
126
- send_btn = gr.Button("Send", variant="primary")
127
-
128
- with gr.Column():
129
- response_output = gr.Textbox(
130
- label="Response",
131
- lines=10,
132
- interactive=False
133
- )
134
 
135
  send_btn.click(
136
  process_message,
137
- inputs=[msg_input, topic_input, summarize_cb],
138
- outputs=[response_output, msg_input]
139
  )
140
 
141
  with gr.Tab("History"):
@@ -145,7 +145,7 @@ with gr.Blocks(title="Groq Chat Debugger") as demo:
145
  history_output = gr.Textbox(label="Chat History", lines=10)
146
 
147
  view_btn.click(view_history, inputs=[history_topic], outputs=[history_output])
148
- clear_btn.click(clear_history, outputs=[history_output])
149
 
150
  with gr.Tab("API Tools"):
151
  gr.Markdown(f"""
@@ -159,4 +159,24 @@ with gr.Blocks(title="Groq Chat Debugger") as demo:
159
  curl_btn.click(manual_curl_example, outputs=[curl_output])
160
 
161
  if __name__ == "__main__":
162
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Berikut adalah versi lengkap kode kamu yang sudah diperbarui:
2
+
3
+ Menggunakan gr.Chatbot agar tampilannya seperti ChatGPT (chat di atas, input di bawah).
4
+
5
+ Error No API Key tetap dicek, tapi tidak menyebabkan crash (ditampilkan di chat).
6
+
7
+ Chat history ditampilkan penuh di gr.Chatbot.
8
+
9
+
10
+
11
+ ---
12
+
13
+ βœ… Kode Lengkap (siap copas & jalan):
14
 
15
  import gradio as gr
16
  import requests
 
22
  # Groq API Configuration
23
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
24
  API_KEY = os.getenv("GROQ_API_KEY")
 
25
  print(f"πŸ”‘ API Key Found: {'Yes' if API_KEY else 'No'}")
26
 
27
  # In-memory chat history storage
 
30
  def groq_with_memory(message: str, topic: str = "general", summarize: bool = False, max_history: int = 10) -> str:
31
  """Groq API call with chat history and optional summarization"""
32
 
 
 
 
33
  if not message.strip():
34
  return "❌ Empty message"
35
 
36
  try:
37
+ if not API_KEY:
38
+ return "❌ No API Key found"
39
+
40
  headers = {
41
  "Authorization": f"Bearer {API_KEY}",
42
  "Content-Type": "application/json"
43
  }
44
 
 
45
  chat_history.append({
46
  "role": "user",
47
  "content": message.strip(),
 
49
  "timestamp": datetime.now().isoformat()
50
  })
51
 
 
52
  recent_history = chat_history[-max_history:]
 
 
53
  messages = [{"role": msg["role"], "content": msg["content"]} for msg in recent_history]
54
 
55
  if summarize:
 
58
  messages.append({"role": "user", "content": summary_prompt})
59
 
60
  payload = {
61
+ "model": "llama3-70b-8192",
62
  "messages": messages,
63
  "max_tokens": 5000,
64
  "temperature": 0.7
 
79
  return response_content
80
  return f"❌ No choices in response: {result}"
81
  return f"❌ HTTP {response.status_code}: {response.text}"
82
+
83
  except Exception as e:
84
  return f"❌ Error: {str(e)}"
85
 
86
  def clear_history():
 
87
  chat_history.clear()
88
+ return [], "βœ… Chat history cleared"
89
 
90
  def view_history(topic: str = None):
 
91
  if not chat_history:
92
  return "❌ No chat history available"
93
 
 
98
  )
99
 
100
  def manual_curl_example():
 
101
  if not API_KEY:
102
  return "❌ No API key available"
103
  return f"""curl -X POST "{API_URL}" \\
 
106
  -d '{{"model": "llama3-8b-8192", "messages": [{{"role": "user", "content": "Hello"}}]}}'
107
  """
108
 
109
+ def process_message(message: str, topic: str, summarize: bool, chatbot):
110
+ if not API_KEY:
111
+ chatbot.append(("user", message))
112
+ chatbot.append(("assistant", "❌ No API Key found."))
113
+ return chatbot, ""
114
+
115
  response = groq_with_memory(message, topic, summarize)
116
+ chatbot.append(("user", message))
117
+ chatbot.append(("assistant", response))
118
+ return chatbot, ""
119
 
120
  # Gradio Interface
121
+ with gr.Blocks(title="Groq Chat UI") as demo:
122
+ gr.Markdown("## πŸ’¬ Groq Chat (Like ChatGPT)")
123
 
124
  with gr.Tab("Chat"):
125
+ chatbot = gr.Chatbot(label="Conversation")
126
+
127
+ with gr.Row():
128
+ msg_input = gr.Textbox(placeholder="Tulis pesan di sini...", label="Your Message", lines=2)
129
+ send_btn = gr.Button("Send", variant="primary")
130
+
131
  with gr.Row():
132
+ topic_input = gr.Textbox(value="general", label="Topic")
133
+ summarize_cb = gr.Checkbox(label="Summarize conversation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  send_btn.click(
136
  process_message,
137
+ inputs=[msg_input, topic_input, summarize_cb, chatbot],
138
+ outputs=[chatbot, msg_input]
139
  )
140
 
141
  with gr.Tab("History"):
 
145
  history_output = gr.Textbox(label="Chat History", lines=10)
146
 
147
  view_btn.click(view_history, inputs=[history_topic], outputs=[history_output])
148
+ clear_btn.click(clear_history, outputs=[chatbot, history_output])
149
 
150
  with gr.Tab("API Tools"):
151
  gr.Markdown(f"""
 
159
  curl_btn.click(manual_curl_example, outputs=[curl_output])
160
 
161
  if __name__ == "__main__":
162
+ demo.launch(server_name="0.0.0.0", server_port=7860)
163
+
164
+
165
+ ---
166
+
167
+ πŸ”§ Catatan:
168
+
169
+ Format chat akan muncul mirip ChatGPT.
170
+
171
+ Kalau API Key tidak ada, akan tetap jalan, tapi menampilkan error di dalam kotak chat (tidak crash).
172
+
173
+ Kamu bisa jalankan dengan:
174
+
175
+
176
+ python namafile.py
177
+
178
+
179
+ ---
180
+
181
+ Siap langsung digunakan. Mau saya bantu buat versi Docker-nya juga?
182
+