DSPy: The framework for programming—not prompting—language models
Python
Input validation and better program awareness
Michael Ryan50de2700c5cc
diff --git a/dspy/propose/grounded_proposer.py b/dspy/propose/grounded_proposer.pyindex b3699b1c7..1bd85b05e 100644--- a/dspy/propose/grounded_proposer.py+++ b/dspy/propose/grounded_proposer.py@@ -183,8 +183,8 @@ class GenerateModuleInstruction(dspy.Module):break# Summarize the program- program_description = ""- module_code = ""+ program_description = "Not available"+ module_code = "Not provided"if self.program_aware:try:program_description = strip_prefix(@@ -194,14 +194,19 @@ class GenerateModuleInstruction(dspy.Module):)if self.verbose: print(f"PROGRAM DESCRIPTION: {program_description}")- # Identify all modules- init_pattern = r"def __init__\([\s\S]*?\):([\s\S]*?)(?=^\s*def|\Z)"- init_content_match = re.search(init_pattern, self.program_code_string)- init_content = init_content_match.group(0)- pattern = r"^(.*dspy\.(ChainOfThought|Predict).*)$" # TODO: make it so that this extends out to any dspy Module- matches = re.findall(pattern, init_content, re.MULTILINE)- modules = [match[0].strip() for match in matches]- module_code = modules[pred_i]+ inputs = []+ outputs = []+ for field_name, field in get_signature(program.predictors()[pred_i]).fields.items():+ # Access the '__dspy_field_type' from the extra metadata+ dspy_field_type = field.json_schema_extra.get('__dspy_field_type')++ # Based on the '__dspy_field_type', append to the respective list+ if dspy_field_type == "input":+ inputs.append(field_name)+ else:+ outputs.append(field_name)++ module_code = f"{program.predictors()[pred_i].__class__.__name__}({', '.join(inputs)}) -> {', '.join(outputs)}"except:if self.verbose: print("Error getting program description. Running without program aware proposer.")self.program_aware = Falsediff --git a/dspy/teleprompt/mipro_optimizer_v2.py b/dspy/teleprompt/mipro_optimizer_v2.pyindex 53a63ed6d..f5c7043d5 100644--- a/dspy/teleprompt/mipro_optimizer_v2.py+++ b/dspy/teleprompt/mipro_optimizer_v2.py@@ -112,6 +112,7 @@ class MIPROv2(Teleprompter):student,*,trainset,+ valset=None,num_trials=30,max_bootstrapped_demos=4,max_labeled_demos=16,@@ -131,6 +132,24 @@ class MIPROv2(Teleprompter):ENDC = "\033[0m" # Resets the color to defaultrandom.seed(seed)++ # Validate inputs+ if not trainset:+ raise ValueError("Trainset cannot be empty.")++ if not valset:+ if len(trainset) < 2:+ raise ValueError("Trainset must have at least 2 examples if no valset specified, or at least 1 example with external validation set.")++ valset_size = min(300, max(1, int(len(trainset) * 0.25))) # 25% of trainset, capped at 300+ cutoff = len(trainset) - valset_size+ valset = trainset[cutoff:]+ trainset = trainset[:cutoff]++ else:+ if len(valset) < 1:+ raise ValueError("Validation set must have at least 1 example if specified.")+estimated_prompt_model_calls = 10 + self.num_candidates * len(student.predictors(),) + (0 if not program_aware_proposer else len(student.predictors()) + 1) # num data summary calls + N * P + (P + 1)