syeda-Rija20 commited on
Commit
08999c8
Β·
verified Β·
1 Parent(s): e8de366

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -39
app.py CHANGED
@@ -1,69 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  from groq import Groq
3
  import gradio as gr
4
 
5
- # Initialize client
6
  client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
7
 
8
  # System prompt
9
  SYSTEM_PROMPT = {
10
  "role": "system",
11
- "content": "You are a helpful, friendly AI assistant."
12
  }
13
 
14
- # Clean message (IMPORTANT FIX)
15
- def clean_message(msg):
16
- return {
17
- "role": msg.get("role"),
18
- "content": msg.get("content")
19
- }
20
-
21
- # Chatbot function
22
- def chatbot(message, history):
23
  try:
24
- messages = [SYSTEM_PROMPT]
 
 
 
25
 
26
- # Limit history
27
- history = history[-6:] if history else []
 
28
 
29
- for item in history:
30
- # Case 1: tuple (user, bot)
31
- if isinstance(item, (list, tuple)) and len(item) == 2:
32
- user_msg, bot_msg = item
 
 
 
33
 
34
- if user_msg:
35
- messages.append({"role": "user", "content": str(user_msg)})
36
- if bot_msg:
37
- messages.append({"role": "assistant", "content": str(bot_msg)})
 
 
 
38
 
39
- # Case 2: dict (REMOVE metadata)
40
- elif isinstance(item, dict):
41
- if "role" in item and "content" in item:
42
- messages.append(clean_message(item))
43
 
44
- # Add current message
45
- messages.append({"role": "user", "content": str(message)})
46
-
47
- # Call Groq
48
- response = client.chat.completions.create(
49
  model="llama-3.3-70b-versatile",
50
  messages=messages,
51
  temperature=0.7,
52
  max_tokens=1024,
 
53
  )
54
 
55
- return response.choices[0].message.content.strip()
 
 
 
 
 
56
 
57
  except Exception as e:
58
- return f"⚠️ Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
 
 
 
60
 
61
- # UI
62
- demo = gr.ChatInterface(
63
- fn=chatbot,
64
- title="πŸš€ Groq AI Chatbot",
65
- description="Fast chatbot powered by Groq",
66
- )
67
 
68
  # Launch
69
  if __name__ == "__main__":
 
1
+ # import os
2
+ # from groq import Groq
3
+ # import gradio as gr
4
+
5
+ # # Initialize client
6
+ # client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
7
+
8
+ # # System prompt
9
+ # SYSTEM_PROMPT = {
10
+ # "role": "system",
11
+ # "content": "You are a helpful, friendly AI assistant."
12
+ # }
13
+
14
+ # # Clean message (IMPORTANT FIX)
15
+ # def clean_message(msg):
16
+ # return {
17
+ # "role": msg.get("role"),
18
+ # "content": msg.get("content")
19
+ # }
20
+
21
+ # # Chatbot function
22
+ # def chatbot(message, history):
23
+ # try:
24
+ # messages = [SYSTEM_PROMPT]
25
+
26
+ # # Limit history
27
+ # history = history[-6:] if history else []
28
+
29
+ # for item in history:
30
+ # # Case 1: tuple (user, bot)
31
+ # if isinstance(item, (list, tuple)) and len(item) == 2:
32
+ # user_msg, bot_msg = item
33
+
34
+ # if user_msg:
35
+ # messages.append({"role": "user", "content": str(user_msg)})
36
+ # if bot_msg:
37
+ # messages.append({"role": "assistant", "content": str(bot_msg)})
38
+
39
+ # # Case 2: dict (REMOVE metadata)
40
+ # elif isinstance(item, dict):
41
+ # if "role" in item and "content" in item:
42
+ # messages.append(clean_message(item))
43
+
44
+ # # Add current message
45
+ # messages.append({"role": "user", "content": str(message)})
46
+
47
+ # # Call Groq
48
+ # response = client.chat.completions.create(
49
+ # model="llama-3.3-70b-versatile",
50
+ # messages=messages,
51
+ # temperature=0.7,
52
+ # max_tokens=1024,
53
+ # )
54
+
55
+ # return response.choices[0].message.content.strip()
56
+
57
+ # except Exception as e:
58
+ # return f"⚠️ Error: {str(e)}"
59
+
60
+
61
+ # # UI
62
+ # demo = gr.ChatInterface(
63
+ # fn=chatbot,
64
+ # title="πŸš€ Groq AI Chatbot",
65
+ # description="Fast chatbot powered by Groq",
66
+ # )
67
+
68
+ # # Launch
69
+ # if __name__ == "__main__":
70
+ # demo.launch()
71
  import os
