Jaita commited on
Commit
8cd9d84
·
verified ·
1 Parent(s): 170f828

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +82 -0
main.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["POSTHOG_DISABLED"] = "true" # Disable PostHog telemetry
3
+ import requests
4
+ from fastapi import FastAPI, HTTPException
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from pydantic import BaseModel
7
+ from dotenv import load_dotenv
8
+ #from kb_embed import search_knowledge_base
9
+ import logging
10
+
11
+ logging.basicConfig(level=logging.INFO)
12
+
13
+ # Load environment variables from the .env file
14
+ load_dotenv()
15
+
16
+ # --- 1. Initialize FastAPI ---
17
+ app = FastAPI()
18
+
19
+ # --- 2. Configure CORS ---
20
+ #origins = [
21
+ # "http://localhost:5173",
22
+ # "http://localhost:3000",
23
+ #]
24
+
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["https://jaita-chatbot-fastapi-backend.hf.space/chat","https://jaita-chatbot-react-frontend-v1.hf.space"],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ # --- 3. Define the Request Data Structure ---
34
+ class ChatInput(BaseModel):
35
+ user_message: str
36
+
37
+ # --- 4. Gemini API Setup ---
38
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
39
+ GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent?key={GEMINI_API_KEY}"
40
+
41
+ # --- 5. Endpoints ---
42
+ @app.get("/")
43
+ async def health_check():
44
+ return {"status": "ok"}
45
+
46
+
47
+ @app.post("/chat")
48
+ async def chat_with_ai(input_data: ChatInput):
49
+ """Handle chat interactions using Google Generative AI via requests."""
50
+ try:
51
+ # Gemini expects contents array with role and parts
52
+ payload = {
53
+ "contents": [
54
+ {
55
+ "role": "user",
56
+ "parts": [{"text": input_data.user_message}],
57
+ }
58
+ ],
59
+ #"generationConfig": {
60
+ # "temperature": 0.7,
61
+ # "maxOutputTokens": 512
62
+ #}
63
+ }
64
+
65
+ # Make POST request to Gemini API
66
+ response = requests.post(GEMINI_URL, json=payload,verify=False)
67
+ response.raise_for_status()
68
+ data = response.json()
69
+
70
+ # Extract text from response
71
+ bot_response = ""
72
+ if "candidates" in data and data["candidates"]:
73
+ parts = data["candidates"][0].get("content", {}).get("parts", [])
74
+ for part in parts:
75
+ if "text" in part:
76
+ bot_response += part["text"]
77
+
78
+ return {"bot_response": bot_response or "No response text."}
79
+
80
+
81
+ except Exception as e:
82
+ raise HTTPException(status_code=500, detail=str(e))