prompt
stringlengths
131
11.8k
completion
stringlengths
7
173
api
stringlengths
11
48
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import pkg_resources try: # When on Colab, let's install pyserini, Pytorch, and Faiss import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') get_ipython().run_line_magic('cd', '$repo_path') get_ipython().system('pip install -e .') if not "pyserini" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install pyserini') if not "torch" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install torch') if not "faiss-cpu" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install faiss-cpu') except: repo_path = '.' if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') if repo_path not in sys.path: sys.path.append(repo_path) import dspy pys_ret_prebuilt = dspy.Pyserini(index='beir-v1.0.0-nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', id_field='_id', text_fields=['title', 'text'])
dspy.settings.configure(rm=pys_ret_prebuilt)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import pkg_resources try: # When on Colab, let's install pyserini, Pytorch, and Faiss import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') get_ipython().run_line_magic('cd', '$repo_path') get_ipython().system('pip install -e .') if not "pyserini" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install pyserini') if not "torch" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install torch') if not "faiss-cpu" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install faiss-cpu') except: repo_path = '.' if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') if repo_path not in sys.path: sys.path.append(repo_path) import dspy pys_ret_prebuilt = dspy.Pyserini(index='beir-v1.0.0-nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', id_field='_id', text_fields=['title', 'text']) dspy.settings.configure(rm=pys_ret_prebuilt) example_question = "How Curry Can Kill Cancer Cells" retrieve =
dspy.Retrieve(k=3)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import pkg_resources try: # When on Colab, let's install pyserini, Pytorch, and Faiss import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') get_ipython().run_line_magic('cd', '$repo_path') get_ipython().system('pip install -e .') if not "pyserini" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install pyserini') if not "torch" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install torch') if not "faiss-cpu" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install faiss-cpu') except: repo_path = '.' if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') if repo_path not in sys.path: sys.path.append(repo_path) import dspy pys_ret_prebuilt = dspy.Pyserini(index='beir-v1.0.0-nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', id_field='_id', text_fields=['title', 'text']) dspy.settings.configure(rm=pys_ret_prebuilt) example_question = "How Curry Can Kill Cancer Cells" retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(example_question).passages print(f"Top {retrieve.k} passages for question: {example_question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') get_ipython().system('wget https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/nfcorpus.zip -P collections') get_ipython().system('unzip collections/nfcorpus.zip -d collections') get_ipython().system('python -m pyserini.encode input --corpus collections/nfcorpus/corpus.jsonl --fields title text output --embeddings indexes/faiss.nfcorpus.contriever-msmarco --to-faiss encoder --encoder facebook/contriever-msmarco --device cuda:0 --pooling mean --fields title text') from datasets import load_dataset dataset = load_dataset(path='json', data_files='collections/nfcorpus/corpus.jsonl', split='train') pys_ret_local =
dspy.Pyserini(index='indexes/faiss.nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', dataset=dataset, id_field='_id', text_fields=['title', 'text'])
dspy.Pyserini
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import pkg_resources try: # When on Colab, let's install pyserini, Pytorch, and Faiss import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') get_ipython().run_line_magic('cd', '$repo_path') get_ipython().system('pip install -e .') if not "pyserini" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install pyserini') if not "torch" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install torch') if not "faiss-cpu" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install faiss-cpu') except: repo_path = '.' if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') if repo_path not in sys.path: sys.path.append(repo_path) import dspy pys_ret_prebuilt = dspy.Pyserini(index='beir-v1.0.0-nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', id_field='_id', text_fields=['title', 'text']) dspy.settings.configure(rm=pys_ret_prebuilt) example_question = "How Curry Can Kill Cancer Cells" retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(example_question).passages print(f"Top {retrieve.k} passages for question: {example_question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') get_ipython().system('wget https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/nfcorpus.zip -P collections') get_ipython().system('unzip collections/nfcorpus.zip -d collections') get_ipython().system('python -m pyserini.encode input --corpus collections/nfcorpus/corpus.jsonl --fields title text output --embeddings indexes/faiss.nfcorpus.contriever-msmarco --to-faiss encoder --encoder facebook/contriever-msmarco --device cuda:0 --pooling mean --fields title text') from datasets import load_dataset dataset = load_dataset(path='json', data_files='collections/nfcorpus/corpus.jsonl', split='train') pys_ret_local = dspy.Pyserini(index='indexes/faiss.nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', dataset=dataset, id_field='_id', text_fields=['title', 'text'])
dspy.settings.configure(rm=pys_ret_local)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import pkg_resources try: # When on Colab, let's install pyserini, Pytorch, and Faiss import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') get_ipython().run_line_magic('cd', '$repo_path') get_ipython().system('pip install -e .') if not "pyserini" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install pyserini') if not "torch" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install torch') if not "faiss-cpu" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install faiss-cpu') except: repo_path = '.' if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') if repo_path not in sys.path: sys.path.append(repo_path) import dspy pys_ret_prebuilt = dspy.Pyserini(index='beir-v1.0.0-nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', id_field='_id', text_fields=['title', 'text']) dspy.settings.configure(rm=pys_ret_prebuilt) example_question = "How Curry Can Kill Cancer Cells" retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(example_question).passages print(f"Top {retrieve.k} passages for question: {example_question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') get_ipython().system('wget https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/nfcorpus.zip -P collections') get_ipython().system('unzip collections/nfcorpus.zip -d collections') get_ipython().system('python -m pyserini.encode input --corpus collections/nfcorpus/corpus.jsonl --fields title text output --embeddings indexes/faiss.nfcorpus.contriever-msmarco --to-faiss encoder --encoder facebook/contriever-msmarco --device cuda:0 --pooling mean --fields title text') from datasets import load_dataset dataset = load_dataset(path='json', data_files='collections/nfcorpus/corpus.jsonl', split='train') pys_ret_local = dspy.Pyserini(index='indexes/faiss.nfcorpus.contriever-msmarco', query_encoder='facebook/contriever-msmarco', dataset=dataset, id_field='_id', text_fields=['title', 'text']) dspy.settings.configure(rm=pys_ret_local) dev_example = "How Curry Can Kill Cancer Cells" retrieve =
dspy.Retrieve(k=3)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama =
dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150)
dspy.HFClientTGI
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2, lm=llama)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict =
dspy.Predict('question -> answer')
dspy.Predict
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter =
BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2)
dspy.teleprompt.BootstrapFewShot
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot =
Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15)
dspy.evaluate.Evaluate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 =
BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS)
dspy.teleprompt.BootstrapFewShotWithRandomSearch
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer =
dspy.ChainOfThought('question -> answer')
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve =
dspy.Retrieve(k=num_passages)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query =
dspy.ChainOfThought("question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer =
dspy.ChainOfThought("context, question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve =
dspy.Retrieve(k=num_passages)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query =
dspy.ChainOfThought("question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_query_from_context =
dspy.ChainOfThought("context, question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_query_from_context = dspy.ChainOfThought("context, question -> search_query") self.generate_answer =
dspy.ChainOfThought("context, question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [
dspy.Example(question=question, answer=answer)
dspy.Example
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [
dspy.Example(question=question, answer=answer)
dspy.Example
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import dspy get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys; sys.path.append('/future/u/okhattab/repos/public/stanfordnlp/dspy') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_query_from_context = dspy.ChainOfThought("context, question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): passages = [] search_query = self.generate_query(question=question).search_query passages += self.retrieve(search_query).passages search_query = self.generate_query_from_context(context=passages, question=question).search_query passages += self.retrieve(search_query).passages return self.generate_answer(context=
deduplicate(passages)
dsp.utils.utils.deduplicate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo =
dspy.OpenAI(model='gpt-3.5-turbo')
dspy.OpenAI
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset =
HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0)
dspy.datasets.HotPotQA
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer =
dspy.Predict(BasicQA)
dspy.Predict
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought =
dspy.ChainOfThought(BasicQA)
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve =
dspy.Retrieve(k=3)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter =
BootstrapFewShot(metric=validate_context_and_answer)
dspy.teleprompt.BootstrapFewShot
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa =
Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5)
dspy.evaluate.evaluate.Evaluate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context = deduplicate(context + passages) pred = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=pred.answer) my_question = "How many storeys are in the castle that David Gregory inherited?" uncompiled_baleen = SimplifiedBaleen() # uncompiled (i.e., zero-shot) program pred = uncompiled_baleen(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=3) def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False hops = [example.question] + [outputs.query for *_, outputs in trace if 'query' in outputs] if max([len(h) for h in hops]) > 100: return False if any(dspy.evaluate.answer_exact_match_str(hops[idx], hops[:idx], frac=0.8) for idx in range(2, len(hops))): return False return True teleprompter =
BootstrapFewShot(metric=validate_context_and_answer_and_hops)
dspy.teleprompt.BootstrapFewShot
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question =
dspy.InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer =
dspy.OutputField(desc="often between 1 and 5 words")
dspy.OutputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context =
dspy.InputField(desc="may contain relevant facts")
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question =
dspy.InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer =
dspy.OutputField(desc="often between 1 and 5 words")
dspy.OutputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM =
dspy.evaluate.answer_exact_match(example, pred)
dspy.evaluate.answer_exact_match
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM =
dspy.evaluate.answer_passage_match(example, pred)
dspy.evaluate.answer_passage_match
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context =
dspy.InputField(desc="may contain relevant facts")
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question =
dspy.InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query =
dspy.OutputField()
dspy.OutputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve =
dspy.Retrieve(k=num_passages)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer =
dspy.ChainOfThought(GenerateAnswer)
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return
dspy.Prediction(context=context, answer=prediction.answer)
dspy.Prediction
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve =
dspy.Retrieve(k=passages_per_hop)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer =
dspy.ChainOfThought(GenerateAnswer)
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context = deduplicate(context + passages) pred = self.generate_answer(context=context, question=question) return
dspy.Prediction(context=context, answer=pred.answer)
dspy.Prediction
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context = deduplicate(context + passages) pred = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=pred.answer) my_question = "How many storeys are in the castle that David Gregory inherited?" uncompiled_baleen = SimplifiedBaleen() # uncompiled (i.e., zero-shot) program pred = uncompiled_baleen(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=3) def validate_context_and_answer_and_hops(example, pred, trace=None): if not
dspy.evaluate.answer_exact_match(example, pred)
dspy.evaluate.answer_exact_match
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context = deduplicate(context + passages) pred = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=pred.answer) my_question = "How many storeys are in the castle that David Gregory inherited?" uncompiled_baleen = SimplifiedBaleen() # uncompiled (i.e., zero-shot) program pred = uncompiled_baleen(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=3) def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not
dspy.evaluate.answer_passage_match(example, pred)
dspy.evaluate.answer_passage_match
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [
dspy.ChainOfThought(GenerateSearchQuery)
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context =
deduplicate(context + passages)
dsp.utils.deduplicate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install dspy-ai') get_ipython().system('pip install openai~=0.28.1') import dspy turbo = dspy.OpenAI(model='gpt-3.5-turbo') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(lm=turbo, rm=colbertv2_wiki17_abstracts) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] len(trainset), len(devset) train_example = trainset[0] print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") dev_example = devset[18] print(f"Question: {dev_example.question}") print(f"Answer: {dev_example.answer}") print(f"Relevant Wikipedia Titles: {dev_example.gold_titles}") print(f"For this dataset, training examples have input keys {train_example.inputs().keys()} and label keys {train_example.labels().keys()}") print(f"For this dataset, dev examples have input keys {dev_example.inputs().keys()} and label keys {dev_example.labels().keys()}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") generate_answer = dspy.Predict(BasicQA) pred = generate_answer(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Predicted Answer: {pred.answer}") turbo.inspect_history(n=1) generate_answer_with_chain_of_thought = dspy.ChainOfThought(BasicQA) pred = generate_answer_with_chain_of_thought(question=dev_example.question) print(f"Question: {dev_example.question}") print(f"Thought: {pred.rationale.split('.', 1)[1].strip()}") print(f"Predicted Answer: {pred.answer}") retrieve = dspy.Retrieve(k=3) topK_passages = retrieve(dev_example.question).passages print(f"Top {retrieve.k} passages for question: {dev_example.question} \n", '-' * 30, '\n') for idx, passage in enumerate(topK_passages): print(f'{idx+1}]', passage, '\n') retrieve("When was the first FIFA World Cup held?").passages[0] class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) from dspy.teleprompt import BootstrapFewShot def validate_context_and_answer(example, pred, trace=None): answer_EM = dspy.evaluate.answer_exact_match(example, pred) answer_PM = dspy.evaluate.answer_passage_match(example, pred) return answer_EM and answer_PM teleprompter = BootstrapFewShot(metric=validate_context_and_answer) compiled_rag = teleprompter.compile(RAG(), trainset=trainset) my_question = "What castle did David Gregory inherit?" pred = compiled_rag(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=1) for name, parameter in compiled_rag.named_predictors(): print(name) print(parameter.demos[0]) print() from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5) metric = dspy.evaluate.answer_exact_match evaluate_on_hotpotqa(compiled_rag, metric=metric) def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) compiled_rag_retrieval_score = evaluate_on_hotpotqa(compiled_rag, metric=gold_passages_retrieved) class GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField() from dsp.utils import deduplicate class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=3, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops def forward(self, question): context = [] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query passages = self.retrieve(query).passages context = deduplicate(context + passages) pred = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=pred.answer) my_question = "How many storeys are in the castle that David Gregory inherited?" uncompiled_baleen = SimplifiedBaleen() # uncompiled (i.e., zero-shot) program pred = uncompiled_baleen(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {pred.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}") turbo.inspect_history(n=3) def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False hops = [example.question] + [outputs.query for *_, outputs in trace if 'query' in outputs] if max([len(h) for h in hops]) > 100: return False if any(
dspy.evaluate.answer_exact_match_str(hops[idx], hops[:idx], frac=0.8)
dspy.evaluate.answer_exact_match_str
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500)
dspy.settings.configure(lm=lm)
dspy.settings.configure
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset =
HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0)
dspy.datasets.HotPotQA
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] train_example = trainset[0] print(train_example) print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class BasicQABot(dspy.Module): def __init__(self): super().__init__() self.generate = dspy.Predict(BasicQA) def forward(self,question): prediction = self.generate(question = question) return dspy.Prediction(answer = prediction.answer) qa_bot = BasicQABot() pred = qa_bot.forward("In the 10th Century A.D. Ealhswith had a son called Æthelweard by which English king?") pred.answer from dspy.teleprompt import KNNFewShot from dspy.predict.knn import KNN knn_teleprompter =
KNNFewShot(KNN, 7, trainset)
dspy.teleprompt.KNNFewShot
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] train_example = trainset[0] print(train_example) print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class BasicQABot(dspy.Module): def __init__(self): super().__init__() self.generate = dspy.Predict(BasicQA) def forward(self,question): prediction = self.generate(question = question) return dspy.Prediction(answer = prediction.answer) qa_bot = BasicQABot() pred = qa_bot.forward("In the 10th Century A.D. Ealhswith had a son called Æthelweard by which English king?") pred.answer from dspy.teleprompt import KNNFewShot from dspy.predict.knn import KNN knn_teleprompter = KNNFewShot(KNN, 7, trainset) compiled_knn = knn_teleprompter.compile(BasicQABot(), trainset=trainset) example = devset[0] pred = compiled_knn(question = example.question) print("Question: ", example.question) print("Expected answer: ", example.answer) print("Prediction: ", pred.answer) lm.inspect_history(1) from dspy.evaluate.evaluate import Evaluate evaluate_on_hotpotqa =
Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5)
dspy.evaluate.evaluate.Evaluate
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] train_example = trainset[0] print(train_example) print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question =
dspy.InputField()
dspy.InputField
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] train_example = trainset[0] print(train_example) print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer =
dspy.OutputField(desc="often between 1 and 5 words")
dspy.OutputField
import openai import dspy import json with open("creds.json", "r") as creds: api_key = json.loads(creds.read())["openai_key"] lm = dspy.OpenAI(model='gpt-4', api_key=api_key, model_type='chat', max_tokens = 500) dspy.settings.configure(lm=lm) from dspy.datasets import HotPotQA dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] train_example = trainset[0] print(train_example) print(f"Question: {train_example.question}") print(f"Answer: {train_example.answer}") class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class BasicQABot(dspy.Module): def __init__(self): super().__init__() self.generate =
dspy.Predict(BasicQA)
dspy.Predict