Spaces:
Running
Running
File size: 2,843 Bytes
0efc631 2785c7b 0efc631 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
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() |