Dhahlan2000 commited on
Commit
ba1be70
·
1 Parent(s): e09f725

trying to fix issuenot getting output

Browse files
Files changed (1) hide show
  1. app.py +38 -24
app.py CHANGED
@@ -7,34 +7,20 @@ from langchain.tools import Tool
7
  from langchain_huggingface import HuggingFacePipeline
8
  import os
9
  from dotenv import load_dotenv
10
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
11
  import torch
12
  from langchain.prompts import PromptTemplate
13
 
14
- # Load environment variables
15
- load_dotenv()
16
- NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")
17
- access_token = os.getenv("API_KEY")
18
-
19
- # Initialize model and pipeline
20
- tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b-it", token=access_token)
21
- model = AutoModelForCausalLM.from_pretrained(
22
- "google/gemma-2b-it",
23
- torch_dtype=torch.bfloat16,
24
- token=access_token
25
- )
26
- pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
27
-
28
- # Define improved prompt template
29
  prompt_template = PromptTemplate(
30
  input_variables=["input"],
31
  template="""Answer the following question as best you can. You have access to the following tools:
32
 
33
- Stock Data Fetcher(ticker) - Fetch recent stock data for a valid stock ticker symbol (e.g., AAPL for Apple).
34
  Stock News Fetcher(ticker) - Fetch recent news articles about a stock ticker.
35
  Moving Average Calculator(ticker, window=5) - Calculate the moving average of a stock over a 5-day window.
36
 
37
  Use the following format:
 
38
  Question: the input question you must answer
39
  Thought: you should always think about what to do
40
  Action: the action to take, should be one of [Stock Data Fetcher, Stock News Fetcher, Moving Average Calculator]
@@ -44,16 +30,33 @@ Observation: the result of the action
44
  Thought: I now know the final answer
45
  Final Answer: the final answer to the original input question
46
 
47
- Strictly follow this format. Do not provide a Final Answer until all Observations are collected.
48
-
49
  Begin!
 
50
  Question: {input}
51
  """
52
  )
53
 
54
- # Helper functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def fetch_stock_data(ticker):
56
  try:
 
57
  stock = yf.Ticker(ticker)
58
  hist = stock.history(period="1mo")
59
  if hist.empty:
@@ -62,6 +65,7 @@ def fetch_stock_data(ticker):
62
  except Exception as e:
63
  return {"error": str(e)}
64
 
 
65
  def fetch_stock_news(ticker, NEWSAPI_KEY):
66
  api_url = f"https://newsapi.org/v2/everything?q={ticker}&apiKey={NEWSAPI_KEY}"
67
  response = requests.get(api_url)
@@ -77,13 +81,15 @@ def calculate_moving_average(ticker, window=5):
77
  hist[f"{window}-day MA"] = hist["Close"].rolling(window=window).mean()
78
  return hist[["Close", f"{window}-day MA"]].tail(5)
79
 
80
- # Tools
 
81
  stock_data_tool = Tool(
82
  name="Stock Data Fetcher",
83
  func=fetch_stock_data,
84
  description="Fetch recent stock data for a valid stock ticker symbol (e.g., AAPL for Apple)."
85
  )
