rairo commited on
Commit
3413d9e
·
verified ·
1 Parent(s): 1cb623e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +66 -45
main.py CHANGED
@@ -423,80 +423,101 @@ def deep_dive():
423
 
424
 
425
  # -----------------------------------------------------------------------------
426
- # ODYSSEUS ENGINE V2: SYSTEM DYNAMICS (SCIENTIFIC EQUILIBRIUM)
427
  # -----------------------------------------------------------------------------
428
 
429
- def validate_odysseus_v2(t: dict) -> (bool, str):
430
- """Ensures the AI output is a valid mathematical simulation."""
431
  try:
432
- if t.get("engine", {}).get("version") != "v2": return False, "Version Mismatch"
433
- render_types = {"biological_growth", "chemical_reactor", "mechanical_stress", "vector_flow"}
434
- if t.get("simulation_type") not in render_types: return False, "Invalid visualizer"
435
-
436
- logic = t.get("logic", {})
437
- if "equilibrium_window" not in logic or "entropy_factor" not in logic:
438
- return False, "Missing physics constants"
439
-
440
  return True, "ok"
441
  except: return False, "Schema corruption"
442
 
443
  @app.route('/api/trial/generate', methods=['POST'])
444
  def generate_trial():
445
  """
446
- Odysseus v2: Designs a System Dynamics simulation based on First Principles.
447
- Analyzes the Epiphany layer to identify a 'Tension' (e.g. Gravity vs Lift).
 
 
 
 
448
  """
449
- logger.info(">>> ODYSSEUS V2 TRIAL GENERATION")
450
  uid = verify_token(request.headers.get('Authorization'))
451
  if not uid: return jsonify({"error": "Unauthorized"}), 401
452
 
453
  payload = request.get_json()
454
  ep_id = payload.get("epiphanyId")
455
- layer_key = payload.get("layerKey") # genesis | scientific_core | engineering_edge | cross_pollination
456
  subject = payload.get("subject")
457
 
458
- # 1. Persistent Cache Check
459
  trial_path = f"epiphanies/{ep_id}/trials/{layer_key}"
460
  existing = db_ref.child(trial_path).get()
461
  if existing: return jsonify(existing), 200
462
 
463
- # 2. Transactional Lock (Prevent double-spending/concurrency)
464
  lock_ref = db_ref.child(f"epiphanies/{ep_id}/trialLocks/{layer_key}")
465
- if lock_ref.get(): return jsonify({"error": "Simulation initializing..."}), 409
466
  lock_ref.set({"uid": uid, "at": datetime.utcnow().isoformat()})
467
 
468
  try:
469
- # 3. High-Intellect Physics Prompting
470
- # We fetch the actual text of the layer for specific context
471
  layer_data = db_ref.child(f"epiphanies/{ep_id}/layers/{layer_key}").get() or {}
472
  context_text = layer_data.get('text', '')
473
 
474
  trial_prompt = f"""
475
- Act as a Scientific Simulation Designer. Create an Odysseus v2 Trial for: {subject}.
476
- Layer Focus: {layer_key}. Context: {context_text}
477
 
478
- Task: Identify the core 'Scientific Tension' of this system (e.g. Photosynthesis balance, Structural load, Ionization equilibrium).
479
 
 
 
 
 
 
 
480
  MANDATORY JSON SCHEMA:
481
  {{
482
- "engine": {{"name": "odysseus", "version": "v2"}},
483
- "simulation_type": "biological_growth | chemical_reactor | mechanical_stress | vector_flow",
484
  "labels": {{
485
  "title": "Feynman-style Title",
486
- "goal": "Explain the goal simply.",
487
- "slider_label": "The force the user controls (e.g. 'Photon Intensity', 'Structural Rigidity')"
 
 
 
 
 
 
 
 
 
 
 
 
 
488
  }},
489
- "logic": {{
490
- "initial_value": 50,
491
- "target_value": 75,
492
- "equilibrium_window": 10,
493
- "entropy_factor": 0.5,
494
- "reaction_latency": 0.2,
495
- "hold_time_ms": 3000
496
  }},
 
 
 
 
497
  "narrative": {{
498
- "on_win": "A Feynman-style explanation of why they succeeded.",
499
- "on_fail": "A Socratic explanation of why the system collapsed."
500
  }}
501
  }}
502
  """
