Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| from utils import is_financial_text, load_qa_data | |
| # Load CSV Q&A pairs (if you want to use them later) | |
| qa_pairs = load_qa_data() | |
| # Hugging Face client | |
| client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") | |
| # Define system message template | |
| DEFAULT_SYSTEM_MSG = "You are a helpful assistant that answers only finance-related questions. Respond truthfully and avoid unrelated topics." | |
| def respond(message, history, system_message, max_tokens, temperature, top_p): | |
| # Check if user question is finance-related before asking the model | |
| if not is_financial_text(message): | |
| yield "I'm specialized in finance and can't assist with that question." | |
| return | |
| # Prepare messages for Zephyr | |
| messages = [{"role": "system", "content": system_message or DEFAULT_SYSTEM_MSG}] | |
| for user_msg, bot_msg in history: | |
| if user_msg: | |
| messages.append({"role": "user", "content": user_msg}) | |
| if bot_msg: | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| messages.append({"role": "user", "content": message}) | |
| # Get model response (streamed) | |
| response = "" | |
| for msg in client.chat_completion( | |
| messages=messages, | |
| stream=True, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| ): | |
| token = msg.choices[0].delta.content | |
| if token: | |
| response += token | |
| yield response | |
| # Gradio interface | |
| demo = gr.ChatInterface( | |
| respond, | |
| additional_inputs=[ | |
| gr.Textbox(value=DEFAULT_SYSTEM_MSG, 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)"), | |
| ], | |
| title="💰 Finance Assistant", | |
| description="Ask finance-related questions only. The assistant will not respond to unrelated topics.", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |