Spaces:
Sleeping

Deep_Research / search_agent.py
rohan131's picture
Upload folder using huggingface_hub
95a30b3 verified
Raw History Blame Contribute Delete
1.89 kB
import os
import requests
import google.generativeai as genai
from dotenv import load_dotenv
from planner_agent import WebSearchItem
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
model = genai.GenerativeModel("gemini-1.5-flash")
def perform_web_search(query: str) -> str:
api_key = os.getenv("SERPAPI_KEY")
if not api_key:
raise ValueError("SERPAPI_KEY environment variable not set")
url = "https://serpapi.com/search"
params = {"q": query, "api_key": api_key, "num": 10}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status() # Raise for HTTP errors
# Try to parse JSON
data = response.json()
# Extract snippets from organic results if present
snippets = [
res.get("snippet", "")
for res in data.get("organic_results", [])
if res.get("snippet")
]
return "\n".join(snippets)
except requests.exceptions.RequestException as e:
print(f"HTTP request error during web search: {e}")
return ""
except ValueError as e:
# JSON decode error or others
print(f"Failed to parse JSON response: {e}")
print("Raw response:", response.text)
return ""
def summarize_search_results(search_term: str, snippets: str) -> str:
INSTRUCTIONS = """
Summarize the following search result snippets in 2–3 paragraphs, under 300 words.
"""
prompt = f"{INSTRUCTIONS}\n\nSearch Term: {search_term}\n\n{snippets}"
response = model.generate_content(prompt)
return response.text.strip()
async def perform_search(item: WebSearchItem) -> str:
snippets = perform_web_search(item.query)
return summarize_search_results(item.query, snippets) if snippets else "No relevant results found."