shanzaejaz commited on
Commit
6a28378
·
verified ·
1 Parent(s): e5b75bf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from groq import Groq
3
+ import os
4
+
5
+ # -----------------------------
6
+ # GROQ CLIENT
7
+ # -----------------------------
8
+ # Make sure you add your Groq API key as a "Secret" on HF Spaces:
9
+ # Go to Settings -> Secrets -> Add "GROQ_API_KEY"
10
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
11
+
12
+ # -----------------------------
13
+ # CHAT FUNCTION
14
+ # -----------------------------
15
+ def chat_with_ai(message, history):
16
+ if history is None:
17
+ history = []
18
+
19
+ # Convert history into proper format for Groq
20
+ messages = [
21
+ {"role": "system", "content": "You are a helpful AI assistant."}
22
+ ]
23
+
24
+ for user, bot in history:
25
+ messages.append({"role": "user", "content": user})
26
+ messages.append({"role": "assistant", "content": bot})
27
+
28
+ messages.append({"role": "user", "content": message})
29
+
30
+ # Call Groq
31
+ response = client.chat.completions.create(
32
+ model="llama-3.3-70b-versatile", # latest working model
33
+ messages=messages,
34
+ temperature=0.7,
35
+ max_tokens=1024
36
+ )
37
+
38
+ reply = response.choices[0].message.content
39
+
40
+ history.append((message, reply))
41
+ # Return updated history for chatbot AND empty string for textbox
42
+ return history, history, ""
43
+
44
+ # -----------------------------
45
+ # GRADIO UI
46
+ # -----------------------------
47
+ with gr.Blocks(title="AI Chatbot") as app:
48
+ gr.Markdown("# 🤖 Simple Groq Chatbot")
49
+
50
+ chatbot = gr.Chatbot(height=400)
51
+ msg = gr.Textbox(placeholder="Type your message...")
52
+ clear = gr.Button("Clear")
53
+
54
+ state = gr.State([])
55
+
56
+ # IMPORTANT: add msg as OUTPUT to clear it
57
+ msg.submit(chat_with_ai, [msg, state], [chatbot, state, msg])
58
+ clear.click(lambda: ([], [], ""), None, [chatbot, state, msg])
59
+
60
+ app.launch()