sakurasan commited on
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# ここを Llama / Mistral など好きなモデルに変更
|
| 6 |
+
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 7 |
+
# MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct" # ← Llama に変更したい場合
|
| 8 |
+
|
| 9 |
+
# モデルとトークナイザのロード
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 12 |
+
MODEL_NAME,
|
| 13 |
+
torch_dtype=torch.float16,
|
| 14 |
+
device_map="auto"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def chat_fn(message, history):
|
| 18 |
+
# 過去履歴を LLM のプロンプト形式に変換
|
| 19 |
+
prompt = ""
|
| 20 |
+
for user, assistant in history:
|
| 21 |
+
prompt += f"<s>[ユーザー]: {user}\n[アシスタント]: {assistant}</s>\n"
|
| 22 |
+
prompt += f"<s>[ユーザー]: {message}\n[アシスタント]:"
|
| 23 |
+
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 25 |
+
|
| 26 |
+
output_ids = model.generate(
|
| 27 |
+
**inputs,
|
| 28 |
+
max_new_tokens=200,
|
| 29 |
+
temperature=0.7,
|
| 30 |
+
do_sample=True,
|
| 31 |
+
top_p=0.9
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 35 |
+
|
| 36 |
+
# 最後のアシスタント発言だけ抽出
|
| 37 |
+
if "[アシスタント]:" in response:
|
| 38 |
+
response = response.split("[アシスタント]:")[-1].strip()
|
| 39 |
+
|
| 40 |
+
history.append((message, response))
|
| 41 |
+
return response, history
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Gradio UI
|
| 45 |
+
with gr.Blocks() as demo:
|
| 46 |
+
gr.Markdown("# 🦙💬 Simple Llama / Mistral Chatbot")
|
| 47 |
+
chatbot = gr.Chatbot()
|
| 48 |
+
msg = gr.Textbox(label="Message")
|
| 49 |
+
|
| 50 |
+
def user_send(user_message, chat_history):
|
| 51 |
+
return "", chat_history + [[user_message, None]]
|
| 52 |
+
|
| 53 |
+
msg.submit(user_send, [msg, chatbot], [msg, chatbot]).then(
|
| 54 |
+
chat_fn, [msg, chatbot], [chatbot]
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
demo.launch()
|