@@ -509,31 +530,31 @@ def generate_trial():
509
 
510
  trial_data = json.loads(_strip_json_fences(res.text))
511
 
512
- # 4. Validation & Spark Charge
513
- ok, why = validate_odysseus_v2(trial_data)
514
  if not ok:
515
  lock_ref.delete()
516
  return jsonify({"error": f"Logic failure: {why}"}), 422
517
 
518
  user_ref = db_ref.child(f'users/{uid}')
519
  credits = user_ref.get().get('credits', 0)
520
- if credits < 1:
521
  lock_ref.delete()
522
- return jsonify({"error": "Insufficient Sparks"}), 402
523
 
524
- # 5. Finalize & Persist
525
  trial_data["createdAt"] = datetime.utcnow().isoformat()
526
  db_ref.child(trial_path).set(trial_data)
527
- user_ref.update({'credits': credits - 1})
528
 
529
  lock_ref.delete()
530
- logger.info(f"Odysseus v2 Trial manifested for {subject}")
531
  return jsonify(trial_data), 201
532
 
533
  except Exception as e:
534
  lock_ref.delete()
535
- logger.error(f"Trial Gen Error: {e}")
536
- return jsonify({"error": "Failed to compile physics logic"}), 500
537
 
538
  # -----------------------------------------------------------------------------
539
  # 5. THE CHIRON MENTOR & SYSTEM UTILS
 
423
 
424
 
425
  # -----------------------------------------------------------------------------
426
+ # ODYSSEUS ENGINE V3: THE SOCRATIC SANDBOX (ENTITY-BASED SIMULATION)
427
  # -----------------------------------------------------------------------------
428
 
429
+ def validate_odysseus_v3(t: dict) -> (bool, str):
430
+ """Ensures the AI output is a valid entity-based sandbox."""
431
  try:
432
+ if t.get("engine", {}).get("version") != "v3": return False, "Version Mismatch"
433
+ req_keys = ["play_style", "entities", "interaction_rules", "goal_state"]
434
+ for k in req_keys:
435
+ if k not in t: return False, f"Missing key: {k}"
436
+ if not isinstance(t.get("entities"), list) or len(t.get("entities")) < 2:
437
+ return False, "Insufficient entities for interaction"
 
 
438
  return True, "ok"
439
  except: return False, "Schema corruption"
440
 
441
  @app.route('/api/trial/generate', methods=['POST'])
442
  def generate_trial():
443
  """
444
+ Odysseus v3: Designs a Component-Interaction Sandbox.
445
+ Play Styles:
446
+ - 'assembly' (Mechanical/Structural)
447
+ - 'reaction' (Chemical/Biological)
448
+ - 'navigation' (Flow/Aero)
449
+ - 'splicer' (Genetic/Hybrid)
450
  """
451
+ logger.info(">>> ODYSSEUS V3: SANDBOX GENERATION")
452
  uid = verify_token(request.headers.get('Authorization'))
453
  if not uid: return jsonify({"error": "Unauthorized"}), 401
454
 
455
  payload = request.get_json()
456
  ep_id = payload.get("epiphanyId")
457
+ layer_key = payload.get("layerKey")
458
  subject = payload.get("subject")
459
 
460
+ # 1. Cache Check
461
  trial_path = f"epiphanies/{ep_id}/trials/{layer_key}"
462
  existing = db_ref.child(trial_path).get()
463
  if existing: return jsonify(existing), 200
464
 
465
+ # 2. Transactional Lock
466
  lock_ref = db_ref.child(f"epiphanies/{ep_id}/trialLocks/{layer_key}")
