broccoli0510 Claude Opus 5.5 commited on
Commit
29964c2
·
1 Parent(s): d2cceef

Add CodeTutor Gradio app

Browse files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (4) hide show
  1. .gitignore +2 -0
  2. README.md +14 -0
  3. app.py +147 -0
  4. requirements.txt +2 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ .venv/
README.md CHANGED
@@ -12,3 +12,17 @@ license: mit
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
15
+
16
+ ## CodeTutor
17
+
18
+ A Gradio chat app that helps you learn programming: explain concepts, debug, review or write code, or get Socratic hints.
19
+
20
+ ### Setup
21
+ 1. In the Space **Settings → Variables and secrets**, add a secret `HF_TOKEN` (a Hugging Face access token with "Make calls to Inference Providers" permission).
22
+ 2. Optional: add a variable `MODEL_ID` to change the default model (default: `Qwen/Qwen2.5-Coder-32B-Instruct`).
23
+
24
+ ### Run locally
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ HF_TOKEN=hf_xxx python app.py
28
+ ```
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CodeTutor - a programming helper chatbot powered by an open LLM on Hugging Face."""
2
+
3
+ import os
4
+
5
+ import gradio as gr
6
+ from huggingface_hub import InferenceClient
7
+
8
+ # Override with the MODEL_ID Space variable; add an HF_TOKEN secret for authentication.
9
+ DEFAULT_MODEL = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
10
+ MODELS = list(
11
+ dict.fromkeys(
12
+ [
13
+ DEFAULT_MODEL,
14
+ "Qwen/Qwen2.5-Coder-32B-Instruct",
15
+ "meta-llama/Llama-3.3-70B-Instruct",
16
+ "deepseek-ai/DeepSeek-V3-0324",
17
+ ]
18
+ )
19
+ )
20
+
21
+ LANGUAGES = [
22
+ "Any",
23
+ "Python",
24
+ "JavaScript",
25
+ "TypeScript",
26
+ "Java",
27
+ "C",
28
+ "C++",
29
+ "C#",
30
+ "Go",
31
+ "Rust",
32
+ "SQL",
33
+ "HTML/CSS",
34
+ "Bash",
35
+ ]
36
+
37
+ MODES = {
38
+ "Explain": "Explain concepts and code clearly, step by step, using small examples.",
39
+ "Debug": (
40
+ "Help find and fix bugs. Identify the root cause first, explain why it happens, "
41
+ "then show the corrected code."
42
+ ),
43
+ "Review": (
44
+ "Review the code for correctness, readability, performance and security. "
45
+ "Give concrete, prioritized suggestions with improved snippets."
46
+ ),
47
+ "Write code": (
48
+ "Write clean, working, well-commented code that solves the request, "
49
+ "then briefly explain how it works."
50
+ ),
51
+ "Socratic tutor": (
52
+ "Act as a patient tutor. Do not give the full solution right away; guide the student "
53
+ "with hints and questions so they reach the answer themselves."
54
+ ),
55
+ }
56
+
57
+ LEVELS = ["Beginner", "Intermediate", "Advanced"]
58
+
59
+
60
+ def build_system_prompt(language: str, mode: str, level: str) -> str:
61
+ lang = "" if language == "Any" else f" The student is working in {language}."
62
+ return (
63
+ "You are CodeTutor, a friendly and expert programming assistant."
64
+ f"{lang} The student's level is {level}; adjust vocabulary and depth accordingly. "
65
+ f"{MODES[mode]} Always put code in fenced Markdown blocks with the language tag. "
66
+ "If the request is ambiguous, ask a short clarifying question."
67
+ )
68
+
69
+
70
+ def content_to_text(content) -> str:
71
+ """Flatten Gradio message content (str, dict or list of parts) into plain text."""
72
+ if isinstance(content, str):
73
+ return content
74
+ if isinstance(content, dict):
75
+ return content.get("text", "") or ""
76
+ if isinstance(content, (list, tuple)):
77
+ return "\n".join(filter(None, (content_to_text(c) for c in content)))
78
+ return ""
79
+
80
+
81
+ def respond(message, history, language, mode, level, model, max_tokens, temperature):
82
+ messages = [{"role": "system", "content": build_system_prompt(language, mode, level)}]
83
+ for turn in history:
84
+ text = content_to_text(turn.get("content"))
85
+ if text and turn.get("role") in ("user", "assistant"):
86
+ messages.append({"role": turn["role"], "content": text})
87
+ messages.append({"role": "user", "content": content_to_text(message)})
88
+
89
+ client = InferenceClient(model=model, token=os.getenv("HF_TOKEN"))
90
+ response = ""
91
+ try:
92
+ for chunk in client.chat_completion(
93
+ messages,
94
+ max_tokens=int(max_tokens),
95
+ temperature=float(temperature),
96
+ stream=True,
97
+ ):
98
+ if not chunk.choices:
99
+ continue
100
+ delta = chunk.choices[0].delta.content
101
+ if delta:
102
+ response += delta
103
+ yield response
104
+ except Exception as e:
105
+ raise gr.Error(f"Model request failed: {e}")
106
+
107
+
108
+ with gr.Blocks(title="CodeTutor") as demo:
109
+ gr.Markdown(
110
+ "# 💻 CodeTutor\n"
111
+ "Your AI programming helper — ask it to explain, debug, review or write code. "
112
+ "Pick a mode and language in **Settings** below the chat."
113
+ )
114
+ gr.ChatInterface(
115
+ respond,
116
+ chatbot=gr.Chatbot(height=520, buttons=["copy", "copy_all"], label="CodeTutor"),
117
+ textbox=gr.Textbox(
118
+ placeholder="Paste your code or ask a programming question...",
119
+ lines=3,
120
+ max_lines=20,
121
+ submit_btn=True,
122
+ ),
123
+ additional_inputs_accordion=gr.Accordion("⚙️ Settings", open=False),
124
+ additional_inputs=[
125
+ gr.Dropdown(LANGUAGES, value="Python", label="Language"),
126
+ gr.Radio(list(MODES), value="Explain", label="Mode"),
127
+ gr.Radio(LEVELS, value="Beginner", label="Your level"),
128
+ gr.Dropdown(MODELS, value=DEFAULT_MODEL, label="Model", allow_custom_value=True),
129
+ gr.Slider(64, 4096, value=1024, step=64, label="Max new tokens"),
130
+ gr.Slider(0.0, 1.5, value=0.3, step=0.05, label="Temperature"),
131
+ ],
132
+ examples=[
133
+ ["What is the difference between a list and a tuple?", "Python", "Explain", "Beginner"],
134
+ [
135
+ "Why does this crash?\n\n```python\nnums = [1, 2, 3]\nfor i in range(len(nums) + 1):\n print(nums[i])\n```",
136
+ "Python",
137
+ "Debug",
138
+ "Beginner",
139
+ ],
140
+ ["Write a function that checks if a string is a palindrome.", "JavaScript", "Write code", "Intermediate"],
141
+ ["How do I reverse a linked list?", "Java", "Socratic tutor", "Intermediate"],
142
+ ],
143
+ cache_examples=False,
144
+ )
145
+
146
+ if __name__ == "__main__":
147
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio==6.31.0
2
+ huggingface_hub