1414from contextlib import asynccontextmanager
1515import json
1616from redis import asyncio as aioredis
17-
1817# Custom imports
1918from topStocks import get_top_stocks
2019from ask import groq_chat
20+ from stockNews import fetch_news
2121from agents import multi_ai
2222from agno .agent import RunResponse
2323
2929
3030if not GROQ_API_KEY :
3131 raise ValueError ("Please provide a GROQ API key" )
32-
3332REDIS_URL = os .getenv ("REDIS_URL" )
3433
3534@asynccontextmanager
@@ -54,8 +53,7 @@ async def lifespan(_: FastAPI):
5453 print (f"❌ Error while closing Redis: { e } " )
5554
5655
57- app = FastAPI (lifespan = lifespan ) # Pass the lifespan context manager to FastAPI
58-
56+ app = FastAPI (lifespan = lifespan )
5957app .add_middleware (
6058 CORSMiddleware ,
6159 allow_origins = ["*" ],
@@ -87,7 +85,18 @@ async def read_top_stocks(cache: RedisBackend = Depends(get_cache)):
8785 await cache .set (cache_key , json .dumps (stock_info ), 10 )
8886 return stock_info
8987
90- @app .get ("/health" ) # Changed to GET since it's retrieving status
88+ @app .get ("/stock-news" )
89+ async def stock_news (cache : RedisBackend = Depends (get_cache )):
90+ cache_key = "stock_news"
91+ cached_result = await cache .get (cache_key )
92+ if cached_result :
93+ return json .loads (cached_result )
94+ news_stack = fetch_news ()
95+ await cache .set (cache_key , json .dumps (news_stack ), 300 )
96+ return news_stack
97+
98+
99+ @app .get ("health/" ) # Changed to GET since it's retrieving status
91100async def health_check ():
92101 try :
93102 return {
@@ -96,7 +105,6 @@ async def health_check():
96105 "uptime" : "OK" ,
97106 "api" : {
98107 "groq_api" : "connected" if GROQ_API_KEY else "not configured" ,
99- "redis_cache" : "connected" if REDIS_URL else "not configured" ,
100108 },
101109 "ip" : requests .get ('https://api.ipify.org' ).text ,
102110 "services" : {
@@ -118,10 +126,18 @@ def chat(query: str):
118126 """
119127 API endpoint to handle user investment-related questions and return AI-generated insights.
120128 """
121-
129+ if not query :
130+ return {"error" : "Query parameter is required" }
131+
122132 try :
123- answer = groq_chat (query )
124- return answer
133+ response = groq_client .chat .completions .create (
134+ model = "llama-3.3-70b-versatile" ,
135+ messages = [{"role" : "system" , "content" : "You are an AI investment assistant." },
136+ {"role" : "user" , "content" : query }]
137+ )
138+
139+ answer = response .choices [0 ].message .content
140+ return {"question" : query , "answer" : answer }
125141
126142 except Exception as e :
127143 return {"error" : str (e )}
@@ -142,4 +158,4 @@ def ask(query: str):
142158 return {"question" : query , "answer" : answer }
143159
144160 except Exception as e :
145- return {"error" : str (e )}
161+ return {"error" : str (e )}
0 commit comments