File size: 10,181 Bytes
cb83f9d
 
aedbcbd
cb83f9d
 
aedbcbd
ae05fd6
 
 
 
 
 
 
 
 
 
437467e
 
ae05fd6
 
 
 
ccbc5fb
ae05fd6
ccbc5fb
 
aedbcbd
ae05fd6
cb83f9d
1ad27de
 
ae05fd6
1ad27de
 
 
cb83f9d
437467e
cb83f9d
ccbc5fb
 
aedbcbd
 
 
 
 
 
 
664e458
aedbcbd
ccbc5fb
aedbcbd
 
 
 
cb83f9d
ae05fd6
 
6dafdaf
ccbc5fb
 
 
 
 
cb83f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccbc5fb
cb83f9d
 
5385efe
ddaf3fe
 
cb83f9d
 
 
1ad27de
 
cb83f9d
 
 
f078020
7130cdb
 
 
 
 
 
 
ae05fd6
 
 
 
 
 
6dafdaf
ae05fd6
 
 
 
 
d100767
7130cdb
cb83f9d
 
 
 
 
f078020
cb83f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
437467e
6dafdaf
 
 
cb83f9d
 
 
 
 
5385efe
cb83f9d
 
 
 
 
 
 
 
 
5385efe
aedbcbd
cb83f9d
ccbc5fb
cb83f9d
 
 
437467e
 
07257ae
437467e
 
07257ae
 
cb83f9d
 
 
 
 
 
5385efe
 
cb83f9d
 
 
 
 
 
5385efe
cb83f9d
 
 
 
 
 
 
5385efe
cb83f9d
 
 
 
 
 
aedbcbd
cb83f9d
 
 
 
 
 
 
 
 
 
aedbcbd
cb83f9d
 
 
 
 
aedbcbd
cb83f9d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import argparse
import os
import requests

import gradio as gr

INTRO = """**Chat with Yoda, Albert Einstein, Elon Musk or Kanye West!**

✨ This demo is powered by HuggingFace Inference API and currently the models [starchat-beta](https://huggingface.co/HuggingFaceH4/starchat-beta) and [falcon-7b](https://huggingface.co/tiiuae/falcon-7b-instruct) are supported. This demo is based on the [falcon-chat demo](https://huggingface.co/spaces/HuggingFaceH4/falcon-chat) by the [HuggingFace H4 team](https://huggingface.co/HuggingFaceH4); major props to them!

🧪 With this demo you can talk to some of your favorite characters and also play with some very powerful models. Although not as powerful as some 40B+ models, the 7B Falcon model and 15.5B starchat-beta models are great chat companions. We intend to add more characters and models in the future.

👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)

👀 **Learn more about Starchat LLM:** [starchat-alpha](https://huggingface.co/blog/starchat-alpha)

👀 **Banner images were created with [stable diffusion web](https://stablediffusionweb.com/).**

➡️️ **Intended Use**: this demo is intended to be a fun showcase of what one can do with HuggingFace Inference API and recent chat models.

⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words.
"""
MODELS = [
    "HuggingFaceH4/starchat-beta",
    "tiiuae/falcon-7b-instruct",
]
HEADERS = {"Authorization": f"Bearer {os.environ['HUB_TOKEN']}"}
TITLE = """<h2 align="center">🚀 TalkToMe</h2>"""
USER_NAME = "User"
INSTRUCTIONS_MAPPING = {
    "Albert Einstein": "The following is a conversation between the highly knowledgeable and intelligent scientist Albert Einstein, and a human user, called User. In the following interactions, User and Albert Einstein will converse in natural language, and Albert Einstein will answer User's questions. Albert Einstein is always eloquent, respectful, polite and inclusive. Albert Einstein invented the theory of Relativity and made important contributions to the theory of Quantum Mechanics. Albert Einstein will never decline to answer a question, and always attempts to give an answer that User would be satisfied with. Albert Einstein knows a lot, and always tells the truth. The conversation begins.\n",
    "Yoda": "The following is a conversation between the highly knowledgeable and intelligent Yoda from Star Wars, and a human user, called User. In the following interactions, User and Yoda will converse in natural language, and Yoda will answer User's questions. Yoda is respectful, polite and inclusive. Yoda is a wise and powerful Jedi Master from the Star Wars universe who speaks as follows: `Speak you must, in his unique and distinctive manner, with wisdom and knowledge to share.`, `Reversed syntax and short phrases, you shall use.`, `May the Force be with you, young Padawan.`. The conversation begins.\n",
    "Elon Musk": "The following is a conversation between entrepeneur and multi-billionair Elon Musk, and a human user, called User. In the following interactions, User and Elon Musk will converse in natural language, and Elon Musk will answer User's questions. Elon Musk is self-centered, arrogant and has a great for business development. Elon Musk owns the electric car company Tesla, the spacecraft engeneering company SpaceX and bought the social media company Twitter. The conversation begins.\n",
    "Kanye West": "The following is a conversation between rapper Kanye West, and a human user, called User. In the following interactions, User and Kanye West will converse in natural language, and Kanye West will answer User's questions. Kanye West is self-centered, arrogant, a self-proclaimed genius and a great musician. Kanye West interrupted an award ceremony for Taylor Swift and ran for president of the united states. The conversation begins.\n",
}
RETRY_COMMAND = "/retry"
STOP_SEQ = [f"\n{USER_NAME}", "<|end|>"]

