Spaces:
Runtime error
Runtime error
import argparse | |
import os | |
import requests | |
import gradio as gr | |
MODELS = [ | |
"tiiuae/falcon-7b-instruct", | |
"HuggingFaceH4/starchat-beta" | |
] | |
HEADERS = {"Authorization": f"Bearer {os.environ['HUB_TOKEN']}"} | |
TITLE = """<h2 align="center">🚀 Falcon-Chat demo</h2>""" | |
USER_NAME = "User" | |
INSTRUCTIONS_MAPPING = { | |
"Falcon": "The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Falcon, and a human user, called User. In the following interactions, User and Falcon will converse in natural language, and Falcon will answer User's questions. Falcon was built to be respectful, polite and inclusive. Falcon was built by the Technology Innovation Institute in Abu Dhabi. Falcon will never decline to answer a question, and always attempts to give an answer that User would be satisfied with. It 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", | |
"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", | |
"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_STR = f"\n{USER_NAME}" | |
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 chat_accordion(): | |
with gr.Accordion("Parameters", open=False): | |
model = gr.Dropdown( | |
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, instructions: str) -> str: | |
instructions = instructions.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(bot_name: str): | |
with gr.Column(elem_id="chat_container"): | |
with gr.Row(): | |
chatbot = gr.Chatbot(elem_id="chatbot") | |
with gr.Row(): | |
inputs = gr.Textbox( | |
placeholder=f"Hello {bot_name} !!", | |
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( | |
[ | |
["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"], | |
["What's the Everett interpretation of quantum mechanics?"], | |
["Give me a list of the top 10 dive sites you would recommend around the world."], | |
["Can you tell me more about deep-water soloing?"], | |
["Can you write a short tweet about the Apache 2.0 release of our latest AI model, Falcon LLM?"], | |
], | |
inputs=inputs, | |
label="Click on any example and press Enter in the input textbox!", | |
) | |
with gr.Row(elem_id="param_container"): | |
with gr.Column(): | |
model, temperature, top_p = chat_accordion() | |
with gr.Column(): | |
with gr.Accordion("Character", open=False): | |
choices = list(INSTRUCTIONS_MAPPING) | |
bot_name = gr.Dropdown( | |
choices=choices, | |
value=choices[0], | |
interactive=True, | |
label="Character", | |
) | |
instructions = INSTRUCTIONS_MAPPING[instructions] | |
def run_chat(message: str, chat_history, bot_name: str, instructions: 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, instructions) | |
model_output = run_model( | |
prompt, | |
model=model, | |
temperature=temperature, | |
top_p=top_p, | |
) | |
model_output = model_output[len(prompt):].split(STOP_STR)[0] | |
chat_history = chat_history + [[message, 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, instructions: str, model: str, temperature: float, top_p: float): | |
yield from run_chat(RETRY_COMMAND, chat_history, bot_name, instructions, model, temperature, top_p) | |
def clear_chat(): | |
return [] | |
inputs.submit( | |
run_chat, | |
[inputs, chatbot, bot_name, instructions, 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, instructions, 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: | |
gr.HTML(TITLE) | |
with gr.Row(): | |
with gr.Column(): | |
gr.Image("home-banner.jpg", elem_id="banner-image", show_label=False) | |
with gr.Column(): | |
gr.Markdown( | |
"""**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!** | |
✨ This demo is powered by [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), finetuned on the [Baize](https://github.com/project-baize/baize-chatbot) dataset, and running with [Text Generation Inference](https://github.com/huggingface/text-generation-inference). [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 1 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the Apache 2.0 license. It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). This demo is made available by the [HuggingFace H4 team](https://huggingface.co/HuggingFaceH4). | |
🧪 This is only a **first experimental preview**: the [H4 team](https://huggingface.co/HuggingFaceH4) intends to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF. | |
👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/) | |
➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions! | |
⚠️ **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. | |
""" | |
) | |
chat() | |
return demo | |
if __name__ == "__main__": | |
demo = get_demo() | |
demo.queue(max_size=128, concurrency_count=16) | |
demo.launch() | |