SageLiao commited on
Commit
1040cbc
โ€ข
1 Parent(s): e47e46e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -47
app.py CHANGED
@@ -1,62 +1,129 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
  temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
38
 
39
- response += token
40
- yield response
41
 
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
 
62
  if __name__ == "__main__":
 
1
+ from threading import Thread
2
+
3
  import gradio as gr
4
+ import spaces
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
 
7
+
8
+ TITLE = "<h1><center>Chat with Llama3-8B-Chinese-Chat-v2.1</center></h1>"
9
+
10
+ DESCRIPTION = "<h3><center>Visit <a href='https://huggingface.co/shenzhi-wang/Llama3-8B-Chinese-Chat' target='_blank'>our model page</a> for details.</center></h3>"
11
+
12
+ DEFAULT_SYSTEM = "You are Llama-3, developed by an independent team. You are a helpful assistant."
13
+
14
+ TOOL_EXAMPLE = '''You have access to the following tools:
15
+ ```python
16
+ def generate_password(length: int, include_symbols: Optional[bool]):
17
+ """
18
+ Generate a random password.
19
+ Args:
20
+ length (int): The length of the password
21
+ include_symbols (Optional[bool]): Include symbols in the password
22
+ """
23
+ pass
24
+ ```
25
+ Write "Action:" followed by a list of actions in JSON that you want to call, e.g.
26
+ Action:
27
+ ```json
28
+ [
29
+ {
30
+ "name": "tool name (one of [generate_password])",
31
+ "arguments": "the input to the tool"
32
+ }
33
+ ]
34
+ ```
35
+ '''
36
+
37
+ CSS = """
38
+ .duplicate-button {
39
+ margin: auto !important;
40
+ color: white !important;
41
+ background: black !important;
42
+ border-radius: 100vh !important;
43
+ }
44
  """
 
 
 
45
 
46
 
47
+ tokenizer = AutoTokenizer.from_pretrained("SageLiao/llama3-LlamaFactory-demo-v3")
48
+ model = AutoModelForCausalLM.from_pretrained("SageLiao/llama3-LlamaFactory-demo-v3", device_map="auto")
 
 
 
 
 
 
 
49
 
50
+ system = "You are the expert for customer service in Amazon.com.Please answer every question as a polite and professional agent for Amazon Company and be as detailed as possible. Please answer the customer's question with the language they used.ๅฆ‚ๆžœไฝฟ็”จ่€…ไฝฟ็”จไธญๆ–‡ๆๅ•๏ผŒ่ซ‹็”จ็น้ซ”ไธญๆ–‡่ˆ‡ๅฐ็ฃ็”จ่ชžๅ›ž็ญ”"
51
+ @spaces.GPU
52
+ def stream_chat(message: str, history: list, system: str, temperature: float, max_new_tokens: int):
53
+ conversation = [{"role": "system", "content": system}]
54
+ for prompt, answer in history:
55
+ conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
56
 
57
+ conversation.append({"role": "user", "content": message})
58
 
59
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(
60
+ model.device
61
+ )
62
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
63
 
64
+ generate_kwargs = dict(
65
+ input_ids=input_ids,
66
+ streamer=streamer,
67
+ max_new_tokens=max_new_tokens,
68
  temperature=temperature,
69
+ do_sample=True,
70
+ )
71
+ if temperature == 0:
72
+ generate_kwargs["do_sample"] = False
73
 
74
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
75
+ t.start()
76
 
77
+ output = ""
78
+ for new_token in streamer:
79
+ output += new_token
80
+ yield output
81
+
82
+
83
+ chatbot = gr.Chatbot(height=450)
84
+
85
+ with gr.Blocks(css=CSS) as demo:
86
+ gr.HTML(TITLE)
87
+ gr.HTML(DESCRIPTION)
88
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
89
+ gr.ChatInterface(
90
+ fn=stream_chat,
91
+ chatbot=chatbot,
92
+ fill_height=True,
93
+ additional_inputs_accordion=gr.Accordion(label="โš™๏ธ Parameters", open=False, render=False),
94
+ additional_inputs=[
95
+ gr.Text(
96
+ value="",
97
+ label="System",
98
+ render=False,
99
+ ),
100
+ gr.Slider(
101
+ minimum=0,
102
+ maximum=1,
103
+ step=0.1,
104
+ value=0.8,
105
+ label="Temperature",
106
+ render=False,
107
+ ),
108
+ gr.Slider(
109
+ minimum=128,
110
+ maximum=4096,
111
+ step=1,
112
+ value=1024,
113
+ label="Max new tokens",
114
+ render=False,
115
+ ),
116
+ ],
117
+ examples=[
118
+ ["ๆˆ‘็š„่“็‰™่€ณๆœบๅไบ†๏ผŒๆˆ‘่ฏฅๅŽป็œ‹็‰™็ง‘่ฟ˜ๆ˜ฏ่€ณ้ผปๅ–‰็ง‘๏ผŸ", ""],
119
+ ["7ๅนดๅ‰๏ผŒๅฆˆๅฆˆๅนด้พ„ๆ˜ฏๅ„ฟๅญ็š„6ๅ€๏ผŒๅ„ฟๅญไปŠๅนด12ๅฒ๏ผŒๅฆˆๅฆˆไปŠๅนดๅคšๅฐ‘ๅฒ๏ผŸ", ""],
120
+ ["ๆˆ‘็š„็ฌ”่ฎฐๆœฌๆ‰พไธๅˆฐไบ†ใ€‚", "ๆ‰ฎๆผ”่ฏธ่‘›ไบฎๅ’Œๆˆ‘ๅฏน่ฏใ€‚"],
121
+ ["ๆˆ‘ๆƒณ่ฆไธ€ไธชๆ–ฐ็š„ๅฏ†็ ๏ผŒ้•ฟๅบฆไธบ8ไฝ๏ผŒๅŒ…ๅซ็‰นๆฎŠ็ฌฆๅทใ€‚", TOOL_EXAMPLE],
122
+ ["How are you today?", "You are Taylor Swift, use beautiful lyrics to answer questions."],
123
+ ["็”จC++ๅฎž็ŽฐKMP็ฎ—ๆณ•๏ผŒๅนถๅŠ ไธŠไธญๆ–‡ๆณจ้‡Š", ""],
124
+ ],
125
+ cache_examples=False,
126
+ )
127
 
128
 
129
  if __name__ == "__main__":