Aniket2006 commited on
Commit
64d56ea
·
1 Parent(s): 4a86366

Update LLM analysis

Browse files
Files changed (1) hide show
  1. llm_analysis.py +66 -14
llm_analysis.py CHANGED
@@ -9,16 +9,71 @@ and provide comprehensive soil and crop insights.
9
  import os
10
  import json
11
  import numpy as np
12
- import google.generativeai as genai
13
- from typing import Dict, Any
14
 
15
- def configure_gemini():
16
- """Configure Gemini API with key from environment."""
17
- api_key = os.environ.get("GEMINI_API_KEY")
18
- if not api_key:
19
- raise ValueError("GEMINI_API_KEY not found in environment variables")
20
- genai.configure(api_key=api_key, transport='rest')
21
- return genai.GenerativeModel('gemini-flash-latest')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def prepare_indices_context(summary_report: Dict, crop_type: str, farmer_context: Dict,
24
  temporal_stats: Dict = None) -> str:
@@ -165,8 +220,6 @@ def analyze_with_llm(summary_report: Dict, crop_type: str, farmer_context: Dict,
165
  Returns:
166
  Dictionary with structured LLM analysis results
167
  """
168
- model = configure_gemini()
169
-
170
  # Prepare context with temporal statistics
171
  indices_context = prepare_indices_context(summary_report, crop_type, farmer_context, temporal_stats)
172
 
@@ -250,9 +303,8 @@ IMPORTANT GUIDELINES:
250
  Return ONLY the JSON object, no additional text.
251
  """
252
 
253
- # Get LLM response
254
- response = model.generate_content(prompt)
255
- response_text = response.text.strip()
256
 
257
  # Remove markdown code blocks if present
258
  if response_text.startswith("```"):
 
9
  import os
10
  import json
11
  import numpy as np
12
+ import requests
13
+ from typing import Dict, Any, List, Optional
14
 
15
+ # ============================================================================
16
+ # GEMINI MULTI-KEY FALLBACK SYSTEM
17
+ # ============================================================================
18
+
19
+ def load_gemini_api_keys() -> List[str]:
20
+ """Load all available Gemini API keys from environment."""
21
+ keys = []
22
+ primary = os.environ.get("GEMINI_API_KEY")
23
+ if primary:
24
+ keys.append(primary)
25
+ for i in range(1, 6):
26
+ key = os.environ.get(f"GEMINI_API_KEY_{i}")
27
+ if key and key not in keys:
28
+ keys.append(key)
29
+ return keys
30
+
31
+ GEMINI_API_KEYS = load_gemini_api_keys()
32
+ _current_key_index = 0
33
+ GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
34
+
35
+ def _get_next_key() -> Optional[str]:
36
+ global _current_key_index
37
+ if not GEMINI_API_KEYS:
38
+ return None
39
+ _current_key_index = (_current_key_index + 1) % len(GEMINI_API_KEYS)
40
+ return GEMINI_API_KEYS[_current_key_index]
41
+
42
+ def call_gemini_with_fallback(prompt: str) -> str:
43
+ global _current_key_index
44
+ if not GEMINI_API_KEYS:
45
+ raise ValueError("No GEMINI_API_KEY configured")
46
+ max_retries_per_key = 2
47
+ keys_tried = 0
48
+ while keys_tried < len(GEMINI_API_KEYS):
49
+ current_key = GEMINI_API_KEYS[_current_key_index]
50
+ url = f"{GEMINI_URL}?key={current_key}"
51
+ for attempt in range(max_retries_per_key):
52
+ try:
53
+ response = requests.post(
54
+ url,
55
+ headers={"Content-Type": "application/json"},
56
+ json={"contents": [{"parts": [{"text": prompt}]}],
57
+ "generationConfig": {"temperature": 0.7, "maxOutputTokens": 4096}},
58
+ timeout=120
59
+ )
60
+ if response.status_code == 200:
61
+ data = response.json()
62
+ if "candidates" in data and len(data["candidates"]) > 0:
63
+ return data["candidates"][0]["content"]["parts"][0]["text"]
64
+ raise ValueError("No response from Gemini")
65
+ elif response.status_code in [429, 403, 500, 502, 503]:
66
+ _get_next_key()
67
+ keys_tried += 1
68
+ break
69
+ else:
70
+ raise ValueError(f"Gemini API error: {response.status_code}")
71
+ except requests.exceptions.RequestException:
72
+ if attempt == max_retries_per_key - 1:
73
+ _get_next_key()
74
+ keys_tried += 1
75
+ continue
76
+ raise ValueError("All API keys exhausted")
77
 
78
  def prepare_indices_context(summary_report: Dict, crop_type: str, farmer_context: Dict,
79
  temporal_stats: Dict = None) -> str:
 
220
  Returns:
221
  Dictionary with structured LLM analysis results
222
  """
 
 
223
  # Prepare context with temporal statistics
224
  indices_context = prepare_indices_context(summary_report, crop_type, farmer_context, temporal_stats)
225
 
 
303
  Return ONLY the JSON object, no additional text.
304
  """
305
 
306
+ # Get LLM response using fallback system
307
+ response_text = call_gemini_with_fallback(prompt).strip()
 
308
 
309
  # Remove markdown code blocks if present
310
  if response_text.startswith("```"):