Affan8 commited on
Commit
b07f5bd
·
verified ·
1 Parent(s): d8a48a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -28
app.py CHANGED
@@ -2,40 +2,45 @@ import os
2
  import gradio as gr
3
  from groq import Groq
4
 
5
- # Read API key from Hugging Face Space secret
6
  api_key = os.environ.get("GROQ_API")
7
 
 
 
 
 
 
 
 
 
8
  def chat_groq(message, history):
9
- """
10
- message: latest user message (string)
11
- history: list of [user,bot] pairs from Gradio
12
- """
13
- try:
14
- system_prompt = "You are a helpful AI assistant."
15
-
16
- messages = [{"role": "system", "content": system_prompt}]
17
-
18
- for user_msg, bot_msg in history:
19
- messages.append({"role": "user", "content": user_msg})
20
- if bot_msg:
 
21
  messages.append({"role": "user", "content": message})
22
 
23
- completion =client.chat.completions.create(
24
- model= MODEL_NAME,
25
- messages=messages,
26
- max_tokens=1024,
27
- temperature=0.7
28
- )
29
-
30
- reply = completion.choices[0].message.content
31
- return reply
32
 
33
- except Exception as e:
34
- return f"Error: {e}"
35
 
36
- ui = gr.ChatInterface(
37
- fn=chat_groq,
38
- title="Affan's GenAI App (Groq)"
39
- )
40
 
 
41
  ui.launch()
 
2
  import gradio as gr
3
  from groq import Groq
4
 
5
+ # Read API key from environment (Hugging Face Spaces secret)
6
  api_key = os.environ.get("GROQ_API")
7
 
8
+ if not api_key:
9
+ raise ValueError("No Groq API key found. Please add it as a secret.")
10
+
11
+ # Initialize Groq client
12
+ client = Groq(api_key=api_key)
13
+
14
+ MODEL_NAME = "openai/gpt-oss-safeguard-20b"
15
+
16
  def chat_groq(message, history):
17
+ try:
18
+ system_prompt = "You are a helpful AI assistant."
19
+ messages = [{"role": "system", "content": system_prompt}]
20
+
21
+ # Handle history safely
22
+ for turn in history:
23
+ if isinstance(turn, list) and len(turn) == 2:
24
+ user_msg, bot_msg = turn
25
+ messages.append({"role": "user", "content": user_msg})
26
+ if bot_msg:
27
+ messages.append({"role": "assistant", "content": bot_msg})
28
+
29
+ # Add latest user message
30
  messages.append({"role": "user", "content": message})
31
 
32
+ completion = client.chat.completions.create(
33
+ model=MODEL_NAME,
34
+ messages=messages,
35
+ max_tokens=1024,
36
+ temperature=0.7
37
+ )
 
 
 
38
 
39
+ reply = completion.choices[0].message.content
40
+ return reply
41
 
42
+ except Exception as e:
43
+ return f"Error: {e}"
 
 
44
 
45
+ ui = gr.ChatInterface(fn=chat_groq, title="Affan's GenAI App (Groq)")
46
  ui.launch()