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717bc81
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import torch
import gradio as gr
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
from fastapi import FastAPI
from fastapi.responses import StreamingResponse, RedirectResponse
from pydantic import BaseModel
import json
from typing import List, Literal
import os
import uvicorn

HF_TOKEN = os.getenv("HF_TOKEN")

MODEL = "meta-llama/Llama-3.2-1B-Instruct"

app = FastAPI()

# base model and tokenizer
base_model = AutoModelForCausalLM.from_pretrained(
    MODEL,
    token=HF_TOKEN,
    dtype=torch.float32, #huggingface free tier only has cpu
    device_map="cpu",
    low_cpu_mem_usage=True
)

base_model.config.use_cache = True

tokenizer = AutoTokenizer.from_pretrained(MODEL, token=HF_TOKEN)

if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# lora adapters
adapter_paths = {
    "English": "./models/English",
    "Spanish": "./models/Spanish",
    "Korean": "./models/Korean"
}

# single PeftModel instance that switches adapters
peft_model = None
loaded_adapters = set()

def load_adapter(language):
    global peft_model

    # first adapter: create the PeftModel
    if peft_model is None:
        peft_model = PeftModel.from_pretrained(
            base_model,
            adapter_paths[language],
            adapter_name=language,
            is_trainable=False
        )

        peft_model.eval()
        loaded_adapters.add(language)
        return peft_model

    # load adapter if not already loaded
    if language not in loaded_adapters:
        peft_model.load_adapter(adapter_paths[language], adapter_name=language)
        loaded_adapters.add(language)

    # switch to the requested adapter
    peft_model.set_adapter(language)
    return peft_model

# the input will be a list of messages that include system, user, and assistant prompts
def generate_text_stream(messages, language, max_length=256, temperature=0.7):

    if language not in adapter_paths:
        yield f"Error: Language '{language}' not supported. Choose from: {list(adapter_paths.keys())}"
        return

    model = load_adapter(language)

    inputs = tokenizer.apply_chat_template(
        messages,
        tokenize=True,
        add_generation_prompt=True, # provides assistant: so that it can start generating
        return_tensors="pt",
        return_dict=True
    ).to(model.device)


    streamer = TextIteratorStreamer(
        tokenizer, 
        skip_prompt=True, 
        skip_special_tokens=True)

    generation_kwargs = {
        **inputs, # the key-value pairs in inputs are applied to this new dictinary
        "max_new_tokens": max_length,
        "temperature": temperature,
        "do_sample": True, # to stop greedy selection
        "pad_token_id": tokenizer.eos_token_id,
        "streamer": streamer,  
        "num_beams": 1, # keep only 1 sequence till the end
        "use_cache": True, #KV caching
    }
    
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()

    for text in streamer:
        yield text
    
    thread.join()

# using pydantic to ensure data schemas

class Message(BaseModel):
    role: Literal["system", "user", "assistant"]   
    content: str

class GenerateRequest(BaseModel):
    messages: List[Message]
    language: str
    max_length: int = 256
    temperature: float = 0.7

# fastAPI endpoints

# return information about the API
@app.get("/api")
def read_api():
    return {
        "message": "Multi-language Chatbot API",
        "languages": list(adapter_paths.keys()),
        "device": "CPU 16GB in Huggingface Space",
        "endpoints": {
            "POST /api/generate": "Generate with streaming",
            "GET /api/languages": "List available languages"
        }
    }

# return information about the langauge of the model
@app.get("/api/languages")
def get_languages():
    return {
        "languages": list(adapter_paths.keys()),
    }

# providing a response through a stream
@app.post("/api/generate")
async def generate_stream_api(request: GenerateRequest):

    # because pydantic uses Message class
    # this needs to be converted again to plain dictionary
    messages_dicts = [{"role": msg.role, "content": msg.content} for msg in request.messages]

    def event_generator():

        try:
            for token in generate_text_stream(
                messages_dicts,
                request.language,
                request.max_length,
                request.temperature
            ):

                yield f"data: {json.dumps({'token': token})}\n\n"

            yield f"data: [DONE]\n\n"

        except Exception as e:
            yield f"data: {json.dumps({'error': str(e)})}\n\n"

    # SSE is implemeted
    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",  # SSE content type
        headers={
            "Cache-Control": "no-cache",  # Don't cache streaming responses
            "Connection": "keep-alive",  # Keep connection open
            "X-Accel-Buffering": "no", 
        }
    )

def chat_gradio(message, history, language, system_prompt, max_length, temperature):

    messages = []

    if system_prompt:
        messages.append({"role": "system", "content": system_prompt})

    # only uses the last 10 messages to keep within context limit
    messages.extend(history[-10:])

    user_msg = {"role": "user", "content": message}
    messages.append(user_msg)

    assistant_msg = {"role": "assistant", "content": ""}
    for token in generate_text_stream(
        messages,
        language,
        max_length,
        temperature
    ):
        assistant_msg["content"] += token
        yield history + [user_msg, assistant_msg]

with gr.Blocks(
    title="Language Learning Chatbot", 
    theme=gr.themes.Soft()
) as demo:

    with gr.Row():
        with gr.Column(scale=2):
            chatbot = gr.Chatbot(
                label="Conversation",
                height=500,
                show_copy_button=True,  # Let users copy messages
                type="messages"
            )

            # User input
            with gr.Row():
                msg = gr.Textbox(
                    label="Your message",
                    placeholder="Type your message here and press Enter...",
                    lines=2,
                    scale=4
                )

            with gr.Row():
                submit_btn = gr.Button("Send", variant="primary", scale=1)
                clear_btn = gr.Button("Clear Chat", scale=1)

        with gr.Column(scale=1):
            gr.Markdown("### ⚙️ Settings")
            
            language_dropdown = gr.Dropdown(
                choices=list(adapter_paths.keys()),
                label="Language",
                value=list(adapter_paths.keys())[0],
                info="Select the language model to use"
            )

            system_prompt_input = gr.Textbox(
                label="System Prompt (Optional)",
                placeholder="e.g., You are a helpful assistant...",
                lines=3,
                info="Set the assistant's behavior"
            )
            
            max_length_slider = gr.Slider(
                minimum=50,
                maximum=512,
                value=256,
                step=1,
                label="Max Length (tokens)",
                info="Maximum tokens to generate"
            )

            temperature_slider = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.7,
                step=0.05,
                label="Temperature",
                info="Higher = more creative"
            )

    # handling enter key in textbox
    msg.submit(
        fn=chat_gradio,
        inputs=[msg, chatbot, language_dropdown, system_prompt_input, max_length_slider, temperature_slider],
        outputs=[chatbot],  # Update chatbot with streaming response
    ).then(
        fn=lambda: gr.update(value=""),  # Clear input after sending
        outputs=[msg]
    )

    # Handle button click
    submit_btn.click(
        fn=chat_gradio,
        inputs=[msg, chatbot, language_dropdown, system_prompt_input, max_length_slider, temperature_slider],
        outputs=[chatbot],
    ).then(
        fn=lambda: gr.update(value=""),
        outputs=[msg]
    )
    
    # Clear chat button
    clear_btn.click(
        fn=lambda: None,  # Return None to clear chatbot
        outputs=[chatbot],
        queue=False  # Don't queue this action
    )

demo.queue(False)
app = gr.mount_gradio_app(app, demo, path="/")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)