def run_model(prompt, model, temperature, top_p):
    api_url = f"https://api-inference.huggingface.co/models/{model}"
    payload = {
        "inputs": prompt,
        "parameters": {
            "max_new_tokens": 128,
            "do_sample": True,
            "temperature": temperature,
            "top_p": top_p
        }
    }
    response = requests.post(api_url, headers=HEADERS, json=payload)
    return response.json()[0]['generated_text']

def get_stream(string: str):
    return enumerate(iter(string.split(" ")))

def parameter_accordion():
    with gr.Accordion("Parameters", open=True):
        model = gr.Radio(
            choices = MODELS,
            value = MODELS[0],
            interactive=True,
            label="Model",
        )
        temperature = gr.Slider(
            minimum=0.1,
            maximum=2.0,
            value=0.8,
            step=0.1,
            interactive=True,
            label="Temperature",
        )
        top_p = gr.Slider(
            minimum=0.1,
            maximum=0.99,
            value=0.9,
            step=0.01,
            interactive=True,
            label="p (nucleus sampling)",
        )
    return model, temperature, top_p


def format_chat_prompt(message: str, chat_history, bot_name: str) -> str:
    print(bot_name)
    instructions = INSTRUCTIONS_MAPPING[bot_name].strip(" ").strip("\n")
    prompt = instructions
    for turn in chat_history:
        user_message, bot_message = turn
        prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{bot_name}: {bot_message}"
    prompt = f"{prompt}\n{USER_NAME}: {message}\n{bot_name}:"
    return prompt


def chat():
    gr.HTML(TITLE)
    with gr.Row():
        with gr.Column():
            banner = gr.Image("Albert Einstein.jpeg", elem_id="banner-image", show_label=False)
        with gr.Column():
            gr.Markdown(INTRO)
                
    with gr.Row(elem_id="param_container"):
        with gr.Column():
            model, temperature, top_p = parameter_accordion()
        with gr.Column():
            with gr.Accordion("Character", open=True):
                choices = list(INSTRUCTIONS_MAPPING)
                bot_name = gr.Radio(
                    choices=choices,
                    value=choices[0],
                    interactive=True,
                    label="Character",
                )
                bot_name.change(fn=lambda value: gr.update(value=f"{value}.jpeg"), inputs=bot_name, outputs=banner)
                        
    with gr.Column(elem_id="chat_container"):
        with gr.Row():
            chatbot = gr.Chatbot(elem_id="chatbot")
        with gr.Row():
            inputs = gr.Textbox(
                placeholder=f"Hi there! Tell me something about yourself.",
                label="Type an input and press Enter",
                max_lines=3,
            )

    with gr.Row(elem_id="button_container"):
        with gr.Column():
            retry_button = gr.Button("♻️ Retry last turn")
        with gr.Column():
            delete_turn_button = gr.Button("🧽 Delete last turn")
        with gr.Column():
            clear_chat_button = gr.Button("✨ Delete all history")

    gr.Examples(
        [
            ["Hi Albert! Why did the apple fall from the tree?"],
            ["Hi Yoda! How do I learn the force?"],
            ["Hi Elon! Give me an idea for a new startup."],
            ["Hi Kanye! What will be the theme of your next album?"],
        ],
        inputs=inputs,
        label="Click on any example and press Enter in the input textbox!",
    )

    def run_chat(message: str, chat_history, bot_name: str, model: str, temperature: float, top_p: float):
        if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
            yield chat_history
            return

        if message == RETRY_COMMAND and chat_history:
            prev_turn = chat_history.pop(-1)
            user_message, _ = prev_turn
            message = user_message

        prompt = format_chat_prompt(message, chat_history, bot_name)
        model_output = run_model(
            prompt,
            model=model,
            temperature=temperature,
            top_p=top_p,
        )
        for stop in STOP_SEQ:
            model_output = model_output[len(prompt):].split(stop)[0]
        chat_history = chat_history + [[message, model_output]]
        print(f"User: {message}")
        print(f"{bot_name}: {model_output}")
        yield chat_history
        return

    def delete_last_turn(chat_history):
        if chat_history:
            chat_history.pop(-1)
        return {chatbot: gr.update(value=chat_history)}

    def run_retry(message: str, chat_history, bot_name, model: str, temperature: float, top_p: float):
        yield from run_chat(RETRY_COMMAND, chat_history, bot_name, model, temperature, top_p)

    def clear_chat():
        return []

    inputs.submit(
        run_chat,
        [inputs, chatbot, bot_name, model, temperature, top_p],
        outputs=[chatbot],
        show_progress=False,
    )
    inputs.submit(lambda: "", inputs=None, outputs=inputs)
    delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
    retry_button.click(
        run_retry,
        [inputs, chatbot, bot_name, model, temperature, top_p],
        outputs=[chatbot],
        show_progress=False,
    )
    clear_chat_button.click(clear_chat, [], chatbot)


def get_demo():
    with gr.Blocks(
        # css=None
        # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
        #        #button_container {width: 700px; margin-left: auto; margin-right: auto;}
        #        #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
        css="""#chatbot {
    font-size: 14px;
    min-height: 300px;
}"""
    ) as demo:
        chat()

    return demo


if __name__ == "__main__":
    demo = get_demo()
    demo.queue(max_size=128, concurrency_count=16)
    demo.launch()