import os from typing import List from pydantic import BaseModel, Field, ValidationError import google.generativeai as genai from dotenv import load_dotenv from utils import extract_json load_dotenv() genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) model = genai.GenerativeModel("gemini-1.5-flash") HOW_MANY_SEARCHES = 5 class WebSearchItem(BaseModel): reason: str query: str class WebSearchPlan(BaseModel): searches: List[WebSearchItem] INSTRUCTIONS = f""" You are a helpful research assistant. Given a query, output exactly {HOW_MANY_SEARCHES} web searches in this JSON format: {{ "searches": [ {{ "reason": "...", "query": "..." }}, ... ] }} """ def generate_search_plan(query: str) -> WebSearchPlan: prompt = f"{INSTRUCTIONS}\n\nQuery: {query}" response = model.generate_content(prompt) raw_text = response.text.strip() print("Gemini raw search plan:\n", raw_text) try: clean_json = extract_json(raw_text) return WebSearchPlan.parse_raw(clean_json) except ValidationError as e: print("❌ Failed to parse Gemini output:", e) raise