Spaces:
Running
Running
import gradio as gr | |
import os | |
from groq import Groq | |
import uuid | |
import markdown | |
def generate_mba_content(topic, api_key): | |
# Setting up the system prompt (assumed to be securely stored in environment variable) | |
system_prompt= os.environ("system_prompt") | |
# Initialize Groq client with user-provided API key | |
try: | |
client = Groq(api_key=api_key) | |
except Exception as e: | |
return f"Error: Failed to initialize Groq client. Check your API key. Details: {str(e)}" | |
# Replace [TOPIC] in the system prompt with the user-provided topic | |
prompt = system_prompt.replace("[TOPIC]", topic) | |
try: | |
# Generate content using Groq API | |
response = client.chat.completions.create( | |
model="llama3-70b-8192", | |
messages=[ | |
{"role": "system", "content": prompt}, | |
{"role": "user", "content": f"Generate content for the topic: {topic}"} | |
], | |
temperature=0.7, | |
max_tokens=1000 | |
) | |
content = response.choices[0].message.content | |
# Convert to markdown if not already in the correct format | |
if not content.startswith("#"): | |
content = markdown.markdown(content) | |
return content | |
except Exception as e: | |
return f"Error: Failed to generate content. Details: {str(e)}" | |
finally: | |
# Clear API key from memory | |
api_key = None | |
if 'client' in locals(): | |
del client | |
# Define Gradio interface | |
def gradio_app(): | |
with gr.Blocks(title="MBA Content Generator") as app: | |
gr.Markdown("# MBA Content Generator") | |
gr.Markdown("Enter a topic and your Groq API key to generate MBA-style content in markdown format.") | |
topic_input = gr.Textbox( | |
label="Topic", | |
placeholder="e.g., Strategic Management, Supply Chain Optimization", | |
lines=1 | |
) | |
api_key_input = gr.Textbox( | |
label="Groq API Key", | |
placeholder="Enter your Groq API key here", | |
type="password", | |
lines=1 | |
) | |
output = gr.Markdown(label="Generated Content") | |
submit_btn = gr.Button("Generate Content") | |
submit_btn.click( | |
fn=generate_mba_content, | |
inputs=[topic_input, api_key_input], | |
outputs=output | |
) | |
gr.Markdown(""" | |
**Note:** Your API key is used securely for this session and cleared from memory afterward. | |
This app is designed for deployment on Hugging Face Spaces. Ensure the environment variable | |
`MBA_SYSTEM_PROMPT` is set securely in your deployment configuration. | |
""") | |
return app | |
# Launch the app (for local testing; Hugging Face Spaces handles deployment) | |
if __name__ == "__main__": | |
app = gradio_app() | |
app.launch() |