# Import required libraries import os # Used to access environment variables (API keys) import gradio as gr # Used to create a simple web UI from groq import Groq # Groq SDK to interact with Groq LLM API # ------------------------------------------------------------------- # Read the Groq API key from environment variables # In Hugging Face Spaces, secrets like API keys are stored securely # in Settings -> Secrets and injected as environment variables. # This avoids hardcoding sensitive credentials in the source code. # ------------------------------------------------------------------- api_key = os.environ.get("GROQ_API_KEY") # ------------------------------------------------------------------- # Initialize the Groq client only if the API key is available. # If the key is missing, we set the client to None so we can # handle the error gracefully instead of crashing the app. # ------------------------------------------------------------------- if api_key: client = Groq(api_key=api_key) else: client = None # ------------------------------------------------------------------- # Core function that performs the AI code review. # This function will be triggered when a user submits code # through the Gradio interface. # ------------------------------------------------------------------- def review_code(code): # --------------------------------------------------------------- # Basic validation: check if user submitted empty input. # strip() removes whitespace and newline characters. # --------------------------------------------------------------- if not code.strip(): return "⚠️ Please paste some code before submitting." # --------------------------------------------------------------- # Ensure the Groq client is initialized. # If the API key is missing, inform the user instead of failing. # --------------------------------------------------------------- if client is None: return "❌ Groq API key not found. Please add GROQ_API_KEY in Hugging Face Space Secrets." # --------------------------------------------------------------- # Prompt Engineering: # We construct a structured prompt to guide the LLM to act # as a professional code reviewer and provide useful feedback. # --------------------------------------------------------------- prompt = f""" You are an expert software engineer acting as a code reviewer. Analyze the following code and provide feedback on: 1. Readability 2. Structure 3. Maintainability 4. Best Practices Also suggest an improved version of the code. Code: {code} """ try: # ----------------------------------------------------------- # Send request to Groq LLM using the chat completion API. # # Model used: # llama-3.3-70b-versatile # A powerful general-purpose model suitable for reasoning # and code analysis. # # Temperature: # Lower value (0.2) ensures more deterministic responses, # which is ideal for code analysis instead of creativity. # ----------------------------------------------------------- completion = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "user", "content": prompt} ], temperature=0.2 ) # ----------------------------------------------------------- # Extract the generated AI response from the API result # and return it to the Gradio interface. # ----------------------------------------------------------- return completion.choices[0].message.content except Exception as e: # ----------------------------------------------------------- # Error handling: # If something goes wrong (API error, network issue, etc.), # we catch the exception and display the error message # instead of crashing the application. # ----------------------------------------------------------- return f"⚠️ Error while reviewing code: {str(e)}" # ------------------------------------------------------------------- # Create the Gradio user interface. # Gradio automatically creates a web application from this config. # ------------------------------------------------------------------- demo = gr.Interface( # Function that will run when user submits input fn=review_code, # Input component: a code editor with syntax highlighting inputs=gr.Code( label="Paste your code here", language="python" ), # Output component: rendered as Markdown for better formatting outputs=gr.Markdown(label="AI Code Review"), # UI Title title="Smart Code Reviewer", # Description shown under the title description="AI assistant that reviews code for readability, structure, maintainability, and best practices." ) # ------------------------------------------------------------------- # Launch the Gradio application. # On Hugging Face Spaces this automatically deploys # the interface as a public web app. # ------------------------------------------------------------------- demo.launch()