CoolFace
Apppublic

waseem112233/java_test_code_app

sourceHugging Faceapache-2.0updated 9mo agoView on Hugging Face
0likes
app.py68 linesDownload Raw Back to root
1import os2import gradio as gr3from google import genai4from google.genai import types5 6# Read API key from environment (set it in HF Spaces: Settings -> Variables and secrets)7GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")8 9if not GEMINI_API_KEY:10    raise RuntimeError("GEMINI_API_KEY is not set in environment variables")11 12# Initialize Gemini client13client = genai.Client(api_key=GEMINI_API_KEY)14MODEL_NAME = "gemini-2.5-flash"  # or "gemini-2.5-pro" if enabled15 16SYSTEM_INSTRUCTION = """17You are 'Educational Tutor Chat', a friendly Java tutor.18- Explain Java concepts simply.19- If user sends code, detect errors and suggest fixes.20- Always show corrected code in `````` code blocks.21"""22 23def chat_with_tutor(message, history):24    """25    Gradio ChatInterface handler.26    - message: current user message (str)27    - history: list of [user, assistant] turns28    Returns: response string29    """30 31    # Build full conversation text from history32    history_text = ""33    for user_msg, assistant_msg in history:34        if user_msg:35            history_text += f"User: {user_msg}\n"36        if assistant_msg:37            history_text += f"Tutor: {assistant_msg}\n"38 39    # Combine system instruction, history, and latest message40    prompt = (41        SYSTEM_INSTRUCTION42        + "\n\nConversation so far:\n"43        + history_text44        + "\nUser: "45        + message46        + "\nTutor:"47    )48 49    try:50        response = client.models.generate_content(51            model=MODEL_NAME,52            contents=[types.Part.from_text(prompt)],53        )54        reply = response.text or "Sorry, I could not generate a response."55    except Exception as e:56        reply = f"An error occurred while contacting the Gemini API: {e}"57 58    return reply59 60demo = gr.ChatInterface(61    fn=chat_with_tutor,62    title="Educational Tutor Chat: Java Coding Assistant",63    description="Ask Java questions, paste code for debugging, and learn interactively.",64)65 66if __name__ == "__main__":67    demo.launch()68