import gradio as gr from openai import OpenAI import os import json # Initialize OpenAI client with API key and base URL from environment variables client = OpenAI( api_key=os.environ["OPENAI_API_KEY"], base_url=os.environ["OPENAI_BASE_URL"] ) # Define the number of results per page and total results to generate RESULTS_PER_PAGE = 10 TOTAL_RESULTS = 30 # Generate 30 results to allow pagination def fetch_search_results(query): """Fetch search results from the LLM based on the user's query.""" if not query.strip(): return None, "Please enter a search query." prompt = f""" You are a search engine that provides informative and relevant results. For the given query '{query}', generate {TOTAL_RESULTS} search results, each with a title and a snippet that summarizes the information. Format the response as a JSON array of objects, where each object has 'title' and 'snippet' fields. Ensure the results are diverse and relevant to the query. """ try: response = client.chat.completions.create( model="gemini-2.0-flash-lite", # Adjust model name as needed messages=[ {"role": "system", "content": "You are a helpful search engine."}, {"role": "user", "content": prompt} ], response_format={"type": "json_object"} # Updated for latest SDK ) content = response.choices[0].message.content results = json.loads(content) # Handle different possible JSON structures if isinstance(results, dict) and "results" in results: results = results["results"] elif isinstance(results, list): pass else: return None, "Error: Unexpected JSON structure." return results, None except Exception as e: return None, f"Error: {str(e)}" def display_search_results(query, page=1): """Display search results for the given query and page number.""" results, error = fetch_search_results(query) if error: return error, None, None # Calculate pagination boundaries start_idx = (page - 1) * RESULTS_PER_PAGE end_idx = start_idx + RESULTS_PER_PAGE total_pages = (len(results) + RESULTS_PER_PAGE - 1) // RESULTS_PER_PAGE # Ensure indices are within bounds if start_idx >= len(results): return "No more results to display.", None, None paginated_results = results[start_idx:end_idx] # Format results into HTML html = """
{snippet}