DSPy: The framework for programming—not prompting—language models
Python
Add global max_errors setting (#8319)
Omar Khattab19d846a0a0db
diff --git a/docs/docs/cheatsheet.md b/docs/docs/cheatsheet.mdindex 3598cc3c7..e4c574a36 100644--- a/docs/docs/cheatsheet.md+++ b/docs/docs/cheatsheet.md@@ -271,7 +271,7 @@ your_dspy_program_compiled = labeled_fewshot_optimizer.compile(student = your_ds```pythonfrom dspy.teleprompt import BootstrapFewShot-fewshot_optimizer = BootstrapFewShot(metric=your_defined_metric, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, max_errors=5)+fewshot_optimizer = BootstrapFewShot(metric=your_defined_metric, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, max_errors=10)your_dspy_program_compiled = fewshot_optimizer.compile(student = your_dspy_program, trainset=trainset)```@@ -281,7 +281,7 @@ your_dspy_program_compiled = fewshot_optimizer.compile(student = your_dspy_progr```pythonfrom dspy.teleprompt import BootstrapFewShot-fewshot_optimizer = BootstrapFewShot(metric=your_defined_metric, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, max_errors=5, teacher_settings=dict(lm=gpt4))+fewshot_optimizer = BootstrapFewShot(metric=your_defined_metric, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, max_errors=10, teacher_settings=dict(lm=gpt4))your_dspy_program_compiled = fewshot_optimizer.compile(student = your_dspy_program, trainset=trainset)```diff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.pyindex 94ce804b6..fd7ce52f3 100644--- a/dspy/dsp/utils/settings.py+++ b/dspy/dsp/utils/settings.py@@ -26,6 +26,7 @@ DEFAULT_CONFIG = dotdict(stream_listeners=[],provide_traceback=False, # Whether to include traceback information in error logs.num_threads=8, # Number of threads to use for parallel processing.+ max_errors=10, # Maximum errors before halting operations.)# Global base configuration and owner trackingdiff --git a/dspy/evaluate/evaluate.py b/dspy/evaluate/evaluate.pyindex 5740ba8a1..484f9747c 100644--- a/dspy/evaluate/evaluate.py+++ b/dspy/evaluate/evaluate.py@@ -56,7 +56,7 @@ class Evaluate:num_threads: Optional[int] = None,display_progress: bool = False,display_table: Union[bool, int] = False,- max_errors: int = 5,+ max_errors: Optional[int] = None,return_all_scores: bool = False,return_outputs: bool = False,provide_traceback: Optional[bool] = None,@@ -71,7 +71,8 @@ class Evaluate:display_progress (bool): Whether to display progress during evaluation.display_table (Union[bool, int]): Whether to display the evaluation results in a table.If a number is passed, the evaluation results will be truncated to that number before displayed.- max_errors (int): The maximum number of errors to allow before stopping evaluation.+ max_errors (Optional[int]): The maximum number of errors to allow before+ stopping evaluation. If ``None``, inherits from ``dspy.settings.max_errors``.return_all_scores (bool): Whether to return scores for every data record in `devset`.return_outputs (bool): Whether to return the dspy program's outputs for every data in `devset`.provide_traceback (Optional[bool]): Whether to provide traceback information during evaluation.@@ -151,7 +152,11 @@ class Evaluate:executor = ParallelExecutor(num_threads=num_threads,disable_progress_bar=not display_progress,- max_errors=self.max_errors,+ max_errors=(+ self.max_errors+ if self.max_errors is not None+ else dspy.settings.max_errors+ ),provide_traceback=self.provide_traceback,compare_results=True,)diff --git a/dspy/predict/parallel.py b/dspy/predict/parallel.pyindex 0f7fc5833..46ec7b8cf 100644--- a/dspy/predict/parallel.py+++ b/dspy/predict/parallel.py@@ -10,7 +10,7 @@ class Parallel:def __init__(self,num_threads: Optional[int] = None,- max_errors: int = 10,+ max_errors: Optional[int] = None,access_examples: bool = True,return_failed_examples: bool = False,provide_traceback: Optional[bool] = None,@@ -18,7 +18,7 @@ class Parallel:):super().__init__()self.num_threads = num_threads or settings.num_threads- self.max_errors = max_errors+ self.max_errors = settings.max_errors if max_errors is None else max_errorsself.access_examples = access_examplesself.return_failed_examples = return_failed_examplesself.provide_traceback = provide_tracebackdiff --git a/dspy/primitives/program.py b/dspy/primitives/program.pyindex 65ad64e33..f39cc8912 100644--- a/dspy/primitives/program.py+++ b/dspy/primitives/program.py@@ -115,7 +115,7 @@ class Module(BaseModule, metaclass=ProgramMeta):self,examples,num_threads: Optional[int] = None,- max_errors: int = 10,+ max_errors: Optional[int] = None,return_failed_examples: bool = False,provide_traceback: Optional[bool] = None,disable_progress_bar: bool = False,@@ -127,10 +127,11 @@ class Module(BaseModule, metaclass=ProgramMeta):examples: List of dspy.Example instances to process.num_threads: Number of threads to use for parallel processing.max_errors: Maximum number of errors allowed before stopping execution.+ If ``None``, inherits from ``dspy.settings.max_errors``.return_failed_examples: Whether to return failed examples and exceptions.provide_traceback: Whether to include traceback information in error logs.disable_progress_bar: Whether to display the progress bar.-+Returns:List of results, and optionally failed examples and exceptions."""diff --git a/dspy/teleprompt/bootstrap.py b/dspy/teleprompt/bootstrap.pyindex 5fe2c8fd0..4cacb0136 100644--- a/dspy/teleprompt/bootstrap.py+++ b/dspy/teleprompt/bootstrap.py@@ -43,7 +43,7 @@ class BootstrapFewShot(Teleprompter):max_bootstrapped_demos=4,max_labeled_demos=16,max_rounds=1,- max_errors=5,+ max_errors=None,):"""A Teleprompter class that composes a set of demos/examples to go into a predictor's prompt.These demos come from a combination of labeled examples in the training set, and bootstrapped demos.@@ -62,7 +62,8 @@ class BootstrapFewShot(Teleprompter):Defaults to 16.max_rounds (int): Number of iterations to attempt generating the required bootstrapexamples. If unsuccessful after `max_rounds`, the program ends. Defaults to 1.- max_errors (int): Maximum number of errors until program ends. Defaults to 5.+ max_errors (Optional[int]): Maximum number of errors until program ends.+ If ``None``, inherits from ``dspy.settings.max_errors``."""self.metric = metricself.metric_threshold = metric_threshold@@ -210,7 +211,12 @@ class BootstrapFewShot(Teleprompter):with self.error_lock:self.error_count += 1current_error_count = self.error_count- if current_error_count >= self.max_errors:+ effective_max_errors = (+ self.max_errors+ if self.max_errors is not None+ else dspy.settings.max_errors+ )+ if current_error_count >= effective_max_errors:raise elogger.error(f"Failed to run or to evaluate example {example} with {self.metric} due to {e}.")diff --git a/dspy/teleprompt/infer_rules.py b/dspy/teleprompt/infer_rules.pyindex 7d4d7e620..70611962d 100644--- a/dspy/teleprompt/infer_rules.py+++ b/dspy/teleprompt/infer_rules.py@@ -19,7 +19,7 @@ class InferRules(BootstrapFewShot):self.num_threads = num_threadsself.rules_induction_program = RulesInductionProgram(num_rules, teacher_settings=teacher_settings)self.metric = kwargs.get("metric")- self.max_errors = kwargs.get("max_errors", 10)+ self.max_errors = kwargs.get("max_errors")def compile(self, student, *, teacher=None, trainset, valset=None):if valset is None:@@ -109,11 +109,14 @@ class InferRules(BootstrapFewShot):]def evaluate_program(self, program, dataset):+ effective_max_errors = (+ self.max_errors if self.max_errors is not None else dspy.settings.max_errors+ )evaluate = Evaluate(devset=dataset,metric=self.metric,num_threads=self.num_threads,- max_errors=self.max_errors,+ max_errors=effective_max_errors,display_table=False,display_progress=True,return_all_scores=True,diff --git a/dspy/teleprompt/mipro_optimizer_v2.py b/dspy/teleprompt/mipro_optimizer_v2.pyindex eae337e33..d80695c6e 100644--- a/dspy/teleprompt/mipro_optimizer_v2.py+++ b/dspy/teleprompt/mipro_optimizer_v2.py@@ -5,7 +5,8 @@ import sysimport textwrapimport timefrom collections import defaultdict-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple+from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Literal,+ Optional, Tuple)import numpy as np@@ -13,16 +14,12 @@ import dspyfrom dspy.evaluate.evaluate import Evaluatefrom dspy.propose import GroundedProposerfrom dspy.teleprompt.teleprompt import Teleprompter-from dspy.teleprompt.utils import (- create_minibatch,- create_n_fewshot_demo_sets,- eval_candidate_program,- get_program_with_highest_avg_score,- get_signature,- print_full_program,- save_candidate_program,- set_signature,-)+from dspy.teleprompt.utils import (create_minibatch,+ create_n_fewshot_demo_sets,+ eval_candidate_program,+ get_program_with_highest_avg_score,+ get_signature, print_full_program,+ save_candidate_program, set_signature)if TYPE_CHECKING:import optuna@@ -60,7 +57,7 @@ class MIPROv2(Teleprompter):auto: Optional[Literal["light", "medium", "heavy"]] = "light",num_candidates: Optional[int] = None,num_threads: Optional[int] = None,- max_errors: int = 10,+ max_errors: Optional[int] = None,seed: int = 9,init_temperature: float = 0.5,verbose: bool = False,@@ -116,12 +113,18 @@ class MIPROv2(Teleprompter):requires_permission_to_run: bool = True,provide_traceback: Optional[bool] = None,) -> Any:-+ effective_max_errors = (+ self.max_errors+ if self.max_errors is not None+ else dspy.settings.max_errors+ )zeroshot_opt = (self.max_bootstrapped_demos == 0) and (self.max_labeled_demos == 0)# If auto is None, and num_trials is not provided (but num_candidates is), raise an error that suggests a good num_trials valueif self.auto is None and (self.num_candidates is not None and num_trials is None):- raise ValueError(f"If auto is None, num_trials must also be provided. Given num_candidates={self.num_candidates}, we'd recommend setting num_trials to ~{self._set_num_trials_from_num_candidates(student, zeroshot_opt, self.num_candidates)}.")+ raise ValueError(+ f"If auto is None, num_trials must also be provided. Given num_candidates={self.num_candidates}, we'd recommend setting num_trials to ~{self._set_num_trials_from_num_candidates(student, zeroshot_opt, self.num_candidates)}."+ )# If auto is None, and num_candidates or num_trials is None, raise an errorif self.auto is None and (self.num_candidates is None or num_trials is None):@@ -129,7 +132,9 @@ class MIPROv2(Teleprompter):# If auto is provided, and either num_candidates or num_trials is not None, raise an errorif self.auto is not None and (self.num_candidates is not None or num_trials is not None):- raise ValueError("If auto is not None, num_candidates and num_trials cannot be set, since they would be overrided by the auto settings. Please either set auto to None, or do not specify num_candidates and num_trials.")+ raise ValueError(+ "If auto is not None, num_candidates and num_trials cannot be set, since they would be overrided by the auto settings. Please either set auto to None, or do not specify num_candidates and num_trials."+ )# Set random seedsseed = seed or self.seed@@ -175,7 +180,7 @@ class MIPROv2(Teleprompter):devset=valset,metric=self.metric,num_threads=self.num_threads,- max_errors=self.max_errors,+ max_errors=effective_max_errors,display_table=False,display_progress=True,provide_traceback=provide_traceback,@@ -382,7 +387,7 @@ class MIPROv2(Teleprompter):""")- print(f"{user_message}\n{user_confirmation_message}\nDo you wish to continue? (y/n): ", end='', flush=True)+ print(f"{user_message}\n{user_confirmation_message}\nDo you wish to continue? (y/n): ", end="", flush=True)# Wait for input with timeoutstart_time = time.time()@@ -409,6 +414,10 @@ class MIPROv2(Teleprompter):zeroshot = self.max_bootstrapped_demos == 0 and self.max_labeled_demos == 0try:+ effective_max_errors = (+ self.max_errors if self.max_errors is not None else dspy.settings.max_errors+ )+demo_candidates = create_n_fewshot_demo_sets(student=program,num_candidate_sets=self.num_fewshot_candidates,@@ -418,7 +427,7 @@ class MIPROv2(Teleprompter):BOOTSTRAPPED_FEWSHOT_EXAMPLES_IN_CONTEXT if zeroshot else self.max_bootstrapped_demos),metric=self.metric,- max_errors=self.max_errors,+ max_errors=effective_max_errors,teacher=teacher,teacher_settings=self.teacher_settings,seed=seed,@@ -498,6 +507,7 @@ class MIPROv2(Teleprompter):seed: int,) -> Optional[Any]:import optuna+# Run optimizationoptuna.logging.set_verbosity(optuna.logging.WARNING)logger.info("==> STEP 3: FINDING OPTIMAL PROMPT PARAMETERS <==")@@ -507,7 +517,11 @@ class MIPROv2(Teleprompter):# Compute the adjusted total trials that we will run (including full evals)run_additional_full_eval_at_end = 1 if num_trials % minibatch_full_eval_steps != 0 else 0- adjusted_num_trials = int((num_trials + num_trials // minibatch_full_eval_steps + 1 + run_additional_full_eval_at_end) if minibatch else num_trials)+ adjusted_num_trials = int(+ (num_trials + num_trials // minibatch_full_eval_steps + 1 + run_additional_full_eval_at_end)+ if minibatch+ else num_trials+ )logger.info(f"== Trial {1} / {adjusted_num_trials} - Full Evaluation of Default Program ==")default_score, _ = eval_candidate_program(@@ -610,7 +624,9 @@ class MIPROv2(Teleprompter):)# If minibatch, perform full evaluation at intervals (and at the very end)- if minibatch and ((trial_num % (minibatch_full_eval_steps+1) == 0) or (trial_num == (adjusted_num_trials-1))):+ if minibatch and (+ (trial_num % (minibatch_full_eval_steps + 1) == 0) or (trial_num == (adjusted_num_trials - 1))+ ):best_score, best_program, total_eval_calls = self._perform_full_evaluation(trial_num,adjusted_num_trials,@@ -759,6 +775,7 @@ class MIPROv2(Teleprompter):def _get_param_distributions(self, program, instruction_candidates, demo_candidates):from optuna.distributions import CategoricalDistribution+param_distributions = {}for i in range(len(instruction_candidates)):@@ -788,6 +805,7 @@ class MIPROv2(Teleprompter):demo_candidates: List,):import optuna+logger.info(f"===== Trial {trial_num + 1} / {adjusted_num_trials} - Full Evaluation =====")# Identify best program to evaluate fullydiff --git a/dspy/teleprompt/random_search.py b/dspy/teleprompt/random_search.pyindex 89fcd5eae..ce0272ac4 100644--- a/dspy/teleprompt/random_search.py+++ b/dspy/teleprompt/random_search.py@@ -1,5 +1,6 @@import random+import dspyfrom dspy.evaluate.evaluate import Evaluatefrom dspy.teleprompt.teleprompt import Teleprompter@@ -33,7 +34,7 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):max_rounds=1,num_candidate_programs=16,num_threads=None,- max_errors=10,+ max_errors=None,stop_at_score=None,metric_threshold=None,):@@ -57,6 +58,12 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):self.trainset = trainsetself.valset = valset or trainset # TODO: FIXME: Note this choice.+ effective_max_errors = (+ self.max_errors+ if self.max_errors is not None+ else dspy.settings.max_errors+ )+scores = []all_subscores = []score_data = []@@ -85,7 +92,7 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):max_labeled_demos=self.max_labeled_demos,teacher_settings=self.teacher_settings,max_rounds=self.max_rounds,- max_errors=self.max_errors,+ max_errors=effective_max_errors,)program = optimizer.compile(student, teacher=teacher, trainset=trainset_copy)@@ -102,7 +109,7 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):max_labeled_demos=self.max_labeled_demos,teacher_settings=self.teacher_settings,max_rounds=self.max_rounds,- max_errors=self.max_errors,+ max_errors=effective_max_errors,)program = optimizer.compile(student, teacher=teacher, trainset=trainset_copy)@@ -111,7 +118,7 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):devset=self.valset,metric=self.metric,num_threads=self.num_threads,- max_errors=self.max_errors,+ max_errors=effective_max_errors,display_table=False,display_progress=True,)@@ -143,7 +150,9 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):# To best program, attach all program candidates in decreasing average scorebest_program.candidate_programs = score_data- best_program.candidate_programs = sorted(best_program.candidate_programs, key=lambda x: x["score"], reverse=True)+ best_program.candidate_programs = sorted(+ best_program.candidate_programs, key=lambda x: x["score"], reverse=True+ )print(f"{len(best_program.candidate_programs)} candidate programs found.")diff --git a/dspy/teleprompt/utils.py b/dspy/teleprompt/utils.pyindex b6578303f..31f5d19a9 100644--- a/dspy/teleprompt/utils.py+++ b/dspy/teleprompt/utils.py@@ -25,6 +25,7 @@ This file consists of helper functions for our variety of optimizers.logger = logging.getLogger(__name__)+def create_minibatch(trainset, batch_size=50, rng=None):"""Create a minibatch from the trainset."""@@ -49,14 +50,19 @@ def eval_candidate_program(batch_size, trainset, candidate_program, evaluate, rntry:# Evaluate on the full trainsetif batch_size >= len(trainset):- return evaluate(candidate_program, devset=trainset, return_all_scores=return_all_scores, callback_metadata={"metric_key": "eval_full"})+ return evaluate(+ candidate_program,+ devset=trainset,+ return_all_scores=return_all_scores,+ callback_metadata={"metric_key": "eval_full"},+ )# Or evaluate on a minibatchelse:return evaluate(candidate_program,devset=create_minibatch(trainset, batch_size, rng),return_all_scores=return_all_scores,- callback_metadata={"metric_key": "eval_minibatch"}+ callback_metadata={"metric_key": "eval_minibatch"},)except Exception:logger.error("An exception occurred during evaluation", exc_info=True)@@ -64,8 +70,15 @@ def eval_candidate_program(batch_size, trainset, candidate_program, evaluate, rnreturn 0.0, [0.0] * len(trainset)return 0.0 # TODO: Handle this better, as -ve scores are possible+def eval_candidate_program_with_pruning(- trial, trial_logs, trainset, candidate_program, evaluate, trial_num, batch_size=100,+ trial,+ trial_logs,+ trainset,+ candidate_program,+ evaluate,+ trial_num,+ batch_size=100,):"""Evaluation of candidate_program with pruning implemented"""@@ -79,7 +92,9 @@ def eval_candidate_program_with_pruning(end_index = min((i + 1) * batch_size, len(trainset))split_trainset = trainset[start_index:end_index]split_score = evaluate(- candidate_program, devset=split_trainset, display_table=0,+ candidate_program,+ devset=split_trainset,+ display_table=0,)print(f"{i}st split score: {split_score}")total_eval_size += len(split_trainset)@@ -136,7 +151,12 @@ def get_program_with_highest_avg_score(param_score_dict, fully_evaled_param_combdef calculate_last_n_proposed_quality(- base_program, trial_logs, evaluate, trainset, devset, n,+ base_program,+ trial_logs,+ evaluate,+ trainset,+ devset,+ n,):"""Calculate the average and best quality of the last n programs proposed. This is useful for seeing if our proposals@@ -176,7 +196,10 @@ def calculate_last_n_proposed_quality(def get_task_model_history_for_full_example(- candidate_program, task_model, devset, evaluate,+ candidate_program,+ task_model,+ devset,+ evaluate,):"""Get a full trace of the task model's history for a given candidate program."""_ = evaluate(candidate_program, devset=devset[:1])@@ -250,6 +273,7 @@ def setup_logging(log_dir):console_handler.setFormatter(console_formatter)logger.addHandler(console_handler)+def get_token_usage(model) -> tuple[int, int]:"""Extract total input tokens and output tokens from a model's interaction history.@@ -282,10 +306,7 @@ def log_token_usage(trial_logs, trial_num, model_dict):for model_name, model in model_dict.items():in_tokens, out_tokens = get_token_usage(model)- token_usage_dict[model_name] = {- "total_input_tokens": in_tokens,- "total_output_tokens": out_tokens- }+ token_usage_dict[model_name] = {"total_input_tokens": in_tokens, "total_output_tokens": out_tokens}# Store token usage info in trial logstrial_logs[trial_num]["token_usage"] = token_usage_dict@@ -293,12 +314,14 @@ def log_token_usage(trial_logs, trial_num, model_dict):### OTHER UTILS ###+def get_prompt_model(prompt_model):if prompt_model:return prompt_modelelse:return dspy.settings.lm+def get_signature(predictor):assert hasattr(predictor, "signature")return predictor.signature@@ -317,7 +340,7 @@ def create_n_fewshot_demo_sets(max_bootstrapped_demos,metric,teacher_settings,- max_errors=10,+ max_errors=None,max_rounds=1,labeled_sample=True,min_num_samples=1,@@ -325,12 +348,13 @@ def create_n_fewshot_demo_sets(teacher=None,include_non_bootstrapped=True,seed=0,- rng=None+ rng=None,):"""This function is copied from random_search.py, and creates fewshot examples in the same way that random search does.This allows us to take advantage of using the same fewshot examples when we use the same random seed in our optimizers."""+ max_errors = dspy.settings.max_errors if max_errors is None else max_errorsdemo_candidates = {}# Account for confusing way this is set up, where we add in 3 more candidate sets to the N specified@@ -344,8 +368,7 @@ def create_n_fewshot_demo_sets(# Go through and create each candidate setfor seed in range(-3, num_candidate_sets):-- print(f"Bootstrapping set {seed+4}/{num_candidate_sets+3}")+ print(f"Bootstrapping set {seed + 4}/{num_candidate_sets + 3}")trainset_copy = list(trainset)@@ -353,15 +376,13 @@ def create_n_fewshot_demo_sets(# zero-shotprogram2 = student.reset_copy()- elif (- seed == -2- and max_labeled_demos > 0- and include_non_bootstrapped- ):+ elif seed == -2 and max_labeled_demos > 0 and include_non_bootstrapped:# labels onlyteleprompter = LabeledFewShot(k=max_labeled_demos)program2 = teleprompter.compile(- student, trainset=trainset_copy, sample=labeled_sample,+ student,+ trainset=trainset_copy,+ sample=labeled_sample,)elif seed == -1:@@ -392,7 +413,9 @@ def create_n_fewshot_demo_sets()program2 = teleprompter.compile(- student, teacher=teacher, trainset=trainset_copy,+ student,+ teacher=teacher,+ trainset=trainset_copy,)for i, _ in enumerate(student.predictors()):@@ -400,20 +423,21 @@ def create_n_fewshot_demo_sets(return demo_candidates+def old_getfile(object):"""Work out which source or compiled file an object was defined in."""if inspect.ismodule(object):- if getattr(object, '__file__', None):+ if getattr(object, "__file__", None):return object.__file__- raise TypeError(f'{object!r} is a built-in module')+ raise TypeError(f"{object!r} is a built-in module")if inspect.isclass(object):- if hasattr(object, '__module__'):+ if hasattr(object, "__module__"):module = sys.modules.get(object.__module__)- if getattr(module, '__file__', None):+ if getattr(module, "__file__", None):return module.__file__- if object.__module__ == '__main__':- raise OSError('source code not available')- raise TypeError(f'{object!r} is a built-in class')+ if object.__module__ == "__main__":+ raise OSError("source code not available")+ raise TypeError(f"{object!r} is a built-in class")if inspect.ismethod(object):object = object.__func__if inspect.isfunction(object):@@ -424,23 +448,26 @@ def old_getfile(object):object = object.f_codeif inspect.iscode(object):return object.co_filename- raise TypeError('module, class, method, function, traceback, frame, or '- f'code object was expected, got {type(object).__name__}')+ raise TypeError(+ f"module, class, method, function, traceback, frame, or code object was expected, got {type(object).__name__}"+ )+def new_getfile(object):if not inspect.isclass(object):return old_getfile(object)# Lookup by parent module (as in current inspect)- if hasattr(object, '__module__'):+ if hasattr(object, "__module__"):object_ = sys.modules.get(object.__module__)- if hasattr(object_, '__file__'):+ if hasattr(object_, "__file__"):return object_.__file__# If parent module is __main__, lookup by methods (NEW)for _, member in inspect.getmembers(object):- if inspect.isfunction(member) and object.__qualname__ + '.' + member.__name__ == member.__qualname__:+ if inspect.isfunction(member) and object.__qualname__ + "." + member.__name__ == member.__qualname__:return inspect.getfile(member)- raise TypeError(f'Source for {object!r} not found')+ raise TypeError(f"Source for {object!r} not found")+inspect.getfile = new_getfilediff --git a/dspy/utils/parallelizer.py b/dspy/utils/parallelizer.pyindex 99c9a39c4..9ad76493f 100644--- a/dspy/utils/parallelizer.py+++ b/dspy/utils/parallelizer.py@@ -17,7 +17,7 @@ class ParallelExecutor:def __init__(self,num_threads=None,- max_errors=5,+ max_errors=None,disable_progress_bar=False,provide_traceback=None,compare_results=False,@@ -31,7 +31,7 @@ class ParallelExecutor:from dspy.dsp.utils.settings import settingsself.num_threads = num_threads or settings.num_threads- self.max_errors = max_errors+ self.max_errors = settings.max_errors if max_errors is None else max_errorsself.disable_progress_bar = disable_progress_barself.provide_traceback = provide_traceback if provide_traceback is not None else settings.provide_tracebackself.compare_results = compare_results@@ -61,7 +61,7 @@ class ParallelExecutor:if self.provide_traceback:logger.error(f"Error for {item}: {e}\n{traceback.format_exc()}")else:- logger.error(f"Error for {item}: {e}. " "Set `provide_traceback=True` for traceback.")+ logger.error(f"Error for {item}: {e}. Set `provide_traceback=True` for traceback.")return Nonereturn safe_func