-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_gui_dev.py
More file actions
1217 lines (1024 loc) · 55.8 KB
/
demo_gui_dev.py
File metadata and controls
1217 lines (1024 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Deterministic Exclusion Demo GUI (Development Build)
FastAPI + Streamlit implementation for rapid prototyping
Usage:
streamlit run demo_gui_dev.py
"""
try:
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
except ModuleNotFoundError as exc:
missing = str(exc).split("No module named ", 1)[-1].strip("'\"")
print(f"Missing optional GUI dependency: {missing}")
print("Install GUI deps: python -m pip install -r requirements-gui.txt")
print("Run the GUI via: streamlit run demo_gui_dev.py")
raise SystemExit(2)
try:
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
except Exception:
get_script_run_ctx = None
if get_script_run_ctx is not None and get_script_run_ctx() is None:
print("This file is a Streamlit app and must be run with Streamlit:")
print(" streamlit run demo_gui_dev.py")
raise SystemExit(2)
import time
import hashlib
import json
from pathlib import Path
from collections import deque
from typing import List, Dict, Optional, Any, Tuple
# Import engine components
import sys
sys.path.insert(0, str(Path(__file__).parent))
from material_field_engine import (
VerifiedSubstrate, Vector2D, MaterialFieldEngine, fp_from_float, fp_to_float, load_config
)
from exclusion_demo import run_deterministic_exclusion_demo
@st.cache_data
def compute_substrate_embeddings_2d(substrate_list: List[str]) -> List[List[float]]:
"""Cached 2D embedding for material field visualization."""
from llm_adapter import DeterministicHashEmbedderND
embedder = DeterministicHashEmbedderND(dim=2)
return [embedder.embed(t) for t in substrate_list]
@st.cache_data
def compute_substrate_embeddings_highd(substrate_list: List[str]) -> List[List[float]]:
"""Cached 16D embedding for physics engine logic."""
from llm_adapter import DeterministicHashEmbedderND
embedder = DeterministicHashEmbedderND(dim=16)
return [embedder.embed(t) for t in substrate_list]
# ============================================================================
# Streamlit Page Configuration
# ============================================================================
st.set_page_config(
page_title="Deterministic Exclusion Demo",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for monospace hash display
st.markdown("""
<style>
.hash-display {
font-family: 'Courier New', monospace;
font-size: 14px;
background-color: #1e1e1e;
color: #00ff00;
padding: 10px;
border-radius: 5px;
word-break: break-all;
}
</style>
""", unsafe_allow_html=True)
# ============================================================================
# Session State Initialization
# ============================================================================
if 'results' not in st.session_state:
st.session_state.results = None
if 'config' not in st.session_state:
st.session_state.config = {
'elastic_modulus_mode': 'multiplicative',
'elastic_modulus_sigma': 0.4,
'lambda_min': 0.35,
'lambda_max': 1.20,
'inference_steps': 8
}
if 'audit_log' not in st.session_state:
st.session_state.audit_log = deque(maxlen=100)
# ============================================================================
# Header
# ============================================================================
st.title("Deterministic Exclusion Demo")
st.markdown("Material-Field Engine GUI")
st.markdown("---")
# ============================================================================
# Sidebar: Configuration Panel
# ============================================================================
st.sidebar.header("Configuration")
# Elastic Modulus Mode
mode = st.sidebar.selectbox(
"Elastic Modulus Mode",
options=['cosine', 'multiplicative', 'rbf'],
index=1, # Default: multiplicative
help="Cosine: direction only | Multiplicative: angle×proximity | RBF: proximity only"
)
# Sigma parameter
sigma = st.sidebar.slider(
"Sigma (σ) - Field Extent",
min_value=0.2,
max_value=1.0,
value=0.4,
step=0.05,
help="Lower = tighter binding, higher = looser binding"
)
st.sidebar.markdown(f"**Current: σ={sigma:.2f}**")
# Lambda max
lambda_max = st.sidebar.slider(
"Lambda Max (lambda_max) - Max Pressure",
min_value=0.5,
max_value=2.0,
value=1.2,
step=0.1,
help="Higher = stricter exclusion"
)
st.sidebar.markdown("---")
# Run button
if st.sidebar.button("Run Deterministic Exclusion Demo", type="primary"):
with st.spinner("Running inference..."):
# Update config
st.session_state.config['elastic_modulus_mode'] = mode
st.session_state.config['elastic_modulus_sigma'] = sigma
st.session_state.config['lambda_max'] = lambda_max
# Run test
results = run_deterministic_exclusion_demo(
elastic_modulus_mode=mode,
sigma=sigma,
print_banner=False,
)
st.session_state.results = results
# Log event
st.session_state.audit_log.append({
'timestamp': time.time(),
'operation': 'run_inference',
'mode': mode,
'sigma': sigma,
'hash': results['hash']
})
st.success("Inference complete.")
# ============================================================================
# Main Content Area
# ============================================================================
# Create tabs
tab1, tab2, tab3, tab4 = st.tabs(["Mechanism Demo", "LLM Guardrail", "Live LLM Testing", "Explain & Tune"])
# ----------------------------------------------------------------------------
# TAB 1: Mechanism Demo (Original)
# ----------------------------------------------------------------------------
with tab1:
if st.session_state.results is None:
st.info("Configure parameters in the sidebar and click 'Run Deterministic Exclusion Demo'.")
else:
results = st.session_state.results
# Row 1: Deterministic Audit Trail
st.header("Deterministic Audit Trail")
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("SHA-256")
st.markdown(f'<div class="hash-display">{results["hash"]}</div>', unsafe_allow_html=True)
with col2:
st.metric("Total Excluded", results["excluded"])
# Row 2: Abstention Indicator
st.header("Outcome Verification")
if results.get("winner_index") is None:
st.error("Abstained")
else:
st.success(f"Winner index: {results['winner_index']}")
st.caption("Expected winner: Candidate 0 | Expected excluded: 3")
# Row 3: Phase Log
st.header("Phase Log")
phase_log = results['phase_log']
import pandas as pd
df = pd.DataFrame(phase_log)
st.dataframe(df[['step', 'phase', 'pressure', 'survivors', 'excluded']], use_container_width=True, hide_index=True)
# Visualization
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[e['step'] for e in phase_log],
y=[e['pressure'] for e in phase_log],
mode='lines+markers',
name='Pressure lambda(t)',
line=dict(color='cyan', width=3)
))
st.plotly_chart(fig, use_container_width=True)
# Row 5: Audit Log
st.header("Run Log")
if st.session_state.audit_log:
log_df = pd.DataFrame(st.session_state.audit_log)
log_df['timestamp'] = pd.to_datetime(log_df['timestamp'], unit='s')
st.dataframe(log_df[['timestamp', 'operation', 'mode', 'sigma', 'hash']], use_container_width=True, hide_index=True)
# ----------------------------------------------------------------------------
# TAB 2: LLM Guardrail Playground (New)
# ----------------------------------------------------------------------------
with tab2:
st.header("Deterministic LLM Filter")
st.markdown("""
A model-agnostic post-processor that evaluates candidate outputs against a verified substrate.
The mechanism deterministically accepts, rejects, or abstains based on explicit constraints.
""")
col_input1, col_input2 = st.columns(2)
with col_input1:
st.subheader("1. Verified Substrate")
st.markdown("Approved facts (Ground Truth). One per line.")
substrate_input = st.text_area(
"Substrate",
value="The sky is blue\nWater is wet\nParis is capital of France",
height=200,
key="llm_substrate"
)
with col_input2:
st.subheader("2. LLM Candidates")
st.markdown("Generated responses (including hallucinations). One per line.")
candidates_input = st.text_area(
"Candidates",
value="The sky is blue\nThe sky is green\nThe sky is made of cheese",
height=200,
key="llm_candidates"
)
# Add full trace checkbox
show_full_trace = st.checkbox(
"Show full stress evolution (all steps for all candidates)",
value=False,
help="Disable for faster UI with large candidate sets"
)
if st.button("Run Guardrail Filter", type="primary"):
from llm_adapter import DeterministicGuardrail, DeterministicHashEmbedderND
import math
# Parse inputs
substrate_list = [line.strip() for line in substrate_input.split('\n') if line.strip()]
candidate_list = [line.strip() for line in candidates_input.split('\n') if line.strip()]
if not substrate_list or not candidate_list:
st.error("Please provide both substrate and candidates.")
else:
with st.spinner("Projecting to material field..."):
# Initialize Guardrail
# Use current sidebar config instead of hardcoded preset
guard = DeterministicGuardrail(
substrate_texts=substrate_list,
config_preset='balanced' # Starting point
)
# Overwrite with current sidebar settings for consistency
guard.config['elastic_modulus_mode'] = st.session_state.config['elastic_modulus_mode']
guard.config['elastic_modulus_sigma'] = st.session_state.config['elastic_modulus_sigma']
guard.config['lambda_max'] = st.session_state.config['lambda_max']
# We want to INSPECT, not just filter
inspection = guard.inspect(candidate_list)
result_text = inspection['selected_text']
metrics = inspection['metrics']
candidate_metrics = metrics.get('candidates')
if candidate_metrics is None:
candidate_metrics = [
{
'phase_log': [],
'fractured': False,
'fractured_step': None,
'stress': 0.0,
'hash': 'N/A',
}
for _ in candidate_list
]
# Build detailed numbers view (high-D physics + 2D projection for plot)
with st.spinner("Computing embeddings..."):
# Use specialized caches for different dimensionality needs
sub_vecs = compute_substrate_embeddings_highd(substrate_list)
sub_vecs_2d = compute_substrate_embeddings_2d(substrate_list)
from llm_adapter import DeterministicHashEmbedderND
embedder_highd = DeterministicHashEmbedderND(dim=16)
cand_vecs = [embedder_highd.embed(t) for t in candidate_list]
# Use 2D for visualization
embedder_2d = DeterministicHashEmbedderND(dim=2)
cand_vecs_2d = [embedder_2d.embed(t) for t in candidate_list]
def cosine_similarity(v1, v2):
"""Cosine similarity between N-D vectors."""
dot = sum(a * b for a, b in zip(v1, v2))
mag1 = math.sqrt(sum(a * a for a in v1))
mag2 = math.sqrt(sum(b * b for b in v2))
if mag1 == 0 or mag2 == 0:
return 0.0
return dot / (mag1 * mag2)
def euclidean_distance(v1, v2):
"""Euclidean distance between N-D vectors."""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
numbers_view = {
"embedder": {
"name": "DeterministicHashEmbedderND",
"definition": "sha256(text) -> 16D in [0,1], projected to 2D for plotting",
},
"substrate": [
{"text": t, "vec2": [round(v[0], 8), round(v[1], 8)]}
for t, v in zip(substrate_list, sub_vecs_2d)
],
"candidates": []
}
# For each candidate, compute detailed metrics
for i, (cand_vec, cand_text) in enumerate(zip(cand_vecs, candidate_list)):
# Compute alignment and distance to each substrate point
per_substrate = []
best_alignment = -1
best_distance = float('inf')
best_j = None
for j, sub_vec in enumerate(sub_vecs):
cos_sim = cosine_similarity(cand_vec, sub_vec)
alignment = (cos_sim + 1.0) / 2.0 # Normalize to [0,1]
dist = euclidean_distance(cand_vec, sub_vec)
per_substrate.append({
"substrate_index": j,
"substrate_text": substrate_list[j],
"cosine_similarity": round(cos_sim, 8),
"alignment_0_1": round(alignment, 8),
"euclidean_distance": round(dist, 8),
})
# Selection rule: highest alignment
if alignment > best_alignment:
best_alignment = alignment
best_distance = dist
best_j = j
# Get engine results for this candidate
cand_metrics = candidate_metrics[i]
phase_log = cand_metrics.get('phase_log', [])
# Build stress evolution - full or abbreviated
if show_full_trace:
stress_evolution = [
{
"step": entry["step"],
"phase": entry["phase"],
"lambda": round(entry["pressure"], 8),
"elastic_modulus_E": round(entry.get("elastic_modulus", 0.0), 8),
"delta_stress": round(entry.get("delta_stress", 0.0), 8),
"cumulative_stress": round(entry["stress"], 8),
"fractured": entry["fractured"]
}
for entry in phase_log
]
else:
# Abbreviated: first 2 steps, fracture step (if any), last step
abbreviated = []
if len(phase_log) > 0:
abbreviated.append(phase_log[0])
if len(phase_log) > 1:
abbreviated.append(phase_log[1])
fracture_step = cand_metrics.get('fractured_step')
if fracture_step is not None and fracture_step > 1:
abbreviated.append(phase_log[fracture_step])
elif len(phase_log) > 2:
abbreviated.append(phase_log[-1])
stress_evolution = [
{
"step": entry["step"],
"phase": entry["phase"],
"lambda": round(entry["pressure"], 8),
"elastic_modulus_E": round(entry.get("elastic_modulus", 0.0), 8),
"delta_stress": round(entry.get("delta_stress", 0.0), 8),
"cumulative_stress": round(entry["stress"], 8),
"fractured": entry["fractured"]
}
for entry in abbreviated
]
if len(phase_log) > len(abbreviated):
stress_evolution.append({
"note": f"...{len(phase_log) - len(abbreviated)} intermediate steps omitted (enable 'Show full stress evolution' to see all)"
})
numbers_view["candidates"].append({
"candidate_index": i,
"text": cand_text,
"vec2": [round(cand_vecs_2d[i][0], 8), round(cand_vecs_2d[i][1], 8)],
"comparisons": per_substrate,
"selection_rule": "highest_alignment",
"selected_by_alignment": {
"substrate_index": best_j,
"substrate_text": substrate_list[best_j] if best_j is not None else None,
"alignment_0_1": round(best_alignment, 8),
"euclidean_distance": round(float(best_distance), 8),
},
"engine": {
"fractured": cand_metrics.get('fractured', False),
"fractured_step": cand_metrics.get('fractured_step'),
"final_stress": round(float(cand_metrics['stress']), 8),
"hash": cand_metrics.get('hash', 'N/A'),
"stress_evolution": stress_evolution
}
})
# Display Result
st.markdown("### Result")
if result_text:
st.success(f"**Selected:** {result_text}")
else:
st.warning("**Abstained**: No candidates met the yield strength requirements.")
# Visualization of the Field
st.markdown("### Material Field Projection")
# Plot
fig_map = go.Figure()
# Plot Substrate (Green Squares)
fig_map.add_trace(go.Scatter(
x=[v[0] for v in sub_vecs_2d],
y=[v[1] for v in sub_vecs_2d],
mode='markers',
name='Substrate (Facts)',
text=substrate_list,
marker=dict(symbol='square', size=12, color='green')
))
# Plot Candidates (Red Circles)
# Differentiate selected vs excluded
selected_idx = metrics['final_output'].candidate_index if metrics['final_output'] else -1
colors = ['gold' if i == selected_idx else 'red' for i in range(len(cand_vecs))]
sizes = [15 if i == selected_idx else 10 for i in range(len(cand_vecs))]
fig_map.add_trace(go.Scatter(
x=[v[0] for v in cand_vecs_2d],
y=[v[1] for v in cand_vecs_2d],
mode='markers+text',
name='Candidates',
text=candidate_list,
textposition='top center',
marker=dict(symbol='circle', size=sizes, color=colors)
))
fig_map.update_layout(
title="Semantic Material Field (2D Mock Projection)",
xaxis_title="Dimension X",
yaxis_title="Dimension Y",
xaxis=dict(range=[0, 1]),
yaxis=dict(range=[0, 1]),
template="plotly_dark",
height=500
)
st.plotly_chart(fig_map, use_container_width=True)
# Metrics JSON
st.markdown("### Metrics")
metrics_json = {
"survived": result_text is not None,
"total_excluded": metrics['total_excluded'],
"falsification_pressure": f"{metrics['phase_log'][-1]['pressure']:.2f} lambda"
}
st.json(metrics_json)
# Complete Numerical Audit Trail
st.markdown("### Complete Numerical Audit Trail")
st.caption("Vectors, distances, selection rule, engine hash, stress evolution")
st.json(numbers_view)
# ----------------------------------------------------------------------------
# TAB 3: LLM Testing
# ----------------------------------------------------------------------------
with tab3:
st.header("LLM Testing")
st.markdown("""
**Live API Testing** - Test any LLM with the Deterministic Guardrail in real-time.
Supports: OpenAI, Anthropic, Google Gemini, local models (Ollama, llama.cpp, vLLM), and any OpenAI-compatible API.
""")
# API Configuration
st.subheader("1. LLM API Configuration")
col_api1, col_api2 = st.columns(2)
with col_api1:
api_preset = st.selectbox(
"Provider Preset",
options=["OpenAI", "Anthropic (Claude)", "Google (Gemini)", "Local (Ollama)", "Local (llama.cpp)", "Custom OpenAI-compatible"],
help="Select a preset or use custom for any OpenAI-compatible endpoint"
)
# Set defaults based on preset
if api_preset == "OpenAI":
default_base_url = "https://api.openai.com/v1"
default_model = "gpt-4.1-nano"
needs_key = True
elif api_preset == "Anthropic (Claude)":
default_base_url = "https://api.anthropic.com/v1"
default_model = "claude-3-5-sonnet-20241022"
needs_key = True
elif api_preset == "Google (Gemini)":
default_base_url = "https://generativelanguage.googleapis.com/v1beta"
default_model = "gemini-2.0-flash-exp"
needs_key = True
elif api_preset == "Local (Ollama)":
default_base_url = "http://localhost:11434/v1"
default_model = "llama3.1"
needs_key = False
elif api_preset == "Local (llama.cpp)":
default_base_url = "http://localhost:8080/v1"
default_model = "local-model"
needs_key = False
else:
default_base_url = "https://api.openai.com/v1"
default_model = "gpt-4.1-nano"
needs_key = True
api_base_url = st.text_input(
"Base URL",
value=default_base_url,
help="API endpoint base URL"
)
with col_api2:
api_key = st.text_input(
"API Key" + (" (optional for local)" if not needs_key else ""),
type="password",
help="Your API key (not required for local models)",
placeholder="sk-..." if needs_key else "not needed for local models"
)
model_name = st.text_input(
"Model Name",
value=default_model,
help="Model identifier"
)
col_temp, col_num = st.columns(2)
with col_temp:
temperature = st.slider("Temperature", 0.0, 2.0, 0.7, 0.1, help="Higher = more creative")
with col_num:
num_responses = st.number_input("Number of Responses", min_value=1, max_value=10, value=3, help="Generate multiple responses for comparison")
col_timeout, col_retry = st.columns(2)
with col_timeout:
request_timeout = st.number_input("Request Timeout (seconds)", min_value=5, max_value=600, value=60, step=5, help="Increase for slow or local models")
with col_retry:
max_retries = st.number_input("Max Retries", min_value=0, max_value=5, value=2, step=1, help="Automatic retries on transient failures")
# Substrate Configuration
st.subheader("2. Verified Substrate (Ground Truth)")
st.markdown("Enter verified facts that define what is correct. One per line.")
substrate_input_llm = st.text_area(
"Substrate Facts",
value="The Eiffel Tower is in Paris\nWater boils at 100°C at sea level\nPython is a programming language",
height=120,
key="llm_test_substrate"
)
# Prompt Configuration
st.subheader("3. Prompt Configuration")
col_prompt1, col_prompt2 = st.columns([3, 1])
with col_prompt1:
user_prompt = st.text_area(
"User Prompt",
value="Tell me a fact about one of the topics mentioned above.",
height=100,
help="The prompt sent to the LLM"
)
with col_prompt2:
use_system_prompt = st.checkbox("Use System Prompt", value=False)
if use_system_prompt:
system_prompt = st.text_area(
"System Prompt (optional)",
value="You are a helpful assistant. Provide accurate, factual information.",
height=100
)
else:
system_prompt = None
# Governance Configuration (Control Surface)
st.subheader("4. Governance Controls")
st.markdown("Adjust the physics strictness to see how the system responds to ambiguity vs. facts.")
gov_col1, gov_col2 = st.columns(2)
with gov_col1:
gov_preset = st.selectbox(
"Governance Preset",
["Forgiving", "Balanced", "Conservative", "Aggressive", "Mission Critical"],
index=1,
help="Sets physics parameters (Lambda/Sigma). 'Forgiving' tolerates ambiguity; 'Mission Critical' demands exact alignment."
)
preset_map = {
"Balanced": "balanced",
"Conservative": "conservative",
"Aggressive": "aggressive",
"Mission Critical": "mission_critical",
"Forgiving": "forgiving"
}
selected_gov_preset = preset_map[gov_preset]
# Educational Display: Show the actual numbers
from material_field_engine import load_config
config_data = load_config(selected_gov_preset)
st.markdown("---")
st.markdown("**Physics Parameters (active settings):**")
p_col1, p_col2, p_col3 = st.columns(3)
with p_col1:
st.metric(
label="Sigma (σ) - Tolerance",
value=config_data['elastic_modulus_sigma'],
help="Field Extent. Higher (0.8) = Vague associations accepted. Lower (0.2) = Exact match required."
)
with p_col2:
st.metric(
label="Lambda Max (λ) - Pressure",
value=config_data['lambda_max'],
help="Max Exclusion Pressure. Higher (1.5+) = Crushes weak bonds (High strictness). Lower (0.5) = Gentle."
)
with p_col3:
st.markdown(f"**Mode**: `{config_data['elastic_modulus_mode']}`")
st.caption("Algorithm usually 'multiplicative' (Angle × Distance).")
st.info(f"💡 **Teacher's Note**: To prevent valid answers from being blocked (fracturing), you would **increase Sigma** (widen the net) or **decrease Lambda** (reduce the pressure).")
with gov_col2:
st.write("**Gate Settings**")
topic_gate_enabled = st.checkbox(
"Enable Topic Gate",
value=False,
help="Fast pre-filter. If unchecked, physics runs on everything (good for demos)."
)
ambiguity_detection = st.checkbox(
"Allow Clarifications",
value=True,
help="If ON, clarifying questions ('Could you specify?') are marked CLARIFY instead of failing."
)
# Run Button
if st.button("🚀 Generate & Test Responses", type="primary"):
# Parse substrate
substrate_list = [line.strip() for line in substrate_input_llm.split('\n') if line.strip()]
if not substrate_list:
st.error("Please provide substrate facts")
elif not user_prompt:
st.error("Please provide a user prompt")
elif not api_base_url.strip():
st.error("Please provide a base URL for the API")
elif not model_name.strip():
st.error("Please provide a model name")
else:
st.info(f"📡 Generating {num_responses} response(s) from {api_preset}...")
from urllib.parse import urlparse
import socket
parsed_url = urlparse(api_base_url)
host = parsed_url.hostname
port = parsed_url.port or (443 if parsed_url.scheme == "https" else 80)
if not host:
st.error("Invalid base URL. Please include scheme (http/https) and host.")
st.stop()
try:
with socket.create_connection((host, port), timeout=3):
pass
except OSError as exc:
st.error(f"Unable to connect to {api_base_url}: {exc}")
if "localhost" in api_base_url or "127.0.0.1" in api_base_url:
st.info("For local providers, ensure the server is running (e.g., `ollama serve`).")
st.stop()
try:
import openai
# Configure client
api_key_value = api_key.strip() if api_key else ""
if not needs_key and not api_key_value:
api_key_value = "local"
client = openai.OpenAI(
api_key=api_key_value,
base_url=api_base_url,
timeout=request_timeout,
max_retries=max_retries
)
responses = []
with st.spinner(f"Calling LLM API ({num_responses} request(s))..."):
for i in range(num_responses):
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": user_prompt})
try:
response = client.chat.completions.create(
model=model_name,
messages=messages,
temperature=temperature
)
responses.append(response.choices[0].message.content)
except openai.APITimeoutError as e:
st.error(f"Request timed out on response {i+1}. Try increasing the timeout.")
raise
except openai.APIConnectionError as e:
st.error(f"Connection error on response {i+1}. Check base URL and server status.")
raise
except openai.OpenAIError as e:
st.error(f"OpenAI API error on response {i+1}: {str(e)}")
raise
except Exception as e:
st.error(f"Error on response {i+1}: {str(e)}")
if i == 0: # If first call fails, stop
raise
if not responses:
st.error("No responses generated")
else:
st.success(f"✓ Generated {len(responses)} response(s)")
# Now run the guardrail
st.markdown("---")
with st.spinner("Running Deterministic Guardrail..."):
from llm_adapter import DeterministicGuardrail, DeterministicHashEmbedderND
import math
guard = DeterministicGuardrail(
substrate_texts=substrate_list,
config_preset=selected_gov_preset,
topic_gate_enabled=topic_gate_enabled,
ambiguity_detection_enabled=ambiguity_detection
)
inspection = guard.inspect(responses)
result_text = inspection['selected_text']
metrics = inspection['metrics']
candidate_metrics = metrics.get('candidates')
if candidate_metrics is None:
candidate_metrics = [
{
'phase_log': [],
'fractured': False,
'fractured_step': None,
'stress': 0.0,
'hash': 'N/A',
}
for _ in responses
]
# Build detailed numbers view (high-D physics + 2D projection for plot)
embedder = DeterministicHashEmbedderND()
sub_vecs = [embedder.embed(t) for t in substrate_list]
resp_vecs = [embedder.embed(t) for t in responses]
sub_vecs_2d = [embedder.project_2d(v) for v in sub_vecs]
resp_vecs_2d = [embedder.project_2d(v) for v in resp_vecs]
def cosine_similarity(v1, v2):
dot = sum(a * b for a, b in zip(v1, v2))
mag1 = math.sqrt(sum(a * a for a in v1))
mag2 = math.sqrt(sum(b * b for b in v2))
if mag1 == 0 or mag2 == 0:
return 0.0
return dot / (mag1 * mag2)
def euclidean_distance(v1, v2):
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
# Display result
st.subheader("Guardrail Decision")
if result_text:
st.success("🟢 **SELECTED RESPONSE**")
st.markdown(f"> {result_text}")
else:
st.warning("🔴 **ABSTAINED** - All responses fractured under stress")
st.caption("The guardrail rejected all responses. None met the yield strength requirements.")
# Show all responses with scores
st.markdown("---")
st.subheader("Detailed Scoring for All Responses")
for i, (response, cand_vec) in enumerate(zip(responses, resp_vecs)):
cand_metrics = candidate_metrics[i]
is_selected = (result_text == response)
# Compute alignment to best substrate
best_alignment = -1
best_substrate = None
best_cos_sim = 0
for j, sub_vec in enumerate(sub_vecs):
cos_sim = cosine_similarity(cand_vec, sub_vec)
alignment = (cos_sim + 1.0) / 2.0
if alignment > best_alignment:
best_alignment = alignment
best_substrate = substrate_list[j]
best_cos_sim = cos_sim
# Display card
fractured = cand_metrics.get('fractured', False)
out_of_domain = cand_metrics.get('out_of_domain', False)
if is_selected:
status = "SELECTED"
elif out_of_domain:
status = "EXCLUDED (Topic Gate)"
elif fractured:
status = "EXCLUDED (Fractured)"
else:
status = "SURVIVED (Not Selected)"
with st.expander(f"**Response {i+1}** - {status}", expanded=is_selected):
st.markdown(f"**Full Response:**")
st.info(response)
st.markdown("---")
# Metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Alignment Score", f"{best_alignment:.4f}", help="Normalized cosine similarity: 0=opposite, 0.5=orthogonal, 1=identical")
with col2:
st.metric("Cosine Similarity", f"{best_cos_sim:.4f}", help="Raw cosine similarity: -1 to 1")
with col3:
st.metric("Final Stress σ", f"{cand_metrics['stress']:.4f}")
with col4:
if out_of_domain:
st.metric("Status", "Topic-gated")
else:
st.metric("Status", "Intact" if not fractured else "Fractured")
st.caption(f"**Best substrate match:** *\"{best_substrate}\"*")
# Show stress evolution chart
st.markdown("**Stress Evolution**")
phase_log = cand_metrics.get('phase_log', [])
stress_data = [entry['stress'] for entry in phase_log]
steps = list(range(len(stress_data)))
fig_stress = go.Figure()
fig_stress.add_trace(go.Scatter(
x=steps,
y=stress_data,
mode='lines+markers',
name='Cumulative Stress',
line=dict(color='red' if fractured else 'green', width=2),
marker=dict(size=6)
))
fig_stress.update_layout(
title=f"Stress Accumulation - Response {i+1}",
yaxis_title="Cumulative Stress σ(k)",
xaxis_title="Inference Step k",
height=300,
template="plotly_dark",
showlegend=True
)
st.plotly_chart(fig_stress, use_container_width=True)
# Summary metrics
st.markdown("---")
st.subheader("Summary Statistics")
summary_cols = st.columns(4)
with summary_cols[0]:
st.metric("Total Responses", len(responses))
with summary_cols[1]:
st.metric("Excluded", metrics['total_excluded'])
with summary_cols[2]:
st.metric("Survived", len(responses) - metrics['total_excluded'])
with summary_cols[3]:
selected = 1 if result_text else 0
st.metric("Selected", selected)
# Detailed audit trail
with st.expander("📊 Complete Numerical Audit Trail (JSON)", expanded=False):
st.caption("Full vectors, distances, comparisons, and stress evolution for reproducibility")
numbers_view = {
"test_metadata": {
"provider": api_preset,
"base_url": api_base_url,
"model": model_name,
"temperature": temperature,
"num_responses": len(responses),
"num_substrate_facts": len(substrate_list),
"prompt": user_prompt,
"system_prompt": system_prompt if system_prompt else "None"
},
"embedder": {
"name": "DeterministicHashEmbedderND",
"description": "Deterministic SHA-256 based 16D projection (2D shown for plotting)",
"definition": "sha256(text) -> 16D in [0,1], projected to 2D"
},
"substrate": [
{"index": idx, "text": t, "vec2": [round(v[0], 8), round(v[1], 8)]}
for idx, (t, v) in enumerate(zip(substrate_list, sub_vecs_2d))
],
"responses": []
}
for i, (response, resp_vec) in enumerate(zip(responses, resp_vecs)):
cand_metrics = candidate_metrics[i]
# Compute all substrate comparisons
comparisons = []
for j, sub_vec in enumerate(sub_vecs):
cos_sim = cosine_similarity(resp_vec, sub_vec)
alignment = (cos_sim + 1.0) / 2.0
dist = euclidean_distance(resp_vec, sub_vec)
comparisons.append({
"substrate_index": j,
"substrate_text": substrate_list[j],
"cosine_similarity": round(cos_sim, 8),
"alignment_0_1": round(alignment, 8),
"euclidean_distance": round(dist, 8),
})
numbers_view["responses"].append({
"response_index": i,
"text": response,
"vec2": [round(resp_vecs_2d[i][0], 8), round(resp_vecs_2d[i][1], 8)],
"substrate_comparisons": comparisons,
"engine_results": {
"fractured": cand_metrics.get('fractured', False),
"fractured_at_step": cand_metrics.get('fractured_step'),
"final_stress": round(float(cand_metrics['stress']), 8),
"determinism_hash": cand_metrics.get('hash', 'N/A')
}
})
st.json(numbers_view)
except ImportError:
st.error("Missing `openai` library. Install with: `pip install openai`")
except Exception as e: