Spaces:
Running
Running
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| import os | |
| token = os.getenv("huggingface_token") | |
| client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=token) | |
| def respond( | |
| message, | |
| history: list[tuple[str, str]], | |
| system_message, | |
| max_tokens, | |
| temperature, | |
| top_p, | |
| ): | |
| messages = [{"role": "system", "content": system_message}] | |
| for user, assistant in history: | |
| if user: | |
| messages.append({"role": "user", "content": user}) | |
| if assistant: | |
| messages.append({"role": "assistant", "content": assistant}) | |
| messages.append({"role": "user", "content": message}) | |
| response = "" | |
| for message in client.chat_completion( | |
| messages, | |
| max_tokens=max_tokens, | |
| stream=True, | |
| temperature=temperature, | |
| top_p=top_p, | |
| ): | |
| token_piece = message.choices[0].delta.content | |
| response += token_piece | |
| yield response | |
| # Make a version of `respond` that's API-callable | |
| def chat_api(message, max_tokens, temperature, top_p): | |
| # Create a minimal prompt with default system message and no chat history | |
| messages = [{"role": "system", "content": DEFAULT_SYSTEM_MESSAGE}] | |
| messages.append({"role": "user", "content": message}) | |
| output = "" | |
| for chunk in client.chat_completion( | |
| messages, | |
| max_tokens=max_tokens, | |
| stream=True, | |
| temperature=temperature, | |
| top_p=top_p, | |
| ): | |
| output += chunk.choices[0].delta.content | |
| return output | |
| DEFAULT_SYSTEM_MESSAGE = ( | |
| "I am Bilguun, a third year software engineering student at McGill University and the founder of VentureCircle. " | |
| "VentureCircle is based in Montreal. " | |
| "I created this chatbot, LaunchPad, to help aspiring entrepreneurs achieve their goals. " | |
| "Your name is LaunchPad. " | |
| "LaunchPad is a friendly AI assistant designed to provide useful and supportive guidance for starting and growing a startup." | |
| ) | |
| # Main demo UI | |
| demo = gr.ChatInterface( | |
| respond, | |
| additional_inputs=[ | |
| gr.Textbox(value=DEFAULT_SYSTEM_MESSAGE, label="System message"), | |
| gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), | |
| gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), | |
| gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"), | |
| ], | |
| ) | |
| # Launch with /chat endpoint | |
| demo.launch(share=True, show_error=True).api(fn=chat_api, inputs=["text", "slider", "slider", "slider"], api_name="/chat") |