arittrabag commited on
Commit
8449547
·
verified ·
1 Parent(s): 3fced9f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -10
app.py CHANGED
@@ -12,23 +12,32 @@ from dotenv import load_dotenv
12
 
13
  load_dotenv()
14
 
15
- # Use the key directly from the environment
16
- genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
 
 
17
 
18
- # Optional debug
19
- print("Gemini key loaded:", os.getenv("GEMINI_API_KEY") is not None)
20
-
21
- model = genai.GenerativeModel("gemini-2.5-flash")
 
 
 
 
 
 
 
22
 
23
  app = FastAPI()
24
 
25
- # Add CORS middleware
26
  app.add_middleware(
27
  CORSMiddleware,
28
- allow_origins=["*"], # Allows all origins
29
  allow_credentials=True,
30
- allow_methods=["*"], # Allows all methods
31
- allow_headers=["*"], # Allows all headers
32
  )
33
 
34
  # Initialize enhanced components
 
12
 
13
  load_dotenv()
14
 
15
+ # Read Gemini API key from Hugging Face secret
16
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
17
+ if not GEMINI_API_KEY:
18
+ raise RuntimeError("GEMINI_API_KEY not found in environment.")
19
 
20
+ def call_gemini(prompt: str) -> str:
21
+ """Use Gemini via REST API instead of gRPC-based SDK"""
22
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={GEMINI_API_KEY}"
23
+ payload = {
24
+ "contents": [{"parts": [{"text": prompt}]}]
25
+ }
26
+ response = requests.post(url, json=payload)
27
+ try:
28
+ return response.json()["candidates"][0]["content"]["parts"][0]["text"]
29
+ except Exception:
30
+ raise HTTPException(status_code=500, detail="Error in Gemini response format.")
31
 
32
  app = FastAPI()
33
 
34
+ # CORS
35
  app.add_middleware(
36
  CORSMiddleware,
37
+ allow_origins=["*"],
38
  allow_credentials=True,
39
+ allow_methods=["*"],
40
+ allow_headers=["*"],
41
  )
42
 
43
  # Initialize enhanced components