Balab2021 commited on
Commit
236d051
·
verified ·
1 Parent(s): 30ebdc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -61
app.py CHANGED
@@ -1,68 +1,112 @@
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="Balab2021/qwen-workflow-planner-qwen2p5-lora")
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
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
- with gr.Blocks() as demo:
63
- with gr.Sidebar():
64
- gr.LoginButton()
65
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
 
68
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
+ import os
5
+ from typing import List, Tuple
6
 
7
+ import gradio as gr
8
+ import torch
9
+ from dotenv import load_dotenv
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer
11
+
12
+ load_dotenv()
13
+
14
+ MODEL_ID = "Balab2021/qwen-workflow-planner-qwen2p5-lora"
15
+
16
+ def get_hf_token() -> str:
17
+ if not HF_TOKEN_KEYS:
18
+ raise RuntimeError(
19
+ "Missing HF_TOKEN_KEYS environment variable. "
20
+ "Set it to one or more token env var names (comma-separated), "
21
+ "for example: HF_TOKEN_KEYS=HF_TOKEN"
22
+ )
23
+
24
+ raw_value = HF_TOKEN_KEYS.strip().strip("\"'")
25
+
26
+ # Allow HF_TOKEN_KEYS to hold a direct Hugging Face token.
27
+ if raw_value.startswith("hf_"):
28
+ return raw_value
29
+
30
+ keys = [key.strip() for key in raw_value.split(",") if key.strip()]
31
+
32
+ if not keys:
33
+ raise RuntimeError(
34
+ "HF_TOKEN_KEYS is empty. "
35
+ "Set it to one or more token env var names, for example: HF_TOKEN"
36
+ )
37
+
38
+ for key in keys:
39
+ token = os.getenv(key)
40
+ if token:
41
+ return token.strip().strip("\"'")
42
+ raise RuntimeError(
43
+ "Missing Hugging Face token. None of the env vars listed in "
44
+ f"HF_TOKEN_KEYS contain a token value. Checked keys: {', '.join(keys)}"
45
+ )
46
+
47
+
48
+ def build_messages(history: List[Tuple[str, str]], user_message: str):
49
+ messages = []
50
+ for user_text, assistant_text in history:
51
+ if user_text:
52
+ messages.append({"role": "user", "content": user_text})
53
+ if assistant_text:
54
+ messages.append({"role": "assistant", "content": assistant_text})
55
+ messages.append({"role": "user", "content": user_message})
56
+ return messages
57
+
58
+
59
+ def create_app():
60
+ load_dotenv()
61
+ token = get_hf_token()
62
+
63
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=token)
64
+ model = AutoModelForCausalLM.from_pretrained(
65
+ MODEL_ID,
66
+ token=token,
67
+ torch_dtype="auto",
68
+ device_map="auto",
69
+ )
70
+
71
+ def chat_fn(
72
+ message: str,
73
+ history: List[Tuple[str, str]],
74
+ temperature: float,
75
+ max_new_tokens: int,
76
+ ) -> str:
77
+ messages = build_messages(history, message)
78
+ prompt = tokenizer.apply_chat_template(
79
+ messages,
80
+ tokenize=False,
81
+ add_generation_prompt=True,
82
+ )
83
+
84
+ inputs = tokenizer(prompt, return_tensors="pt")
85
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
86
+
87
+ with torch.no_grad():
88
+ output_ids = model.generate(
89
+ **inputs,
90
+ max_new_tokens=max_new_tokens,
91
+ temperature=temperature,
92
+ do_sample=temperature > 0,
93
+ pad_token_id=tokenizer.eos_token_id,
94
+ )
95
+
96
+ generated_ids = output_ids[0][inputs["input_ids"].shape[-1] :]
97
+ response = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
98
+ return response
99
+
100
+ demo = gr.ChatInterface(
101
+ fn=chat_fn,
102
+ additional_inputs=[
103
+ gr.Slider(0.0, 1.5, value=0.2, step=0.05, label="Temperature"),
104
+ gr.Slider(32, 2048, value=512, step=32, label="Max New Tokens"),
105
+ ],
106
+ title="Qwen Workflow Planner Chat",
107
+ description=f"Model: {MODEL_ID}",
108
+ )
109
+ return demo
110
 
111
 
112
  if __name__ == "__main__":