shukdevdatta123 commited on
Commit
378ea6c
·
verified ·
1 Parent(s): 4e8a031

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -90
app.py CHANGED
@@ -1,110 +1,198 @@
1
  import gradio as gr
2
- from openai import OpenAI
 
 
 
3
 
4
- def process_language(api_key, task, user_message):
5
- if not api_key:
6
- return "⚠️ Please enter your Groq API Key"
 
 
7
 
8
- client = OpenAI(
9
- base_url="https://api.groq.com/openai/v1",
10
- api_key=api_key
11
- )
12
-
13
- system_message = ("You are a bilingual language tutor. Respond in the language used in the question. "
14
- "For conversations, keep exchanges natural. For grammar explanations, provide "
15
- "detailed rules with English/Chinese examples.")
16
 
 
 
 
 
17
  try:
18
- completion = client.chat.completions.create(
19
- model="groq-model-v1",
20
- messages=[
21
- {"role": "system", "content": system_message},
22
- {"role": "user", "content": f"{task}: {user_message}"}
23
- ]
24
  )
25
- return completion.choices[0].message.content
 
 
 
 
26
  except Exception as e:
27
- return f" Error: {str(e)}"
28
 
29
- def process_pseudocode(api_key, user_idea):
30
- if not api_key:
31
- return "⚠️ Please enter your Groq API Key"
 
 
 
 
 
32
 
33
- client = OpenAI(
34
- base_url="https://api.groq.com/openai/v1",
35
- api_key=api_key
36
- )
37
-
38
- system_message = ("Generate clear, step-by-step pseudocode for the given idea. "
39
- "Use programming conventions but avoid actual code. Structure your answer with:")
40
 
41
  try:
42
- completion = client.chat.completions.create(
43
- model="groq-model-v1",
44
- messages=[
45
- {"role": "system", "content": system_message},
46
- {"role": "user", "content": user_idea}
47
- ]
 
 
 
 
 
 
 
 
 
 
 
48
  )
49
- return completion.choices[0].message.content
 
 
 
 
 
 
50
  except Exception as e:
51
- return f"Error: {str(e)}"
 
 
 
 
 
52
 
53
- def process_algorithm(api_key, challenge):
54
- if not api_key:
55
- return "⚠️ Please enter your Groq API Key"
 
 
 
 
 
 
 
 
 
 
56
 
57
- client = OpenAI(
58
- base_url="https://api.groq.com/openai/v1",
59
- api_key=api_key
60
- )
 
 
 
 
 
 
 
61
 
62
- system_message = ("Suggest multiple approaches to solve the problem. Compare time/space complexity, "
63
- "trade-offs, and ideal use cases. Structure your answer clearly.")
 
 
 
 
 
64
 
