Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#Gradio app# app.py# app.py - Original approach with profile objectimport gradio as grimport requestsMODAL_URL = "https://devsam2898--personal-investment-strategist-9-web.modal.run/strategy"def get_investment_strategy(age_group, income, expenses, risk_profile, goal, timeframe):"""Get investment strategy from Modal backend"""payload = {"profile": {"age_group": age_group,"income": income,"expenses": expenses,"risk_profile": risk_profile,"goal": goal,"timeframe": timeframe}}try:response = requests.post(MODAL_URL, json=payload, timeout=60)if response.status_code == 200:return response.json().get("strategy", "No strategy returned.")else:return f"β Error {response.status_code}: {response.text}"except Exception as e:return f"β Network error: {str(e)}"demo = gr.Interface(fn=get_investment_strategy,inputs=[gr.Dropdown(["20s", "30s", "40s", "50s+"], label="Age Group", value="30s"),gr.Textbox(label="Monthly Income ($)", value="6000"),gr.Textbox(label="Monthly Expenses ($)", value="4000"),gr.Radio(["Conservative", "Moderate", "Aggressive"], label="Risk Tolerance", value="Moderate"),gr.Textbox(label="Financial Goal (e.g., buy a house)", value="retirement planning"),gr.Textbox(label="Timeframe (e.g., 5 years)", value="10 years")],outputs=gr.Markdown(label="Investment Strategy"),title="π Personal Finance Strategist",description="Powered by LlamaIndex + Nebius Qwen3 | Get personalized strategies based on life stage and goals.",theme="soft",allow_flagging="never")if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147#Gradio app# app.py# app.py - Original approach with profile object# app.pyimport gradio as grimport requestsimport jsonMODAL_URL = "https://devsam2898--personal-investment-strategist-10-web.modal.run/strategy"def get_investment_strategy(age_group, income, expenses, risk_profile, goal, timeframe):"""Get investment strategy from Modal backend"""# Input validationif not all([age_group, income, expenses, risk_profile, goal, timeframe]):return "β Please fill in all fields to get a personalized strategy."# Convert income and expenses to numbers if they're stringstry:income_val = float(income.replace('$', '').replace(',', '')) if isinstance(income, str) else float(income)expenses_val = float(expenses.replace('$', '').replace(',', '')) if isinstance(expenses, str) else float(expenses)except ValueError:return "β Please enter valid numbers for income and expenses."payload = {"profile": {"age_group": age_group,"income": income_val,"expenses": expenses_val,"risk_profile": risk_profile,"goal": goal,"timeframe": timeframe}}try:print(f"Sending request to: {MODAL_URL}")print(f"Payload: {json.dumps(payload, indent=2)}")response = requests.post(MODAL_URL,json=payload,headers={'Content-Type': 'application/json','Accept': 'application/json'},timeout=30 # Add timeout)print(f"Response status: {response.status_code}")print(f"Response headers: {dict(response.headers)}")if response.status_code == 200:result = response.json()strategy = result.get("strategy", "No strategy returned.")return f"## π Your Personalized Investment Strategy\n\n{strategy}"else:error_msg = f"β **Error {response.status_code}**\n\n"try:error_detail = response.json()error_msg += f"Details: {error_detail}"except:error_msg += f"Response: {response.text}"return error_msgexcept requests.exceptions.Timeout:return "β **Request Timeout**: The service is taking too long to respond. Please try again."except requests.exceptions.ConnectionError:return "β **Connection Error**: Unable to connect to the backend service. Please check if the Modal service is running."except requests.exceptions.RequestException as e:return f"β **Network Error**: {str(e)}"except Exception as e:return f"β **Unexpected Error**: {str(e)}"# Test function to verify the function worksdef test_function():return "β Function is working correctly!"# Create the interfacewith gr.Blocks(theme="soft", title="π Personal Finance Strategist") as interface:gr.Markdown("""# π Personal Finance Strategist**Powered by LlamaIndex + Nebius Qwen3**Get personalized investment strategies based on your life stage and financial goals.""")with gr.Row():with gr.Column(scale=1):age_group = gr.Dropdown(choices=["20s", "30s", "40s", "50s+"],label="Age Group",value="30s")income = gr.Textbox(label="Monthly Income ($)",value="6000",placeholder="e.g., 6000")expenses = gr.Textbox(label="Monthly Expenses ($)",value="4000",placeholder="e.g., 4000")with gr.Column(scale=1):risk_profile = gr.Radio(choices=["Conservative", "Moderate", "Aggressive"],label="Risk Tolerance",value="Moderate")goal = gr.Textbox(label="Financial Goal",placeholder="e.g., buy a house, retirement, emergency fund")timeframe = gr.Textbox(label="Timeframe",placeholder="e.g., 5 years, 10 years")with gr.Row():submit_btn = gr.Button("Get Investment Strategy", variant="primary")test_btn = gr.Button("Test Connection", variant="secondary")output = gr.Markdown(label="Investment Strategy")# Event handlerssubmit_btn.click(fn=get_investment_strategy,inputs=[age_group, income, expenses, risk_profile, goal, timeframe],outputs=output)test_btn.click(fn=test_function,outputs=output)if __name__ == "__main__":interface.launch(server_name="0.0.0.0",server_port=7860,share=False)
app.py+124-25