haduykien commited on
Commit
b3f0da0
·
verified ·
1 Parent(s): 1ab6647

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -31
app.py CHANGED
@@ -1,52 +1,53 @@
1
- import os
2
  import gradio as gr
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
 
5
- # Lấy token từ Secrets (Settings > New secret trong Space)
6
- hf_token = os.environ.get("HF_TOKEN")
7
 
8
- # Model ID (có thể đổi sang model open nếu không có quyền)
9
- model_id = "meta-llama/Llama-3.1-8B-Instruct"
 
 
 
 
 
10
 
11
- # Tải tokenizer và pipeline với token
12
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
13
  pipe = pipeline(
14
  "text-generation",
15
- model=model_id,
16
  tokenizer=tokenizer,
17
- device_map="auto", # tự động chọn GPU/CPU
18
- torch_dtype="auto", # FP16 nếu GPU hỗ trợ
19
- token=hf_token
20
  )
21
 
22
- # Hàm trả lời
23
- def chat(user_input, history):
24
- messages = [{"role": "system", "content": "Bạn một trợ lý AI hữu ích."}]
25
- for h in history:
26
- messages.append({"role": "user", "content": h[0]})
27
- messages.append({"role": "assistant", "content": h[1]})
28
- messages.append({"role": "user", "content": user_input})
29
-
30
- response = pipe(messages, max_new_tokens=300, do_sample=True, temperature=0.7)
31
- # Hugging Face pipeline trả về có thể khác format → ta xử lý
32
- if isinstance(response[0]["generated_text"], list):
33
- answer = response[0]["generated_text"][-1]["content"]
34
- else:
35
- answer = response[0]["generated_text"]
36
-
37
- history.append((user_input, answer))
38
  return history, history
39
 
40
- # UI Gradio
41
  with gr.Blocks() as demo:
42
- gr.Markdown("# 🚀 Chatbot chạy bằng LLaMA trên Hugging Face Space")
43
  chatbot = gr.Chatbot()
44
  msg = gr.Textbox(placeholder="Nhập tin nhắn...")
45
- clear = gr.Button("Xoá hội thoại")
46
 
47
  state = gr.State([])
48
 
49
- msg.submit(chat, [msg, state], [chatbot, state])
50
  clear.click(lambda: ([], []), None, [chatbot, state], queue=False)
51
 
52
  demo.launch()
 
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
 
4
+ # Model nhỏ hơn để chạy được trên Space
5
+ MODEL_ID = "context-labs/meta-llama-Llama-3.2-3B-Instruct-FP16"
6
 
7
+ # Load tokenizer + model
8
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ MODEL_ID,
11
+ device_map="auto", # tự động dùng GPU nếu có
12
+ torch_dtype="auto"
13
+ )
14
 
15
+ # Tạo pipeline
 
16
  pipe = pipeline(
17
  "text-generation",
18
+ model=model,
19
  tokenizer=tokenizer,
20
+ max_new_tokens=512
 
 
21
  )
22
 
23
+ # Hàm chat
24
+ def chat_fn(message, history):
25
+ # format lại hội thoại cho giống chat
26
+ prompt = ""
27
+ for user, bot in history:
28
+ prompt += f"User: {user}\nAssistant: {bot}\n"
29
+ prompt += f"User: {message}\nAssistant:"
30
+
31
+ outputs = pipe(prompt, do_sample=True, temperature=0.7, top_p=0.9)
32
+ reply = outputs[0]["generated_text"][len(prompt):]
33
+ return reply.strip()
34
+
35
+ # Hàm Gradio
36
+ def respond(message, history):
37
+ reply = chat_fn(message, history)
38
+ history.append((message, reply))
39
  return history, history
40
 
41
+ # UI
42
  with gr.Blocks() as demo:
43
+ gr.Markdown("# 💬 Chat với LLaMA 3.2 3B FP16")
44
  chatbot = gr.Chatbot()
45
  msg = gr.Textbox(placeholder="Nhập tin nhắn...")
46
+ clear = gr.Button("Xóa hội thoại")
47
 
48
  state = gr.State([])
49
 
50
+ msg.submit(respond, [msg, state], [chatbot, state])
51
  clear.click(lambda: ([], []), None, [chatbot, state], queue=False)
52
 
53
  demo.launch()