DSPy: The framework for programming—not prompting—language models
Python
Use decorators to change control flow
Shangyint4938d4786bf8
diff --git a/dspy/assertions/assertions.py b/dspy/assertions/assertions.pyindex 3bbb308fc..749479dbd 100644--- a/dspy/assertions/assertions.py+++ b/dspy/assertions/assertions.py@@ -15,7 +15,10 @@ class Assert:def __call__(self) -> bool:result = self.assert_fun(*self.args, **self.kwargs)if isinstance(result, bool):- return result+ if result:+ return True+ else:+ raise AssertionError(f"Assertion {self.assert_fun} failed")else:raise ValueError("Assertion function should always return [bool]")@@ -36,4 +39,16 @@ class Assertions(dspy.Module):return Trueelse:return assertion()++def assert_transform(backtrack=2):+ def wrapper(func):+ def inner(*args, **kwargs):+ for i in range(backtrack):+ try:+ return func(*args, **kwargs)+ except AssertionError as e:+ # Add metadata to state+ pass+ return inner+ return wrapperdiff --git a/tot_assertion.ipynb b/tot_assertion.ipynbindex 68ffd7d39..6785cd1df 100644--- a/tot_assertion.ipynb+++ b/tot_assertion.ipynb@@ -31,7 +31,7 @@},{"cell_type": "code",- "execution_count": 2,+ "execution_count": 3,"metadata": {},"outputs": [{@@ -49,7 +49,7 @@},{"cell_type": "code",- "execution_count": 3,+ "execution_count": 4,"metadata": {},"outputs": [{@@ -58,7 +58,7 @@"(20, 50)"]},- "execution_count": 3,+ "execution_count": 4,"metadata": {},"output_type": "execute_result"}@@ -202,7 +202,7 @@},{"cell_type": "code",- "execution_count": 8,+ "execution_count": 5,"metadata": {},"outputs": [],"source": [@@ -440,149 +440,9 @@},{"cell_type": "code",- "execution_count": 12,+ "execution_count": null,"metadata": {},- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "Average Metric: 20 / 50 (40.0): 100%|██████████| 50/50 [01:53<00:00, 2.26s/it]"- ]- },- {- "name": "stdout",- "output_type": "stream",- "text": [- "Average Metric: 20 / 50 (40.0%)\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "\n",- "/Users/shangyin/Projects/dspy-fork/dspy/evaluate/evaluate.py:122: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.\n",- " df = df.applymap(truncate_cell)\n"- ]- },- {- "data": {- "text/html": [- "<style type=\"text/css\">\n",- "#T_73a1e th {\n",- " text-align: left;\n",- "}\n",- "#T_73a1e td {\n",- " text-align: left;\n",- "}\n",- "#T_73a1e_row0_col0, #T_73a1e_row0_col1, #T_73a1e_row0_col2, #T_73a1e_row0_col3, #T_73a1e_row0_col4, #T_73a1e_row0_col5, #T_73a1e_row1_col0, #T_73a1e_row1_col1, #T_73a1e_row1_col2, #T_73a1e_row1_col3, #T_73a1e_row1_col4, #T_73a1e_row1_col5, #T_73a1e_row2_col0, #T_73a1e_row2_col1, #T_73a1e_row2_col2, #T_73a1e_row2_col3, #T_73a1e_row2_col4, #T_73a1e_row2_col5, #T_73a1e_row3_col0, #T_73a1e_row3_col1, #T_73a1e_row3_col2, #T_73a1e_row3_col3, #T_73a1e_row3_col4, #T_73a1e_row3_col5, #T_73a1e_row4_col0, #T_73a1e_row4_col1, #T_73a1e_row4_col2, #T_73a1e_row4_col3, #T_73a1e_row4_col4, #T_73a1e_row4_col5 {\n",- " text-align: left;\n",- " white-space: pre-wrap;\n",- " word-wrap: break-word;\n",- " max-width: 400px;\n",- "}\n",- "</style>\n",- "<table id=\"T_73a1e\">\n",- " <thead>\n",- " <tr>\n",- " <th class=\"blank level0\" > </th>\n",- " <th id=\"T_73a1e_level0_col0\" class=\"col_heading level0 col0\" >question</th>\n",- " <th id=\"T_73a1e_level0_col1\" class=\"col_heading level0 col1\" >example_answer</th>\n",- " <th id=\"T_73a1e_level0_col2\" class=\"col_heading level0 col2\" >gold_titles</th>\n",- " <th id=\"T_73a1e_level0_col3\" class=\"col_heading level0 col3\" >context</th>\n",- " <th id=\"T_73a1e_level0_col4\" class=\"col_heading level0 col4\" >pred_answer</th>\n",- " <th id=\"T_73a1e_level0_col5\" class=\"col_heading level0 col5\" >answer_exact_match</th>\n",- " </tr>\n",- " </thead>\n",- " <tbody>\n",- " <tr>\n",- " <th id=\"T_73a1e_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",- " <td id=\"T_73a1e_row0_col0\" class=\"data row0 col0\" >Are both Cangzhou and Qionghai in the Hebei province of China?</td>\n",- " <td id=\"T_73a1e_row0_col1\" class=\"data row0 col1\" >no</td>\n",- " <td id=\"T_73a1e_row0_col2\" class=\"data row0 col2\" >{'Cangzhou', 'Qionghai'}</td>\n",- " <td id=\"T_73a1e_row0_col3\" class=\"data row0 col3\" >['Cangzhou | Cangzhou () is a prefecture-level city in eastern Hebei province, People\\'s Republic of China. At the 2010 census, Cangzhou\\'s built-up (\"or metro\") area...</td>\n",- " <td id=\"T_73a1e_row0_col4\" class=\"data row0 col4\" >No</td>\n",- " <td id=\"T_73a1e_row0_col5\" class=\"data row0 col5\" >✔️ [True]</td>\n",- " </tr>\n",- " <tr>\n",- " <th id=\"T_73a1e_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",- " <td id=\"T_73a1e_row1_col0\" class=\"data row1 col0\" >Who conducts the draft in which Marc-Andre Fleury was drafted to the Vegas Golden Knights for the 2017-18 season?</td>\n",- " <td id=\"T_73a1e_row1_col1\" class=\"data row1 col1\" >National Hockey League</td>\n",- " <td id=\"T_73a1e_row1_col2\" class=\"data row1 col2\" >{'2017 NHL Expansion Draft', '2017–18 Pittsburgh Penguins season'}</td>\n",- " <td id=\"T_73a1e_row1_col3\" class=\"data row1 col3\" >['2017–18 Pittsburgh Penguins season | The 2017–18 Pittsburgh Penguins season will be the 51st season for the National Hockey League ice hockey team that was...</td>\n",- " <td id=\"T_73a1e_row1_col4\" class=\"data row1 col4\" >The National Hockey League (NHL)</td>\n",- " <td id=\"T_73a1e_row1_col5\" class=\"data row1 col5\" >❌ [False]</td>\n",- " </tr>\n",- " <tr>\n",- " <th id=\"T_73a1e_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",- " <td id=\"T_73a1e_row2_col0\" class=\"data row2 col0\" >The Wings entered a new era, following the retirement of which Canadian retired professional ice hockey player and current general manager of the Tampa Bay...</td>\n",- " <td id=\"T_73a1e_row2_col1\" class=\"data row2 col1\" >Steve Yzerman</td>\n",- " <td id=\"T_73a1e_row2_col2\" class=\"data row2 col2\" >{'2006–07 Detroit Red Wings season', 'Steve Yzerman'}</td>\n",- " <td id=\"T_73a1e_row2_col3\" class=\"data row2 col3\" >['Steve Yzerman | Stephen Gregory \"Steve\" Yzerman ( ; born May 9, 1965) is a Canadian retired professional ice hockey player and current general manager...</td>\n",- " <td id=\"T_73a1e_row2_col4\" class=\"data row2 col4\" >Steve Yzerman</td>\n",- " <td id=\"T_73a1e_row2_col5\" class=\"data row2 col5\" >✔️ [True]</td>\n",- " </tr>\n",- " <tr>\n",- " <th id=\"T_73a1e_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n",- " <td id=\"T_73a1e_row3_col0\" class=\"data row3 col0\" >What river is near the Crichton Collegiate Church?</td>\n",- " <td id=\"T_73a1e_row3_col1\" class=\"data row3 col1\" >the River Tyne</td>\n",- " <td id=\"T_73a1e_row3_col2\" class=\"data row3 col2\" >{'Crichton Castle', 'Crichton Collegiate Church'}</td>\n",- " <td id=\"T_73a1e_row3_col3\" class=\"data row3 col3\" >[\"Crichton Collegiate Church | Crichton Collegiate Church is situated about 0.6 mi south west of the hamlet of Crichton in Midlothian, Scotland. Crichton itself is...</td>\n",- " <td id=\"T_73a1e_row3_col4\" class=\"data row3 col4\" >River Tyne</td>\n",- " <td id=\"T_73a1e_row3_col5\" class=\"data row3 col5\" >✔️ [True]</td>\n",- " </tr>\n",- " <tr>\n",- " <th id=\"T_73a1e_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n",- " <td id=\"T_73a1e_row4_col0\" class=\"data row4 col0\" >In the 10th Century A.D. Ealhswith had a son called Æthelweard by which English king?</td>\n",- " <td id=\"T_73a1e_row4_col1\" class=\"data row4 col1\" >King Alfred the Great</td>\n",- " <td id=\"T_73a1e_row4_col2\" class=\"data row4 col2\" >{'Æthelweard (son of Alfred)', 'Ealhswith'}</td>\n",- " <td id=\"T_73a1e_row4_col3\" class=\"data row4 col3\" >[\"Æthelweard of East Anglia | Æthelweard (died 854) was a 9th-century king of East Anglia, the long-lived Anglo-Saxon kingdom which today includes the English counties...</td>\n",- " <td id=\"T_73a1e_row4_col4\" class=\"data row4 col4\" >Alfred the Great</td>\n",- " <td id=\"T_73a1e_row4_col5\" class=\"data row4 col5\" >❌ [False]</td>\n",- " </tr>\n",- " </tbody>\n",- "</table>\n"- ],- "text/plain": [- "<pandas.io.formats.style.Styler at 0x13ffa0610>"- ]- },- "metadata": {},- "output_type": "display_data"- },- {- "data": {- "text/html": [- "\n",- " <div style='\n",- " text-align: center; \n",- " font-size: 16px; \n",- " font-weight: bold; \n",- " color: #555; \n",- " margin: 10px 0;'>\n",- " ... 45 more rows not displayed ...\n",- " </div>\n",- " "- ],- "text/plain": [- "<IPython.core.display.HTML object>"- ]- },- "metadata": {},- "output_type": "display_data"- },- {- "data": {- "text/plain": [- "40.0"- ]- },- "execution_count": 12,- "metadata": {},- "output_type": "execute_result"- }- ],+ "outputs": [],"source": ["from dspy.evaluate.evaluate import Evaluate\n","\n",@@ -596,7 +456,7 @@},{"cell_type": "code",- "execution_count": 9,+ "execution_count": 7,"metadata": {},"outputs": [],"source": [@@ -610,12 +470,12 @@},{"cell_type": "code",- "execution_count": 10,+ "execution_count": 2,"metadata": {},"outputs": [],"source": ["from dsp.utils import deduplicate\n",- "from dspy import Assertions, Assert\n",+ "from dspy import Assertions, Assert, assert_transform\n","\n","class SimplifiedBaleen(dspy.Module):\n"," def __init__(self, passages_per_hop=3, max_hops=2):\n",@@ -649,6 +509,7 @@" self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n"," self.max_hops = max_hops\n"," \n",+ " @assert_transform(backtrack=2)\n"," def forward(self, question):\n"," context = []\n"," \n",@@ -658,7 +519,7 @@" # During compile time, this assertion might have some return value\n"," # If it's false, what shall we do? We do not have the python control flow.\n"," # can we do tracing to get control flow?\n",- " self.assertion(Assert(lambda: query not in query_so_far, query))\n",+ " self.assertion(Assert(lambda q: q not in query_so_far, query))\n"," passages = self.retrieve(query).passages\n"," context = deduplicate(context + passages)\n","\n",