-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathmain.py
More file actions
86 lines (63 loc) · 2.63 KB
/
main.py
File metadata and controls
86 lines (63 loc) · 2.63 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
from fastapi import FastAPI, HTTPException
import uvicorn
import os
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
from app.api.routes.AIChatbot import chatbot
from app.api.routes.SentimentAnalysis import sentiment
from app.api.routes.StockData import stock_data
from chromadb import PersistentClient
from chromadb.config import Settings
import google.generativeai as genai
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
chroma_client = PersistentClient(path="./db")
collection = chroma_client.get_or_create_collection(name="fintech_docs")
app = FastAPI()
origins = [
os.getenv("FRONTEND_URL"),
os.getenv("TYPESCRIPT_BACKEND_URL")
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(chatbot.router, prefix="/api/v1/chatbot", tags=["chatbot"])
app.include_router(sentiment.router, prefix="/api/v1/news", tags=["sentiment"])
app.include_router(stock_data.router, prefix="/api/v1/stocks", tags=["stocks"])
@app.get("/")
def root():
return {"message": "Welcome to FinTechFore Python Backend", "status": "Ok"}
# 🔍 Chroma vector search using Gemini embeddings
@app.get("/chroma-search")
def chroma_search(q: str):
try:
# Try to generate embedding using Google API
embedding_result = genai.embed_content(
model="models/embedding-001",
content=q
)
if "embedding" not in embedding_result:
raise HTTPException(status_code=500, detail="Failed to generate embedding")
embedding = embedding_result["embedding"]
result = collection.query(query_embeddings=[embedding], n_results=3)
# Return documents if they exist, otherwise return empty list
if "documents" in result and result["documents"]:
return result["documents"][0] if len(result["documents"]) > 0 else []
else:
return []
except Exception as e:
error_msg = str(e)
print(f"Chroma search error: {error_msg}") # Log the error for debugging
# Check if it's a quota exceeded error
if "quota" in error_msg.lower() or "429" in error_msg:
# Return a default response when quota is exceeded
return ["We're currently experiencing high demand. Please try again later or check back soon."]
else:
# Provide a more helpful message for other errors
return [f"Search temporarily unavailable: {str(e)[:100]}..."]
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)