Skip to content
This repository was archived by the owner on May 30, 2025. It is now read-only.

Commit ad00d7c

Browse files
author
yashksaini-coder
committed
Refactor stock news fetching to use GROQ API and enhance web agent capabilities; update requirements and improve health check endpoint with uptime tracking.
1 parent 87d2401 commit ad00d7c

File tree

4 files changed

+71
-37
lines changed

4 files changed

+71
-37
lines changed

controllers/stockNews.py

Lines changed: 51 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,59 @@
1-
import finnhub
2-
import time
3-
import requests
4-
import dotenv
1+
import groq
52
import os
3+
from dotenv import load_dotenv
4+
load_dotenv()
65

7-
dotenv.load_dotenv()
6+
# AI assistant imports
7+
from fastapi.responses import HTMLResponse, JSONResponse
8+
from agno.agent import Agent
9+
from agno.models.groq import Groq
10+
from agno.tools.yfinance import YFinanceTools
11+
from agno.tools.duckduckgo import DuckDuckGoTools
12+
from agno.agent import Agent, RunResponse
13+
from agno.tools.wikipedia import WikipediaTools
14+
from agno.tools.calculator import CalculatorTools
815

9-
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
16+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
17+
groq_client = groq.Client(api_key=GROQ_API_KEY)
1018

11-
if not NEWS_API_KEY:
12-
raise ValueError("Please provide a NEWS API key")
19+
if not GROQ_API_KEY:
20+
raise ValueError("Please provide a GROQ API key")
21+
22+
# Enhanced web search agent with more capabilities
23+
web_agent = Agent(
24+
name="web_agent",
25+
role="comprehensive web research and information gathering specialist",
26+
model=Groq(id="llama-3.1-8b-instant", api_key=GROQ_API_KEY),
27+
tools=[
28+
DuckDuckGoTools(search=True, news=True),
29+
WikipediaTools(),
30+
],
31+
instructions=[
32+
"You are an advanced web research specialist capable of handling complex queries",
33+
"Your primary objectives are to:",
34+
"1. Break down complex queries into manageable sub-tasks",
35+
"2. Gather information from multiple sources for comprehensive answers",
36+
"3. Verify information across different sources",
37+
"4. Provide well-structured, detailed responses with proper citations",
38+
"5. Handle ambiguous queries by asking clarifying questions when needed",
39+
"6. Maintain context throughout multi-step queries",
40+
"7. Format responses in clear, organized markdown with proper sections",
41+
"When dealing with complex queries:",
42+
"- Start by analyzing the query components",
43+
"- Identify required information sources",
44+
"- Gather data systematically",
45+
"- Synthesize information coherently",
46+
"- Provide clear reasoning for your conclusions"
47+
]
48+
)
1349

14-
session = requests.Session()
15-
session.headers.update({
16-
"User-Agent": "Chrome/122.0.0.0"
17-
})
1850
def fetch_news():
51+
"""Fetch latest news articles related to stocks and financial markets"""
1952
try:
20-
21-
finnhub_client = finnhub.Client(api_key=NEWS_API_KEY)
22-
23-
news_list =finnhub_client.general_news('general', min_id=4)
24-
news_stack=[]
25-
for news in news_list[:10]:
26-
news_stack.append([news['headline'],news['url']])
27-
print("✅ Data fetching done successfully!")
28-
return news_stack
53+
response: RunResponse = web_agent.run("Latest news articles related to stocks and financial markets")
54+
return {
55+
"question": "Latest news articles related to stocks and financial markets",
56+
"answer": response.content
57+
}
2958
except Exception as e:
30-
print(f"❌ Error fetching news: {e}")
31-
time.sleep(5)
59+
raise RuntimeError(f"Error fetching news: {str(e)}")

