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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -50
app.py CHANGED
@@ -1,17 +1,3 @@
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
17
  import os
@@ -22,7 +8,7 @@ from datetime import datetime
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
28
  chat_history: List[Dict[str, str]] = []
@@ -31,11 +17,11 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
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}",
@@ -77,19 +63,19 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
77
  "timestamp": datetime.now().isoformat()
78
  })
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
 
94
  filtered = [msg for msg in chat_history if topic is None or msg["topic"] == topic]
95
  return "\n".join(
@@ -99,7 +85,7 @@ def view_history(topic: str = None):
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}" \\
104
  -H "Authorization: Bearer {API_KEY}" \\
105
  -H "Content-Type: application/json" \\
@@ -109,7 +95,7 @@ def manual_curl_example():
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)
@@ -119,8 +105,8 @@ def process_message(message: str, topic: str, summarize: bool, 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
 
@@ -149,9 +135,9 @@ with gr.Blocks(title="Groq Chat UI") as demo:
149
 
150
  with gr.Tab("API Tools"):
151
  gr.Markdown(f"""
152
- **API Status:** {'βœ… Ready' if API_KEY else '❌ No API Key'}
153
- **Endpoint:** `{API_URL}`
154
- **Models:** `llama3-8b-8192`, `llama3-70b-8192`, `mixtral-8x7b-32768`
155
  """)
156
 
157
  curl_btn = gr.Button("Generate cURL Example")
@@ -159,24 +145,4 @@ with gr.Blocks(title="Groq Chat UI") 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)
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
 
8
  # Groq API Configuration
9
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
  API_KEY = os.getenv("GROQ_API_KEY")
11
+ print(f"API Key Found: {'Yes' if API_KEY else 'No'}")
12
 
13
  # In-memory chat history storage
14
  chat_history: List[Dict[str, str]] = []
 
17
  """Groq API call with chat history and optional summarization"""
18
 
19
  if not message.strip():
20
+ return "Empty message"
21
 
22
  try:
23
  if not API_KEY:
24
+ return "No API Key found"
25
 
26
  headers = {
27
  "Authorization": f"Bearer {API_KEY}",
 
63
  "timestamp": datetime.now().isoformat()
64
  })
65
  return response_content
66
+ return f"No choices in response: {result}"
67
+ return f"HTTP {response.status_code}: {response.text}"
68
 
69
  except Exception as e:
70
+ return f"Error: {str(e)}"
71
 
72
  def clear_history():
73
  chat_history.clear()
74
+ return [], "Chat history cleared"
75
 
76
  def view_history(topic: str = None):
77
  if not chat_history:
78
+ return "No chat history available"
79
 
80
  filtered = [msg for msg in chat_history if topic is None or msg["topic"] == topic]
81
  return "\n".join(
 
85
 
86
  def manual_curl_example():
87
  if not API_KEY:
88
+ return "No API key available"
89
  return f"""curl -X POST "{API_URL}" \\
90
  -H "Authorization: Bearer {API_KEY}" \\
91
  -H "Content-Type: application/json" \\
 
95
  def process_message(message: str, topic: str, summarize: bool, chatbot):
96
  if not API_KEY:
97
  chatbot.append(("user", message))
98
+ chatbot.append(("assistant", "No API Key found."))
99
  return chatbot, ""
100
 
101
  response = groq_with_memory(message, topic, summarize)
 
105
 
106
  # Gradio Interface
107
  with gr.Blocks(title="Groq Chat UI") as demo:
108
+ gr.Markdown("## Groq Chat UI")
109
+
110
  with gr.Tab("Chat"):
111
  chatbot = gr.Chatbot(label="Conversation")
112
 
 
135
 
136
  with gr.Tab("API Tools"):
137
  gr.Markdown(f"""
138
+ API Status: {"Ready" if API_KEY else "No API Key"}
139
+ Endpoint: {API_URL}
140
+ Models: llama3-8b-8192, llama3-70b-8192, mixtral-8x7b-32768
141
  """)
142
 
143
  curl_btn = gr.Button("Generate cURL Example")
 
145
  curl_btn.click(manual_curl_example, outputs=[curl_output])
146
 
147
  if __name__ == "__main__":
148
+ demo.launch(server_name="0.0.0.0", server_port=7860)