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

Commit 6942958

Browse files
author
yashksaini-coder
committed
convert GET ai reqs to POST requests
1 parent 79b5230 commit 6942958

File tree

1 file changed

+45
-34
lines changed

1 file changed

+45
-34
lines changed

routes/agentRoutes.py

Lines changed: 45 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,19 @@
22
import datetime
33
import json
44
import requests
5-
from fastapi import FastAPI, APIRouter, Request, Query
5+
from fastapi import FastAPI, APIRouter, Request, Body
66
from fastapi.responses import HTMLResponse, JSONResponse
77
from fastapi.templating import Jinja2Templates
8+
from pydantic import BaseModel
89
from agno.agent import RunResponse
910
from controllers.agent import multi_agent
1011
import dotenv
1112
import groq
1213

14+
# Define a Pydantic model for the request body
15+
class QueryRequest(BaseModel):
16+
query: str
17+
1318
router = APIRouter()
1419
templates = Jinja2Templates(directory="templates")
1520

@@ -38,7 +43,7 @@ async def health_check(request: Request):
3843
"gemini_api":"connected" if GEMINI_API_KEY else "not configured",
3944
},
4045
"ip": requests.get('https://api.ipify.org').text,
41-
46+
4247
}
4348

4449
# Check if request is from a browser or format is explicitly set to html
@@ -61,7 +66,7 @@ async def health_check(request: Request):
6166
"current_year": current_year
6267
}
6368
)
64-
69+
6570
return JSONResponse(content=response_data)
6671

6772
except Exception as e:
@@ -70,7 +75,7 @@ async def health_check(request: Request):
7075
"timestamp": datetime.datetime.now().isoformat(),
7176
"error": str(e)
7277
}
73-
78+
7479
# Check if request is from a browser or format is explicitly set to html
7580
accept_header = request.headers.get("accept", "")
7681
if "text/html" in accept_header:
@@ -91,15 +96,16 @@ async def health_check(request: Request):
9196
"current_year": current_year
9297
}
9398
)
94-
95-
return JSONResponse(content=error_response)
9699

97-
@router.get("/agent", response_class=HTMLResponse, name="agent")
98-
def agent(request: Request, query: str = Query(None, description="The investment question to ask")):
100+
return JSONResponse(content=error_response)
99101

102+
@router.post("/agent", response_class=HTMLResponse, name="agent")
103+
async def agent(request: Request, payload: QueryRequest = Body(...)):
100104
"""
101-
API endpoint to handle user investment-related questions and return AI-generated insights.
105+
API endpoint to handle user investment-related questions via POST request body
106+
and return AI-generated insights.
102107
"""
108+
query = payload.query
103109
# Check if request is from a browser or format is explicitly set to html
104110
accept_header = request.headers.get("accept", "")
105111
if "text/html" in accept_header:
@@ -108,41 +114,45 @@ def agent(request: Request, query: str = Query(None, description="The investment
108114
"question": "Should I invest in index funds?",
109115
"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."
110116
}
117+
example_request_body = {"query": "Should I invest in index funds?"}
111118

112119
return templates.TemplateResponse(
113120
"route.html",
114121
{
115122
"request": request,
116123
"route_path": "/agent",
117-
"method": "GET",
124+
"method": "POST",
118125
"full_path": str(request.url).split("?")[0],
119-
"description": "Agent endpoint that uses a multi-AI system to provide sophisticated investment advice.",
126+
"description": "Agent endpoint that uses a multi-AI system to provide sophisticated investment advice. Accepts a JSON body with a 'query' field.",
120127
"parameters": [
121-
{"name": "query", "type": "string", "description": "The investment question to ask"},
128+
{"name": "Request Body", "type": "JSON", "description": "JSON object containing the 'query' field."},
122129
{"name": "format", "type": "string", "description": "Response format (html or json)"}
123130
],
124-
"example_query": "Should I invest in index funds?",
131+
"example_query": json.dumps(example_request_body, indent=2), # Show example request body
125132
"example_response": json.dumps(example_response, indent=2),
126133
"current_year": current_year
127134
}
128135
)
129-
136+
130137
if not query:
131-
return JSONResponse(content={"error": "Query parameter is required"})
132-
138+
# This check might be redundant if QueryRequest enforces the field, but kept for clarity
139+
return JSONResponse(content={"error": "Query field in request body is required"}, status_code=400)
140+
133141
try:
134142
response: RunResponse = multi_agent.run(query)
135143
answer = response.content
136144
return JSONResponse(content={"question": query, "answer": answer})
137-
145+
138146
except Exception as e:
139-
return JSONResponse(content={"error": str(e)})
140-
141-
@router.get("/chat", response_class=HTMLResponse)
142-
def chat(request: Request, query: str = None):
147+
return JSONResponse(content={"error": str(e)}, status_code=500)
148+
149+
@router.post("/chat", response_class=HTMLResponse)
150+
async def chat(request: Request, payload: QueryRequest = Body(...)):
143151
"""
144-
API endpoint to handle user investment-related questions and return AI-generated insights.
152+
API endpoint to handle user investment-related questions via POST request body
153+
and return AI-generated insights using Groq's LLaMa model.
145154
"""
155+
query = payload.query
146156
# Check if request is from a browser or format is explicitly set to html
147157
accept_header = request.headers.get("accept", "")
148158
if "text/html" in accept_header:
@@ -151,38 +161,39 @@ def chat(request: Request, query: str = None):
151161
"question": "What are good tech stocks to invest in?",
152162
"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."
153163
}
154-
164+
example_request_body = {"query": "What are good tech stocks to invest in?"}
165+
155166
return templates.TemplateResponse(
156167
"route.html",
157168
{
158169
"request": request,
159170
"route_path": "/chat",
160-
"method": "GET",
171+
"method": "GET", # Changed to GET since we're just displaying info
161172
"full_path": str(request.url).split("?")[0],
162-
"description": "Chat endpoint that uses Groq's LLaMa model to answer investment questions.",
173+
"description": "Chat endpoint that uses Groq's LLaMa model to answer investment questions. For actual queries, use POST with a JSON body containing a 'query' field.",
163174
"parameters": [
164-
{"name": "query", "type": "string", "description": "The investment question to ask"},
165175
{"name": "format", "type": "string", "description": "Response format (html or json)"}
166176
],
167-
"example_query": "What are good tech stocks to invest in?",
177+
"example_query": "Using POST: " + json.dumps(example_request_body, indent=2),
168178
"example_response": json.dumps(example_response, indent=2),
169179
"current_year": current_year
170180
}
171181
)
172-
182+
173183
# Handle regular API calls
174184
if not query:
175-
return JSONResponse(content={"error": "Query parameter is required"})
176-
185+
# This check might be redundant if QueryRequest enforces the field, but kept for clarity
186+
return JSONResponse(content={"error": "Query field in request body is required"}, status_code=400)
187+
177188
try:
178189
response = groq_client.chat.completions.create(
179-
model="llama-3.3-70b-versatile",
190+
model="llama-3.3-70b-versatile",
180191
messages=[{"role": "system", "content": "You are an AI investment assistant."},
181192
{"role": "user", "content": query}]
182193
)
183-
194+
184195
answer = response.choices[0].message.content
185196
return JSONResponse(content={"question": query, "answer": answer})
186-
197+
187198
except Exception as e:
188-
return JSONResponse(content={"error": str(e)})
199+
return JSONResponse(content={"error": str(e)}, status_code=500)

0 commit comments

Comments
 (0)