86
 
 
87
  stock_news_tool = Tool(
88
  name="Stock News Fetcher",
89
  func=lambda ticker: fetch_stock_news(ticker, NEWSAPI_KEY),
@@ -96,9 +102,7 @@ moving_average_tool = Tool(
96
  description="Calculate the moving average of a stock over a 5-day window."
97
  )
98
 
99
- # Initialize agent
100
  tools = [stock_data_tool, stock_news_tool, moving_average_tool]
101
- llm = HuggingFacePipeline(pipeline=pipe)
102
 
103
  agent = initialize_agent(
104
  tools=tools,
@@ -109,19 +113,29 @@ agent = initialize_agent(
109
  handle_parsing_errors=True
110
  )
111
 
112
- # Streamlit interface
 
 
 
 
 
113
  st.title("Trading Helper Agent")
114
 
115
  query = st.text_input("Enter your query:")
116
 
117
  if st.button("Submit"):
118
  if query:
 
119
  with st.spinner("Processing..."):
120
  try:
121
  response = agent.run(query)
 
122
  st.success("Response:")
123
  st.write(response)
124
  except Exception as e:
125
  st.error(f"An error occurred: {e}")
 
 
 
126
  else:
127
  st.warning("Please enter a query.")
 
7
  from langchain_huggingface import HuggingFacePipeline
8
  import os
9
  from dotenv import load_dotenv
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer,pipeline
11
  import torch
12
  from langchain.prompts import PromptTemplate
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  prompt_template = PromptTemplate(
15
  input_variables=["input"],
16
  template="""Answer the following question as best you can. You have access to the following tools:
17
 
18
+ Stock Data Fetcher(ticker) - Fetch recent stock data for a valid stock ticker (e.g., AAPL for Apple).
19
  Stock News Fetcher(ticker) - Fetch recent news articles about a stock ticker.
20
  Moving Average Calculator(ticker, window=5) - Calculate the moving average of a stock over a 5-day window.
21
 
22
  Use the following format:
23
+
24
  Question: the input question you must answer
25
  Thought: you should always think about what to do
26
  Action: the action to take, should be one of [Stock Data Fetcher, Stock News Fetcher, Moving Average Calculator]
 
30
  Thought: I now know the final answer
31
  Final Answer: the final answer to the original input question
32
 
 
 
33
  Begin!
34
+
35
  Question: {input}
36
  """
37
  )
38
 
39
+
40
+ load_dotenv()
41
+ NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")
42
+ access_token = os.getenv("API_KEY")
43
+
44
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b-it", token = access_token)
45
+ model = AutoModelForCausalLM.from_pretrained(
46
+ "google/gemma-2b-it",
47
+ torch_dtype=torch.bfloat16,
48
+ token = access_token
49
+ )
50
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=2048)
51
+
52
+ def validate_ticker(ticker):
53
+ # Ensure ticker is uppercase and length is reasonable (1-5 characters)
54
+ return ticker.strip().upper()
55
+
56
+
57
  def fetch_stock_data(ticker):
58
  try:
59
+ ticker = ticker.strip().upper()
60
  stock = yf.Ticker(ticker)
61
  hist = stock.history(period="1mo")
62
  if hist.empty:
 
65
  except Exception as e:
66
  return {"error": str(e)}
67
 
68
+
69
  def fetch_stock_news(ticker, NEWSAPI_KEY):
70
  api_url = f"https://newsapi.org/v2/everything?q={ticker}&apiKey={NEWSAPI_KEY}"
71
  response = requests.get(api_url)
 
81
  hist[f"{window}-day MA"] = hist["Close"].rolling(window=window).mean()
82
  return hist[["Close", f"{window}-day MA"]].tail(5)
83
 
84
+ llm = HuggingFacePipeline(pipeline=pipe)
85
+
86
  stock_data_tool = Tool(
87
  name="Stock Data Fetcher",
88
  func=fetch_stock_data,
89
  description="Fetch recent stock data for a valid stock ticker symbol (e.g., AAPL for Apple)."
90
  )
91
 
92
+
93
  stock_news_tool = Tool(
94
  name="Stock News Fetcher",
95
  func=lambda ticker: fetch_stock_news(ticker, NEWSAPI_KEY),
 
102
  description="Calculate the moving average of a stock over a 5-day window."
103
  )
104
 
 
105
  tools = [stock_data_tool, stock_news_tool, moving_average_tool]
 
106
 
107
  agent = initialize_agent(
108
  tools=tools,
 
113
  handle_parsing_errors=True
114
  )
115
 
116
+
117
+ print(fetch_stock_data("AAPL"))
118
+ print(fetch_stock_news("AAPL", NEWSAPI_KEY))
119
+ print(calculate_moving_average("AAPL"))
120
+
121
+
122
  st.title("Trading Helper Agent")
123
 
124
  query = st.text_input("Enter your query:")
125
 
126
  if st.button("Submit"):
127
  if query:
128
+ st.write("Debug: User Query ->", query)
129
  with st.spinner("Processing..."):
130
  try:
131
  response = agent.run(query)
132
+ st.write("Debug: Agent Response ->", response)
133
  st.success("Response:")
134
  st.write(response)
135
  except Exception as e:
136
  st.error(f"An error occurred: {e}")
137
+ # Log the full LLM output for debugging
138
+ if hasattr(e, "output"):
139
+ st.write("Raw Output:", e.output)
140
  else:
141
  st.warning("Please enter a query.")