Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,137 +1,114 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
-
import hashlib
|
| 4 |
-
import asyncio
|
| 5 |
-
import pickle
|
| 6 |
-
import time
|
| 7 |
-
from openai import AsyncOpenAI
|
| 8 |
-
from functools import lru_cache
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
#
|
|
|
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
-
print(f"Error
|
| 61 |
exit()
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
|
| 65 |
-
async def fetch_grok_response(prompt: str, model: str) -> str:
|
| 66 |
-
start_time = time.time()
|
| 67 |
-
try:
|
| 68 |
-
stream = await client.chat.completions.create(
|
| 69 |
-
model=model,
|
| 70 |
-
messages=[
|
| 71 |
-
{"role": "system", "content": (
|
| 72 |
-
"You are a financial advisor. Provide concise stock market investment advice. "
|
| 73 |
-
"Avoid specific company recommendations without data; suggest ETFs or strategies. "
|
| 74 |
-
"Advise consulting a certified financial planner."
|
| 75 |
-
)},
|
| 76 |
-
{"role": "user", "content": prompt}
|
| 77 |
-
],
|
| 78 |
-
temperature=0.2,
|
| 79 |
-
max_tokens=150,
|
| 80 |
-
top_p=1.0,
|
| 81 |
-
stream=True
|
| 82 |
-
)
|
| 83 |
-
response = ""
|
| 84 |
-
async for chunk in stream:
|
| 85 |
-
if chunk.choices[0].delta.content:
|
| 86 |
-
response += chunk.choices[0].delta.content
|
| 87 |
-
print(f"API call took {time.time() - start_time:.2f} seconds")
|
| 88 |
-
return response.strip()
|
| 89 |
-
except Exception as e:
|
| 90 |
-
print(f"API call took {time.time() - start_time:.2f} seconds")
|
| 91 |
-
return f"Error generating response: {str(e)}"
|
| 92 |
-
|
| 93 |
-
# Define async chat function
|
| 94 |
-
async def chat_with_model(message, history=None): # Ignore history
|
| 95 |
try:
|
| 96 |
if not isinstance(message, str):
|
| 97 |
return "Error: User input must be a string"
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
-
return f"Error
|
| 118 |
-
|
| 119 |
-
# Wrapper for Gradio compatibility
|
| 120 |
-
def chat_with_model_sync(message, history=None):
|
| 121 |
-
return asyncio.run(chat_with_model(message, history))
|
| 122 |
|
| 123 |
# Create Gradio interface
|
| 124 |
interface = gr.ChatInterface(
|
| 125 |
-
fn=
|
| 126 |
-
title="Financial Advisor Chatbot (
|
| 127 |
-
description=
|
| 128 |
-
"Ask for advice on starting to invest in the stock market! Powered by xAI's Grok 3 Mini API for faster responses. "
|
| 129 |
-
"Provides single, direct answers without conversation history. "
|
| 130 |
-
"Monitor API rate limits in the xAI Developer Console (console.x.ai)."
|
| 131 |
-
),
|
| 132 |
examples=[
|
| 133 |
"Hi, pretend you are a financial advisor. Now tell me how can I start investing in stock market?",
|
| 134 |
-
"You have a list of companies you recommend?"
|
|
|
|
| 135 |
]
|
| 136 |
)
|
| 137 |
|
|
|
|
| 1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2 |
+
import torch
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Define device
|
| 6 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
|
| 8 |
+
# Expanded response cache with more common questions
|
| 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"
|
| 14 |
+
"3. **Brokerage**: Choose Fidelity (low fees), Vanguard (index funds like VTI), or Robinhood (commission-free).\n"
|
| 15 |
+
"4. **Investments**: Start with ETFs (e.g., VOO for S&P 500) or mutual funds.\n"
|
| 16 |
+
"5. **Strategy**: Use dollar-cost averaging with $100-$500 monthly.\n"
|
| 17 |
+
"6. **Risks**: Diversify and monitor.\n"
|
| 18 |
+
"Consult a certified financial planner."
|
| 19 |
+
),
|
| 20 |
+
"do you have a list of companies you recommend?": (
|
| 21 |
+
"I cannot recommend specific companies without current market data. Instead, consider ETFs like VOO (S&P 500) or QQQ (tech-focused) for broad exposure. "
|
| 22 |
+
"For stocks, research sectors like technology (e.g., Apple, Microsoft) or consumer goods (e.g., Procter & Gamble) using Yahoo Finance or Morningstar. "
|
| 23 |
+
"Consult a certified financial planner."
|
| 24 |
+
),
|
| 25 |
+
"can you provide me a list of companies you recommend?": (
|
| 26 |
+
"I cannot provide specific company recommendations without up-to-date market analysis. For safer investments, consider ETFs like VOO (S&P 500) or QQQ (tech-focused). "
|
| 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 |
+
}
|
| 50 |
|
| 51 |
+
# Load model
|
| 52 |
+
model_name = "facebook/opt-350m"
|
| 53 |
try:
|
| 54 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, clean_up_tokenization_spaces=False)
|
| 55 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 56 |
+
model_name,
|
| 57 |
+
device_map="auto",
|
| 58 |
+
torch_dtype=torch.float16
|
| 59 |
+
).to(device)
|
| 60 |
except Exception as e:
|
| 61 |
+
print(f"Error loading OPT-350m: {e}")
|
| 62 |
exit()
|
| 63 |
|
| 64 |
+
# Define chat function with enhanced prompt
|
| 65 |
+
def chat_with_model(message, history=None): # Ignore history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
if not isinstance(message, str):
|
| 68 |
return "Error: User input must be a string"
|
| 69 |
+
if message in response_cache:
|
| 70 |
+
return response_cache[message]
|
| 71 |
+
full_prompt = (
|
| 72 |
+
"You are a financial advisor with expertise in stock market investments. "
|
| 73 |
+
"Provide accurate, detailed, and actionable advice in a single response. "
|
| 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 |
+
outputs = model.generate(
|
| 91 |
+
**inputs,
|
| 92 |
+
max_new_tokens=30, # Adjustable for speed vs. quality
|
| 93 |
+
do_sample=True,
|
| 94 |
+
top_p=0.9,
|
| 95 |
+
temperature=0.4,
|
| 96 |
+
pad_token_id=tokenizer.eos_token_id
|
| 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:
|
| 101 |
+
return f"Error generating response: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# Create Gradio interface
|
| 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 single, direct answers without conversation history.",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|