import gradio as gr from gradio_client import Client from bs4 import BeautifulSoup import os # Initialize the client for the OpenResearcher space client = Client("OpenResearcher/OpenResearcher") def research_topic(question): # 1. Get the API Key from Hugging Face Secrets (Environment Variables) # If testing locally, you can replace os.getenv with your actual string, # but for HF Spaces, use the Secret to keep it safe. api_key = os.getenv("SERPER_KEY") if not api_key: return "Error: SERPER_KEY not found in Environment Variables. Please add it in Space Settings." print(f"Researching: {question}...") try: # 2. Call the OpenResearcher API result = client.predict( question=question, serper_key=api_key, max_rounds=50, api_name="/start_research" ) # The API returns [user_input, full_html_log] at indices 0 and 1 raw_html = result[1] # 3. Parse the HTML to find only the "answer-section" soup = BeautifulSoup(raw_html, 'html.parser') # Look for the div containing the final conclusion answer_section = soup.find('div', class_='answer-section') if answer_section: # Return the clean HTML return str(answer_section) else: # Fallback: Sometimes the API fails or returns a different format return f"