This is my code for report finder agent using tavily api key, now i would like to replace it with brave api key that ive generated, i would also like the change the query in such a way that we can get sustainability the latest reports after 2023, if 2025 is available then should not give 2023 here is the code : import os
from datetime import datetime
import requests
from dotenv import load_dotenv
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font
import google.generativeai as genai

load_dotenv()

TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not TAVILY_API_KEY or not GOOGLE_API_KEY:
    raise ValueError("API keys missing in .env")

genai.configure(api_key=GOOGLE_API_KEY)
gemini = genai.GenerativeModel("models/gemini-1.5-flash-latest")

already_saved = False

def is_valid_url(url):
    try:
        response = requests.head(url, allow_redirects=True, timeout=10)
        if response.status_code in [200, 301, 302, 403]:
            return True
        response = requests.get(url, allow_redirects=True, timeout=10)
        return response.status_code in [200, 301, 302, 403]
    except:
        return False


def search_with_tavily(company_name, max_results=10):
    url = "https://api.tavily.com/search"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {TAVILY_API_KEY}"
    }
    query = f"{company} sustainability report for the year /2024/ OR ahead filetype:pdf"
    payload = {
        "query": query,
        "max_results": max_results,
        "include_answer": False
    }
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        results = response.json().get("results", [])
        return [item.get("url") for item in results if item.get("url")]
    except:
        return []


def ask_gemini_best_link(company_name, links):
    if not links:
        return "Not available"

    links_text = "\n".join(f"- {link}" for link in links)
    prompt = f"""
Find the most relevant and official ESG or Sustainability report link for the company: {company_name}.
From the links below, choose the one that points to the official website or PDF/report with real content.

Here are the links:
{links_text}
 Reply with only the most relevant link.
 If none of them are official or relevant, say: Not available
"""
    try:
        response = gemini.generate_content(prompt)
        result = response.text.strip()

        for line in result.splitlines():
            if line.strip().startswith("http"):
                return line.strip()
        return "Not available"
    except Exception as e:
        print("[ERROR] Gemini failed:", e)
        return "Not available"


def get_sustainability_report_link(company_name):
    links = search_with_tavily(company_name)
    best_link = ask_gemini_best_link(company_name, links)

    if is_valid_url(best_link):
        return best_link
    else:
        return "Not available"


def save_to_excel(company, report_link):
    global already_saved
    if already_saved:
        return
    file_name = "sustainability_reports.xlsx"
    headers = ["Timestamp", "Company", "Report Link", "Status"]
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    status = "Valid" if report_link != "Not available" else "Not available"

    if not os.path.exists(file_name):
        wb = Workbook()
        ws = wb.active
        ws.title = "Reports"
        for col_num, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col_num, value=header)
            cell.font = Font(bold=True)
    else:
        wb = load_workbook(file_name)
        ws = wb.active

    row = ws.max_row + 1
    ws.cell(row=row, column=1, value=timestamp)
    ws.cell(row=row, column=2, value=company)

    link_cell = ws.cell(row=row, column=3)
    if report_link != "Not available":
        link_cell.value = report_link
        link_cell.hyperlink = report_link
        link_cell.style = "Hyperlink"
    else:
        link_cell.value = "Not available"
        link_cell.font = Font(color="FF0000")

    status_cell = ws.cell(row=row, column=4, value=status)
    if status == "Not available":
        status_cell.font = Font(color="FF0000", italic=True)

    wb.save(file_name)
    already_saved = True
    print(f"[SUCCESS] Saved result to {file_name}")

if __name__ == "__main__":
    company = input("Enter company name: ").strip()
    print(f"[INFO] Getting sustainability report for: {company}")
    report_link = get_sustainability_report_link(company)
    print(f"[RESULT] Found link: {report_link}")
    save_to_excel(company, report_link)