-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_routes.py
More file actions
131 lines (106 loc) · 5.42 KB
/
simple_routes.py
File metadata and controls
131 lines (106 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from app.core.api_client import get_api_client
from app.llm.llm_client import LLMClient
import structlog
log = structlog.get_logger()
router = APIRouter()
class ChatRequest(BaseModel):
message: str
conversation_id: str = "default"
class NL2SQLRequest(BaseModel):
prompt: str
@router.post("/simple_search")
async def simple_search():
"""Simple endpoint to test Scripbox API connectivity"""
try:
api_client = await get_api_client()
result = await api_client.search_funds(query="", items_per_page=10)
funds = result.get('data', {}).get('items', [])
if not funds:
return {"message": "No funds found", "count": 0}
# Format the response nicely
fund_list = []
for fund in funds[:5]: # Show top 5
fund_info = {
"name": fund.get('name', 'Unknown'),
"amc": fund.get('amc_name', 'Unknown'),
"nav": fund.get('nav', 0),
"aum": fund.get('aum', 0),
"return_1year": fund.get('return_1year', 0)
}
fund_list.append(fund_info)
return {
"message": "✅ Connected to Scripbox API successfully!",
"total_funds": len(funds),
"sample_funds": fund_list
}
except Exception as e:
log.error("Simple search failed", error=str(e))
raise HTTPException(status_code=500, detail=f"Search failed: {str(e)}")
@router.post("/simple_chat")
async def simple_chat(request: ChatRequest):
"""Simple chat endpoint that works with Scripbox API"""
try:
api_client = await get_api_client()
llm = LLMClient()
user_message = request.message.lower()
# Simple intent detection
if any(word in user_message for word in ['fund', 'mutual', 'investment', 'top', 'best']):
# Search for funds
result = await api_client.search_funds(query="", items_per_page=10)
funds = result.get('data', {}).get('items', [])
if not funds:
return {"response": "I couldn't find any mutual funds data. The API might be unavailable."}
# Format top 3 funds
fund_summaries = []
for fund in funds[:3]:
summary = f"**{fund.get('name', 'Unknown Fund')}**\n"
summary += f"- AMC: {fund.get('amc_name', 'Unknown')}\n"
summary += f"- NAV: ₹{fund.get('nav', 0):,.2f}\n"
summary += f"- 1 Year Return: {fund.get('return_1year', 0)*100:.2f}%\n"
summary += f"- AUM: ₹{fund.get('aum', 0):,.0f}\n"
fund_summaries.append(summary)
response = f"Here are some top mutual funds from Scripbox:\n\n" + "\n\n".join(fund_summaries)
# Add LLM enhancement if available
try:
enhanced_response = await llm.get_response(
f"User asked: {request.message}\n\nFund data:\n{response}\n\nProvide a helpful, conversational response about these mutual funds:"
)
return {"response": enhanced_response}
except:
return {"response": response}
else:
# General conversation
try:
response = await llm.get_response(
f"You are a helpful mutual fund investment assistant. User said: {request.message}\n\n"
"Provide a helpful response about mutual funds and investments."
)
return {"response": response}
except Exception as e:
return {"response": f"Hello! I'm your mutual fund assistant. I can help you with information about mutual funds, performance analysis, and investment advice. You asked: '{request.message}' - but I'm having trouble with my AI service right now. Try asking about specific funds or fund performance!"}
except Exception as e:
log.error("Simple chat failed", error=str(e))
return {"response": "I'm sorry, I'm having technical difficulties right now. Please try again in a moment."}
@router.post("/simple_nl2sql")
async def simple_nl2sql(request: NL2SQLRequest):
"""Simple NL2SQL that uses Scripbox API instead of database"""
try:
api_client = await get_api_client()
prompt = request.prompt.lower()
# Simple intent matching
if any(word in prompt for word in ['fund', 'search', 'show', 'list', 'find']):
result = await api_client.search_funds(query="", items_per_page=5)
funds = result.get('data', {}).get('items', [])
if funds:
fund_names = [fund.get('name', 'Unknown') for fund in funds]
response = f"Found {len(funds)} mutual funds:\n\n" + "\n".join([f"• {name}" for name in fund_names])
else:
response = "No mutual funds found."
return {"response": response}
else:
return {"response": "I can help you search for mutual funds. Try asking 'show me mutual funds' or 'search funds'."}
except Exception as e:
log.error("Simple NL2SQL failed", error=str(e))
return {"response": "I'm having trouble accessing the fund data right now. Please try again."}