QuantumLearner commited on
Commit
7bad375
·
verified ·
1 Parent(s): 2cbe35b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -24
app.py CHANGED
@@ -23,14 +23,14 @@ import pandas as pd
23
 
24
  load_dotenv()
25
 
26
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
27
- FMP_API_KEY = os.getenv("FMP_API_KEY")
28
-
29
- print("DEBUG: GROQ_API_KEY ->", GROQ_API_KEY)
30
- print("DEBUG: FMP_API_KEY ->", FMP_API_KEY)
31
 
32
  embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
33
- llm = Groq(model="llama3-70b-8192", api_key=GROQ_API_KEY)
34
 
35
  service_context = ServiceContext.from_defaults(
36
  llm=llm,
@@ -39,9 +39,13 @@ service_context = ServiceContext.from_defaults(
39
  )
40
 
41
  def fetch_annual_report_10k(symbol: str) -> str:
 
42
  print("DEBUG: fetch_annual_report_10k called with symbol:", symbol)
43
  current_year = datetime.datetime.now().year
44
- url = f"https://financialmodelingprep.com/api/v4/financial-reports-json?symbol={symbol}&year={current_year}&period=FY&apikey={FMP_API_KEY}"
 
 
 
45
  print("DEBUG: URL ->", url)
46
  try:
47
  response = requests.get(url, timeout=10)
@@ -99,9 +103,10 @@ async def on_chat_start():
99
  annual_report_text = fetch_annual_report_10k(ticker_symbol)
100
  print("DEBUG: annual_report_text snippet ->", annual_report_text[:200])
101
 
102
- if annual_report_text.startswith("HTTP error") or \
103
- annual_report_text.startswith("Request error") or \
104
- annual_report_text.startswith("An unexpected error occurred"):
 
105
  await cl.Message(content=annual_report_text).send()
106
  return
107
 
@@ -114,15 +119,19 @@ async def on_chat_start():
114
  cl.user_session.set("index", index)
115
  query_engine = index.as_query_engine()
116
 
 
117
  summary_response = await cl.make_async(query_engine.query)(summary_prompt)
118
- print("DEBUG: summary_response snippet ->", summary_response[:200])
119
-
120
- await cl.Message(content=f"**Summary:**\n{summary_response}").send()
 
121
 
 
122
  questions_response = await cl.make_async(query_engine.query)(question_prompt)
123
- print("DEBUG: questions_response snippet ->", questions_response[:200])
 
124
 
125
- questions_format = str(questions_response).split('\n')
126
  relevant_questions = [
127
  question.strip() for question in questions_format
128
  if question.strip() and question.strip()[0].isdigit()
@@ -131,9 +140,10 @@ async def on_chat_start():
131
  await cl.Message(content="Generated strategic questions and answers:").send()
132
  for question in relevant_questions:
133
  await cl.Message(content=f"**{question}**").send()
134
- answer = await cl.make_async(query_engine.query)(question)
135
- print(f"DEBUG: Answer for '{question[:30]}' snippet ->", answer[:200])
136
- await cl.Message(content=f"**Answer:**\n{answer}").send()
 
137
 
138
  msg.content = "Processing done. You can now ask more questions about the 10-K report!"
139
  await msg.update()
@@ -155,11 +165,20 @@ async def main(message: cl.Message):
155
  user_query = message.content
156
  print("DEBUG: user_query ->", user_query)
157
 
158
- response = await cl.make_async(query_engine.query)(user_query)
159
- print("DEBUG: response snippet ->", str(response)[:200])
 
 
 
 
160
 
161
- response_message = cl.Message(content="")
162
- for token in str(response):
163
- await response_message.stream_token(token=token)
 
164
 
165
- await response_message.send()
 
 
 
 
 
23
 
24
  load_dotenv()
25
 
26
+ # Omit printing actual keys for safety.
27
+ groq_api_key = os.getenv("GROQ_API_KEY")
28
+ fmp_api_key = os.getenv("FMP_API_KEY")
29
+ print("DEBUG: GROQ_API_KEY ->", "***REDACTED***" if groq_api_key else None)
30
+ print("DEBUG: FMP_API_KEY ->", "***REDACTED***" if fmp_api_key else None)
31
 
32
  embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
33
+ llm = Groq(model="llama3-70b-8192", api_key=groq_api_key)
34
 
35
  service_context = ServiceContext.from_defaults(
36
  llm=llm,
 
39
  )
40
 
41
  def fetch_annual_report_10k(symbol: str) -> str:
42
+ """Fetch the latest 10-K JSON response for a given stock ticker."""
43
  print("DEBUG: fetch_annual_report_10k called with symbol:", symbol)
44
  current_year = datetime.datetime.now().year
45
+ url = (
46
+ "https://financialmodelingprep.com/api/v4/financial-reports-json"
47
+ f"?symbol={symbol}&year={current_year}&period=FY&apikey={fmp_api_key}"
48
+ )
49
  print("DEBUG: URL ->", url)
50
  try:
51
  response = requests.get(url, timeout=10)
 
103
  annual_report_text = fetch_annual_report_10k(ticker_symbol)
104
  print("DEBUG: annual_report_text snippet ->", annual_report_text[:200])
105
 
106
+ # Check for various errors
107
+ if (annual_report_text.startswith("HTTP error") or
108
+ annual_report_text.startswith("Request error") or
109
+ annual_report_text.startswith("An unexpected error occurred")):
110
  await cl.Message(content=annual_report_text).send()
111
  return
112
 
 
119
  cl.user_session.set("index", index)
120
  query_engine = index.as_query_engine()
121
 
122
+ # Summaries
123
  summary_response = await cl.make_async(query_engine.query)(summary_prompt)
124
+ # Convert to string in case it's a special object
125
+ summary_text = str(summary_response)
126
+ print("DEBUG: summary_response snippet ->", summary_text[:200])
127
+ await cl.Message(content=f"**Summary:**\n{summary_text}").send()
128
 
129
+ # Questions
130
  questions_response = await cl.make_async(query_engine.query)(question_prompt)
131
+ questions_text = str(questions_response)
132
+ print("DEBUG: questions_response snippet ->", questions_text[:200])
133
 
134
+ questions_format = questions_text.split('\n')
135
  relevant_questions = [
136
  question.strip() for question in questions_format
137
  if question.strip() and question.strip()[0].isdigit()
 
140
  await cl.Message(content="Generated strategic questions and answers:").send()
141
  for question in relevant_questions:
142
  await cl.Message(content=f"**{question}**").send()
143
+ answer_obj = await cl.make_async(query_engine.query)(question)
144
+ answer_text = str(answer_obj)
145
+ print(f"DEBUG: Answer for '{question[:30]}' snippet ->", answer_text[:200])
146
+ await cl.Message(content=f"**Answer:**\n{answer_text}").send()
147
 
148
  msg.content = "Processing done. You can now ask more questions about the 10-K report!"
149
  await msg.update()
 
165
  user_query = message.content
166
  print("DEBUG: user_query ->", user_query)
167
 
168
+ try:
169
+ # Run the query
170
+ raw_response = await cl.make_async(query_engine.query)(user_query)
171
+ # Convert to string to avoid 'Response' object subscript issues
172
+ response_str = str(raw_response)
173
+ print("DEBUG: response_str snippet ->", response_str[:200])
174
 
175
+ # Stream the text token by token
176
+ response_message = cl.Message(content="")
177
+ for token in response_str:
178
+ await response_message.stream_token(token=token)
179
 
180
+ await response_message.send()
181
+
182
+ except Exception as e:
183
+ print("DEBUG: Error in main query ->", str(e))
184
+ await cl.Message(content=f"Error while processing your question: {str(e)}").send()