"""FastAPI endpoints used by the React frontend.
Provides:
- /api/landscape build a template and return a Plotly contour + hints
- /api/baseline_race run 4 LR-tuned baselines and return plots + summary
- /api/arena full Phase-D evaluation of a user optimizer vs Adam
- /api/llm_run SSE-streamed LLM-driven episode
"""
from __future__ import annotations
import asyncio
import json
import re
import time
from typing import Any, Optional
import numpy as np
import requests
from fastapi import APIRouter, Query
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
try:
from ..arena import auto_test_draft, run_arena, ArenaResult
from ..landscapes import BUILDERS, build_landscape, structural_hints
from ..reference_optimizers import (
run_baseline_tuned, tune_adam_lr,
)
from ..rewards import ast_novelty_score, compute_optcoder_reward
from ..sandbox import SandboxError, compile_optimizer
from ..models import LandscapeforgeAction
from ..prompts import build_prompt, parse_action
from .landscapeforge_environment import LandscapeforgeEnvironment
except ImportError: # flat layout
from arena import auto_test_draft, run_arena, ArenaResult # type: ignore
from landscapes import BUILDERS, build_landscape, structural_hints # type: ignore
from reference_optimizers import ( # type: ignore
run_baseline_tuned, tune_adam_lr,
)
from rewards import ast_novelty_score, compute_optcoder_reward # type: ignore
from sandbox import SandboxError, compile_optimizer # type: ignore
from models import LandscapeforgeAction # type: ignore
from prompts import build_prompt, parse_action # type: ignore
from server.landscapeforge_environment import LandscapeforgeEnvironment # type: ignore
router = APIRouter(prefix="/api", tags=["lf-frontend"])
# ---------- palette constants for Plotly layouts ----------
_PLOTLY_LAYOUT = dict(
font=dict(family="Inter", color="#f3f0e8", size=12),
paper_bgcolor="#2a2824", plot_bgcolor="#1f1d1a",
hoverlabel=dict(bgcolor="#f3f0e8", font_color="#1f1d1a"),
legend=dict(bgcolor="rgba(31,29,26,0.85)",
bordercolor="#403b34", borderwidth=1,
font=dict(color="#f3f0e8")),
)
_AXIS = dict(gridcolor="#403b34", zerolinecolor="#554e45",
showline=True, linecolor="#554e45",
tickfont=dict(color="#b5ada0"))
_DEFAULT_MARGIN = dict(l=60, r=30, t=60, b=55)
_TITLE = dict(x=0.02, xanchor="left", font=dict(size=14, color="#f3f0e8"))
OPT_COLORS = {
"sgd": "#c05450",
"momentum": "#d9865b",
"adam": "#5b7a6b",
"lbfgs": "#556b99",
"custom": "#e28763",
}
# ---------- shared plot helpers ----------
def _color(name: str) -> str:
return OPT_COLORS.get(name.split("(")[0].strip(), "#e28763")
def _contour_fig(ls, trajectories=None, title=None):
import numpy as np
if ls.dim != 2:
return _empty_fig(f"{ls.name} · dim={ls.dim}\nContour is 2-D only", 480)
CLIP = 8.0
xs_all, ys_all = [0.0], [0.0]
for traj in (trajectories or {}).values():
arr = np.asarray(traj)
if arr.size == 0:
continue
mask = (np.abs(arr) <= CLIP).all(axis=1) & np.isfinite(arr).all(axis=1)
good = arr[mask]
if good.size:
xs_all.extend(good[:, 0].tolist())
ys_all.extend(good[:, 1].tolist())
x_min = max(min(xs_all) - 1.5, -CLIP); x_max = min(max(xs_all) + 1.5, CLIP)
y_min = max(min(ys_all) - 1.5, -CLIP); y_max = min(max(ys_all) + 1.5, CLIP)
x_min, x_max = min(x_min, -3.5), max(x_max, 3.5)
y_min, y_max = min(y_min, -3.5), max(y_max, 3.5)
g = 70
xs = np.linspace(x_min, x_max, g)
ys = np.linspace(y_min, y_max, g)
X, Y = np.meshgrid(xs, ys)
Z = np.empty_like(X)
for i in range(g):
for j in range(g):
Z[i, j] = ls.f(np.array([X[i, j], Y[i, j]]))
finite = Z[np.isfinite(Z)]
lo, hi = map(float, np.percentile(finite, [2, 95]))
data = [dict(
type="contour", x=xs.tolist(), y=ys.tolist(), z=Z.tolist(),
zmin=lo, zmax=hi,
colorscale=[
[0.0, "#1f1d1a"], [0.15, "#2f2a22"], [0.3, "#4a2f22"],
[0.5, "#7a4229"], [0.7, "#c25a3a"], [0.85, "#e28763"],
[1.0, "#f4d6c5"],
],
contours=dict(coloring="heatmap", showlabels=False),
line=dict(width=0.5, color="rgba(243,240,232,0.12)"),
colorbar=dict(title=dict(text="f(x)",
font=dict(size=11, color="#f3f0e8")),
thickness=12, len=0.85,
tickfont=dict(size=10, color="#b5ada0"),
outlinewidth=0),
hovertemplate="x₁=%{x:.3f}
x₂=%{y:.3f}
f=%{z:.3f}
x₁=%{x:.3f}
x₂=%{y:.3f}"
"
f=%{y:.4g}
" + ylabel + "=%{y:.4g}{n}: {lr:g}"
for n, lr in lrs.items())
best = min(finals, key=finals.get)
return {
"contour": _contour_fig(ls, trajectories=traj_2d,
title=f"{req.template} — baselines racing (LR-tuned)"),
"curves": _curves_fig(curves, "f(x) vs step"),
"finals": _bar_fig(finals, "Final f after 50 steps",
"f(x) at step 50"),
"summary_md": (
f"
{ls.description}
" f"Tuned LR per baseline (7-point sweep, 30 steps): {lr_list}
" f"Best baseline: {best} at f = "
f"{finals[best]:.4f}
{my_p:.3g}")
else:
speedup_line = (f"Speedup vs Adam: {speedup:.3g}× "
f"(your descent {my_p:.3g}, Adam's "
f"{adam_p:.3g})")
return {
"contour": contour or _empty_fig(f"{req.template} · dim={dim}\nContour is 2-D only"),
"progress": _bar_fig(
{"custom": user_arena.mean_progress,
"adam (tuned)": adam_arena.mean_progress},
"Arena mean progress",
"mean(f₀ − f_N) over 10 seeds",
),
"breakdown": bk,
"total": reward.r_total,
"summary_md": (
f"{best_lr:g}{user_arena.crash_fraction:.0%}{reward.r_total:+.3f}"
+ (f" "
f"= {' + '.join(parts)}" if parts else "")
+ "final_f={s['final_f']:.3g}",
})
if action.kind == "run_baseline" and lar.get("final_f") is not None:
output_chips.append({
"kind": "info",
"text": f"final_f={lar['final_f']:.3g}",
})
for k, v in (lar.get("feedback") or {}).items():
output_chips.append({
"kind": "good" if v >= 0 else "warn",
"text": f"{k} {v:+.3f}",
})
if action.kind == "draft":
action_str = f"draft ({len(action.code or '')} chars)"
elif action.kind == "run_baseline":
action_str = f"run_baseline({action.baseline_name})"
elif action.kind == "inspect":
action_str = (f"inspect(draft={action.draft_idx}, "
f"[{action.step_range_start},{action.step_range_end}])")
else:
action_str = "commit"
yield _sse("message", {
"kind": "turn",
"turn": turn, "kind_of": action.kind,
"action_str": action_str, "output": output_chips,
"duration_s": dt,
"budget_remaining": obs.budget_remaining,
"code": action.code if action.kind == "draft" else None,
})
if obs.done:
bk = obs.r_optcoder_breakdown or {}
yield _sse("message", {
"kind": "done",
"reason": (obs.last_action_result or {}).get("reason"),
"reward": obs.r_optcoder or 0.0,
"final_regret": obs.final_regret or 0.0,
"my_progress": bk.get("my_progress", 0.0),
"adam_progress": bk.get("adam_progress", 0.0),
"speedup_vs_adam": bk.get("speedup_vs_adam", 0.0),
"breakdown": bk,
})
yield "event: end\ndata: {}\n\n"
return
yield _sse("message", {
"kind": "error",
"message": f"reached MAX_TURNS ({max_turns}) without commit",
})
yield "event: end\ndata: {}\n\n"
return StreamingResponse(gen(), media_type="text/event-stream")