Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -5,9 +5,9 @@ import gradio as gr
|
|
5 |
# Define device
|
6 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
|
8 |
-
# Expanded response cache
|
9 |
response_cache = {
|
10 |
-
"
|
11 |
"As a financial advisor, here’s a guide to start investing in the stock market:\n"
|
12 |
"1. **Learn**: Use Investopedia or “The Intelligent Investor” by Benjamin Graham.\n"
|
13 |
"2. **Goals**: Set objectives (e.g., retirement) and assess risk tolerance.\n"
|
@@ -27,24 +27,32 @@ response_cache = {
|
|
27 |
"If interested in stocks, explore stable companies in technology (e.g., Apple, Microsoft) or healthcare (e.g., Johnson & Johnson) using Yahoo Finance. "
|
28 |
"Always consult a financial planner for tailored advice."
|
29 |
),
|
30 |
-
"
|
31 |
"I cannot recommend specific companies without current market data. Instead, consider ETFs like VOO (S&P 500) or QQQ (tech-focused) for broad exposure. "
|
32 |
"For stocks, research sectors like technology (e.g., Apple, Microsoft) or consumer goods (e.g., Procter & Gamble) using Yahoo Finance or Morningstar. "
|
33 |
"Consult a certified financial planner."
|
34 |
),
|
35 |
-
"
|
36 |
"To start investing in stocks, educate yourself using resources like Investopedia or books such as 'The Intelligent Investor.' "
|
37 |
"Set investment goals and assess your risk tolerance. Open an account with a brokerage like Fidelity or Vanguard, "
|
38 |
"and begin with diversified options like ETFs (e.g., VOO) or mutual funds. Consult a financial planner for personalized advice."
|
39 |
),
|
40 |
-
"
|
41 |
"I can’t recommend specific stocks without current market data. For a safer approach, consider ETFs like VOO (S&P 500) or QQQ (tech-focused). "
|
42 |
"If you prefer stocks, research companies in strong sectors like technology or healthcare using tools like Yahoo Finance. "
|
43 |
"Consult a financial planner for up-to-date advice."
|
44 |
),
|
45 |
-
"
|
46 |
"Stocks represent ownership in a company and offer potential growth but with higher risk. Bonds are loans to a company or government, "
|
47 |
"providing steady interest with lower risk. Stocks may pay dividends, while bonds pay coupons. Diversifying with both can balance risk and return."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
)
|
49 |
}
|
50 |
|
@@ -61,40 +69,44 @@ except Exception as e:
|
|
61 |
print(f"Error loading OPT-350m: {e}")
|
62 |
exit()
|
63 |
|
64 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
def chat_with_model(message, history=None): # Ignore history
|
66 |
try:
|
67 |
-
|
68 |
-
|
69 |
-
if
|
70 |
-
return response_cache[
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
"Do not rely on prior conversation context. "
|
75 |
-
"If you cannot provide specific recommendations (e.g., individual companies), "
|
76 |
-
"explain why and offer general guidance or alternative suggestions.\n\n"
|
77 |
-
"Examples:\n"
|
78 |
-
"Q: How can I start investing in the stock market?\n"
|
79 |
-
"A: Start by educating yourself with resources like Investopedia or 'The Intelligent Investor.' "
|
80 |
-
"Set clear goals and assess your risk tolerance. Choose a brokerage like Fidelity or Vanguard, "
|
81 |
-
"and consider starting with ETFs or mutual funds.\n\n"
|
82 |
-
"Q: What are some good companies to invest in?\n"
|
83 |
-
"A: I cannot recommend specific companies without current market data. "
|
84 |
-
"Consider ETFs like VOO or QQQ for broad exposure, or research stable sectors like technology or healthcare.\n\n"
|
85 |
-
"Now, answer the following question:\n"
|
86 |
-
"Q: {message}\n"
|
87 |
-
"A:"
|
88 |
-
).format(message=message)
|
89 |
inputs = tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
98 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
99 |
return response[len(full_prompt):].strip() if response.startswith(full_prompt) else response
|
100 |
except Exception as e:
|
@@ -104,11 +116,13 @@ def chat_with_model(message, history=None): # Ignore history
|
|
104 |
interface = gr.ChatInterface(
|
105 |
fn=chat_with_model,
|
106 |
title="Financial Advisor Chatbot (OPT-350m)",
|
107 |
-
description="Ask for advice on starting to invest in the stock market! Powered by Meta AI's OPT-350m. Provides
|
108 |
examples=[
|
109 |
"Hi, pretend you are a financial advisor. Now tell me how can I start investing in stock market?",
|
110 |
"You have a list of companies you recommend?",
|
111 |
-
"What's the difference between stocks and bonds?"
|
|
|
|
|
112 |
]
|
113 |
)
|
114 |
|
|
|
5 |
# Define device
|
6 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
|
8 |
+
# Expanded and normalized response cache
|
9 |
response_cache = {
|
10 |
+
"hi, pretend you are a financial advisor. now tell me how can i start investing in stock market?": (
|
11 |
"As a financial advisor, here’s a guide to start investing in the stock market:\n"
|
12 |
"1. **Learn**: Use Investopedia or “The Intelligent Investor” by Benjamin Graham.\n"
|
13 |
"2. **Goals**: Set objectives (e.g., retirement) and assess risk tolerance.\n"
|
|
|
27 |
"If interested in stocks, explore stable companies in technology (e.g., Apple, Microsoft) or healthcare (e.g., Johnson & Johnson) using Yahoo Finance. "
|
28 |
"Always consult a financial planner for tailored advice."
|
29 |
),
|
30 |
+
"you have a list of companies you recommend?": (
|
31 |
"I cannot recommend specific companies without current market data. Instead, consider ETFs like VOO (S&P 500) or QQQ (tech-focused) for broad exposure. "
|
32 |
"For stocks, research sectors like technology (e.g., Apple, Microsoft) or consumer goods (e.g., Procter & Gamble) using Yahoo Finance or Morningstar. "
|
33 |
"Consult a certified financial planner."
|
34 |
),
|
35 |
+
"how do i start investing in stocks?": (
|
36 |
"To start investing in stocks, educate yourself using resources like Investopedia or books such as 'The Intelligent Investor.' "
|
37 |
"Set investment goals and assess your risk tolerance. Open an account with a brokerage like Fidelity or Vanguard, "
|
38 |
"and begin with diversified options like ETFs (e.g., VOO) or mutual funds. Consult a financial planner for personalized advice."
|
39 |
),
|
40 |
+
"what are the best stocks to buy right now?": (
|
41 |
"I can’t recommend specific stocks without current market data. For a safer approach, consider ETFs like VOO (S&P 500) or QQQ (tech-focused). "
|
42 |
"If you prefer stocks, research companies in strong sectors like technology or healthcare using tools like Yahoo Finance. "
|
43 |
"Consult a financial planner for up-to-date advice."
|
44 |
),
|
45 |
+
"what's the difference between stocks and bonds?": (
|
46 |
"Stocks represent ownership in a company and offer potential growth but with higher risk. Bonds are loans to a company or government, "
|
47 |
"providing steady interest with lower risk. Stocks may pay dividends, while bonds pay coupons. Diversifying with both can balance risk and return."
|
48 |
+
),
|
49 |
+
"how much should i invest?": (
|
50 |
+
"The amount to invest depends on your financial situation, goals, and risk tolerance. Start with what you can afford after covering expenses and an emergency fund (e.g., 3-6 months’ savings). "
|
51 |
+
"Consider investing $100-$500 monthly in ETFs like VOO using dollar-cost averaging. Consult a financial planner for personalized advice."
|
52 |
+
),
|
53 |
+
"what is dollar-cost averaging?": (
|
54 |
+
"Dollar-cost averaging involves investing a fixed amount regularly (e.g., $100 monthly) into assets like ETFs, regardless of market conditions. "
|
55 |
+
"This reduces the risk of buying at a high price and smooths out costs over time. It’s ideal for long-term investing."
|
56 |
)
|
57 |
}
|
58 |
|
|
|
69 |
print(f"Error loading OPT-350m: {e}")
|
70 |
exit()
|
71 |
|
72 |
+
# Pre-tokenize static prompt prefix
|
73 |
+
prompt_prefix = (
|
74 |
+
"You are a financial advisor with expertise in stock market investments. "
|
75 |
+
"Provide accurate, detailed, and actionable advice in a single response. "
|
76 |
+
"If you cannot provide specific recommendations (e.g., individual companies), "
|
77 |
+
"explain why and offer general guidance.\n\n"
|
78 |
+
"Example:\n"
|
79 |
+
"Q: How can I start investing in the stock market?\n"
|
80 |
+
"A: Start by educating yourself with resources like Investopedia or 'The Intelligent Investor.' "
|
81 |
+
"Set clear goals and assess your risk tolerance. Choose a brokerage like Fidelity or Vanguard, "
|
82 |
+
"and consider starting with ETFs or mutual funds.\n\n"
|
83 |
+
"Now, answer the following question:\n"
|
84 |
+
"Q: "
|
85 |
+
)
|
86 |
+
prefix_tokens = tokenizer(prompt_prefix, return_tensors="pt", truncation=True, max_length=512).to(device)
|
87 |
+
|
88 |
+
# Define chat function
|
89 |
def chat_with_model(message, history=None): # Ignore history
|
90 |
try:
|
91 |
+
# Normalize input for cache lookup
|
92 |
+
cache_key = message.lower().strip()
|
93 |
+
if cache_key in response_cache:
|
94 |
+
return response_cache[cache_key]
|
95 |
+
|
96 |
+
# Construct prompt
|
97 |
+
full_prompt = prompt_prefix + message + "\nA:"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
inputs = tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
|
99 |
+
|
100 |
+
# Generate response
|
101 |
+
with torch.no_grad():
|
102 |
+
outputs = model.generate(
|
103 |
+
**inputs,
|
104 |
+
max_new_tokens=20, # Reduced for speed
|
105 |
+
do_sample=True,
|
106 |
+
top_p=0.9,
|
107 |
+
temperature=0.3, # Lowered for faster convergence
|
108 |
+
pad_token_id=tokenizer.eos_token_id
|
109 |
+
)
|
110 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
111 |
return response[len(full_prompt):].strip() if response.startswith(full_prompt) else response
|
112 |
except Exception as e:
|
|
|
116 |
interface = gr.ChatInterface(
|
117 |
fn=chat_with_model,
|
118 |
title="Financial Advisor Chatbot (OPT-350m)",
|
119 |
+
description="Ask for advice on starting to invest in the stock market! Powered by Meta AI's OPT-350m. Provides fast, direct answers without conversation history.",
|
120 |
examples=[
|
121 |
"Hi, pretend you are a financial advisor. Now tell me how can I start investing in stock market?",
|
122 |
"You have a list of companies you recommend?",
|
123 |
+
"What's the difference between stocks and bonds?",
|
124 |
+
"How much should I invest?",
|
125 |
+
"What is dollar-cost averaging?"
|
126 |
]
|
127 |
)
|
128 |
|