DSPy: The framework for programming—not prompting—language models
Python
Pull from original fork repo
Isaac Miller687d4b0b6171
diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.ymlindex 6b4221ade..76cea5cb6 100644--- a/.github/workflows/run_tests.yml+++ b/.github/workflows/run_tests.yml@@ -16,7 +16,7 @@ jobs:permissions:contents: writesteps:- - uses: actions/checkout@v3+ - uses: actions/checkout@v4- uses: actions/setup-python@v5- uses: chartboost/ruff-action@v1with:@@ -33,8 +33,6 @@ jobs:python-version: ["3.9"]steps:- uses: actions/checkout@v4- with:- ref: ${{ github.head_ref }}- name: Load cached Poetry installationid: cached-poetryuses: actions/cache@v3@@ -66,8 +64,6 @@ jobs:python-version: ["3.9"]steps:- uses: actions/checkout@v4- with:- ref: ${{ github.head_ref }}- name: Load cached Poetry installationid: cached-poetryuses: actions/cache@v3@@ -99,8 +95,6 @@ jobs:python-version: ["3.9"]steps:- uses: actions/checkout@v4- with:- ref: ${{ github.head_ref }}- name: Load cached Poetry installationid: cached-poetryuses: actions/cache@v3diff --git a/dspy/evaluate/evaluate.py b/dspy/evaluate/evaluate.pyindex 714a617dc..d83574477 100644--- a/dspy/evaluate/evaluate.py+++ b/dspy/evaluate/evaluate.py@@ -23,8 +23,18 @@ we print the number of failures, the first N examples that failed, and the firstclass Evaluate:- def __init__(self, *, devset, metric=None, num_threads=1, display_progress=False,- display_table=False, display=True, max_errors=5, return_outputs=False):+ def __init__(+ self,+ *,+ devset,+ metric=None,+ num_threads=1,+ display_progress=False,+ display_table=False,+ display=True,+ max_errors=5,+ return_outputs=False,+ ):self.devset = devsetself.metric = metricself.num_threads = num_threads@@ -40,7 +50,7 @@ class Evaluate:ncorrect = 0ntotal = 0reordered_devset = []-+pbar = tqdm.tqdm(total=len(devset), dynamic_ncols=True, disable=not display_progress)for idx, arg in devset:example_idx, example, prediction, score = wrapped_program(idx, arg)@@ -49,14 +59,14 @@ class Evaluate:ntotal += 1self._update_progress(pbar, ncorrect, ntotal)pbar.close()-+return reordered_devset, ncorrect, ntotaldef _execute_multi_thread(self, wrapped_program, devset, num_threads, display_progress):ncorrect = 0ntotal = 0reordered_devset = []-+with ThreadPoolExecutor(max_workers=num_threads) as executor:futures = {executor.submit(wrapped_program, idx, arg) for idx, arg in devset}pbar = tqdm.tqdm(total=len(devset), dynamic_ncols=True, disable=not display_progress)@@ -75,9 +85,18 @@ class Evaluate:pbar.set_description(f"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)})")pbar.update()- def __call__(self, program, metric=None, devset=None, num_threads=None,- display_progress=None, display_table=None, display=None,- return_all_scores=False, return_outputs=False):+ def __call__(+ self,+ program,+ metric=None,+ devset=None,+ num_threads=None,+ display_progress=None,+ display_table=None,+ display=None,+ return_all_scores=False,+ return_outputs=False,+ ):metric = metric if metric is not None else self.metricdevset = devset if devset is not None else self.devsetnum_threads = num_threads if num_threads is not None else self.num_threads@@ -89,7 +108,7 @@ class Evaluate:display_table = display_table if display else Falsereturn_outputs = return_outputs if return_outputs is not False else self.return_outputsresults = []-+def wrapped_program(example_idx, example):# NOTE: TODO: Won't work if threads create threads!creating_new_thread = threading.get_ident() not in dsp.settings.stack_by_thread@@ -101,14 +120,16 @@ class Evaluate:try:prediction = program(**example.inputs())- score = metric(example, prediction) # FIXME: TODO: What's the right order? Maybe force name-based kwargs!-+ score = metric(+ example, prediction+ ) # FIXME: TODO: What's the right order? Maybe force name-based kwargs!+# increment assert and suggest failures to program's attributes- if hasattr(program, '_assert_failures'):+ if hasattr(program, "_assert_failures"):program._assert_failures += dsp.settings.assert_failures- if hasattr(program, '_suggest_failures'):+ if hasattr(program, "_suggest_failures"):program._suggest_failures += dsp.settings.suggest_failures-+return example_idx, example, prediction, scoreexcept Exception as e:with self.error_lock:@@ -127,7 +148,9 @@ class Evaluate:if num_threads == 1:reordered_devset, ncorrect, ntotal = self._execute_single_thread(wrapped_program, devset, display_progress)else:- reordered_devset, ncorrect, ntotal = self._execute_multi_thread(wrapped_program, devset, num_threads, display_progress)+ reordered_devset, ncorrect, ntotal = self._execute_multi_thread(+ wrapped_program, devset, num_threads, display_progress+ )if return_outputs: # Handle the return_outputs logicresults = [(example, prediction, score) for _, example, prediction, score in reordered_devset]@@ -137,7 +160,9 @@ class Evaluate:predicted_devset = sorted(reordered_devset)# data = [{**example, **prediction, 'correct': score} for example, prediction, score in zip(reordered_devset, preds, scores)]- data = [merge_dicts(example, prediction) | {'correct': score} for _, example, prediction, score in predicted_devset]+ data = [+ merge_dicts(example, prediction) | {"correct": score} for _, example, prediction, score in predicted_devset+ ]df = pd.DataFrame(data)@@ -145,9 +170,9 @@ class Evaluate:df = df.applymap(truncate_cell)# Rename the 'correct' column to the name of the metric object- assert(callable(metric))+ assert callable(metric)metric_name = metric.__name__ if isinstance(metric, types.FunctionType) else metric.__class__.__name__- df.rename(columns={'correct': metric_name}, inplace=True)+ df.rename(columns={"correct": metric_name}, inplace=True)if display_table:if isinstance(display_table, int):@@ -158,23 +183,23 @@ class Evaluate:truncated_rows = 0styled_df = configure_dataframe_display(df_to_display, metric_name)-+ipython_display(styled_df)if truncated_rows > 0:# Simplified message about the truncated rowsmessage = f"""<div style='- text-align: center;- font-size: 16px;- font-weight: bold;- color: #555;+ text-align: center;+ font-size: 16px;+ font-weight: bold;+ color: #555;margin: 10px 0;'>... {truncated_rows} more rows not displayed ...</div>"""ipython_display(HTML(message))-+if return_all_scores and return_outputs:return round(100 * ncorrect / ntotal, 2), results, [score for *_, score in reordered_devset]elif return_all_scores:@@ -206,28 +231,34 @@ def truncate_cell(content):"""Truncate content of a cell to 25 words."""words = str(content).split()if len(words) > 25:- return ' '.join(words[:25]) + '...'+ return " ".join(words[:25]) + "..."return content+def configure_dataframe_display(df, metric_name):"""Set various pandas display options for DataFrame."""pd.options.display.max_colwidth = None- pd.set_option('display.max_colwidth', 20) # Adjust the number as needed- pd.set_option('display.width', 400) # Adjust+ pd.set_option("display.max_colwidth", 20) # Adjust the number as needed+ pd.set_option("display.width", 400) # Adjust# df[metric_name] = df[metric_name].apply(lambda x: f'✔️ [{x}]' if x is True else f'❌ [{x}]')- df.loc[:, metric_name] = df[metric_name].apply(lambda x: f'✔️ [{x}]' if x is True else f'{x}')+ df.loc[:, metric_name] = df[metric_name].apply(lambda x: f"✔️ [{x}]" if x is True else f"{x}")# Return styled DataFrame- return df.style.set_table_styles([- {'selector': 'th', 'props': [('text-align', 'left')]},- {'selector': 'td', 'props': [('text-align', 'left')]},- ]).set_properties(**{- 'text-align': 'left',- 'white-space': 'pre-wrap',- 'word-wrap': 'break-word',- 'max-width': '400px',- })+ return df.style.set_table_styles(+ [+ {"selector": "th", "props": [("text-align", "left")]},+ {"selector": "td", "props": [("text-align", "left")]},+ ]+ ).set_properties(+ **{+ "text-align": "left",+ "white-space": "pre-wrap",+ "word-wrap": "break-word",+ "max-width": "400px",+ }+ )+# FIXME: TODO: The merge_dicts stuff above is way too quick and dirty.# TODO: the display_table can't handle False but can handle 0! Not sure how it works with True exactly, probably fails too.