RoastCalcAI / app.py
Nick088's picture
Update app.py
9ab5f9b verified
import groq
from groq import Groq, AuthenticationError, RateLimitError
import gradio as gr
import re
import json
import os
# Setup Groq
client = groq.Client(api_key=os.environ.get("GROQ_API_KEY"))
model = "llama-3.3-70b-versatile"
def handle_groq_error(e, model_name):
error_data = e.args[0]
if isinstance(error_data, str):
json_match = re.search(r'(\{.*\})', error_data)
if json_match:
json_str = json_match.group(1)
json_str = json_str.replace("'", '"')
error_data = json.loads(json_str)
if isinstance(e, AuthenticationError):
if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
error_message = error_data['error']['message']
raise discord.app_commands.AppCommandError(error_message)
elif isinstance(e, RateLimitError):
if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
error_message = error_data['error']['message']
error_message = re.sub(r'org_[a-zA-Z0-9]+', 'org_(censored)', error_message)
raise discord.app_commands.AppCommandError(error_message)
else:
raise discord.app_commands.AppCommandError(f"Error during Groq API call: {e}")
def calculate_and_roast(expression):
try:
# Basic calculator functionality (limited for safety)
allowed_chars = set("0123456789+-*/(). ")
if not all(char in allowed_chars for char in expression):
return "Invalid input: Only numbers and basic operators (+, -, *, /) are allowed.", None
result = eval(expression)
# Groq API call
try:
prompt = f"Roast me for calculating something as simple as '{expression}'. Make it funny."
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model=model
)
roast = chat_completion.choices[0].message.content
return result, roast
except AuthenticationError as e:
handle_groq_error(e, model)
except RateLimitError as e:
handle_groq_error(e, model)
except (ValueError, TypeError, SyntaxError, ZeroDivisionError) as e:
return f"Calculation error: {e}", None
with gr.Blocks() as interface:
input_expression = gr.Textbox(label="Enter an expression")
calculate_button = gr.Button("Calculate and Roast")
output_result = gr.Textbox(label="Result")
output_roast = gr.Textbox(label="Roast")
calculate_button.click(
fn=calculate_and_roast,
inputs=input_expression,
outputs=[output_result, output_roast],
)
interface.launch(share=True)