467
+ if lock_ref.get(): return jsonify({"error": "Designing Sandbox..."}), 409
468
  lock_ref.set({"uid": uid, "at": datetime.utcnow().isoformat()})
469
 
470
  try:
471
+ # Fetch Context
 
472
  layer_data = db_ref.child(f"epiphanies/{ep_id}/layers/{layer_key}").get() or {}
473
  context_text = layer_data.get('text', '')
474
 
475
  trial_prompt = f"""
476
+ Act as a Socratic Game Architect. Create an Odysseus v3 Sandbox for: {subject}.
477
+ Context: {context_text}
478
 
479
+ Task: Design a playable simulation where the user interacts with scientific components.
480
 
481
+ Play Styles to choose from:
482
+ - 'assembly': Dragging parts into a blueprint.
483
+ - 'reaction': Tapping to add catalysts/energy to a system.
484
+ - 'navigation': Drawing paths for flow/vectors.
485
+ - 'splicer': Combining two traits to survive.
486
+
487
  MANDATORY JSON SCHEMA:
488
  {{
489
+ "engine": {{"name": "odysseus", "version": "v3"}},
490
+ "play_style": "assembly | reaction | navigation | splicer",
491
  "labels": {{
492
  "title": "Feynman-style Title",
493
+ "goal": "One sentence Socratic goal",
494
+ "tool_name": "The name of the user's interaction tool (e.g. 'Dropper', 'Wrench', 'Ionizer')"
495
+ }},
496
+ "entities": [
497
+ {{
498
+ "id": "e1",
499
+ "type": "target | actor | obstacle",
500
+ "label": "Name (e.g. 'Chloroplast', 'Photon')",
501
+ "initial_state": {{"x": 50, "y": 50, "health": 100}}
502
+ }}
503
+ ],
504
+ "interaction_rules": {{
505
+ "on_contact": "Explain what happens when entities touch",
506
+ "physics_modifier": "Gravity/Friction/Volatility level (0-1)",
507
+ "entropy_per_second": "How fast the system decays if left alone"
508
  }},
509
+ "goal_state": {{
510
+ "metric": "stability | growth | flow_rate",
511
+ "target_value": 100,
512
+ "win_threshold_ms": 3000
 
 
 
513
  }},
514
+ "realtime_insights": [
515
+ {{"trigger": "start", "text": "Profound Feynman opening statement."}},
516
+ {{"trigger": "midway", "text": "Observation about the system's strain."}}
517
+ ],
518
  "narrative": {{
519
+ "on_win": "Scientific explanation of the victory.",
520
+ "on_fail": "Socratic explanation of the failure."
521
  }}
522
  }}
523
  """
 
530
 
531
  trial_data = json.loads(_strip_json_fences(res.text))
532
 
533
+ # 3. Validation & Charge 4 Sparks (High-Complexity reasoning)
534
+ ok, why = validate_odysseus_v3(trial_data)
535
  if not ok:
536
  lock_ref.delete()
537
  return jsonify({"error": f"Logic failure: {why}"}), 422
538
 
539
  user_ref = db_ref.child(f'users/{uid}')
540
  credits = user_ref.get().get('credits', 0)
541
+ if credits < 4:
542
  lock_ref.delete()
543
+ return jsonify({"error": "Insufficient Sparks for a Sandbox Trial."}), 402
544
 
545
+ # 4. Finalize
546
  trial_data["createdAt"] = datetime.utcnow().isoformat()
547
  db_ref.child(trial_path).set(trial_data)
548
+ user_ref.update({'credits': credits - 4})
549
 
550
  lock_ref.delete()
551
+ logger.info(f"Odysseus v3 Sandbox manifested for {subject}")
552
  return jsonify(trial_data), 201
553
 
554
  except Exception as e:
555
  lock_ref.delete()
556
+ logger.error(f"Sandbox Gen Error: {e}")
557
+ return jsonify({"error": "Failed to compile Sandbox logic"}), 500
558
 
559
  # -----------------------------------------------------------------------------
560
  # 5. THE CHIRON MENTOR & SYSTEM UTILS