File size: 5,295 Bytes
29964c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""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()