userName commited on
Commit
6e3dcd4
·
1 Parent(s): ecf601d

Update app.py with full DAN-L3-R1-8B support

Browse files
Files changed (2) hide show
  1. app.py +72 -55
  2. requirements.txt.txt +7 -0
app.py CHANGED
@@ -1,70 +1,87 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
24
 
25
- response = ""
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
41
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
 
 
 
 
 
68
 
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
+ # app.py
2
+ import os
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
  import gradio as gr
 
5
 
6
+ # 设置缓存目录(节省空间)
7
+ os.environ["HF_HOME"] = "/tmp/hf_cache"
8
 
9
+ # 模型名称(来自 Hugging Face)
10
+ model_name = "UnfilteredAI/DAN-L3-R1-8B"
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # 加载分词器
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
 
15
+ # 创建文本生成 pipeline
16
+ pipe = pipeline(
17
+ "text-generation",
18
+ model=model_name,
19
+ tokenizer=tokenizer,
20
+ model_kwargs={"torch_dtype": "auto"}, # 自动选择精度(如 float16)
21
+ device_map="auto", # 自动使用 GPU(如果有)
22
+ max_new_tokens=512,
23
+ temperature=0.7,
24
+ top_p=0.9,
25
+ repetition_penalty=1.1,
26
+ return_full_text=False, # 只返回生成的回复,不包含输入
27
+ )
28
 
29
+ # 定义生成函数
30
+ def generate_response(user_input, history):
31
+ # 将对话历史转换为 messages 格式
32
+ messages = []
33
+ for idx, (user_msg, assistant_msg) in enumerate(history):
34
+ messages.append({"role": "user", "content": user_msg})
35
+ messages.append({"role": "assistant", "content": assistant_msg})
36
+
37
+ # 添加当前用户输入
38
+ messages.append({"role": "user", "content": user_input})
39
 
40
+ # 调用模型生成回复
41
+ try:
42
+ outputs = pipe(messages)
43
+ response = outputs[0]["generated_text"].strip()
44
+ except Exception as e:
45
+ response = f"❌ 模型生成出错:{str(e)}"
46
 
47
+ # 返回更新后的对话历史
48
+ history.append((user_input, response))
49
+ return "", history
 
 
 
 
 
 
 
 
50
 
51
+ # 创建 Gradio 界面
52
+ with gr.Blocks(title="💬 DAN-L3-R1-8B AI 助手", theme=gr.themes.Soft()) as demo:
53
+ gr.Markdown("# 💬 DAN-L3-R1-8B AI 助手")
54
+ gr.Markdown("基于 [UnfilteredAI/DAN-L3-R1-8B](https://huggingface.co/UnfilteredAI/DAN-L3-R1-8B) 的对话系统")
55
 
56
+ chatbot = gr.Chatbot(height=600, show_copy_button=True)
57
+ with gr.Row():
58
+ textbox = gr.Textbox(
59
+ placeholder="请输入你的问题...",
60
+ show_label=False,
61
+ scale=7,
62
+ container=False,
63
+ )
64
+ submit_btn = gr.Button("发送", scale=1)
65
 
66
+ # 示例问题
67
+ gr.Examples(
68
+ examples=[
69
+ "你是谁?",
70
+ "讲个笑话",
71
+ "写一首关于秋天的诗",
72
+ "解释量子力学"
73
+ ],
74
+ inputs=textbox
75
+ )
 
 
 
 
 
 
 
 
 
76
 
77
+ # 清空按钮
78
+ clear_btn = gr.Button("🗑️ 清空聊天")
 
 
79
 
80
+ # 事件绑定
81
+ textbox.submit(fn=generate_response, inputs=[textbox, chatbot], outputs=[textbox, chatbot])
82
+ submit_btn.click(fn=generate_response, inputs=[textbox, chatbot], outputs=[textbox, chatbot])
83
+ clear_btn.click(fn=lambda: ("", None), outputs=[textbox, chatbot])
84
 
85
+ # 启动应用
86
  if __name__ == "__main__":
87
+ demo.launch()
requirements.txt.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers>=4.34.0
2
+ torch>=2.1.0
3
+ accelerate>=0.25.0
4
+ gradio>=4.0.0
5
+ sentencepiece
6
+ safetensors
7
+ huggingface_hub