Skip to content

Commit 7204e98

Browse files
author
yashksaini-coder
committed
Enhance agent and stock routes with HTML response support and improved error handling
1 parent 8e49066 commit 7204e98

File tree

2 files changed

+251
-61
lines changed

2 files changed

+251
-61
lines changed

routes/agentRoutes.py

Lines changed: 120 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import os
22
import datetime
3+
import json
34
import requests
45
import groq
5-
from fastapi import FastAPI, APIRouter
6-
from fastapi.responses import HTMLResponse
6+
from fastapi import FastAPI, APIRouter, Request, Query
7+
from fastapi.responses import HTMLResponse, JSONResponse
78
from fastapi.templating import Jinja2Templates
89
from agno.agent import RunResponse
910
from controllers.agents import multi_ai
@@ -20,10 +21,11 @@
2021
if not GROQ_API_KEY:
2122
raise ValueError("Please provide a GROQ API key")
2223

23-
@router.get("/health") # Changed to GET since it's retrieving status
24-
async def health_check():
24+
@router.get("/health", response_class=HTMLResponse)
25+
async def health_check(request: Request):
26+
"""Health check endpoint to verify the API server status and connections."""
2527
try:
26-
return {
28+
response_data = {
2729
"status": "healthy",
2830
"timestamp": datetime.datetime.now().isoformat(),
2931
"uptime": "OK",
@@ -37,20 +39,94 @@ async def health_check():
3739
},
3840
}
3941

42+
# Check if request is from a browser or format is explicitly set to html
43+
accept_header = request.headers.get("accept", "")
44+
if "text/html" in accept_header:
45+
current_year = datetime.datetime.now().year
46+
return templates.TemplateResponse(
47+
"route.html",
48+
{
49+
"request": request,
50+
"route_path": "/health",
51+
"method": "GET",
52+
"full_path": str(request.url).split("?")[0],
53+
"description": "Health check endpoint to verify the API server status and connections.",
54+
"parameters": [
55+
{"name": "format", "type": "string", "description": "Response format (html or json)"}
56+
],
57+
"example_query": "",
58+
"example_response": json.dumps(response_data, indent=2),
59+
"current_year": current_year
60+
}
61+
)
62+
63+
return JSONResponse(content=response_data)
64+
4065
except Exception as e:
41-
return {
66+
error_response = {
4267
"status": "unhealthy",
4368
"timestamp": datetime.datetime.now().isoformat(),
4469
"error": str(e)
4570
}
71+
72+
# Check if request is from a browser or format is explicitly set to html
73+
accept_header = request.headers.get("accept", "")
74+
if "text/html" in accept_header:
75+
current_year = datetime.datetime.now().year
76+
return templates.TemplateResponse(
77+
"route.html",
78+
{
79+
"request": request,
80+
"route_path": "/health",
81+
"method": "GET",
82+
"full_path": str(request.url).split("?")[0],
83+
"description": "Health check endpoint to verify the API server status and connections.",
84+
"parameters": [
85+
{"name": "format", "type": "string", "description": "Response format (html or json)"}
86+
],
87+
"example_query": "",
88+
"example_response": json.dumps(error_response, indent=2),
89+
"current_year": current_year
90+
}
91+
)
92+
93+
return JSONResponse(content=error_response)
4694

47-
@router.get("/chat")
48-
def chat(query: str):
95+
@router.get("/chat", response_class=HTMLResponse)
96+
def chat(request: Request, query: str = None):
4997
"""
5098
API endpoint to handle user investment-related questions and return AI-generated insights.
5199
"""
100+
# Check if request is from a browser or format is explicitly set to html
101+
accept_header = request.headers.get("accept", "")
102+
if "text/html" in accept_header:
103+
current_year = datetime.datetime.now().year
104+
example_response = {
105+
"question": "What are good tech stocks to invest in?",
106+
"answer": "Some popular tech stocks to consider include Apple (AAPL), Microsoft (MSFT), Google (GOOGL), and Amazon (AMZN). However, you should always do your own research and consider your investment goals and risk tolerance before investing."
107+
}
108+
109+
return templates.TemplateResponse(
110+
"route.html",
111+
{
112+
"request": request,
113+
"route_path": "/chat",
114+
"method": "GET",
115+
"full_path": str(request.url).split("?")[0],
116+
"description": "Chat endpoint that uses Groq's LLaMa model to answer investment questions.",
117+
"parameters": [
118+
{"name": "query", "type": "string", "description": "The investment question to ask"},
119+
{"name": "format", "type": "string", "description": "Response format (html or json)"}
120+
],
121+
"example_query": "What are good tech stocks to invest in?",
122+
"example_response": json.dumps(example_response, indent=2),
123+
"current_year": current_year
124+
}
125+
)
126+
127+
# Handle regular API calls
52128
if not query:
53-
return {"error": "Query parameter is required"}
129+
return JSONResponse(content={"error": "Query parameter is required"})
54130

55131
try:
56132
response = groq_client.chat.completions.create(
@@ -60,25 +136,52 @@ def chat(query: str):
60136
)
61137

62138
answer = response.choices[0].message.content
63-
return {"question": query, "answer": answer}
139+
return JSONResponse(content={"question": query, "answer": answer})
64140

65141
except Exception as e:
66-
return {"error": str(e)}
67-
142+
return JSONResponse(content={"error": str(e)})
68143

69-
@router.get("/agent")
70-
def ask(query: str):
144+
@router.get("/agent", response_class=HTMLResponse)
145+
def ask(request: Request, query: str = None):
71146
"""
72147
API endpoint to handle user investment-related questions and return AI-generated insights.
73148
"""
149+
# Check if request is from a browser or format is explicitly set to html
150+
accept_header = request.headers.get("accept", "")
151+
if "text/html" in accept_header:
152+
current_year = datetime.datetime.now().year
153+
example_response = {
154+
"question": "Should I invest in index funds?",
155+
"answer": "Index funds are often a good choice for passive investors looking for broad market exposure with low fees. They offer diversification and typically outperform actively managed funds in the long term. However, the suitability depends on your investment goals, time horizon, and risk tolerance."
156+
}
157+
158+
return templates.TemplateResponse(
159+
"route.html",
160+
{
161+
"request": request,
162+
"route_path": "/agent",
163+
"method": "GET",
164+
"full_path": str(request.url).split("?")[0],
165+
"description": "Agent endpoint that uses a multi-AI system to provide sophisticated investment advice.",
166+
"parameters": [
167+
{"name": "query", "type": "string", "description": "The investment question to ask"},
168+
{"name": "format", "type": "string", "description": "Response format (html or json)"}
169+
],
170+
"example_query": "Should I invest in index funds?",
171+
"example_response": json.dumps(example_response, indent=2),
172+
"current_year": current_year
173+
}
174+
)
175+
176+
# Handle regular API calls
74177
if not query:
75-
return {"error": "Query parameter is required"}
178+
return JSONResponse(content={"error": "Query parameter is required"})
76179

77180
try:
78181
response: RunResponse = multi_ai.run(query)
79182
answer = response.content
80183

81-
return {"question": query, "answer": answer}
184+
return JSONResponse(content={"question": query, "answer": answer})
82185

83186
except Exception as e:
84-
return {"error": str(e)}
187+
return JSONResponse(content={"error": str(e)})

0 commit comments

Comments
 (0)