from dspy.teleprompt import BootstrapFewShot from app.ai.nutrition import nutrition_module from app.core.ai_config import configure_dspy from scripts.nutrition_data import train_examples # 0. Configure DSPy configure_dspy() # 1. Define Validated Examples (The "Train Set") # ... (rest of the file) ... # 2. Define a Metric def validate_nutrition(example, pred, trace=None): # Check if the predicted calories are within 15% of the actual calories actual_cals = example.nutritional_info.calories pred_cals = pred.nutritional_info.calories threshold = 0.15 lower = actual_cals * (1 - threshold) upper = actual_cals * (1 + threshold) return lower <= pred_cals <= upper # 3. Setup the Optimizer teleprompter = BootstrapFewShot(metric=validate_nutrition, max_bootstrapped_demos=8, max_labeled_demos=8) # 4. Compile (Optimize) the Module print("Optimizing... (this calls the LLM for each example)") compiled_nutrition = teleprompter.compile(nutrition_module, trainset=train_examples) # 5. Save validity # Correct path relative to backend/ directory compiled_nutrition.save("app/ai/nutrition_compiled.json") print("Optimization complete! Saved to app/ai/nutrition_compiled.json") # 6. Usage # To use the optimized version in production, you would load it: # nutrition_module.load("backend/app/ai/nutrition_compiled.json")