Update app.py
Browse files
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
|
| 6 |
api_key = os.environ.get("GROQ_API")
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def chat_groq(message, history):
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
messages.append({"role": "user", "content": message})
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
reply = completion.choices[0].message.content
|
| 31 |
-
return reply
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 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()
|