File size: 6,085 Bytes
6cc0a7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import spaces
import os

# Model configuration
MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"  # Small, efficient open-source model
MAX_NEW_TOKENS = 512
TEMPERATURE = 0.7
TOP_P = 0.95

# Initialize model and tokenizer
print(f"Loading model: {MODEL_NAME}")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    device_map="auto",
    trust_remote_code=True
)

# Create text generation pipeline
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    device_map="auto"
)

@spaces.GPU(duration=60)  # Request GPU for 60 seconds per call (for Hugging Face Spaces)
def generate_response(message, history, system_message, max_tokens, temperature, top_p):
    """Generate a response using the LLM."""
    
    # Build conversation context
    messages = []
    
    # Add system message if provided
    if system_message:
        messages.append({"role": "system", "content": system_message})
    
    # Add conversation history
    for user_msg, assistant_msg in history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": assistant_msg})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    # Apply chat template
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    
    # Generate response
    try:
        outputs = pipe(
            text,
            max_new_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
            do_sample=True,
            return_full_text=False
        )
        
        response = outputs[0]["generated_text"]
        return response
        
    except Exception as e:
        return f"Error generating response: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="Open Source LLM Chat", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # Open Source LLM Chat
        
        This app uses **{model}** - an open-source language model.
        
        ### Features:
        - Interactive chat interface
        - Adjustable generation parameters
        - Custom system messages
        - Deployed on Hugging Face Spaces
        """.format(model=MODEL_NAME)
    )
    
    with gr.Row():
        with gr.Column(scale=2):
            chatbot = gr.Chatbot(
                label="Chat History",
                height=500,
                bubble_full_width=False
            )
            
            msg = gr.Textbox(
                label="Your Message",
                placeholder="Type your message here and press Enter...",
                lines=2
            )
            
            with gr.Row():
                submit = gr.Button("Send", variant="primary")
                clear = gr.Button("Clear Chat")
        
        with gr.Column(scale=1):
            gr.Markdown("### Settings")
            
            system_message = gr.Textbox(
                label="System Message (Optional)",
                placeholder="You are a helpful AI assistant...",
                lines=3
            )
            
            max_tokens = gr.Slider(
                minimum=50,
                maximum=2048,
                value=MAX_NEW_TOKENS,
                step=50,
                label="Max Tokens"
            )
            
            temperature = gr.Slider(
                minimum=0.1,
                maximum=2.0,
                value=TEMPERATURE,
                step=0.1,
                label="Temperature (Creativity)"
            )
            
            top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=TOP_P,
                step=0.05,
                label="Top-p (Nucleus Sampling)"
            )
            
            gr.Markdown(
                """
                ### Parameter Guide:
                - **Max Tokens**: Maximum length of response
                - **Temperature**: Higher = more creative, Lower = more focused
                - **Top-p**: Controls diversity of word choices
                """
            )
    
    gr.Markdown(
        """
        ---
        ### Tips:
        - Start with a clear, specific question
        - Adjust temperature for creative vs. factual responses
        - Use system messages to set the AI's behavior
        - Clear chat if responses become inconsistent
        """
    )
    
    # Handle message submission
    def user_submit(message, history):
        return "", history + [[message, None]]
    
    def bot_respond(history, system_message, max_tokens, temperature, top_p):
        if len(history) == 0 or history[-1][1] is not None:
            return history
            
        message = history[-1][0]
        bot_message = generate_response(
            message, 
            history[:-1],  # Don't include the current message in history
            system_message,
            max_tokens,
            temperature,
            top_p
        )
        history[-1][1] = bot_message
        return history
    
    # Wire up the interface
    msg.submit(
        user_submit, 
        [msg, chatbot], 
        [msg, chatbot], 
        queue=False
    ).then(
        bot_respond,
        [chatbot, system_message, max_tokens, temperature, top_p],
        chatbot
    )
    
    submit.click(
        user_submit,
        [msg, chatbot],
        [msg, chatbot],
        queue=False
    ).then(
        bot_respond,
        [chatbot, system_message, max_tokens, temperature, top_p],
        chatbot
    )
    
    clear.click(lambda: None, None, chatbot, queue=False)

# Launch the app
if __name__ == "__main__":
    demo.launch(
        share=False,
        show_error=True
    )