65
- try:
66
- completion = client.chat.completions.create(
67
- model="groq-model-v1",
68
- messages=[
69
- {"role": "system", "content": system_message},
70
- {"role": "user", "content": challenge}
71
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  )
73
- return completion.choices[0].message.content
74
- except Exception as e:
75
- return f"❌ Error: {str(e)}"
76
-
77
- with gr.Blocks(theme=gr.themes.Soft()) as app:
78
- gr.Markdown("# 🚀 Code & Language Learning Assistant (Groq Version)")
79
- api_key = gr.Textbox(label="Enter your Groq API Key", type="password")
80
 
81
- with gr.Tabs():
82
- with gr.Tab("🇬🇧/🇨🇳 Language Learning Buddy"):
83
- with gr.Row():
84
- with gr.Column():
85
- task_type = gr.Radio(
86
- choices=["Simulate bilingual conversation", "Explain grammar rules"],
87
- label="Select Task Type"
88
- )
89
- lang_input = gr.Textbox(label="Your message/question", lines=3)
90
- lang_btn = gr.Button("Get Assistance")
91
- lang_output = gr.Textbox(label="Assistant Response", interactive=False, lines=10)
92
- lang_btn.click(process_language, [api_key, task_type, lang_input], lang_output)
93
-
94
- with gr.Tab("📝 Pseudocode Explainer"):
95
- with gr.Row():
96
- with gr.Column():
97
- pseudo_input = gr.Textbox(label="Your idea (e.g., 'How to build a calculator app')", lines=3)
98
- pseudo_btn = gr.Button("Generate Steps")
99
- pseudo_output = gr.Textbox(label="Step-by-Step Pseudocode", interactive=False, lines=10)
100
- pseudo_btn.click(process_pseudocode, [api_key, pseudo_input], pseudo_output)
101
-
102
- with gr.Tab("🧠 Algorithm Brainstormer"):
103
- with gr.Row():
104
- with gr.Column():
105
- algo_input = gr.Textbox(label="Challenge description (e.g., 'Sort list without built-in functions')", lines=3)
106
- algo_btn = gr.Button("Brainstorm Solutions")
107
- algo_output = gr.Textbox(label="Suggested Approaches", interactive=False, lines=10)
108
- algo_btn.click(process_algorithm, [api_key, algo_input], algo_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- app.launch()
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import re
4
+ from groq import Groq
5
+ from groq.errors import AuthenticationError, APIError
6
 
7
+ def validate_api_key(api_key):
8
+ """Validate if the API key has the correct format."""
9
+ # Basic format check for Groq API keys (they typically start with 'gsk_')
10
+ if not api_key.strip():
11
+ return False, "API key cannot be empty"
12
 
13
+ if not api_key.startswith("gsk_"):
14
+ return False, "Invalid API key format. Groq API keys typically start with 'gsk_'"
 
 
 
 
 
 
15
 
16
+ return True, "API key looks valid"
17
+
18
+ def test_api_connection(api_key):
19
+ """Test the API connection with a minimal request."""
20
  try:
21
+ client = Groq(api_key=api_key)
22
+ # Making a minimal API call to test the connection
23
+ client.chat.completions.create(
24
+ model="deepseek-r1-distill-llama-70b",
25
+ messages=[{"role": "user", "content": "test"}],
26
+ max_tokens=5
27
  )
28
+ return True, "API connection successful"
29
+ except AuthenticationError:
30
+ return False, "Authentication failed: Invalid API key"
31
+ except APIError as e:
32
+ return False, f"API Error: {str(e)}"
33
  except Exception as e:
34
+ return False, f"Error connecting to Groq API: {str(e)}"
35
 
36
+ def chat_with_groq(api_key, model, user_message, temperature, max_tokens, top_p, chat_history):
37
+ """
38
+ Interact with the Groq API to get a response.
39
+ """
40
+ # Validate API key
41
+ is_valid, message = validate_api_key(api_key)
42
+ if not is_valid:
43
+ return chat_history + [[user_message, f"Error: {message}"]]
44
 
45
+ # Test API connection
46
+ connection_valid, connection_message = test_api_connection(api_key)
47
+ if not connection_valid:
48
+ return chat_history + [[user_message, f"Error: {connection_message}"]]
 
 
 
49
 
50
  try:
51
+ # Format history for the API
52
+ messages = []
53
+ for human, assistant in chat_history:
54
+ messages.append({"role": "user", "content": human})
55
+ messages.append({"role": "assistant", "content": assistant})
56
+
57
+ # Add the current message
58
+ messages.append({"role": "user", "content": user_message})
59
+
60
+ # Create the client and make the API call
61
+ client = Groq(api_key=api_key)
62
+ response = client.chat.completions.create(
63
+ model=model,
64
+ messages=messages,
65
+ temperature=temperature,
66
+ max_tokens=max_tokens,
67
+ top_p=top_p
68
  )
69
+
70
+ # Extract the response text
71
+ assistant_response = response.choices[0].message.content
72
+
73
+ # Return updated chat history
74
+ return chat_history + [[user_message, assistant_response]]
75
+
76
  except Exception as e:
77
+ error_message = f"Error: {str(e)}"
78
+ return chat_history + [[user_message, error_message]]
79
+
80
+ def clear_conversation():
81
+ """Clear the conversation history."""
82
+ return []
83
 
84
+ # Define available models
85
+ models = [
86
+ "deepseek-r1-distill-llama-70b",
87
+ "llama3-70b-8192",
88
+ "llama3-8b-8192",
89
+ "mixtral-8x7b-32768",
90
+ "gemma-7b-it"
91
+ ]
92
+
93
+ # Create the Gradio interface
94
+ with gr.Blocks(title="Groq AI Chat Interface") as app:
95
+ gr.Markdown("# Groq AI Chat Interface")
96
+ gr.Markdown("Enter your Groq API key to start chatting with AI models.")
97
 
98
+ with gr.Row():
99
+ with gr.Column(scale=2):
100
+ api_key_input = gr.Textbox(
101
+ label="Groq API Key",
102
+ placeholder="Enter your Groq API key (starts with gsk_)",
103
+ type="password"
104
+ )
105
+
106
+ with gr.Column(scale=1):
107
+ test_button = gr.Button("Test API Connection")
108
+ api_status = gr.Textbox(label="API Status", interactive=False)
109
 
110
+ with gr.Row():
111
+ with gr.Column():
112
+ model_dropdown = gr.Dropdown(
113
+ choices=models,
114
+ label="Select Model",
115
+ value="deepseek-r1-distill-llama-70b"
116
+ )
117
 
118
+ with gr.Row():
119
+ with gr.Column():
120
+ with gr.Accordion("Advanced Settings", open=False):
121
+ temperature_slider = gr.Slider(
122
+ minimum=0.0, maximum=1.0, value=0.7, step=0.01,
123
+ label="Temperature (higher = more creative, lower = more focused)"
124
+ )
125
+ max_tokens_slider = gr.Slider(
126
+ minimum=256, maximum=8192, value=4096, step=256,
127
+ label="Max Tokens (maximum length of response)"
128
+ )
129
+ top_p_slider = gr.Slider(
130
+ minimum=0.0, maximum=1.0, value=0.95, step=0.01,
131
+ label="Top P (nucleus sampling probability threshold)"
132
+ )
133
+
134
+ chatbot = gr.Chatbot(label="Conversation", height=500)
135
+
136
+ with gr.Row():
137
+ message_input = gr.Textbox(
138
+ label="Your Message",
139
+ placeholder="Type your message here...",
140
+ lines=3
141
  )
 
 
 
 
 
 
 
142
 
143
+ with gr.Row():
144
+ submit_button = gr.Button("Send", variant="primary")
145
+ clear_button = gr.Button("Clear Conversation")
146
+
147
+ # Connect components with functions
148
+ submit_button.click(
149
+ fn=chat_with_groq,
150
+ inputs=[
151
+ api_key_input,
152
+ model_dropdown,
153
+ message_input,
154
+ temperature_slider,
155
+ max_tokens_slider,
156
+ top_p_slider,
157
+ chatbot
158
+ ],
159
+ outputs=chatbot
160
+ ).then(
161
+ fn=lambda: "",
162
+ inputs=None,
163
+ outputs=message_input
164
+ )
165
+
166
+ message_input.submit(
167
+ fn=chat_with_groq,
168
+ inputs=[
169
+ api_key_input,
170
+ model_dropdown,
171
+ message_input,
172
+ temperature_slider,
173
+ max_tokens_slider,
174
+ top_p_slider,
175
+ chatbot
176
+ ],
177
+ outputs=chatbot
178
+ ).then(
179
+ fn=lambda: "",
180
+ inputs=None,
181
+ outputs=message_input
182
+ )
183
+
184
+ clear_button.click(
185
+ fn=clear_conversation,
186
+ inputs=None,
187
+ outputs=chatbot
188
+ )
189
+
190
+ test_button.click(
191
+ fn=test_api_connection,
192
+ inputs=[api_key_input],
193
+ outputs=[api_status]
194
+ )
195
 
196
+ # Launch the app
197
+ if __name__ == "__main__":
198
+ app.launch(share=False)