Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Add assertion draft

Shangyint834f95ec0e60
diff --git a/dspy/__init__.py b/dspy/__init__.py
index 84d1487f1..26ea97644 100644
--- a/dspy/__init__.py
+++ b/dspy/__init__.py
@@ -4,6 +4,7 @@ from .signatures import *
from .retrieve import *
from .predict import *
from .primitives import *
+from .assertions import *
# from .evaluation import *
@@ -18,4 +19,6 @@ OpenAI = dsp.GPT3
ColBERTv2 = dsp.ColBERTv2
Pyserini = dsp.PyseriniRetriever
HFClientTGI = dsp.HFClientTGI
-ChatModuleClient = ChatModuleClient
\ No newline at end of file
+ChatModuleClient = ChatModuleClient
+
+print("Running from local DSPy package.")
\ No newline at end of file
diff --git a/dspy/assertions/__init__.py b/dspy/assertions/__init__.py
new file mode 100644
index 000000000..ca1facabb
--- /dev/null
+++ b/dspy/assertions/__init__.py
@@ -0,0 +1 @@
+from .assertions import *
\ No newline at end of file
diff --git a/dspy/assertions/assertions.py b/dspy/assertions/assertions.py
new file mode 100644
index 000000000..18b3f0014
--- /dev/null
+++ b/dspy/assertions/assertions.py
@@ -0,0 +1,41 @@
+# Note(shangyin): What abstractions we want to make about assertions?
+# things to consider: what we want to assert, and what would be the syntax?
+# One possible starting point would be constraints on the output of a module
+from typing import Any
+import dspy
+
+# compile time assertion
+class Assert:
+ def __init__(self, assert_fun, *args, **kwargs):
+ self.assert_fun = assert_fun
+ self.args = args
+ self.kwargs = kwargs
+
+ # assert fun should always return bool
+ def __call__(self) -> list[bool]:
+ result = self.assert_fun(*self.args, **self.kwargs)
+ if isinstance(result, bool):
+ return [result]
+ elif isinstance(result, list) and all(isinstance(x, bool) for x in result):
+ return result
+ else:
+ raise ValueError("Assertion function should always return [bool]")
+
+# we could possibly to have runtime assertions as well
+# class RuntimeAssert(Assert): ...
+
+
+class Assertions(dspy.Module):
+ def __init__(self) -> None:
+ self.assertions = []
+
+ def add(self, assertion: Assert):
+ self.assertions.append(assertion)
+
+ def __call__(self, assertion: Assert):
+ self.add(assertion)
+ if self._compiled:
+ return True
+ else:
+ return assertion()
+
diff --git a/tot_assertion.ipynb b/tot_assertion.ipynb
new file mode 100644
index 000000000..68ffd7d39
--- /dev/null
+++ b/tot_assertion.ipynb
@@ -0,0 +1,699 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Running from local DSPy package.\n"
+ ]
+ }
+ ],
+ "source": [
+ "import dspy\n",
+ "import os\n",
+ "\n",
+ "# To set the OPENAI_API_KEY environment variable,\n",
+ "# put it in a file named .env in the same directory as this file.\n",
+ "API_KEY = os.environ.get(\"OPENAI_API_KEY\")\n",
+ "assert API_KEY is not None, \"Please set your OPENAI_API_KEY environment variable.\"\n",
+ "\n",
+ "turbo = dspy.OpenAI(model='gpt-3.5-turbo', api_key=API_KEY)\n",
+ "\n",
+ "colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')\n",
+ "\n",
+ "dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "3.11.5 | packaged by conda-forge | (main, Aug 27 2023, 03:33:12) [Clang 15.0.7 ]\n"
+ ]
+ }
+ ],
+ "source": [
+ "import sys\n",
+ "print(sys.version)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(20, 50)"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "from dspy.datasets import HotPotQA\n",
+ "\n",
+ "# Load the dataset.\n",
+ "dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0)\n",
+ "\n",
+ "# Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata.\n",
+ "trainset = [x.with_inputs('question') for x in dataset.train]\n",
+ "devset = [x.with_inputs('question') for x in dataset.dev]\n",
+ "\n",
+ "len(trainset), len(devset)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Question: At My Window was released by which American singer-songwriter?\n",
+ "Answer: John Townes Van Zandt\n",
+ "Question: What is the nationality of the chef and restaurateur featured in Restaurant: Impossible?\n",
+ "Answer: English\n",
+ "Relevant Wikipedia Titles: {'Restaurant: Impossible', 'Robert Irvine'}\n"
+ ]
+ }
+ ],
+ "source": [
+ "train_example = trainset[0]\n",
+ "print(f\"Question: {train_example.question}\")\n",
+ "print(f\"Answer: {train_example.answer}\")\n",
+ "\n",
+ "dev_example = devset[18]\n",
+ "print(f\"Question: {dev_example.question}\")\n",
+ "print(f\"Answer: {dev_example.answer}\")\n",
+ "print(f\"Relevant Wikipedia Titles: {dev_example.gold_titles}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Question: What is the nationality of the chef and restaurateur featured in Restaurant: Impossible?\n",
+ "Predicted Answer: American\n"
+ ]
+ }
+ ],
+ "source": [
+ "class BasicQA(dspy.Signature):\n",
+ " \"\"\"Answer questions with short factoid answers.\"\"\"\n",
+ "\n",
+ " question = dspy.InputField()\n",
+ " answer = dspy.OutputField(desc=\"often between 1 and 5 words\")\n",
+ "\n",
+ "# Define the predictor.\n",
+ "generate_answer = dspy.Predict(BasicQA)\n",
+ "\n",
+ "# Call the predictor on a particular input.\n",
+ "pred = generate_answer(question=dev_example.question)\n",
+ "\n",
+ "# Print the input and the prediction.\n",
+ "print(f\"Question: {dev_example.question}\")\n",
+ "print(f\"Predicted Answer: {pred.answer}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Answer questions with short factoid answers.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Question: ${question}\n",
+ "Answer: often between 1 and 5 words\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Question: What is the nationality of the chef and restaurateur featured in Restaurant: Impossible?\n",
+ "Answer:\u001b[32m American\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "turbo.inspect_history(n=1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Question: What is the nationality of the chef and restaurateur featured in Restaurant: Impossible?\n",
+ "Thought: We know that the chef and restaurateur featured in Restaurant: Impossible is Robert Irvine.\n",
+ "Predicted Answer: British\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Define the predictor. Notice we're just changing the class. The signature BasicQA is unchanged.\n",
+ "generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA)\n",
+ "\n",
+ "# Call the predictor on the same input.\n",
+ "pred = generate_answer_with_chain_of_thought(question=dev_example.question)\n",
+ "\n",
+ "# Print the input, the chain of thought, and the prediction.\n",
+ "print(f\"Question: {dev_example.question}\")\n",
+ "print(f\"Thought: {pred.rationale.split('.', 1)[1].strip()}\")\n",
+ "print(f\"Predicted Answer: {pred.answer}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class GenerateAnswer(dspy.Signature):\n",
+ " \"\"\"Answer questions with short factoid answers.\"\"\"\n",
+ "\n",
+ " context = dspy.InputField(desc=\"may contain relevant facts\")\n",
+ " question = dspy.InputField()\n",
+ " answer = dspy.OutputField(desc=\"often between 1 and 5 words\")\n",
+ "\n",
+ "class RAG(dspy.Module):\n",
+ " def __init__(self, num_passages=3):\n",
+ " super().__init__()\n",
+ "\n",
+ " self.retrieve = dspy.Retrieve(k=num_passages)\n",
+ " self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n",
+ " \n",
+ " def forward(self, question):\n",
+ " context = self.retrieve(question).passages\n",
+ " prediction = self.generate_answer(context=context, question=question)\n",
+ " return dspy.Prediction(context=context, answer=prediction.answer)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 55%|█████▌ | 11/20 [00:28<00:23, 2.60s/it]\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Bootstrapped 4 full traces after 12 examples in round 0.\n",
+ "Question: What castle did David Gregory inherit?\n",
+ "Predicted Answer: Kinnairdy Castle\n",
+ "Retrieved Contexts (truncated): ['David Gregory (physician) | David Gregory (20 December 1625 – 1720) was a Scottish physician and inventor. His surname is sometimes spelt as Gregorie, the original Scottish spelling. He inherited Kinn...', 'Gregory Tarchaneiotes | Gregory Tarchaneiotes (Greek: Γρηγόριος Ταρχανειώτης , Italian: \"Gregorio Tracanioto\" or \"Tracamoto\" ) was a \"protospatharius\" and the long-reigning catepan of Italy from 998 t...', 'David Gregory (mathematician) | David Gregory (originally spelt Gregorie) FRS (? 1659 – 10 October 1708) was a Scottish mathematician and astronomer. He was professor of mathematics at the University ...']\n"
+ ]
+ }
+ ],
+ "source": [
+ "from dspy.teleprompt import BootstrapFewShot\n",
+ "\n",
+ "# Validation logic: check that the predicted answer is correct.\n",
+ "# Also check that the retrieved context does actually contain that answer.\n",
+ "def validate_context_and_answer(example, pred, trace=None):\n",
+ " answer_EM = dspy.evaluate.answer_exact_match(example, pred)\n",
+ " answer_PM = dspy.evaluate.answer_passage_match(example, pred)\n",
+ " return answer_EM and answer_PM\n",
+ "\n",
+ "# Set up a basic teleprompter, which will compile our RAG program.\n",
+ "teleprompter = BootstrapFewShot(metric=validate_context_and_answer)\n",
+ "\n",
+ "# Compile!\n",
+ "compiled_rag = teleprompter.compile(RAG(), trainset=trainset)\n",
+ "\n",
+ "# Ask any question you like to this simple RAG program.\n",
+ "my_question = \"What castle did David Gregory inherit?\"\n",
+ "\n",
+ "# Get the prediction. This contains `pred.context` and `pred.answer`.\n",
+ "pred = compiled_rag(my_question)\n",
+ "\n",
+ "# Print the contexts and the answer.\n",
+ "print(f\"Question: {my_question}\")\n",
+ "print(f\"Predicted Answer: {pred.answer}\")\n",
+ "print(f\"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Answer questions with short factoid answers.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Question: At My Window was released by which American singer-songwriter?\n",
+ "Answer: John Townes Van Zandt\n",
+ "\n",
+ "Question: \"Everything Has Changed\" is a song from an album released under which record label ?\n",
+ "Answer: Big Machine Records\n",
+ "\n",
+ "Question: The Victorians - Their Story In Pictures is a documentary series written by an author born in what year?\n",
+ "Answer: 1950\n",
+ "\n",
+ "Question: Which Pakistani cricket umpire who won 3 consecutive ICC umpire of the year awards in 2009, 2010, and 2011 will be in the ICC World Twenty20?\n",
+ "Answer: Aleem Sarwar Dar\n",
+ "\n",
+ "Question: Having the combination of excellent foot speed and bat speed helped Eric Davis, create what kind of outfield for the Los Angeles Dodgers?\n",
+ "Answer: \"Outfield of Dreams\"\n",
+ "\n",
+ "Question: Who is older, Aleksandr Danilovich Aleksandrov or Anatoly Fomenko?\n",
+ "Answer: Aleksandr Danilovich Aleksandrov\n",
+ "\n",
+ "Question: The Organisation that allows a community to influence their operation or use and to enjoy the benefits arisingwas founded in what year?\n",
+ "Answer: 2010\n",
+ "\n",
+ "Question: Tombstone stared an actor born May 17, 1955 known as who?\n",
+ "Answer: Bill Paxton\n",
+ "\n",
+ "Question: In what year was the club founded that played Manchester City in the 1972 FA Charity Shield\n",
+ "Answer: 1874\n",
+ "\n",
+ "Question: which American actor was Candace Kita guest starred with\n",
+ "Answer: Bill Murray\n",
+ "\n",
+ "Question: Which is taller, the Empire State Building or the Bank of America Tower?\n",
+ "Answer: The Empire State Building\n",
+ "\n",
+ "Question: Which company distributed this 1977 American animated film produced by Walt Disney Productions for which Sherman Brothers wrote songs?\n",
+ "Answer: Buena Vista Distribution\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Context: may contain relevant facts\n",
+ "\n",
+ "Question: ${question}\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to ${produce the answer}. We ...\n",
+ "\n",
+ "Answer: often between 1 and 5 words\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Context:\n",
+ "[1] «Tae Kwon Do Times | Tae Kwon Do Times is a magazine devoted to the martial art of taekwondo, and is published in the United States of America. While the title suggests that it focuses on taekwondo exclusively, the magazine also covers other Korean martial arts. \"Tae Kwon Do Times\" has published articles by a wide range of authors, including He-Young Kimm, Thomas Kurz, Scott Shaw, and Mark Van Schuyver.»\n",
+ "[2] «Kwon Tae-man | Kwon Tae-man (born 1941) was an early Korean hapkido practitioner and a pioneer of the art, first in Korea and then in the United States. He formed one of the earliest dojang's for hapkido in the United States in Torrance, California, and has been featured in many magazine articles promoting the art.»\n",
+ "[3] «Hee Il Cho | Cho Hee Il (born October 13, 1940) is a prominent Korean-American master of taekwondo, holding the rank of 9th \"dan\" in the martial art. He has written 11 martial art books, produced 70 martial art training videos, and has appeared on more than 70 martial arts magazine covers. Cho won several national and international competitions as a taekwondo competitor, and has appeared in several films, including \"Fight to Win\", \"Best of the Best\", \"Bloodsport II\", and \"Bloodsport III\". He founded the Action International Martial Arts Association (AIMAA) in 1980, and is its President. Cho is a member of both \"Black Belt\" magazine's Hall of Fame and \"Tae Kwon Do Times\" magazine's Hall of Fame.»\n",
+ "\n",
+ "Question: Which magazine has published articles by Scott Shaw, Tae Kwon Do Times or Southwest Art?\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to produce the answer. We know from the context that \"Tae Kwon Do Times\" is a magazine that covers taekwondo and other Korean martial arts. It has published articles by authors like Scott Shaw. On the other hand, there is no information about Southwest Art magazine in the context.\n",
+ "\n",
+ "Answer: Tae Kwon Do Times\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Context:\n",
+ "[1] «Rosario Dawson | Rosario Isabel Dawson (born May 9, 1979) is an American actress, producer, singer, comic book writer, and political activist. She made her film debut in the 1995 teen drama \"Kids\". Her subsequent film roles include \"He Got Game\", \"Men in Black II\", \"25th Hour\", \"Rent\", \"Sin City\", \"Death Proof\", \"Seven Pounds\", \"\", and \"Top Five\". Dawson has also provided voice-over work for Disney and DC.»\n",
+ "[2] «Sarai Gonzalez | Sarai Isaura Gonzalez (born 2005) is an American Latina child actress who made her professional debut at the age of 11 on the Spanish-language \"\"Soy Yo\"\" (\"That's Me\") music video by Bomba Estéreo. Cast as a \"nerdy\" tween with a \"sassy\" and \"confident\" attitude, her performance turned her into a \"Latina icon\" for \"female empowerment, identity and self-worth\". She subsequently appeared in two get out the vote videos for Latinos in advance of the 2016 United States elections.»\n",
+ "[3] «Gabriela (2001 film) | Gabriela is a 2001 American romance film, starring Seidy Lopez in the title role alongside Jaime Gomez as her admirer Mike. The film has been cited as an inspiration behind the Premiere Weekend Club, which supports Latino film-making.»\n",
+ "\n",
+ "Question: Which American actress who made their film debut in the 1995 teen drama \"Kids\" was the co-founder of Voto Latino?\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to produce the answer. We know that the actress made her film debut in 1995 and co-founded Voto Latino.\n",
+ "\n",
+ "Answer: Rosario Dawson\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Context:\n",
+ "[1] «Battle of Kursk | The Battle of Kursk was a Second World War engagement between German and Soviet forces on the Eastern Front near Kursk (450 km south-west of Moscow) in the Soviet Union during July and August 1943. The battle began with the launch of the German offensive, Operation Citadel (German: \"Unternehmen Zitadelle\" ), on 5 July, which had the objective of pinching off the Kursk salient with attacks on the base of the salient from north and south simultaneously. After the German offensive stalled on the northern side of the salient, on 12 July the Soviets commenced their Kursk Strategic Offensive Operation with the launch of Operation Kutuzov (Russian: Кутузов ) against the rear of the German forces in the northern side. On the southern side, the Soviets also launched powerful counterattacks the same day, one of which led to a large armoured clash, the Battle of Prokhorovka. On 3 August, the Soviets began the second phase of the Kursk Strategic Offensive Operation with the launch of Operation Polkovodets Rumyantsev (Russian: Полководец Румянцев ) against the German forces in the southern side of the Kursk salient.»\n",
+ "[2] «Operation Mars | Operation Mars, also known as the Second Rzhev-Sychevka Offensive Operation (Russian: Вторая Ржевско-Сычёвская наступательная операция), was the codename for an offensive launched by Soviet forces against German forces during World War II. It took place between 25 November and 20 December 1942 around the Rzhev salient in the vicinity of Moscow.»\n",
+ "[3] «Kholm Pocket | The Kholm Pocket (German: \"Kessel von Cholm\" ; Russian: Холмский котёл ) was the name given for the encirclement of German troops by the Red Army around Kholm south of Leningrad, during World War II on the Eastern Front, from 23 January 1942 until 5 May 1942. A much larger pocket was simultaneously surrounded in Demyansk, about 100 km to the northeast. These were the results of German retreat following their defeat during the Battle of Moscow.»\n",
+ "\n",
+ "Question: What is the code name for the German offensive that started this Second World War engagement on the Eastern Front (a few hundred kilometers from Moscow) between Soviet and German forces, which included 102nd Infantry Division?\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to produce the answer. We know that the German offensive that started the Battle of Kursk was called Operation Citadel. We also know that the Battle of Kursk took place on the Eastern Front, a few hundred kilometers from Moscow. Additionally, we know that the 102nd Infantry Division was involved in this battle.\n",
+ "\n",
+ "Answer: Operation Citadel\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Context:\n",
+ "[1] «Kerry Condon | Kerry Condon (born 4 January 1983) is an Irish television and film actress, best known for her role as Octavia of the Julii in the HBO/BBC series \"Rome,\" as Stacey Ehrmantraut in AMC's \"Better Call Saul\" and as the voice of F.R.I.D.A.Y. in various films in the Marvel Cinematic Universe. She is also the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of \"Hamlet.\"»\n",
+ "[2] «Corona Riccardo | Corona Riccardo (c. 1878October 15, 1917) was an Italian born American actress who had a brief Broadway stage career before leaving to become a wife and mother. Born in Naples she came to acting in 1894 playing a Mexican girl in a play at the Empire Theatre. Wilson Barrett engaged her for a role in his play \"The Sign of the Cross\" which he took on tour of the United States. Riccardo played the role of Ancaria and later played Berenice in the same play. Robert B. Mantell in 1898 who struck by her beauty also cast her in two Shakespeare plays, \"Romeo and Juliet\" and \"Othello\". Author Lewis Strang writing in 1899 said Riccardo was the most promising actress in America at the time. Towards the end of 1898 Mantell chose her for another Shakespeare part, Ophelia im Hamlet. Afterwards she was due to join Augustin Daly's Theatre Company but Daly died in 1899. In 1899 she gained her biggest fame by playing Iras in the first stage production of Ben-Hur.»\n",
+ "[3] «Judi Dench | Dame Judith Olivia \"Judi\" Dench, {'1': \", '2': \", '3': \", '4': \"} (born 9 December 1934) is an English actress and author. Dench made her professional debut in 1957 with the Old Vic Company. Over the following few years, she performed in several of Shakespeare's plays in such roles as Ophelia in \"Hamlet\", Juliet in \"Romeo and Juliet\", and Lady Macbeth in \"Macbeth\". Although most of her work during this period was in theatre, she also branched into film work and won a BAFTA Award as Most Promising Newcomer. She drew strong reviews for her leading role in the musical \"Cabaret\" in 1968.»\n",
+ "\n",
+ "Question: Who acted in the shot film The Shore and is also the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of \"Hamlet.\" ?\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to produce the answer. We know that the actress we are looking for is the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of \"Hamlet.\" We also know that she acted in the short film The Shore.\n",
+ "\n",
+ "Answer: Kerry Condon\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Context:\n",
+ "[1] «David Gregory (physician) | David Gregory (20 December 1625 – 1720) was a Scottish physician and inventor. His surname is sometimes spelt as Gregorie, the original Scottish spelling. He inherited Kinnairdy Castle in 1664. Three of his twenty-nine children became mathematics professors. He is credited with inventing a military cannon that Isaac Newton described as \"being destructive to the human species\". Copies and details of the model no longer exist. Gregory's use of a barometer to predict farming-related weather conditions led him to be accused of witchcraft by Presbyterian ministers from Aberdeen, although he was never convicted.»\n",
+ "[2] «Gregory Tarchaneiotes | Gregory Tarchaneiotes (Greek: Γρηγόριος Ταρχανειώτης , Italian: \"Gregorio Tracanioto\" or \"Tracamoto\" ) was a \"protospatharius\" and the long-reigning catepan of Italy from 998 to 1006. In December 999, and again on February 2, 1002, he reinstituted and confirmed the possessions of the abbey and monks of Monte Cassino in Ascoli. In 1004, he fortified and expanded the castle of Dragonara on the Fortore. He gave it three circular towers and one square one. He also strengthened Lucera.»\n",
+ "[3] «David Gregory (mathematician) | David Gregory (originally spelt Gregorie) FRS (? 1659 – 10 October 1708) was a Scottish mathematician and astronomer. He was professor of mathematics at the University of Edinburgh, Savilian Professor of Astronomy at the University of Oxford, and a commentator on Isaac Newton's \"Principia\".»\n",
+ "\n",
+ "Question: What castle did David Gregory inherit?\n",
+ "\n",
+ "Reasoning: Let's think step by step in order to\u001b[32m produce the answer. We know that David Gregory inherited a castle. The name of the castle is mentioned in the context.\n",
+ "\n",
+ "Answer: Kinnairdy Castle\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "turbo.inspect_history(n=1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "generate_answer\n",
+ "Example({'augmented': True, 'context': ['Tae Kwon Do Times | Tae Kwon Do Times is a magazine devoted to the martial art of taekwondo, and is published in the United States of America. While the title suggests that it focuses on taekwondo exclusively, the magazine also covers other Korean martial arts. \"Tae Kwon Do Times\" has published articles by a wide range of authors, including He-Young Kimm, Thomas Kurz, Scott Shaw, and Mark Van Schuyver.', \"Kwon Tae-man | Kwon Tae-man (born 1941) was an early Korean hapkido practitioner and a pioneer of the art, first in Korea and then in the United States. He formed one of the earliest dojang's for hapkido in the United States in Torrance, California, and has been featured in many magazine articles promoting the art.\", 'Hee Il Cho | Cho Hee Il (born October 13, 1940) is a prominent Korean-American master of taekwondo, holding the rank of 9th \"dan\" in the martial art. He has written 11 martial art books, produced 70 martial art training videos, and has appeared on more than 70 martial arts magazine covers. Cho won several national and international competitions as a taekwondo competitor, and has appeared in several films, including \"Fight to Win\", \"Best of the Best\", \"Bloodsport II\", and \"Bloodsport III\". He founded the Action International Martial Arts Association (AIMAA) in 1980, and is its President. Cho is a member of both \"Black Belt\" magazine\\'s Hall of Fame and \"Tae Kwon Do Times\" magazine\\'s Hall of Fame.'], 'question': 'Which magazine has published articles by Scott Shaw, Tae Kwon Do Times or Southwest Art?', 'rationale': 'produce the answer. We know from the context that \"Tae Kwon Do Times\" is a magazine that covers taekwondo and other Korean martial arts. It has published articles by authors like Scott Shaw. On the other hand, there is no information about Southwest Art magazine in the context.', 'answer': 'Tae Kwon Do Times'}) (input_keys=None)\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "for name, parameter in compiled_rag.named_predictors():\n",
+ " print(name)\n",
+ " print(parameter.demos[0])\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "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\" >&nbsp;</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"
+ }
+ ],
+ "source": [
+ "from dspy.evaluate.evaluate import Evaluate\n",
+ "\n",
+ "# Set up the `evaluate_on_hotpotqa` function. We'll use this many times below.\n",
+ "evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5)\n",
+ "\n",
+ "# Evaluate the `compiled_rag` program with the `answer_exact_match` metric.\n",
+ "metric = dspy.evaluate.answer_exact_match\n",
+ "evaluate_on_hotpotqa(compiled_rag, metric=metric)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class GenerateSearchQuery(dspy.Signature):\n",
+ " \"\"\"Write a simple search query that will help answer a complex question.\"\"\"\n",
+ "\n",
+ " context = dspy.InputField(desc=\"may contain relevant facts\")\n",
+ " question = dspy.InputField()\n",
+ " query = dspy.OutputField()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from dsp.utils import deduplicate\n",
+ "from dspy import Assertions, Assert\n",
+ "\n",
+ "class SimplifiedBaleen(dspy.Module):\n",
+ " def __init__(self, passages_per_hop=3, max_hops=2):\n",
+ " super().__init__()\n",
+ "\n",
+ " self.assertion = Assertions()\n",
+ " self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n",
+ " self.retrieve = dspy.Retrieve(k=passages_per_hop)\n",
+ " self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n",
+ " self.max_hops = max_hops\n",
+ " \n",
+ " def forward(self, question):\n",
+ " context = []\n",
+ " \n",
+ " for hop in range(self.max_hops):\n",
+ " query = self.generate_query[hop](context=context, question=question).query\n",
+ " passages = self.retrieve(query).passages\n",
+ " context = deduplicate(context + passages)\n",
+ "\n",
+ " pred = self.generate_answer(context=context, question=question)\n",
+ " return dspy.Prediction(context=context, answer=pred.answer)\n",
+ " \n",
+ "# How to backtrack?\n",
+ "class SimplifiedBaleenWithAssertion(dspy.Module):\n",
+ " def __init__(self, passages_per_hop=3, max_hops=2):\n",
+ " super().__init__()\n",
+ "\n",
+ " self.assertion = Assertions()\n",
+ " self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n",
+ " self.retrieve = dspy.Retrieve(k=passages_per_hop)\n",
+ " self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n",
+ " self.max_hops = max_hops\n",
+ " \n",
+ " def forward(self, question):\n",
+ " context = []\n",
+ " \n",
+ " query_so_far = [] \n",
+ " for hop in range(self.max_hops):\n",
+ " query = self.generate_query[hop](context=context, question=question).query\n",
+ " # 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",
+ " passages = self.retrieve(query).passages\n",
+ " context = deduplicate(context + passages)\n",
+ "\n",
+ " pred = self.generate_answer(context=context, question=question)\n",
+ " return dspy.Prediction(context=context, answer=pred.answer)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "dspy",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.5"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}