Jaita commited on
Commit
330a100
·
verified ·
1 Parent(s): 8cd9d84

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +32 -52
main.py CHANGED
@@ -1,82 +1,62 @@
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))
 
1
  import os
 
 
2
  from fastapi import FastAPI, HTTPException
 
3
  from pydantic import BaseModel
4
+ import google.generativeai as genai
 
 
5
 
6
+ # --- 0. Config ---
7
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
8
+ if not GEMINI_API_KEY:
9
+ raise RuntimeError("GEMINI_API_KEY is not set in environment.")
10
+
11
+ # Configure the SDK
12
+ genai.configure(api_key=GEMINI_API_KEY)
13
 
14
+ # Choose the model
15
+ MODEL_NAME = "gemini-2.5-flash-lite"
16
+ model = genai.GenerativeModel(MODEL_NAME)
17
 
18
+ # --- 1. FastAPI ---
19
  app = FastAPI()
20
 
21
  # --- 2. Configure CORS ---
22
+ origins = [
23
+ "https://jaita-chatbot-react-frontend-v1.hf.space"
24
+ "https://jaita-chatbot-fastapi-backend.hf.space/chat",
25
+ ]
26
 
27
  app.add_middleware(
28
  CORSMiddleware,
29
+ allow_origins=origins,
30
  allow_credentials=True,
31
  allow_methods=["*"],
32
  allow_headers=["*"],
33
  )
34
 
35
+ # --- 3. Schemas ---
36
  class ChatInput(BaseModel):
37
  user_message: str
38
 
39
+ # --- 4. Health check ---
 
 
 
 
40
  @app.get("/")
41
  async def health_check():
42
  return {"status": "ok"}
43
 
44
+ # --- 5. Chat endpoint using direct Gemini SDK ---
45
  @app.post("/chat")
46
  async def chat_with_ai(input_data: ChatInput):
47
+ """
48
+ Handle chat interactions using the official Google Generative AI SDK.
49
+ """
50
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # Call Gemini directly via SDK
53
+ resp = model.generate_content(
54
+ input_data.user_message,
55
+ )
56
+ print("resp",resp)
57
+ bot_response = getattr(resp, "text", None) or "No response text."
58
+ print("bot_response",bot_response)
59
+ return {"bot_response": bot_response}
60
 
61
  except Exception as e:
62
+ raise HTTPException(status_code=500, detail=str(e))