requirements.txt

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,17 @@ click==8.1.8
1010
colorama==0.4.6
1111
distro==1.9.0
1212
dnspython==2.7.0
13-
docstring_parser==0.16
14-
duckduckgo_search==7.3.2
15-
email_validator==2.2.0
13+
docstring-parser==0.16
14+
duckduckgo-search==7.3.2
15+
email-validator==2.2.0
1616
fastapi==0.115.8
1717
fastapi-cache2==0.2.2
1818
fastapi-cli==0.0.7
1919
finnhub-python==2.4.22
20-
Flask==3.1.0
20+
flask==3.1.0
2121
frozendict==2.4.6
2222
gitdb==4.0.12
23-
GitPython==3.1.44
23+
gitpython==3.1.44
2424
google-auth==2.38.0
2525
google-genai==1.5.0
2626
groq==0.18.0
@@ -31,29 +31,30 @@ httptools==0.6.4
3131
httpx==0.28.1
3232
idna==3.10
3333
itsdangerous==2.2.0
34-
Jinja2==3.1.5
34+
jinja2==3.1.5
3535
lxml==5.3.1
3636
markdown-it-py==3.0.0
37-
MarkupSafe==3.0.2
37+
markupsafe==3.0.2
3838
mdurl==0.1.2
3939
multitasking==0.0.11
4040
numpy==2.2.3
4141
pandas==2.2.3
4242
peewee==3.17.9
4343
pendulum==3.0.0
44+
pip==24.2
4445
platformdirs==4.3.6
4546
primp==0.12.1
4647
pyasn1==0.6.1
47-
pyasn1_modules==0.4.1
48+
pyasn1-modules==0.4.1
4849
pydantic==2.10.6
50+
pydantic-core==2.27.2
4951
pydantic-settings==2.7.1
50-
pydantic_core==2.27.2
51-
Pygments==2.19.1
52+
pygments==2.19.1
5253
python-dateutil==2.9.0.post0
5354
python-dotenv==1.0.1
5455
python-multipart==0.0.20
5556
pytz==2025.1
56-
PyYAML==6.0.2
57+
pyyaml==6.0.2
5758
redis==5.2.1
5859
requests==2.32.3
5960
rich==13.9.4
@@ -68,12 +69,13 @@ starlette==0.45.3
6869
time-machine==2.16.0
6970
tomli==2.2.1
7071
typer==0.15.1
71-
typing_extensions==4.12.2
72+
typing-extensions==4.12.2
7273
tzdata==2025.1
7374
urllib3==2.3.0
7475
uvicorn==0.34.0
7576
watchfiles==1.0.4
7677
webencodings==0.5.1
7778
websockets==14.2
78-
Werkzeug==3.1.3
79+
werkzeug==3.1.3
80+
wikipedia==1.4.0
7981
yfinance==0.2.54

routes/agentRoutes.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,18 @@
2121
if not GROQ_API_KEY:
2222
raise ValueError("Please provide a GROQ API key")
2323

24+
start_time = datetime.datetime.now(datetime.timezone.utc)
25+
2426
@router.get("/health", response_class=HTMLResponse)
2527
async def health_check(request: Request):
2628
"""Health check endpoint to verify the API server status and connections."""
29+
uptime = (datetime.datetime.now(datetime.timezone.utc) - start_time).total_seconds()
2730
try:
2831
response_data = {
2932
"status": "healthy",
3033
"timestamp": datetime.datetime.now().isoformat(),
3134
"uptime": "OK",
35+
"uptime_seconds": uptime,
3236
"api": {
3337
"groq_api": "connected" if GROQ_API_KEY else "not configured",
3438
"gemini_api":"connected" if GEMINI_API_KEY else "not configured",

routes/stockRoutes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ async def stock_news(request: Request):
5656
"full_path": f"{request.url.scheme}://{request.url.netloc}/stock-news",
5757
"description": "Returns latest news articles related to stocks and financial markets",
5858
"parameters": [],
59-
"example_response": json.dumps(result[:2], indent=2),
59+
"example_response": json.dumps(result, indent=2),
6060
"current_year": datetime.datetime.now().year
6161
})
6262
return result

0 commit comments

Comments
 (0)