mgbam's picture
Update app.py
c984bb4 verified
raw
history blame
16.6 kB
import gradio as gr
from huggingface_hub import InferenceClient
import os
import random # For a bit of mock variety if needed
# --- ALGOFORGE PRIME™ CONFIGURATION & SECRETS ---
# THE SACRED HF_TOKEN - ENSURE THIS IS IN YOUR SPACE SECRETS
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
print("WARNING: HF_TOKEN not found. LLM calls will fail. Please add HF_TOKEN to your Space Secrets!")
# You might want to raise an error or display a persistent warning in the UI
# Initialize the Inference Client - The Conduit to a Universe of Models!
client = InferenceClient(token=HF_TOKEN)
# Curated List of Models for Different Tasks (User Selectable!)
# You can expand this list. Ensure they are text-generation or instruct models.
AVAILABLE_MODELS = {
"General & Logic (Balanced)": "mistralai/Mistral-7B-Instruct-v0.2",
"Code Generation (Strong)": "codellama/CodeLlama-34b-Instruct-hf", # Might be slow, consider smaller CodeLlama
"Creative & Versatile (Fast)": "google/gemma-7b-it",
"Compact & Quick (Good for CPU tests)": "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
}
DEFAULT_MODEL = "mistralai/Mistral-7B-Instruct-v0.2"
# --- CORE AI ENGINEERING: LLM INTERACTION FUNCTIONS ---
def call_llm_via_api(prompt_text, model_id, temperature=0.7, max_new_tokens=350, system_prompt=None):
"""
Centralized function to call the Hugging Face Inference API.
As an SRE, I like centralized, observable points of failure/success!
"""
if not HF_TOKEN:
return "ERROR: HF_TOKEN is not configured. Cannot contact the LLM Oracle."
full_prompt = prompt_text
if system_prompt: # Some models use system prompts differently, this is a basic way
full_prompt = f"<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n{prompt_text} [/INST]"
try:
response_stream = client.text_generation(
full_prompt,
model=model_id,
max_new_tokens=max_new_tokens,
temperature=temperature if temperature > 0 else None, # API expects None for temp 0
stream=False # Keep it simple for this demo; stream=True for real-time
)
# The response structure might vary slightly based on the model/client version.
# Typically, it's just the generated string.
# If it returns a dict: response_stream.get("generated_text", response_stream)
return response_stream
except Exception as e:
print(f"LLM API Call Error ({model_id}): {e}")
return f"LLM API Error: Could not connect or process request with {model_id}. Details: {str(e)}"
# --- ALGOFORGE PRIME™ - THE GRAND ORCHESTRATOR ---
def run_algoforge_simulation(
problem_type, problem_description, initial_hints,
num_initial_solutions, selected_model_key,
gen_temp, gen_max_tokens,
eval_temp, eval_max_tokens,
evolve_temp, evolve_max_tokens
):
if not problem_description:
return "ERROR: Problem Description is the lifeblood of innovation! Please provide it.", "", "", "", ""
if not HF_TOKEN:
# This message will appear in the output fields if the token is missing
no_token_msg = "CRITICAL ERROR: HF_TOKEN is missing. AlgoForge Prime™ cannot access its cognitive core. Please configure HF_TOKEN in Space Secrets."
return no_token_msg, no_token_msg, no_token_msg, no_token_msg
model_id = AVAILABLE_MODELS.get(selected_model_key, DEFAULT_MODEL)
log_entries = [f"**AlgoForge Prime™ Initializing...**\nSelected Model Core: {model_id} ({selected_model_key})\nProblem Type: {problem_type}"]
# --- STAGE 1: GENESIS ENGINE - MULTIVERSE SOLUTION GENERATION ---
log_entries.append("\n**Stage 1: Genesis Engine - Generating Initial Solution Candidates...**")
generated_solutions_raw = []
system_prompt_generate = f"You are an expert {problem_type.lower().replace(' ', '_')} algorithm designer. Your goal is to brainstorm multiple diverse solutions."
for i in range(num_initial_solutions):
prompt_generate = (
f"Problem Description: \"{problem_description}\"\n"
f"Consider these initial thoughts/constraints: \"{initial_hints if initial_hints else 'None'}\"\n"
f"Please provide one distinct and complete solution/algorithm for this problem. "
f"This is solution attempt #{i+1} of {num_initial_solutions}. Try a different approach if possible."
)
log_entries.append(f" Sending to Genesis Engine (Attempt {i+1}):\n Model: {model_id}\n Prompt (snippet): {prompt_generate[:150]}...")
solution_text = call_llm_via_api(prompt_generate, model_id, gen_temp, gen_max_tokens, system_prompt_generate)
generated_solutions_raw.append(solution_text)
log_entries.append(f" Genesis Engine Response (Attempt {i+1} - Snippet): {solution_text[:150]}...")
if not any(sol and not sol.startswith("LLM API Error") and not sol.startswith("ERROR:") for sol in generated_solutions_raw):
log_entries.append(" Genesis Engine failed to produce viable candidates.")
return "No valid solutions generated by the Genesis Engine.", "", "", "\n".join(log_entries)
# --- STAGE 2: CRITIQUE CRUCIBLE - RUTHLESS EVALUATION ---
log_entries.append("\n**Stage 2: Critique Crucible - Evaluating Candidates...**")
evaluated_solutions_display = []
evaluated_sols_data = []
system_prompt_evaluate = "You are a highly critical and insightful AI algorithm evaluator. Your task is to assess a given solution based on clarity, potential correctness, and perceived efficiency. Provide a concise critique and a numerical score from 1 (poor) to 10 (excellent)."
for i, sol_text in enumerate(generated_solutions_raw):
if sol_text.startswith("LLM API Error") or sol_text.startswith("ERROR:"):
critique = f"Solution {i+1} could not be generated due to an API error."
score = 0
else:
prompt_evaluate = (
f"Problem Reference: \"{problem_description[:200]}...\"\n"
f"Evaluate the following proposed solution:\n```\n{sol_text}\n```\n"
f"Provide your critique and a score (e.g., 'Critique: This is okay. Score: 7/10')."
)
log_entries.append(f" Sending to Critique Crucible (Solution {i+1}):\n Model: {model_id}\n Prompt (snippet): {prompt_evaluate[:150]}...")
evaluation_text = call_llm_via_api(prompt_evaluate, model_id, eval_temp, eval_max_tokens, system_prompt_evaluate)
log_entries.append(f" Critique Crucible Response (Solution {i+1} - Snippet): {evaluation_text[:150]}...")
# Attempt to parse score (this is a simple parser, can be improved)
parsed_score = 0
try:
# Look for "Score: X/10" or "Score: X"
score_match = [s for s in evaluation_text.split() if s.endswith("/10")]
if score_match:
parsed_score = int(score_match[0].split('/')[0].split(':')[-1].strip())
else: # Try just a number if X/10 not found
nums = [int(s) for s in evaluation_text.replace(":"," ").split() if s.isdigit()]
if nums: parsed_score = max(min(nums[-1],10),0) # Take last number, cap at 10
except ValueError:
parsed_score = random.randint(3,7) # Fallback if parsing fails
critique = evaluation_text
score = parsed_score
evaluated_solutions_display.append(f"**Candidate {i+1}:**\n```text\n{sol_text}\n```\n**Crucible Verdict (Score: {score}/10):**\n{critique}\n---")
evaluated_sols_data.append({"id": i+1, "solution": sol_text, "score": score, "critique": critique})
if not evaluated_sols_data:
log_entries.append(" Critique Crucible yielded no evaluations.")
return "\n\n".join(evaluated_solutions_display) if evaluated_solutions_display else "Generation OK, but evaluation failed.", "", "", "\n".join(log_entries)
# --- STAGE 3: SELECTION & ASCENSION PREP ---
evaluated_sols_data.sort(key=lambda x: x["score"], reverse=True)
best_initial_solution_data = evaluated_sols_data[0]
log_entries.append(f"\n**Stage 3: Champion Selected - Candidate {best_initial_solution_data['id']} (Score: {best_initial_solution_data['score']}) chosen for evolution.**")
# --- STAGE 4: EVOLUTIONARY FORGE - PURSUIT OF PERFECTION ---
log_entries.append("\n**Stage 4: Evolutionary Forge - Refining the Champion...**")
system_prompt_evolve = f"You are an elite AI algorithm optimizer. Your task is to take a good solution and make it significantly better, focusing on {problem_type.lower()} best practices, efficiency, or clarity."
prompt_evolve = (
f"Original Problem: \"{problem_description}\"\n"
f"The current leading solution (Score: {best_initial_solution_data['score']}/10) is:\n```\n{best_initial_solution_data['solution']}\n```\n"
f"Original Critique: \"{best_initial_solution_data['critique']}\"\n"
f"Your mission: Evolve this solution. Make it demonstrably superior. Explain the key improvements you've made."
)
log_entries.append(f" Sending to Evolutionary Forge:\n Model: {model_id}\n Prompt (snippet): {prompt_evolve[:150]}...")
evolved_solution_text = call_llm_via_api(prompt_evolve, model_id, evolve_temp, evolve_max_tokens, system_prompt_evolve)
log_entries.append(f" Evolutionary Forge Response (Snippet): {evolved_solution_text[:150]}...")
# --- FINAL OUTPUT ASSEMBLY ---
initial_solutions_output_md = "\n\n".join(evaluated_solutions_display)
best_solution_output_md = (
f"**Champion Candidate {best_initial_solution_data['id']} (Original Score: {best_initial_solution_data['score']}/10):**\n"
f"```text\n{best_initial_solution_data['solution']}\n```\n"
f"**Original Crucible Verdict:**\n{best_initial_solution_data['critique']}"
)
evolved_solution_output_md = f"**✨ AlgoForge Prime™ Evolved Artifact ✨:**\n```text\n{evolved_solution_text}\n```"
log_entries.append("\n**AlgoForge Prime™ Cycle Complete.**")
final_log_output = "\n".join(log_entries)
return initial_solutions_output_md, best_solution_output_md, evolved_solution_output_md, final_log_output
# --- GRADIO UI: THE COMMAND DECK OF ALGOFORGE PRIME™ ---
intro_markdown = """
# ✨ AlgoForge Prime™ ✨: Conceptual Algorithmic Evolution
Welcome, Architect of the Future! I am your humble servant, an AI-driven system inspired by the groundbreaking work of pioneers like Google DeepMind's AlphaEvolve.
My purpose? To demonstrate a *simplified, conceptual* workflow for AI-assisted algorithm discovery and refinement.
**This is NOT AlphaEvolve.** This is a creative exploration using powerful Hugging Face LLMs via your `HF_TOKEN`.
**The Process, Distilled:**
1. **Genesis Engine:** We command an LLM to generate multiple diverse solutions to your problem.
2. **Critique Crucible:** Another (or the same) LLM instance evaluates these candidates, scoring them.
3. **Evolutionary Forge:** The highest-scoring candidate is fed back to an LLM with the directive: *IMPROVE IT!*
**Your `HF_TOKEN` must be set in this Space's Secrets for AlgoForge Prime™ to function!**
"""
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), title="AlgoForge Prime™") as demo:
gr.Markdown(intro_markdown)
if not HF_TOKEN:
gr.Markdown("<h2 style='color:red;'>⚠️ CRITICAL: `HF_TOKEN` is NOT detected in Space Secrets. AlgoForge Prime™ is non-operational. Please add your token.</h2>")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## 💡 1. Define the Challenge")
problem_type_dd = gr.Dropdown(
["Python Algorithm", "Data Structure Logic", "Mathematical Optimization", "Conceptual System Design", "Pseudocode Refinement"],
label="Type of Problem/Algorithm",
value="Python Algorithm"
)
problem_desc_tb = gr.Textbox(
lines=5,
label="Problem Description / Desired Outcome",
placeholder="e.g., 'Develop a Python function to efficiently find all prime factors of a large integer.' OR 'Design a heuristic for optimizing delivery routes in a dense urban area.'"
)
initial_hints_tb = gr.Textbox(
lines=3,
label="Initial Thoughts / Constraints / Seed Ideas (Optional)",
placeholder="e.g., 'Consider dynamic programming.' OR 'Avoid brute-force if N > 1000.' OR 'Must be implementable in Verilog later.'"
)
gr.Markdown("## ⚙️ 2. Configure The Forge")
model_select_dd = gr.Dropdown(
choices=list(AVAILABLE_MODELS.keys()),
value=list(AVAILABLE_MODELS.keys())[0], # Default to first model in dict
label="Select LLM Core Model"
)
num_solutions_slider = gr.Slider(1, 5, value=3, step=1, label="Number of Initial Solutions (Genesis Engine)")
with gr.Accordion("Advanced LLM Parameters (Tune with Caution!)", open=False):
gr.Markdown("Higher temperature = more creative/random. Lower = more focused/deterministic.")
with gr.Row():
gen_temp_slider = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="Genesis Temp")
gen_max_tokens_slider = gr.Slider(100, 1000, value=350, step=50, label="Genesis Max Tokens")
with gr.Row():
eval_temp_slider = gr.Slider(0.0, 1.5, value=0.5, step=0.1, label="Crucible Temp")
eval_max_tokens_slider = gr.Slider(100, 500, value=200, step=50, label="Crucible Max Tokens")
with gr.Row():
evolve_temp_slider = gr.Slider(0.0, 1.5, value=0.8, step=0.1, label="Evolution Temp")
evolve_max_tokens_slider = gr.Slider(100, 1000, value=400, step=50, label="Evolution Max Tokens")
submit_btn = gr.Button("🚀 ENGAGE ALGOFORGE PRIME™ 🚀", variant="primary", size="lg")
with gr.Column(scale=2):
gr.Markdown("## 🔥 3. The Forge's Output")
with gr.Tabs():
with gr.TabItem("📜 Genesis Candidates & Crucible Verdicts"):
output_initial_solutions_md = gr.Markdown(label="LLM-Generated Initial Solutions & Evaluations")
with gr.TabItem("🏆 Champion Candidate (Pre-Evolution)"):
output_best_solution_md = gr.Markdown(label="Evaluator's Top Pick")
with gr.TabItem("🌟 Evolved Artifact"):
output_evolved_solution_md = gr.Markdown(label="Refined Solution from the Evolutionary Forge")
with gr.TabItem("🛠️ LLM Interaction Log (SRE View)"):
output_interaction_log_md = gr.Markdown(label="Detailed Log of LLM Prompts & (Snippets of) Responses")
submit_btn.click(
fn=run_algoforge_simulation,
inputs=[
problem_type_dd, problem_desc_tb, initial_hints_tb,
num_solutions_slider, model_select_dd,
gen_temp_slider, gen_max_tokens_slider,
eval_temp_slider, eval_max_tokens_slider,
evolve_temp_slider, evolve_max_tokens_slider
],
outputs=[
output_initial_solutions_md, output_best_solution_md,
output_evolved_solution_md, output_interaction_log_md
]
)
gr.Markdown("---")
gr.Markdown(
"**Disclaimer:** As the architect of this marvel, I must remind you: this is a *conceptual demonstration*. Real AI-driven algorithm discovery is vastly more complex and resource-intensive. LLM outputs are probabilistic and require rigorous human oversight and verification. This tool is for inspiration and exploration, not production deployment of unverified algorithms. Handle with brilliance and caution!"
"\n\n*Powered by Gradio, Hugging Face Inference API, and the boundless spirit of innovation.*"
)
# To launch this magnificent creation:
if __name__ == "__main__":
if not HF_TOKEN:
print("="*80)
print("WARNING: HF_TOKEN environment variable not set.")
print("AlgoForge Prime™ requires this token to communicate with Hugging Face LLMs.")
print("Please set it in your environment or Space Secrets.")
print("The UI will load, but LLM functionality will be disabled.")
print("="*80)
demo.launch(debug=True) # Debug=True is useful for local development