72
  from groq import Groq
73
  import gradio as gr
74
 
75
+ # Initialize Groq
76
  client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
77
 
78
  # System prompt
79
  SYSTEM_PROMPT = {
80
  "role": "system",
81
+ "content": "You are a helpful, friendly AI assistant. Answer clearly."
82
  }
83
 
84
+ # Extract text from uploaded file (basic version)
85
+ def read_file(file):
86
+ if file is None:
87
+ return ""
88
+
 
 
 
 
89
  try:
90
+ content = file.read().decode("utf-8", errors="ignore")
91
+ return content[:3000] # limit size
92
+ except:
93
+ return ""
94
 
95
+ # Streaming chatbot
96
+ def chatbot(message, history, file):
97
+ messages = [SYSTEM_PROMPT]
98
 
99
+ # Add file content if uploaded
100
+ file_text = read_file(file)
101
+ if file_text:
102
+ messages.append({
103
+ "role": "user",
104
+ "content": f"Here is a document:\n{file_text}"
105
+ })
106
 
107
+ # Add history safely
108
+ if history:
109
+ for user_msg, bot_msg in history[-5:]:
110
+ if user_msg:
111
+ messages.append({"role": "user", "content": str(user_msg)})
112
+ if bot_msg:
113
+ messages.append({"role": "assistant", "content": str(bot_msg)})
114
 
115
+ # Add current message
116
+ messages.append({"role": "user", "content": message})
 
 
117
 
118
+ try:
119
+ # STREAMING RESPONSE
120
+ stream = client.chat.completions.create(
 
 
121
  model="llama-3.3-70b-versatile",
122
  messages=messages,
123
  temperature=0.7,
124
  max_tokens=1024,
125
+ stream=True,
126
  )
127
 
128
+ partial_response = ""
129
+
130
+ for chunk in stream:
131
+ if chunk.choices[0].delta.content:
132
+ partial_response += chunk.choices[0].delta.content
133
+ yield partial_response # streaming output
134
 
135
  except Exception as e:
136
+ yield f"⚠️ Error: {str(e)}"
137
+
138
+
139
+ # Custom UI with Blocks (modern design)
140
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
141
+
142
+ gr.Markdown("# πŸš€ Groq AI Chatbot")
143
+ gr.Markdown("πŸ’¬ Chat like ChatGPT | πŸ“„ Upload file support")
144
+
145
+ chatbot_ui = gr.Chatbot(height=400)
146
+
147
+ with gr.Row():
148
+ msg = gr.Textbox(
149
+ placeholder="Type your message...",
150
+ scale=4
151
+ )
152
+ file = gr.File(label="πŸ“„ Upload file", scale=1)
153
+
154
+ send = gr.Button("Send πŸš€")
155
+
156
+ def user_submit(user_message, history, file):
157
+ return "", history + [[user_message, None]], file
158
+
159
+ def bot_response(history, file):
160
+ user_message = history[-1][0]
161
 
162
+ for response in chatbot(user_message, history[:-1], file):
163
+ history[-1][1] = response
164
+ yield history
165
 
166
+ send.click(user_submit, [msg, chatbot_ui, file], [msg, chatbot_ui, file])\
167
+ .then(bot_response, [chatbot_ui, file], chatbot_ui)
 
 
 
 
168
 
169
  # Launch
170
  if __name__ == "__main__":