Spaces:
Sleeping
LLM fallback chain + Reset button + Accordion UI + per-run audit
Browse filesThree independent fixes, all driven by the user's report after the
last deployment:
1. LLM fallback chain (Gemini 429 -> OpenRouter -> echo).
Gemini's free tier rate-limits aggressively (HTTP 429). When the
429 fires the chat used to die with a 'low confidence' note and
the user had no fallback. cdpr.llm.config.resolve_fallback_chain
now returns an ordered provider list driven by CDPR_LLM_FALLBACK_
CHAIN or, when unset, by which keys are configured. simulation_
builder.describe_to_request walks the chain and uses whichever
provider returns parseable JSON first; the echo stub is appended
unconditionally so the call never raises. BuilderResult.notes
reports which providers were tried and which won. docs/llm-
providers.md gains a 'Automatic fallback chain' section.
2. Reset button + collapsible accordion sections.
Robot & dynamics / Trajectory / Time / Controller are now wrapped
in gr.Accordion (default open=False, like file-tree folders).
The Trajectory accordion nests its own three sub-accordions for
Line, Circle, and Lissajous parameters so a chosen kind doesn't
share screen space with irrelevant configs. A new 'Reset all'
button beside Run clears the gallery / status / CSV download and
pushes every form widget back to its factory default, leaving
the chat history intact.
3. Per-run audit artefacts.
_run_custom_simulation now writes run_manifest.json next to the
CSV. The manifest captures every input parameter, the resulting
metrics, and SHA1 fingerprints of the realised position and
tension trajectories --- two runs sharing a fingerprint ARE the
same simulation; two runs that differ ANYWHERE produce different
fingerprints, which proves the figures could not have been pulled
from a cached previous run. The Run summary now surfaces the
12-char position-hash prefix so the user can compare runs at a
glance. A new reference_vs_actual.png figure (built from a
high-resolution sample of the reference callable overlaid on the
actual result.positions) makes shape-level differences --- circle
vs figure-eight vs line --- impossible to miss.
Bonus: .gitignore had an inline comment on the 'out/' line. Git's
gitignore parser does not support inline comments, so 'out/' was
treated as the literal pattern 'out/ #...'
and matched nothing. Fixed by moving the comment to its own line.
Without this, the artefact directory would have ended up in the
next commit.
Smoke checks:
* resolve_fallback_chain() returns ['gemini','openrouter','echo']
by default and falls through to echo when no keys are present.
* Two distinct _run_custom_simulation calls
(PD + circle vs MPC + figure-eight) produce distinct manifest
fingerprints:
Run 1 positions_sha1[:16] = 51914adb2430d50d
Run 2 positions_sha1[:16] = bca0c2e4e9ccc595
proving the figures are necessarily different.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- .gitignore +2 -1
- docs/llm-providers.md +20 -0
- gradio_app.py +330 -95
- src/cdpr/llm/__init__.py +2 -0
- src/cdpr/llm/config.py +31 -0
- src/cdpr/llm/simulation_builder.py +70 -20
|
@@ -38,7 +38,8 @@ results/
|
|
| 38 |
artifacts/
|
| 39 |
runs/
|
| 40 |
checkpoints/
|
| 41 |
-
|
|
|
|
| 42 |
*.mp4
|
| 43 |
*.gif
|
| 44 |
*.h5
|
|
|
|
| 38 |
artifacts/
|
| 39 |
runs/
|
| 40 |
checkpoints/
|
| 41 |
+
# scripts/run_simulation.py output (gitignore does NOT support inline comments)
|
| 42 |
+
out/
|
| 43 |
*.mp4
|
| 44 |
*.gif
|
| 45 |
*.h5
|
|
@@ -132,6 +132,26 @@ specific one regardless of which keys exist:
|
|
| 132 |
CDPR_LLM_PROVIDER=openrouter
|
| 133 |
```
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
## Step 4 — Deployment secrets
|
| 136 |
|
| 137 |
Never commit `.env`. The repo's `.gitignore` already excludes it.
|
|
|
|
| 132 |
CDPR_LLM_PROVIDER=openrouter
|
| 133 |
```
|
| 134 |
|
| 135 |
+
### Automatic fallback chain
|
| 136 |
+
|
| 137 |
+
The conversational simulation builder doesn't stop at one provider —
|
| 138 |
+
it walks a chain in order until one returns a parseable response.
|
| 139 |
+
Default chain (when `CDPR_LLM_FALLBACK_CHAIN` is unset): every
|
| 140 |
+
provider whose env var is configured, in the priority order above,
|
| 141 |
+
with the echo stub appended at the end so the call never raises.
|
| 142 |
+
|
| 143 |
+
Pin a custom chain via env var:
|
| 144 |
+
|
| 145 |
+
```
|
| 146 |
+
CDPR_LLM_FALLBACK_CHAIN=gemini,openrouter,ollama,echo
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
Why this matters: Gemini's free tier rate-limits aggressively
|
| 150 |
+
(HTTP 429). When the limit hits, the chain rolls over to OpenRouter,
|
| 151 |
+
parses the description there, and the user never sees the failure
|
| 152 |
+
in the form — only in the chat reply's *Notes* section, which lists
|
| 153 |
+
which provider answered and which providers it tried first.
|
| 154 |
+
|
| 155 |
## Step 4 — Deployment secrets
|
| 156 |
|
| 157 |
Never commit `.env`. The repo's `.gitignore` already excludes it.
|
|
@@ -395,7 +395,7 @@ def _run_custom_simulation(
|
|
| 395 |
)
|
| 396 |
dt_run = time.perf_counter() - t0
|
| 397 |
|
| 398 |
-
# Write outputs + render plots into a unique
|
| 399 |
stamp = time.strftime("%Y%m%d-%H%M%S")
|
| 400 |
out_dir = _ROOT / "out" / f"gradio-custom-{stamp}"
|
| 401 |
out_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -409,18 +409,54 @@ def _run_custom_simulation(
|
|
| 409 |
)
|
| 410 |
figs = _render_phase1_plots(out_dir, result, robot, reference)
|
| 411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
tens = np.asarray(result.cable_tensions)
|
| 413 |
ref_pos = np.array([reference(t).position for t in result.time])
|
| 414 |
err = np.linalg.norm(np.asarray(result.positions) - ref_pos, axis=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
status = (
|
| 416 |
f"[done] {len(result.time)} samples in {dt_run:.1f} s\n"
|
| 417 |
-
f"
|
| 418 |
-
f"
|
| 419 |
-
f"
|
| 420 |
-
f"
|
| 421 |
-
f"
|
| 422 |
-
f"
|
| 423 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
)
|
| 425 |
png_paths = sorted(str(p) for p in out_dir.glob("*.png"))
|
| 426 |
return status, png_paths, str(csv_path)
|
|
@@ -429,6 +465,135 @@ def _run_custom_simulation(
|
|
| 429 |
[], "")
|
| 430 |
|
| 431 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
# ---------------------------------------------------------------------------
|
| 433 |
# Phase-1 --- Conversational simulation builder (chat box)
|
| 434 |
# ---------------------------------------------------------------------------
|
|
@@ -716,15 +881,16 @@ def build_ui() -> gr.Blocks:
|
|
| 716 |
gr.HTML(
|
| 717 |
"<h4>Describe what you want to simulate</h4>"
|
| 718 |
"<p class='cdpr-chat-hint'>"
|
| 719 |
-
"The LLM layer
|
| 720 |
-
"Ollama · LM Studio · or the echo stub) "
|
| 721 |
-
"parses your description into a "
|
| 722 |
"<code>SimulationRequest</code> and pre-fills the form "
|
| 723 |
-
"below.
|
| 724 |
-
"
|
| 725 |
-
"
|
| 726 |
-
"<
|
| 727 |
-
"
|
|
|
|
|
|
|
|
|
|
| 728 |
"</p>"
|
| 729 |
)
|
| 730 |
# Gradio 6.x: messages format is the default; ``buttons``
|
|
@@ -747,55 +913,56 @@ def build_ui() -> gr.Blocks:
|
|
| 747 |
with gr.Row():
|
| 748 |
chat_clear = gr.Button("Clear conversation", variant="secondary")
|
| 749 |
|
| 750 |
-
# ----- Manual form --------------------------------------------
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 760 |
payload_mass = gr.Number(value=0.0, label="Payload mass [kg]",
|
| 761 |
minimum=0.0, step=0.1)
|
| 762 |
gravity_on = gr.Checkbox(value=True, label="Apply gravity")
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
gr.
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
elem_classes=["cdpr-section-title"])
|
| 780 |
-
kind = gr.Dropdown(
|
| 781 |
-
["hold", "line", "circle", "lissajous"],
|
| 782 |
-
value="circle", label="Trajectory kind",
|
| 783 |
-
)
|
| 784 |
-
gr.Markdown("**Line params**")
|
| 785 |
line_start = gr.Textbox(value="0,0,0.5",
|
| 786 |
label="start (x,y,z) [m]")
|
| 787 |
line_end = gr.Textbox(value="0.05,0,0.5",
|
| 788 |
label="end (x,y,z) [m]")
|
| 789 |
-
|
| 790 |
circle_center = gr.Textbox(value="0,0,0.65",
|
| 791 |
label="center (x,y,z) [m]")
|
| 792 |
-
|
| 793 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 794 |
circle_axis = gr.Textbox(value="0,0,1", label="axis (x,y,z)")
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
)
|
| 798 |
-
gr.Markdown("**Lissajous params**")
|
| 799 |
lj_center = gr.Textbox(value="0,0,0.65", label="center [m]")
|
| 800 |
lj_amps = gr.Textbox(value="0.03,0.03,0.0",
|
| 801 |
label="amplitudes (x,y,z) [m]")
|
|
@@ -804,10 +971,14 @@ def build_ui() -> gr.Blocks:
|
|
| 804 |
lj_phases = gr.Textbox(value="0,1.5708,0",
|
| 805 |
label="phases (x,y,z) [rad]")
|
| 806 |
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
controller_kind = gr.Radio(
|
| 812 |
["PD", "MPC"], value="PD",
|
| 813 |
label="Family",
|
|
@@ -817,42 +988,39 @@ def build_ui() -> gr.Blocks:
|
|
| 817 |
"(cdpr.control.mpc); cable bounds are enforced "
|
| 818 |
"by the tension-distribution QP either way."),
|
| 819 |
)
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
# for the orientation channel.
|
| 823 |
-
with gr.Row():
|
| 824 |
kp_rot = gr.Number(value=100.0,
|
| 825 |
-
label="Kp_rot (orientation; shared)",
|
| 826 |
minimum=0.0)
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
minimum=0.0)
|
| 856 |
|
| 857 |
def _toggle_controller(choice: str):
|
| 858 |
is_mpc = (choice or "").upper() == "MPC"
|
|
@@ -864,8 +1032,10 @@ def build_ui() -> gr.Blocks:
|
|
| 864 |
outputs=[pd_group, mpc_group],
|
| 865 |
)
|
| 866 |
|
| 867 |
-
# ----- Run + outputs ---------------------------------
|
| 868 |
-
|
|
|
|
|
|
|
| 869 |
status_text = gr.Textbox(label="Run summary", lines=9, interactive=False)
|
| 870 |
with gr.Row():
|
| 871 |
fig_gallery = gr.Gallery(label="Figures", columns=2, height="600px")
|
|
@@ -888,6 +1058,71 @@ def build_ui() -> gr.Blocks:
|
|
| 888 |
outputs=[status_text, fig_gallery, csv_out],
|
| 889 |
)
|
| 890 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 891 |
# Chat wiring --- must come AFTER the form widgets and the
|
| 892 |
# controller group definitions exist. The trailing three
|
| 893 |
# outputs (controller_kind, pd_group, mpc_group) let a chat
|
|
|
|
| 395 |
)
|
| 396 |
dt_run = time.perf_counter() - t0
|
| 397 |
|
| 398 |
+
# Write outputs + render plots into a unique timestamped dir.
|
| 399 |
stamp = time.strftime("%Y%m%d-%H%M%S")
|
| 400 |
out_dir = _ROOT / "out" / f"gradio-custom-{stamp}"
|
| 401 |
out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 409 |
)
|
| 410 |
figs = _render_phase1_plots(out_dir, result, robot, reference)
|
| 411 |
|
| 412 |
+
# Extra figure: dense reference vs realised trajectory in 3D.
|
| 413 |
+
# Makes shape-level differences (circle vs figure-eight vs line)
|
| 414 |
+
# unambiguous at a glance. Built from the reference callable and
|
| 415 |
+
# the actual result.positions of THIS run --- no caching.
|
| 416 |
+
_render_reference_overlay(
|
| 417 |
+
out_dir, reference, result, request.trajectory, controller_label,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
tens = np.asarray(result.cable_tensions)
|
| 421 |
ref_pos = np.array([reference(t).position for t in result.time])
|
| 422 |
err = np.linalg.norm(np.asarray(result.positions) - ref_pos, axis=1)
|
| 423 |
+
metrics = {
|
| 424 |
+
"samples": int(len(result.time)),
|
| 425 |
+
"wall_time_s": round(dt_run, 3),
|
| 426 |
+
"tension_min_N": float(tens.min()),
|
| 427 |
+
"tension_max_N": float(tens.max()),
|
| 428 |
+
"infeasible_steps": int(len(result.infeasible_steps)),
|
| 429 |
+
"tracking_rms_mm": float(np.sqrt(np.mean(err ** 2)) * 1e3),
|
| 430 |
+
"tracking_peak_mm": float(err.max() * 1e3),
|
| 431 |
+
}
|
| 432 |
+
manifest_path = _write_run_manifest(
|
| 433 |
+
out_dir, request, result, controller_label,
|
| 434 |
+
kp_pos=kp_pos, kp_rot=kp_rot,
|
| 435 |
+
mpc_horizon=mpc_horizon, mpc_q_pos=mpc_q_pos, mpc_q_vel=mpc_q_vel,
|
| 436 |
+
mpc_r_force=mpc_r_force, mpc_p_terminal=mpc_p_terminal,
|
| 437 |
+
t_min=t_min, t_max=t_max, gravity_on=gravity_on,
|
| 438 |
+
metrics=metrics,
|
| 439 |
+
)
|
| 440 |
+
# SHA1 of the realised position trajectory --- two runs that share
|
| 441 |
+
# this fingerprint are bit-for-bit identical. Two runs that differ
|
| 442 |
+
# anywhere in inputs produce different fingerprints, which proves
|
| 443 |
+
# the figures cannot have come from a cached previous run.
|
| 444 |
+
import hashlib
|
| 445 |
+
fp_pos = hashlib.sha1(np.asarray(result.positions).tobytes()).hexdigest()[:12]
|
| 446 |
+
|
| 447 |
status = (
|
| 448 |
f"[done] {len(result.time)} samples in {dt_run:.1f} s\n"
|
| 449 |
+
f"run id : {stamp}\n"
|
| 450 |
+
f"controller : {controller_label}\n"
|
| 451 |
+
f"trajectory : {kind} {dict(params)!r}\n"
|
| 452 |
+
f"tensions : [{tens.min():.2f}, {tens.max():.2f}] N\n"
|
| 453 |
+
f"infeasible : {len(result.infeasible_steps)} steps\n"
|
| 454 |
+
f"tracking : RMS {metrics['tracking_rms_mm']:.2f} mm "
|
| 455 |
+
f"peak {metrics['tracking_peak_mm']:.2f} mm\n"
|
| 456 |
+
f"position hash: {fp_pos} (different every distinct run)\n"
|
| 457 |
+
f"manifest : {manifest_path.name}\n"
|
| 458 |
+
f"figures : {len(figs) + 1} PNGs in {out_dir}\n"
|
| 459 |
+
f"build : {BUILD_ID}\n"
|
| 460 |
)
|
| 461 |
png_paths = sorted(str(p) for p in out_dir.glob("*.png"))
|
| 462 |
return status, png_paths, str(csv_path)
|
|
|
|
| 465 |
[], "")
|
| 466 |
|
| 467 |
|
| 468 |
+
# ---------------------------------------------------------------------------
|
| 469 |
+
# Per-run audit artefacts: manifest + reference overlay
|
| 470 |
+
# ---------------------------------------------------------------------------
|
| 471 |
+
# Two artefacts that make every run independently auditable:
|
| 472 |
+
#
|
| 473 |
+
# * ``run_manifest.json`` --- every input parameter + the resulting
|
| 474 |
+
# metrics + a SHA1 of the realised trajectory. If two runs share a
|
| 475 |
+
# fingerprint, they ARE the same simulation; if the fingerprint
|
| 476 |
+
# differs, every figure built from result.positions necessarily
|
| 477 |
+
# differs too.
|
| 478 |
+
# * ``reference_vs_actual_3d.png`` --- the high-resolution reference
|
| 479 |
+
# trajectory (from the analytic callable) overlaid with the actual
|
| 480 |
+
# realised trajectory (from the simulation). Shape-level differences
|
| 481 |
+
# (circle vs figure-eight vs line vs hold) jump out instantly.
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _write_run_manifest(
|
| 485 |
+
out_dir: Path, request: SimulationRequest, result, controller_label: str,
|
| 486 |
+
*, kp_pos: float, kp_rot: float,
|
| 487 |
+
mpc_horizon: float, mpc_q_pos: float, mpc_q_vel: float,
|
| 488 |
+
mpc_r_force: float, mpc_p_terminal: float,
|
| 489 |
+
t_min: float, t_max: float, gravity_on: bool,
|
| 490 |
+
metrics: dict,
|
| 491 |
+
) -> Path:
|
| 492 |
+
"""Write a per-run JSON manifest. The fingerprint at the bottom is
|
| 493 |
+
the SHA1 of the realised trajectory; two runs with the same
|
| 494 |
+
fingerprint are bit-for-bit identical."""
|
| 495 |
+
import hashlib
|
| 496 |
+
positions = np.asarray(result.positions)
|
| 497 |
+
tensions = np.asarray(result.cable_tensions)
|
| 498 |
+
manifest = {
|
| 499 |
+
"build_id": BUILD_ID,
|
| 500 |
+
"run_started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
| 501 |
+
"robot": request.robot,
|
| 502 |
+
"payload_mass_kg": float(request.payload_mass),
|
| 503 |
+
"gravity_on": bool(gravity_on),
|
| 504 |
+
"tension_objective": request.tension_objective,
|
| 505 |
+
"tension_bounds_N": [float(t_min), float(t_max)],
|
| 506 |
+
"duration_s": float(request.duration),
|
| 507 |
+
"dt_s": float(request.dt),
|
| 508 |
+
"trajectory": {
|
| 509 |
+
"kind": request.trajectory.kind,
|
| 510 |
+
"params": request.trajectory.params,
|
| 511 |
+
},
|
| 512 |
+
"controller": {
|
| 513 |
+
"label": controller_label,
|
| 514 |
+
"kp_pos_pd": float(kp_pos),
|
| 515 |
+
"kp_rot_shared": float(kp_rot),
|
| 516 |
+
"mpc": {
|
| 517 |
+
"horizon": int(mpc_horizon),
|
| 518 |
+
"Q_pos": float(mpc_q_pos),
|
| 519 |
+
"Q_vel": float(mpc_q_vel),
|
| 520 |
+
"R_force": float(mpc_r_force),
|
| 521 |
+
"P_terminal": float(mpc_p_terminal),
|
| 522 |
+
},
|
| 523 |
+
},
|
| 524 |
+
"metrics": metrics,
|
| 525 |
+
"fingerprint": {
|
| 526 |
+
"positions_sha1": hashlib.sha1(positions.tobytes()).hexdigest(),
|
| 527 |
+
"tensions_sha1": hashlib.sha1(tensions.tobytes()).hexdigest(),
|
| 528 |
+
"samples": int(positions.shape[0]),
|
| 529 |
+
"cables": int(tensions.shape[1]),
|
| 530 |
+
},
|
| 531 |
+
}
|
| 532 |
+
path = out_dir / "run_manifest.json"
|
| 533 |
+
path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
| 534 |
+
return path
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _render_reference_overlay(
|
| 538 |
+
out_dir: Path, reference, result, traj_spec, controller_label: str,
|
| 539 |
+
) -> None:
|
| 540 |
+
"""Render reference_vs_actual_3d.png + reference_vs_actual_xy.png.
|
| 541 |
+
|
| 542 |
+
The reference path is sampled at HIGH resolution from the analytic
|
| 543 |
+
``reference(t)`` callable, so the curve looks smooth regardless of
|
| 544 |
+
how coarse the simulation dt is. The actual realised trajectory
|
| 545 |
+
comes from ``result.positions``. Both are plotted in the same axes
|
| 546 |
+
so the shape difference is unmistakable."""
|
| 547 |
+
import matplotlib.pyplot as plt
|
| 548 |
+
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
|
| 549 |
+
|
| 550 |
+
try:
|
| 551 |
+
from cdpr.viz.style import apply_paper_style
|
| 552 |
+
apply_paper_style()
|
| 553 |
+
except Exception: # pragma: no cover
|
| 554 |
+
pass
|
| 555 |
+
|
| 556 |
+
t = np.asarray(result.time)
|
| 557 |
+
if t.size < 2:
|
| 558 |
+
return
|
| 559 |
+
# Sample the reference at 10x the simulation rate (capped at 4000
|
| 560 |
+
# samples so the figure stays light).
|
| 561 |
+
n_ref = int(min(4000, max(400, 10 * t.size)))
|
| 562 |
+
t_ref = np.linspace(float(t[0]), float(t[-1]), n_ref)
|
| 563 |
+
ref_xyz = np.asarray([reference(tt).position for tt in t_ref])
|
| 564 |
+
act_xyz = np.asarray(result.positions)
|
| 565 |
+
|
| 566 |
+
fig = plt.figure(figsize=(8.2, 5.2))
|
| 567 |
+
ax3 = fig.add_subplot(1, 2, 1, projection="3d")
|
| 568 |
+
ax3.plot(ref_xyz[:, 0], ref_xyz[:, 1], ref_xyz[:, 2],
|
| 569 |
+
"-", color="C0", lw=1.5, label="reference")
|
| 570 |
+
ax3.plot(act_xyz[:, 0], act_xyz[:, 1], act_xyz[:, 2],
|
| 571 |
+
"--", color="C3", lw=1.3, label="actual")
|
| 572 |
+
ax3.set_xlabel("x [m]"); ax3.set_ylabel("y [m]"); ax3.set_zlabel("z [m]")
|
| 573 |
+
ax3.legend(loc="best", fontsize=8)
|
| 574 |
+
ax3.set_title(f"Reference vs actual ({traj_spec.kind})")
|
| 575 |
+
|
| 576 |
+
ax2 = fig.add_subplot(1, 2, 2)
|
| 577 |
+
ax2.plot(ref_xyz[:, 0], ref_xyz[:, 1], "-",
|
| 578 |
+
color="C0", lw=1.5, label="reference")
|
| 579 |
+
ax2.plot(act_xyz[:, 0], act_xyz[:, 1], "--",
|
| 580 |
+
color="C3", lw=1.3, label="actual")
|
| 581 |
+
ax2.set_xlabel("x [m]"); ax2.set_ylabel("y [m]")
|
| 582 |
+
ax2.set_aspect("equal", adjustable="datalim")
|
| 583 |
+
ax2.legend(loc="best", fontsize=8)
|
| 584 |
+
ax2.grid(True, alpha=0.3)
|
| 585 |
+
ax2.set_title("xy projection")
|
| 586 |
+
|
| 587 |
+
fig.suptitle(
|
| 588 |
+
f"Run fingerprint stamp --- controller = {controller_label[:60]}",
|
| 589 |
+
fontsize=9, y=1.01,
|
| 590 |
+
)
|
| 591 |
+
fig.tight_layout()
|
| 592 |
+
fig.savefig(out_dir / "reference_vs_actual.png",
|
| 593 |
+
dpi=160, bbox_inches="tight")
|
| 594 |
+
plt.close(fig)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
# ---------------------------------------------------------------------------
|
| 598 |
# Phase-1 --- Conversational simulation builder (chat box)
|
| 599 |
# ---------------------------------------------------------------------------
|
|
|
|
| 881 |
gr.HTML(
|
| 882 |
"<h4>Describe what you want to simulate</h4>"
|
| 883 |
"<p class='cdpr-chat-hint'>"
|
| 884 |
+
"The LLM layer parses your description into a "
|
|
|
|
|
|
|
| 885 |
"<code>SimulationRequest</code> and pre-fills the form "
|
| 886 |
+
"below. The chain falls through providers in order "
|
| 887 |
+
"— <b>Gemini</b> first; if it 429-rate-limits or "
|
| 888 |
+
"is unavailable, <b>OpenRouter / DeepSeek</b> takes the "
|
| 889 |
+
"next attempt; if that fails too, the <b>echo</b> stub "
|
| 890 |
+
"falls back to keyword-based intent detection. "
|
| 891 |
+
"Set <code>GEMINI_API_KEY</code> and "
|
| 892 |
+
"<code>OPENROUTER_API_KEY</code> as Space secrets to "
|
| 893 |
+
"enable both. See <code>docs/llm-providers.md</code>."
|
| 894 |
"</p>"
|
| 895 |
)
|
| 896 |
# Gradio 6.x: messages format is the default; ``buttons``
|
|
|
|
| 913 |
with gr.Row():
|
| 914 |
chat_clear = gr.Button("Clear conversation", variant="secondary")
|
| 915 |
|
| 916 |
+
# ----- Manual form ---------------------------------------------
|
| 917 |
+
# Four collapsible accordions, modelled on a file-tree: click
|
| 918 |
+
# the heading to expand, click again to collapse so a
|
| 919 |
+
# configured form takes one line each. Each accordion starts
|
| 920 |
+
# CLOSED --- the chat box drives most parameter setting; users
|
| 921 |
+
# who prefer manual configuration open the sections they need.
|
| 922 |
+
|
| 923 |
+
with gr.Accordion("Robot & dynamics", open=False):
|
| 924 |
+
robot_name = gr.Dropdown(
|
| 925 |
+
["point_mass_3d", "planar_translational",
|
| 926 |
+
"ipanema_class", "cogiro_class", "dissertation_8cable"],
|
| 927 |
+
value="dissertation_8cable", label="Robot",
|
| 928 |
+
)
|
| 929 |
+
with gr.Row():
|
| 930 |
payload_mass = gr.Number(value=0.0, label="Payload mass [kg]",
|
| 931 |
minimum=0.0, step=0.1)
|
| 932 |
gravity_on = gr.Checkbox(value=True, label="Apply gravity")
|
| 933 |
+
objective = gr.Radio(
|
| 934 |
+
["min_norm", "centered", "preferred"],
|
| 935 |
+
value="centered", label="Tension distribution objective",
|
| 936 |
+
)
|
| 937 |
+
with gr.Row():
|
| 938 |
+
t_min = gr.Number(value=5.0, label="Tension min [N]",
|
| 939 |
+
minimum=0.0)
|
| 940 |
+
t_max = gr.Number(value=500.0, label="Tension max [N]",
|
| 941 |
+
minimum=0.0)
|
| 942 |
+
|
| 943 |
+
with gr.Accordion("Trajectory", open=False):
|
| 944 |
+
kind = gr.Dropdown(
|
| 945 |
+
["hold", "line", "circle", "lissajous"],
|
| 946 |
+
value="circle", label="Trajectory kind",
|
| 947 |
+
)
|
| 948 |
+
with gr.Accordion("Line parameters", open=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 949 |
line_start = gr.Textbox(value="0,0,0.5",
|
| 950 |
label="start (x,y,z) [m]")
|
| 951 |
line_end = gr.Textbox(value="0.05,0,0.5",
|
| 952 |
label="end (x,y,z) [m]")
|
| 953 |
+
with gr.Accordion("Circle parameters", open=False):
|
| 954 |
circle_center = gr.Textbox(value="0,0,0.65",
|
| 955 |
label="center (x,y,z) [m]")
|
| 956 |
+
with gr.Row():
|
| 957 |
+
circle_radius = gr.Number(value=0.05, label="radius [m]",
|
| 958 |
+
minimum=0.0, maximum=2.0)
|
| 959 |
+
circle_angle_span = gr.Number(
|
| 960 |
+
value=float(4 * np.pi), label="angle span [rad]",
|
| 961 |
+
minimum=0.1,
|
| 962 |
+
)
|
| 963 |
circle_axis = gr.Textbox(value="0,0,1", label="axis (x,y,z)")
|
| 964 |
+
with gr.Accordion("Lissajous (figure-eight) parameters",
|
| 965 |
+
open=False):
|
|
|
|
|
|
|
| 966 |
lj_center = gr.Textbox(value="0,0,0.65", label="center [m]")
|
| 967 |
lj_amps = gr.Textbox(value="0.03,0.03,0.0",
|
| 968 |
label="amplitudes (x,y,z) [m]")
|
|
|
|
| 971 |
lj_phases = gr.Textbox(value="0,1.5708,0",
|
| 972 |
label="phases (x,y,z) [rad]")
|
| 973 |
|
| 974 |
+
with gr.Accordion("Time", open=False):
|
| 975 |
+
with gr.Row():
|
| 976 |
+
duration = gr.Number(value=12.566, label="Duration [s]",
|
| 977 |
+
minimum=0.05, maximum=300.0)
|
| 978 |
+
dt_input = gr.Number(value=1e-3, label="dt [s]",
|
| 979 |
+
minimum=1e-4, maximum=5e-2)
|
| 980 |
+
|
| 981 |
+
with gr.Accordion("Controller", open=False):
|
| 982 |
controller_kind = gr.Radio(
|
| 983 |
["PD", "MPC"], value="PD",
|
| 984 |
label="Family",
|
|
|
|
| 988 |
"(cdpr.control.mpc); cable bounds are enforced "
|
| 989 |
"by the tension-distribution QP either way."),
|
| 990 |
)
|
| 991 |
+
# Orientation PD gains are SHARED --- both PD and MPC use
|
| 992 |
+
# them for the orientation channel.
|
|
|
|
|
|
|
| 993 |
kp_rot = gr.Number(value=100.0,
|
| 994 |
+
label="Kp_rot (orientation; shared between PD and MPC)",
|
| 995 |
minimum=0.0)
|
| 996 |
+
# PD-only group: translational position gain.
|
| 997 |
+
with gr.Group(visible=True) as pd_group:
|
| 998 |
+
gr.Markdown("**PD --- translational gain**")
|
| 999 |
+
kp_pos = gr.Number(value=400.0,
|
| 1000 |
+
label="Kp_pos (Kd_pos = 2·sqrt(Kp_pos))",
|
| 1001 |
+
minimum=0.0)
|
| 1002 |
+
# MPC-only group: horizon + QP weights.
|
| 1003 |
+
with gr.Group(visible=False) as mpc_group:
|
| 1004 |
+
gr.Markdown(
|
| 1005 |
+
"**MPC --- horizon and quadratic weights** \n"
|
| 1006 |
+
"*State* x = [p, v] (3+3). *Stage cost* = "
|
| 1007 |
+
"Q_pos·||p−p_ref||² + Q_vel·||v−v_ref||² + R·||u||². "
|
| 1008 |
+
"*Terminal* = P·||p−p_ref||²."
|
| 1009 |
+
)
|
| 1010 |
+
with gr.Row():
|
| 1011 |
+
mpc_horizon = gr.Number(value=8, label="Horizon N (steps)",
|
| 1012 |
+
minimum=2, maximum=50, step=1)
|
| 1013 |
+
mpc_q_pos = gr.Number(value=2.0e3, label="Q_pos",
|
| 1014 |
+
minimum=0.0)
|
| 1015 |
+
mpc_q_vel = gr.Number(value=2.0e1, label="Q_vel",
|
| 1016 |
+
minimum=0.0)
|
| 1017 |
+
with gr.Row():
|
| 1018 |
+
mpc_r_force = gr.Number(value=1.0e-3,
|
| 1019 |
+
label="R (force penalty)",
|
| 1020 |
+
minimum=0.0)
|
| 1021 |
+
mpc_p_terminal = gr.Number(value=1.0e4,
|
| 1022 |
+
label="P (terminal)",
|
| 1023 |
+
minimum=0.0)
|
|
|
|
| 1024 |
|
| 1025 |
def _toggle_controller(choice: str):
|
| 1026 |
is_mpc = (choice or "").upper() == "MPC"
|
|
|
|
| 1032 |
outputs=[pd_group, mpc_group],
|
| 1033 |
)
|
| 1034 |
|
| 1035 |
+
# ----- Run + Reset + outputs ---------------------------------
|
| 1036 |
+
with gr.Row():
|
| 1037 |
+
run_btn = gr.Button("Run simulation", variant="primary", scale=3)
|
| 1038 |
+
reset_btn = gr.Button("Reset all", variant="secondary", scale=1)
|
| 1039 |
status_text = gr.Textbox(label="Run summary", lines=9, interactive=False)
|
| 1040 |
with gr.Row():
|
| 1041 |
fig_gallery = gr.Gallery(label="Figures", columns=2, height="600px")
|
|
|
|
| 1058 |
outputs=[status_text, fig_gallery, csv_out],
|
| 1059 |
)
|
| 1060 |
|
| 1061 |
+
# ----- Reset handler -----------------------------------------
|
| 1062 |
+
# Reset clears the gallery / status / CSV download and pushes
|
| 1063 |
+
# every form widget back to its factory default. The chat
|
| 1064 |
+
# history is intentionally preserved --- it documents the
|
| 1065 |
+
# research session.
|
| 1066 |
+
def _reset_form():
|
| 1067 |
+
return (
|
| 1068 |
+
# outputs first (cleared)
|
| 1069 |
+
"", # status_text
|
| 1070 |
+
None, # fig_gallery
|
| 1071 |
+
None, # csv_out
|
| 1072 |
+
# robot & dynamics
|
| 1073 |
+
"dissertation_8cable", # robot_name
|
| 1074 |
+
0.0, # payload_mass
|
| 1075 |
+
True, # gravity_on
|
| 1076 |
+
"centered", # objective
|
| 1077 |
+
5.0, # t_min
|
| 1078 |
+
500.0, # t_max
|
| 1079 |
+
# trajectory
|
| 1080 |
+
"circle", # kind
|
| 1081 |
+
"0,0,0.5", # line_start
|
| 1082 |
+
"0.05,0,0.5", # line_end
|
| 1083 |
+
"0,0,0.65", # circle_center
|
| 1084 |
+
0.05, # circle_radius
|
| 1085 |
+
"0,0,1", # circle_axis
|
| 1086 |
+
float(4 * np.pi), # circle_angle_span
|
| 1087 |
+
"0,0,0.65", # lj_center
|
| 1088 |
+
"0.03,0.03,0.0", # lj_amps
|
| 1089 |
+
"1.0,2.0,0.0", # lj_freqs
|
| 1090 |
+
"0,1.5708,0", # lj_phases
|
| 1091 |
+
# time
|
| 1092 |
+
12.566, # duration
|
| 1093 |
+
1e-3, # dt_input
|
| 1094 |
+
# controller
|
| 1095 |
+
"PD", # controller_kind
|
| 1096 |
+
400.0, # kp_pos
|
| 1097 |
+
100.0, # kp_rot
|
| 1098 |
+
8, # mpc_horizon
|
| 1099 |
+
2.0e3, # mpc_q_pos
|
| 1100 |
+
2.0e1, # mpc_q_vel
|
| 1101 |
+
1.0e-3, # mpc_r_force
|
| 1102 |
+
1.0e4, # mpc_p_terminal
|
| 1103 |
+
# group visibility
|
| 1104 |
+
gr.update(visible=True), # pd_group
|
| 1105 |
+
gr.update(visible=False), # mpc_group
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
reset_btn.click(
|
| 1109 |
+
fn=_reset_form,
|
| 1110 |
+
inputs=None,
|
| 1111 |
+
outputs=[
|
| 1112 |
+
status_text, fig_gallery, csv_out,
|
| 1113 |
+
robot_name, payload_mass, gravity_on, objective, t_min, t_max,
|
| 1114 |
+
kind,
|
| 1115 |
+
line_start, line_end,
|
| 1116 |
+
circle_center, circle_radius, circle_axis, circle_angle_span,
|
| 1117 |
+
lj_center, lj_amps, lj_freqs, lj_phases,
|
| 1118 |
+
duration, dt_input,
|
| 1119 |
+
controller_kind, kp_pos, kp_rot,
|
| 1120 |
+
mpc_horizon, mpc_q_pos, mpc_q_vel,
|
| 1121 |
+
mpc_r_force, mpc_p_terminal,
|
| 1122 |
+
pd_group, mpc_group,
|
| 1123 |
+
],
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
# Chat wiring --- must come AFTER the form widgets and the
|
| 1127 |
# controller group definitions exist. The trailing three
|
| 1128 |
# outputs (controller_kind, pd_group, mpc_group) let a chat
|
|
@@ -39,6 +39,7 @@ from cdpr.llm.config import (
|
|
| 39 |
LLMConfig,
|
| 40 |
available_providers,
|
| 41 |
default_provider_name,
|
|
|
|
| 42 |
)
|
| 43 |
from cdpr.llm.factory import build_provider
|
| 44 |
|
|
@@ -50,5 +51,6 @@ __all__ = [
|
|
| 50 |
"LLMConfig",
|
| 51 |
"available_providers",
|
| 52 |
"default_provider_name",
|
|
|
|
| 53 |
"build_provider",
|
| 54 |
]
|
|
|
|
| 39 |
LLMConfig,
|
| 40 |
available_providers,
|
| 41 |
default_provider_name,
|
| 42 |
+
resolve_fallback_chain,
|
| 43 |
)
|
| 44 |
from cdpr.llm.factory import build_provider
|
| 45 |
|
|
|
|
| 51 |
"LLMConfig",
|
| 52 |
"available_providers",
|
| 53 |
"default_provider_name",
|
| 54 |
+
"resolve_fallback_chain",
|
| 55 |
"build_provider",
|
| 56 |
]
|
|
@@ -31,6 +31,7 @@ except ImportError: # pragma: n
|
|
| 31 |
|
| 32 |
|
| 33 |
_DEFAULT_PROVIDER_ENV = "CDPR_LLM_PROVIDER"
|
|
|
|
| 34 |
|
| 35 |
# Canonical env-var names. These are referenced by the providers and
|
| 36 |
# documented in .env.example and docs/llm-providers.md.
|
|
@@ -138,3 +139,33 @@ def available_providers() -> dict[str, bool]:
|
|
| 138 |
"lmstudio": bool(os.environ.get(LMSTUDIO_URL_ENV)),
|
| 139 |
"echo": True,
|
| 140 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
_DEFAULT_PROVIDER_ENV = "CDPR_LLM_PROVIDER"
|
| 34 |
+
_FALLBACK_CHAIN_ENV = "CDPR_LLM_FALLBACK_CHAIN"
|
| 35 |
|
| 36 |
# Canonical env-var names. These are referenced by the providers and
|
| 37 |
# documented in .env.example and docs/llm-providers.md.
|
|
|
|
| 139 |
"lmstudio": bool(os.environ.get(LMSTUDIO_URL_ENV)),
|
| 140 |
"echo": True,
|
| 141 |
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def resolve_fallback_chain(explicit: str | None = None) -> list[str]:
|
| 145 |
+
"""Return the ordered list of providers to try in sequence.
|
| 146 |
+
|
| 147 |
+
The chain comes from (in priority order):
|
| 148 |
+
|
| 149 |
+
1. The ``explicit`` argument, when a caller pins a chain.
|
| 150 |
+
2. The ``CDPR_LLM_FALLBACK_CHAIN`` env var, comma-separated.
|
| 151 |
+
3. An auto-built chain from the configured providers in the
|
| 152 |
+
standard priority (gemini -> openrouter -> ollama -> lmstudio),
|
| 153 |
+
with the echo stub appended unconditionally as the final
|
| 154 |
+
fall-back so the simulator never crashes.
|
| 155 |
+
|
| 156 |
+
Unknown provider names are silently dropped. The echo stub is
|
| 157 |
+
appended if missing so the chain always ends in something callable.
|
| 158 |
+
"""
|
| 159 |
+
_try_load_env()
|
| 160 |
+
raw = explicit or os.environ.get(_FALLBACK_CHAIN_ENV) or ""
|
| 161 |
+
if raw.strip():
|
| 162 |
+
candidates = [c.strip().lower() for c in raw.split(",") if c.strip()]
|
| 163 |
+
else:
|
| 164 |
+
configured = available_providers()
|
| 165 |
+
candidates = [name for name in ("gemini", "openrouter",
|
| 166 |
+
"ollama", "lmstudio")
|
| 167 |
+
if configured.get(name)]
|
| 168 |
+
chain = [c for c in candidates if c in PROVIDER_NAMES]
|
| 169 |
+
if "echo" not in chain:
|
| 170 |
+
chain.append("echo")
|
| 171 |
+
return chain
|
|
@@ -37,7 +37,12 @@ from dataclasses import dataclass, field
|
|
| 37 |
from typing import Any
|
| 38 |
|
| 39 |
from cdpr.interface.specs import SimulationRequest, TrajectorySpec
|
| 40 |
-
from cdpr.llm import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
# Secret-scrub pattern applied to any error string that surfaces in
|
|
@@ -111,14 +116,27 @@ def describe_to_request(
|
|
| 111 |
description: str,
|
| 112 |
*,
|
| 113 |
provider: str | None = None,
|
|
|
|
| 114 |
) -> BuilderResult:
|
| 115 |
"""Parse ``description`` into a :class:`SimulationRequest`.
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
``
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
"""
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
messages = [
|
| 123 |
LLMMessage(role="system", content=_SYSTEM_PROMPT),
|
| 124 |
LLMMessage(role="user", content=description.strip()),
|
|
@@ -126,27 +144,59 @@ def describe_to_request(
|
|
| 126 |
raw_text = ""
|
| 127 |
parsed: dict[str, Any] = {}
|
| 128 |
notes: list[str] = []
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
raw_text = resp.text
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
|
| 144 |
request, confidence = _request_from_parsed(parsed, description, notes)
|
| 145 |
|
|
|
|
|
|
|
|
|
|
| 146 |
return BuilderResult(
|
| 147 |
request=request,
|
| 148 |
-
provider=
|
| 149 |
-
model=
|
| 150 |
raw_text=raw_text,
|
| 151 |
confidence=confidence,
|
| 152 |
follow_up_questions=list(parsed.get("follow_up_questions", []) or []),
|
|
|
|
| 37 |
from typing import Any
|
| 38 |
|
| 39 |
from cdpr.interface.specs import SimulationRequest, TrajectorySpec
|
| 40 |
+
from cdpr.llm import (
|
| 41 |
+
LLMMessage,
|
| 42 |
+
LLMUnavailableError,
|
| 43 |
+
build_provider,
|
| 44 |
+
resolve_fallback_chain,
|
| 45 |
+
)
|
| 46 |
|
| 47 |
|
| 48 |
# Secret-scrub pattern applied to any error string that surfaces in
|
|
|
|
| 116 |
description: str,
|
| 117 |
*,
|
| 118 |
provider: str | None = None,
|
| 119 |
+
fallback_chain: list[str] | None = None,
|
| 120 |
) -> BuilderResult:
|
| 121 |
"""Parse ``description`` into a :class:`SimulationRequest`.
|
| 122 |
|
| 123 |
+
Walks a chain of providers in order; the first one that returns
|
| 124 |
+
parseable JSON wins. When a provider raises
|
| 125 |
+
:class:`LLMUnavailableError` (rate limit, model retired, network
|
| 126 |
+
failure, etc.) the chain continues to the next one and records
|
| 127 |
+
the failure in ``notes``. The echo stub is always at the end so
|
| 128 |
+
the call never raises --- the directive's 'never crash' rule.
|
| 129 |
+
|
| 130 |
+
When ``provider`` is given, it pins a single provider (no fallback).
|
| 131 |
+
Otherwise the chain comes from ``fallback_chain`` or
|
| 132 |
+
:func:`cdpr.llm.config.resolve_fallback_chain` (which honours
|
| 133 |
+
``CDPR_LLM_FALLBACK_CHAIN``).
|
| 134 |
"""
|
| 135 |
+
if provider:
|
| 136 |
+
chain = [provider]
|
| 137 |
+
else:
|
| 138 |
+
chain = list(fallback_chain or resolve_fallback_chain())
|
| 139 |
+
|
| 140 |
messages = [
|
| 141 |
LLMMessage(role="system", content=_SYSTEM_PROMPT),
|
| 142 |
LLMMessage(role="user", content=description.strip()),
|
|
|
|
| 144 |
raw_text = ""
|
| 145 |
parsed: dict[str, Any] = {}
|
| 146 |
notes: list[str] = []
|
| 147 |
+
tried: list[str] = []
|
| 148 |
+
winner_provider = ""
|
| 149 |
+
winner_model = ""
|
| 150 |
+
|
| 151 |
+
for name in chain:
|
| 152 |
+
tried.append(name)
|
| 153 |
+
try:
|
| 154 |
+
llm = build_provider(name)
|
| 155 |
+
except LLMUnavailableError as exc:
|
| 156 |
+
notes.append(
|
| 157 |
+
f"Provider {name!r} unavailable at construction: "
|
| 158 |
+
f"{_redact(str(exc))}. Trying next in chain."
|
| 159 |
+
)
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
resp = llm.complete(messages, max_tokens=900, temperature=0.0)
|
| 164 |
+
except LLMUnavailableError as exc:
|
| 165 |
+
notes.append(
|
| 166 |
+
f"Provider {name!r} call failed: {_redact(str(exc))}. "
|
| 167 |
+
"Trying next in chain."
|
| 168 |
+
)
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
# Got a response; try to extract JSON. JSON failures from a
|
| 172 |
+
# real LLM are not retryable on a different LLM (echo, in
|
| 173 |
+
# particular, never returns valid JSON), but we still want the
|
| 174 |
+
# raw text in the result for audit. Treat 'no JSON' the same
|
| 175 |
+
# way as 'no provider' so the fallback chain keeps trying.
|
| 176 |
raw_text = resp.text
|
| 177 |
+
winner_provider = getattr(llm, "name", name)
|
| 178 |
+
winner_model = getattr(llm, "model", "")
|
| 179 |
+
try:
|
| 180 |
+
parsed = _extract_json(raw_text)
|
| 181 |
+
break
|
| 182 |
+
except (ValueError, KeyError) as exc:
|
| 183 |
+
notes.append(
|
| 184 |
+
f"Provider {name!r} returned non-JSON text: "
|
| 185 |
+
f"{_redact(str(exc))}. Trying next in chain."
|
| 186 |
+
)
|
| 187 |
+
# Clear parsed so the next iteration starts fresh.
|
| 188 |
+
parsed = {}
|
| 189 |
+
continue
|
| 190 |
|
| 191 |
request, confidence = _request_from_parsed(parsed, description, notes)
|
| 192 |
|
| 193 |
+
if tried:
|
| 194 |
+
notes.append("Provider chain tried: " + " -> ".join(tried))
|
| 195 |
+
|
| 196 |
return BuilderResult(
|
| 197 |
request=request,
|
| 198 |
+
provider=winner_provider,
|
| 199 |
+
model=winner_model,
|
| 200 |
raw_text=raw_text,
|
| 201 |
confidence=confidence,
|
| 202 |
follow_up_questions=list(parsed.get("follow_up_questions", []) or []),
|