Aniket2006 commited on
Commit
f0c4cb2
·
1 Parent(s): dcb1582

feat: migrate from Gemini to Groq API for LLM calls

Browse files
Files changed (2) hide show
  1. app.py +29 -20
  2. requirements.txt +1 -1
app.py CHANGED
@@ -24,7 +24,7 @@ from fastapi.middleware.cors import CORSMiddleware
24
  from fastapi.responses import StreamingResponse
25
  from pydantic import BaseModel
26
  import asyncio
27
- import google.generativeai as genai
28
 
29
  from supabase_client import SupabaseClient
30
  from prompts import PERSONA_DEFINITIONS, EXPERIENCE_MAP, TECH_COMFORT_MAP, INNOVATION_MAP, FARMING_GOAL_MAP
@@ -50,16 +50,17 @@ SAR_API_URL = os.getenv("SAR_API_URL", "https://aniket2006-agrow-backend-v2.hf.s
50
  SENTINEL2_API_URL = os.getenv("SENTINEL2_API_URL", "https://aniket2006-agrow-sentinel2.hf.space")
51
 
52
  # ============================================================================
53
- # GEMINI SETUP
54
  # ============================================================================
55
- GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
56
- if GEMINI_API_KEY:
57
- genai.configure(api_key=GEMINI_API_KEY)
58
- model = genai.GenerativeModel('gemini-2.5-flash')
59
- logger.info("Gemini API configured successfully")
 
60
  else:
61
- model = None
62
- logger.warning("GEMINI_API_KEY not set - chatbot will return mock responses")
63
 
64
  # Supabase
65
  supabase = SupabaseClient()
@@ -504,24 +505,32 @@ def generate_response(user_message: str, history: List[Dict], context: Dict) ->
504
  history = history or []
505
  context_used = context.get("data_sources", [])
506
 
507
- if model is None:
508
- return "Please configure GEMINI_API_KEY for real responses.", []
509
 
510
  try:
511
  prompt = build_llm_prompt(user_message, context, history)
512
 
513
- response = model.generate_content(
514
- prompt,
515
- generation_config=genai.types.GenerationConfig(
516
- temperature=0.7,
517
- max_output_tokens=4096,
518
- )
 
 
 
 
 
 
 
 
519
  )
520
 
521
- return response.text, context_used
522
 
523
  except Exception as e:
524
- logger.error(f"Gemini error: {e}")
525
  traceback.print_exc()
526
  return f"I apologize, but I encountered an error: {str(e)}", []
527
 
@@ -539,7 +548,7 @@ async def root():
539
 
540
  @app.get("/health")
541
  async def health():
542
- return {"status": "healthy", "gemini_configured": model is not None}
543
 
544
 
545
  @app.post("/session/new", response_model=SessionResponse)
 
24
  from fastapi.responses import StreamingResponse
25
  from pydantic import BaseModel
26
  import asyncio
27
+ from groq import Groq
28
 
29
  from supabase_client import SupabaseClient
30
  from prompts import PERSONA_DEFINITIONS, EXPERIENCE_MAP, TECH_COMFORT_MAP, INNOVATION_MAP, FARMING_GOAL_MAP
 
50
  SENTINEL2_API_URL = os.getenv("SENTINEL2_API_URL", "https://aniket2006-agrow-sentinel2.hf.space")
51
 
52
  # ============================================================================
53
+ # GROQ SETUP
54
  # ============================================================================
55
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "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")
56
+ GROQ_MODEL = "llama-3.3-70b-versatile"
57
+
58
+ if GROQ_API_KEY:
59
+ groq_client = Groq(api_key=GROQ_API_KEY)
60
+ logger.info(f"Groq API configured with model {GROQ_MODEL}")
61
  else:
62
+ groq_client = None
63
+ logger.warning("GROQ_API_KEY not set - chatbot will return mock responses")
64
 
65
  # Supabase
66
  supabase = SupabaseClient()
 
505
  history = history or []
506
  context_used = context.get("data_sources", [])
507
 
508
+ if groq_client is None:
509
+ return "Please configure GROQ_API_KEY for real responses.", []
510
 
511
  try:
512
  prompt = build_llm_prompt(user_message, context, history)
513
 
514
+ chat_completion = groq_client.chat.completions.create(
515
+ messages=[
516
+ {
517
+ "role": "system",
518
+ "content": "You are AGROW AI, an expert agricultural advisor. Provide helpful, data-driven advice."
519
+ },
520
+ {
521
+ "role": "user",
522
+ "content": prompt
523
+ }
524
+ ],
525
+ model=GROQ_MODEL,
526
+ temperature=0.7,
527
+ max_tokens=4096,
528
  )
529
 
530
+ return chat_completion.choices[0].message.content, context_used
531
 
532
  except Exception as e:
533
+ logger.error(f"Groq error: {e}")
534
  traceback.print_exc()
535
  return f"I apologize, but I encountered an error: {str(e)}", []
536
 
 
548
 
549
  @app.get("/health")
550
  async def health():
551
+ return {"status": "healthy", "groq_configured": groq_client is not None}
552
 
553
 
554
  @app.post("/session/new", response_model=SessionResponse)
requirements.txt CHANGED
@@ -4,4 +4,4 @@ pydantic==2.5.2
4
  requests>=2.28.0
5
  supabase>=2.0.0
6
  python-dotenv==1.0.0
7
- google-generativeai>=0.3.0
 
4
  requests>=2.28.0
5
  supabase>=2.0.0
6
  python-dotenv==1.0.0
7
+ groq>=0.4.0