Spaces:
Runtime error
Runtime error
Download app.py from broccoli0510/CodeTutor: direct link, hf CLI and curl.
- Browser
- Download file 5.3 kB
-
https://huggingface.co/spaces/broccoli0510/CodeTutor/resolve/main/app.py
- Command line
-
hf download hf://spaces/broccoli0510/CodeTutor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/broccoli0510/CodeTutor/resolve/main/app.py
5.3 kB
| """CodeTutor - a programming helper chatbot powered by an open LLM on Hugging Face.""" | |
| import os | |
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| # Override with the MODEL_ID Space variable; add an HF_TOKEN secret for authentication. | |
| DEFAULT_MODEL = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct") | |
| MODELS = list( | |
| dict.fromkeys( | |
| [ | |
| DEFAULT_MODEL, | |
| "Qwen/Qwen2.5-Coder-32B-Instruct", | |
| "meta-llama/Llama-3.3-70B-Instruct", | |
| "deepseek-ai/DeepSeek-V3-0324", | |
| ] | |
| ) | |
| ) | |
| LANGUAGES = [ | |
| "Any", | |
| "Python", | |
| "JavaScript", | |
| "TypeScript", | |
| "Java", | |
| "C", | |
| "C++", | |
| "C#", | |
| "Go", | |
| "Rust", | |
| "SQL", | |
| "HTML/CSS", | |
| "Bash", | |
| ] | |
| MODES = { | |
| "Explain": "Explain concepts and code clearly, step by step, using small examples.", | |
| "Debug": ( | |
| "Help find and fix bugs. Identify the root cause first, explain why it happens, " | |
| "then show the corrected code." | |
| ), | |
| "Review": ( | |
| "Review the code for correctness, readability, performance and security. " | |
| "Give concrete, prioritized suggestions with improved snippets." | |
| ), | |
| "Write code": ( | |
| "Write clean, working, well-commented code that solves the request, " | |
| "then briefly explain how it works." | |
| ), | |
| "Socratic tutor": ( | |
| "Act as a patient tutor. Do not give the full solution right away; guide the student " | |
| "with hints and questions so they reach the answer themselves." | |
| ), | |
| } | |
| LEVELS = ["Beginner", "Intermediate", "Advanced"] | |
| def build_system_prompt(language: str, mode: str, level: str) -> str: | |
| lang = "" if language == "Any" else f" The student is working in {language}." | |
| return ( | |
| "You are CodeTutor, a friendly and expert programming assistant." | |
| f"{lang} The student's level is {level}; adjust vocabulary and depth accordingly. " | |
| f"{MODES[mode]} Always put code in fenced Markdown blocks with the language tag. " | |
| "If the request is ambiguous, ask a short clarifying question." | |
| ) | |
| def content_to_text(content) -> str: | |
| """Flatten Gradio message content (str, dict or list of parts) into plain text.""" | |
| if isinstance(content, str): | |
| return content | |
| if isinstance(content, dict): | |
| return content.get("text", "") or "" | |
| if isinstance(content, (list, tuple)): | |
| return "\n".join(filter(None, (content_to_text(c) for c in content))) | |
| return "" | |
| def respond(message, history, language, mode, level, model, max_tokens, temperature): | |
| messages = [{"role": "system", "content": build_system_prompt(language, mode, level)}] | |
| for turn in history: | |
| text = content_to_text(turn.get("content")) | |
| if text and turn.get("role") in ("user", "assistant"): | |
| messages.append({"role": turn["role"], "content": text}) | |
| messages.append({"role": "user", "content": content_to_text(message)}) | |
| client = InferenceClient(model=model, token=os.getenv("HF_TOKEN")) | |
| response = "" | |
| try: | |
| for chunk in client.chat_completion( | |
| messages, | |
| max_tokens=int(max_tokens), | |
| temperature=float(temperature), | |
| stream=True, | |
| ): | |
| if not chunk.choices: | |
| continue | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| response += delta | |
| yield response | |
| except Exception as e: | |
| raise gr.Error(f"Model request failed: {e}") | |
| with gr.Blocks(title="CodeTutor") as demo: | |
| gr.Markdown( | |
| "# 💻 CodeTutor\n" | |
| "Your AI programming helper — ask it to explain, debug, review or write code. " | |
| "Pick a mode and language in **Settings** below the chat." | |
| ) | |
| gr.ChatInterface( | |
| respond, | |
| chatbot=gr.Chatbot(height=520, buttons=["copy", "copy_all"], label="CodeTutor"), | |
| textbox=gr.Textbox( | |
| placeholder="Paste your code or ask a programming question...", | |
| lines=3, | |
| max_lines=20, | |
| submit_btn=True, | |
| ), | |
| additional_inputs_accordion=gr.Accordion("⚙️ Settings", open=False), | |
| additional_inputs=[ | |
| gr.Dropdown(LANGUAGES, value="Python", label="Language"), | |
| gr.Radio(list(MODES), value="Explain", label="Mode"), | |
| gr.Radio(LEVELS, value="Beginner", label="Your level"), | |
| gr.Dropdown(MODELS, value=DEFAULT_MODEL, label="Model", allow_custom_value=True), | |
| gr.Slider(64, 4096, value=1024, step=64, label="Max new tokens"), | |
| gr.Slider(0.0, 1.5, value=0.3, step=0.05, label="Temperature"), | |
| ], | |
| examples=[ | |
| ["What is the difference between a list and a tuple?", "Python", "Explain", "Beginner"], | |
| [ | |
| "Why does this crash?\n\n```python\nnums = [1, 2, 3]\nfor i in range(len(nums) + 1):\n print(nums[i])\n```", | |
| "Python", | |
| "Debug", | |
| "Beginner", | |
| ], | |
| ["Write a function that checks if a string is a palindrome.", "JavaScript", "Write code", "Intermediate"], | |
| ["How do I reverse a linked list?", "Java", "Socratic tutor", "Intermediate"], | |
| ], | |
| cache_examples=False, | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |