import gradio as gr import google.generativeai as genai import os import json import time def make_api_call(model, messages, max_tokens, is_final_answer=False): for attempt in range(3): try: response = model.generate_content(messages) return json.loads(response.text) except Exception as e: if attempt == 2: if is_final_answer: return {"title": "Error", "content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"} else: return {"title": "Error", "content": f"Failed to generate step after 3 attempts. Error: {str(e)}", "next_action": "final_answer"} time.sleep(1) # Wait for 1 second before retrying def generate_response(model, prompt): messages = [ {"role": "user", "parts": ["""You are an expert AI assistant that explains your reasoning step by step. For each step, provide a title that describes what you're doing in that step, along with the content. Decide if you need another step or if you're ready to give the final answer. Respond in JSON format with 'title', 'content', and 'next_action' (either 'continue' or 'final_answer') keys. USE AS MANY REASONING STEPS AS POSSIBLE. AT LEAST 3. BE AWARE OF YOUR LIMITATIONS AS AN LLM AND WHAT YOU CAN AND CANNOT DO. IN YOUR REASONING, INCLUDE EXPLORATION OF ALTERNATIVE ANSWERS. CONSIDER YOU MAY BE WRONG, AND IF YOU ARE WRONG IN YOUR REASONING, WHERE IT WOULD BE. FULLY TEST ALL OTHER POSSIBILITIES. YOU CAN BE WRONG. WHEN YOU SAY YOU ARE RE-EXAMINING, ACTUALLY RE-EXAMINE, AND USE ANOTHER APPROACH TO DO SO. DO NOT JUST SAY YOU ARE RE-EXAMINING. USE AT LEAST 3 METHODS TO DERIVE THE ANSWER. USE BEST PRACTICES. Example of a valid JSON response: ```json { "title": "Identifying Key Information", "content": "To begin solving this problem, we need to carefully examine the given information and identify the crucial elements that will guide our solution process. This involves...", "next_action": "continue" }``` Now, please respond to the following prompt: """ + prompt]}, {"role": "model", "parts": ["Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."]} ] steps = [] step_count = 1 total_thinking_time = 0 while True: start_time = time.time() step_data = make_api_call(model, messages, 300) end_time = time.time() thinking_time = end_time - start_time total_thinking_time += thinking_time # Handle potential errors if step_data.get('title') == "Error": steps.append((f"Step {step_count}: {step_data.get('title')}", step_data.get('content'), thinking_time)) break step_title = f"Step {step_count}: {step_data.get('title', 'No Title')}" step_content = step_data.get('content', 'No Content') steps.append((step_title, step_content, thinking_time)) messages.append({"role": "model", "parts": [json.dumps(step_data)]}) if step_data.get('next_action') == 'final_answer': break step_count += 1 # Generate final answer messages.append({"role": "user", "parts": ["Please provide the final answer based on your reasoning above."]}) start_time = time.time() final_data = make_api_call(model, messages, 200, is_final_answer=True) end_time = time.time() thinking_time = end_time - start_time total_thinking_time += thinking_time if final_data.get('title') == "Error": steps.append(("Final Answer", final_data.get('content'), thinking_time)) else: steps.append(("Final Answer", final_data.get('content', 'No Content'), thinking_time)) return steps, total_thinking_time def format_steps(steps, total_time): html_content = "" for title, content, thinking_time in steps: if title == "Final Answer": html_content += "
{}
".format(content.replace('\n', '{}
Thinking time for this step: {:.2f} seconds