prompt
stringlengths 131
11.8k
| completion
stringlengths 7
173
| api
stringlengths 11
48
|
---|---|---|
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = | dspy.InputField(desc="may contain relevant facts") | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = | dspy.OutputField(desc="includes citations") | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = | dspy.InputField(desc="may contain relevant facts") | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = | dspy.InputField(desc="between 1 to 2 sentences") | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = | dspy.OutputField(desc="boolean indicating if text is faithful to context") | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = | dspy.ChainOfThought(CheckCitationFaithfulness) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = | normalize_text(pred.paragraph) | dsp.utils.normalize_text |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = | dspy.ChainOfThought(GenerateCitedParagraph) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = | dspy.Prediction(context=context, paragraph=pred.paragraph) | dspy.Prediction |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any(normalize_text(answer) in normalized_context for answer in gold_answers) else 0
def evaluate(module):
correctness_values = []
recall_values = []
precision_values = []
citation_faithfulness_values = []
for i in range(len(devset)):
example = devset[i]
try:
pred = module(question=example.question)
correctness_values.append(answer_correctness(example, pred))
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
citation_faithfulness_values.append(citation_faithfulness_score)
recall = calculate_recall(example, pred)
precision = calculate_precision(example, pred)
recall_values.append(recall)
precision_values.append(precision)
except Exception as e:
print(f"Failed generation with error: {e}")
average_correctness = sum(correctness_values) / len(devset) if correctness_values else 0
average_recall = sum(recall_values) / len(devset) if recall_values else 0
average_precision = sum(precision_values) / len(devset) if precision_values else 0
average_citation_faithfulness = sum(citation_faithfulness_values) / len(devset) if citation_faithfulness_values else 0
print(f"Average Correctness: {average_correctness}")
print(f"Average Recall: {average_recall}")
print(f"Average Precision: {average_precision}")
print(f"Average Citation Faithfulness: {average_citation_faithfulness}")
longformqa = LongFormQA()
evaluate(longformqa)
question = devset[6].question
pred = longformqa(question)
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
print(f"Question: {question}")
print(f"Predicted Paragraph: {pred.paragraph}")
print(f"Citation Faithfulness: {citation_faithfulness_score}")
class LongFormQAWithAssertions(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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any(normalize_text(answer) in normalized_context for answer in gold_answers) else 0
def evaluate(module):
correctness_values = []
recall_values = []
precision_values = []
citation_faithfulness_values = []
for i in range(len(devset)):
example = devset[i]
try:
pred = module(question=example.question)
correctness_values.append(answer_correctness(example, pred))
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
citation_faithfulness_values.append(citation_faithfulness_score)
recall = calculate_recall(example, pred)
precision = calculate_precision(example, pred)
recall_values.append(recall)
precision_values.append(precision)
except Exception as e:
print(f"Failed generation with error: {e}")
average_correctness = sum(correctness_values) / len(devset) if correctness_values else 0
average_recall = sum(recall_values) / len(devset) if recall_values else 0
average_precision = sum(precision_values) / len(devset) if precision_values else 0
average_citation_faithfulness = sum(citation_faithfulness_values) / len(devset) if citation_faithfulness_values else 0
print(f"Average Correctness: {average_correctness}")
print(f"Average Recall: {average_recall}")
print(f"Average Precision: {average_precision}")
print(f"Average Citation Faithfulness: {average_citation_faithfulness}")
longformqa = LongFormQA()
evaluate(longformqa)
question = devset[6].question
pred = longformqa(question)
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
print(f"Question: {question}")
print(f"Predicted Paragraph: {pred.paragraph}")
print(f"Citation Faithfulness: {citation_faithfulness_score}")
class LongFormQAWithAssertions(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_cited_paragraph = | dspy.ChainOfThought(GenerateCitedParagraph) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any(normalize_text(answer) in normalized_context for answer in gold_answers) else 0
def evaluate(module):
correctness_values = []
recall_values = []
precision_values = []
citation_faithfulness_values = []
for i in range(len(devset)):
example = devset[i]
try:
pred = module(question=example.question)
correctness_values.append(answer_correctness(example, pred))
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
citation_faithfulness_values.append(citation_faithfulness_score)
recall = calculate_recall(example, pred)
precision = calculate_precision(example, pred)
recall_values.append(recall)
precision_values.append(precision)
except Exception as e:
print(f"Failed generation with error: {e}")
average_correctness = sum(correctness_values) / len(devset) if correctness_values else 0
average_recall = sum(recall_values) / len(devset) if recall_values else 0
average_precision = sum(precision_values) / len(devset) if precision_values else 0
average_citation_faithfulness = sum(citation_faithfulness_values) / len(devset) if citation_faithfulness_values else 0
print(f"Average Correctness: {average_correctness}")
print(f"Average Recall: {average_recall}")
print(f"Average Precision: {average_precision}")
print(f"Average Citation Faithfulness: {average_citation_faithfulness}")
longformqa = LongFormQA()
evaluate(longformqa)
question = devset[6].question
pred = longformqa(question)
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
print(f"Question: {question}")
print(f"Predicted Paragraph: {pred.paragraph}")
print(f"Citation Faithfulness: {citation_faithfulness_score}")
class LongFormQAWithAssertions(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = | dspy.Prediction(context=context, paragraph=pred.paragraph) | dspy.Prediction |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(dspy.Module):
def __init__(self, passages_per_hop=3, max_hops=2):
super().__init__()
self.generate_query = [ | dspy.ChainOfThought(GenerateSearchQuery) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any(normalize_text(answer) in normalized_context for answer in gold_answers) else 0
def evaluate(module):
correctness_values = []
recall_values = []
precision_values = []
citation_faithfulness_values = []
for i in range(len(devset)):
example = devset[i]
try:
pred = module(question=example.question)
correctness_values.append(answer_correctness(example, pred))
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
citation_faithfulness_values.append(citation_faithfulness_score)
recall = calculate_recall(example, pred)
precision = calculate_precision(example, pred)
recall_values.append(recall)
precision_values.append(precision)
except Exception as e:
print(f"Failed generation with error: {e}")
average_correctness = sum(correctness_values) / len(devset) if correctness_values else 0
average_recall = sum(recall_values) / len(devset) if recall_values else 0
average_precision = sum(precision_values) / len(devset) if precision_values else 0
average_citation_faithfulness = sum(citation_faithfulness_values) / len(devset) if citation_faithfulness_values else 0
print(f"Average Correctness: {average_correctness}")
print(f"Average Recall: {average_recall}")
print(f"Average Precision: {average_precision}")
print(f"Average Citation Faithfulness: {average_citation_faithfulness}")
longformqa = LongFormQA()
evaluate(longformqa)
question = devset[6].question
pred = longformqa(question)
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
print(f"Question: {question}")
print(f"Predicted Paragraph: {pred.paragraph}")
print(f"Citation Faithfulness: {citation_faithfulness_score}")
class LongFormQAWithAssertions(dspy.Module):
def __init__(self, passages_per_hop=3, max_hops=2):
super().__init__()
self.generate_query = [ | dspy.ChainOfThought(GenerateSearchQuery) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any(normalize_text(answer) in normalized_context for answer in gold_answers) else 0
def evaluate(module):
correctness_values = []
recall_values = []
precision_values = []
citation_faithfulness_values = []
for i in range(len(devset)):
example = devset[i]
try:
pred = module(question=example.question)
correctness_values.append(answer_correctness(example, pred))
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
citation_faithfulness_values.append(citation_faithfulness_score)
recall = calculate_recall(example, pred)
precision = calculate_precision(example, pred)
recall_values.append(recall)
precision_values.append(precision)
except Exception as e:
print(f"Failed generation with error: {e}")
average_correctness = sum(correctness_values) / len(devset) if correctness_values else 0
average_recall = sum(recall_values) / len(devset) if recall_values else 0
average_precision = sum(precision_values) / len(devset) if precision_values else 0
average_citation_faithfulness = sum(citation_faithfulness_values) / len(devset) if citation_faithfulness_values else 0
print(f"Average Correctness: {average_correctness}")
print(f"Average Recall: {average_recall}")
print(f"Average Precision: {average_precision}")
print(f"Average Citation Faithfulness: {average_citation_faithfulness}")
longformqa = LongFormQA()
evaluate(longformqa)
question = devset[6].question
pred = longformqa(question)
citation_faithfulness_score, _ = citation_faithfulness(None, pred, None)
print(f"Question: {question}")
print(f"Predicted Paragraph: {pred.paragraph}")
print(f"Citation Faithfulness: {citation_faithfulness_score}")
class LongFormQAWithAssertions(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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().system('git clone https://huggingface.co/arnavs11/DSPy_LongFormQA_Cache')
get_ipython().run_line_magic('cd', 'DSPy_LongFormQA_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_LongFormQA_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_LongFormQA_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import EM, normalize_text
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
get_ipython().run_line_magic('cd', 'dspy/examples/longformqa')
from utils import extract_text_by_citation, correct_citation_format, has_citations, citations_check
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
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(f"Question: {train_example.question}")
print(f"Answer: {train_example.answer}")
print(f"Relevant Wikipedia Titles: {train_example.gold_titles}")
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}")
from dsp.utils import deduplicate
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()
class GenerateCitedParagraph(dspy.Signature):
"""Generate a paragraph with citations."""
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
paragraph = dspy.OutputField(desc="includes citations")
class LongFormQA(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_cited_paragraph = dspy.ChainOfThought(GenerateCitedParagraph)
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_cited_paragraph(context=context, question=question)
pred = dspy.Prediction(context=context, paragraph=pred.paragraph)
return pred
class CheckCitationFaithfulness(dspy.Signature):
"""Verify that the text is based on the provided context."""
context = dspy.InputField(desc="may contain relevant facts")
text = dspy.InputField(desc="between 1 to 2 sentences")
faithfulness = dspy.OutputField(desc="boolean indicating if text is faithful to context")
def citation_faithfulness(example, pred, trace):
paragraph, context = pred.paragraph, pred.context
citation_dict = extract_text_by_citation(paragraph)
if not citation_dict:
return False, None
context_dict = {str(i): context[i].split(' | ')[1] for i in range(len(context))}
faithfulness_results = []
unfaithful_citations = []
check_citation_faithfulness = dspy.ChainOfThought(CheckCitationFaithfulness)
for citation_num, texts in citation_dict.items():
if citation_num not in context_dict:
continue
current_context = context_dict[citation_num]
for text in texts:
try:
result = check_citation_faithfulness(context=current_context, text=text)
is_faithful = result.faithfulness.lower() == 'true'
faithfulness_results.append(is_faithful)
if not is_faithful:
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'context': current_context})
except ValueError as e:
faithfulness_results.append(False)
unfaithful_citations.append({'paragraph': paragraph, 'text': text, 'error': str(e)})
final_faithfulness = all(faithfulness_results)
if not faithfulness_results:
return False, None
return final_faithfulness, unfaithful_citations
def extract_cited_titles_from_paragraph(paragraph, context):
cited_indices = [int(m.group(1)) for m in re.finditer(r'\[(\d+)\]\.', paragraph)]
cited_indices = [index - 1 for index in cited_indices if index <= len(context)]
cited_titles = [context[index].split(' | ')[0] for index in cited_indices]
return cited_titles
def calculate_recall(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
recall = len(intersection) / len(gold_titles) if gold_titles else 0
return recall
def calculate_precision(example, pred, trace=None):
gold_titles = set(example['gold_titles'])
found_cited_titles = set(extract_cited_titles_from_paragraph(pred.paragraph, pred.context))
intersection = gold_titles.intersection(found_cited_titles)
precision = len(intersection) / len(found_cited_titles) if found_cited_titles else 0
return precision
def answer_correctness(example, pred, trace=None):
assert hasattr(example, 'answer'), "Example does not have 'answer'."
normalized_context = normalize_text(pred.paragraph)
if isinstance(example.answer, str):
gold_answers = [example.answer]
elif isinstance(example.answer, list):
gold_answers = example.answer
else:
raise ValueError("'example.answer' is not string or list.")
return 1 if any( | normalize_text(answer) | dsp.utils.normalize_text |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = | dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat') | dspy.OpenAI |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
| dspy.settings.configure(lm=turbo) | dspy.settings.configure |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = | dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat') | dspy.OpenAI |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat')
RUN_FROM_SCRATCH = False
get_ipython().system('git clone https://github.com/selenashe/ScoNe.git')
def load_scone(dirname):
dfs = []
for filename in glob.glob(dirname + "/*.csv"):
df = pd.read_csv(filename, index_col=0)
df['category'] = os.path.basename(filename).replace(".csv", "")
dfs.append(df)
data_df = pd.concat(dfs)
def as_example(row):
suffix = '' if row['category'] == 'one_scoped' else '_edited'
hkey = 'sentence2' + suffix
question = row[hkey][0].lower() + row[hkey][1: ].strip(".")
question = f"Can we logically conclude for sure that {question}?"
label = "Yes" if row['gold_label' + suffix] == 'entailment' else "No"
return dspy.Example({
"context": row['sentence1' + suffix],
"question": question,
"answer": label,
"category": row['category']
}).with_inputs("context", "question")
return list(data_df.apply(as_example, axis=1).values)
all_train = load_scone("ScoNe/scone_nli/train")
random.seed(1)
random.shuffle(all_train)
train, dev = all_train[: 200], all_train[200: 250]
len(train), len(dev)
random.seed(1)
test = load_scone(dirname=f"ScoNe/scone_nli/test")
test = [ex for ex in test if ex.category == "one_scoped"]
pd.Series([ex.answer for ex in test]).value_counts()
scone_accuracy = dspy.evaluate.metrics.answer_exact_match
evaluator = | Evaluate(devset=test, num_threads=1, display_progress=True, display_table=0) | dspy.evaluate.Evaluate |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat')
RUN_FROM_SCRATCH = False
get_ipython().system('git clone https://github.com/selenashe/ScoNe.git')
def load_scone(dirname):
dfs = []
for filename in glob.glob(dirname + "/*.csv"):
df = pd.read_csv(filename, index_col=0)
df['category'] = os.path.basename(filename).replace(".csv", "")
dfs.append(df)
data_df = pd.concat(dfs)
def as_example(row):
suffix = '' if row['category'] == 'one_scoped' else '_edited'
hkey = 'sentence2' + suffix
question = row[hkey][0].lower() + row[hkey][1: ].strip(".")
question = f"Can we logically conclude for sure that {question}?"
label = "Yes" if row['gold_label' + suffix] == 'entailment' else "No"
return dspy.Example({
"context": row['sentence1' + suffix],
"question": question,
"answer": label,
"category": row['category']
}).with_inputs("context", "question")
return list(data_df.apply(as_example, axis=1).values)
all_train = load_scone("ScoNe/scone_nli/train")
random.seed(1)
random.shuffle(all_train)
train, dev = all_train[: 200], all_train[200: 250]
len(train), len(dev)
random.seed(1)
test = load_scone(dirname=f"ScoNe/scone_nli/test")
test = [ex for ex in test if ex.category == "one_scoped"]
pd.Series([ex.answer for ex in test]).value_counts()
scone_accuracy = dspy.evaluate.metrics.answer_exact_match
evaluator = Evaluate(devset=test, num_threads=1, display_progress=True, display_table=0)
class ScoNeSignature(dspy.Signature):
("""You are given some context (a premise) and a question (a hypothesis). """
"""You must indicate with Yes/No answer whether we can logically """
"""conclude the hypothesis from the premise.""")
context = | dspy.InputField() | dspy.InputField |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat')
RUN_FROM_SCRATCH = False
get_ipython().system('git clone https://github.com/selenashe/ScoNe.git')
def load_scone(dirname):
dfs = []
for filename in glob.glob(dirname + "/*.csv"):
df = pd.read_csv(filename, index_col=0)
df['category'] = os.path.basename(filename).replace(".csv", "")
dfs.append(df)
data_df = pd.concat(dfs)
def as_example(row):
suffix = '' if row['category'] == 'one_scoped' else '_edited'
hkey = 'sentence2' + suffix
question = row[hkey][0].lower() + row[hkey][1: ].strip(".")
question = f"Can we logically conclude for sure that {question}?"
label = "Yes" if row['gold_label' + suffix] == 'entailment' else "No"
return dspy.Example({
"context": row['sentence1' + suffix],
"question": question,
"answer": label,
"category": row['category']
}).with_inputs("context", "question")
return list(data_df.apply(as_example, axis=1).values)
all_train = load_scone("ScoNe/scone_nli/train")
random.seed(1)
random.shuffle(all_train)
train, dev = all_train[: 200], all_train[200: 250]
len(train), len(dev)
random.seed(1)
test = load_scone(dirname=f"ScoNe/scone_nli/test")
test = [ex for ex in test if ex.category == "one_scoped"]
pd.Series([ex.answer for ex in test]).value_counts()
scone_accuracy = dspy.evaluate.metrics.answer_exact_match
evaluator = Evaluate(devset=test, num_threads=1, display_progress=True, display_table=0)
class ScoNeSignature(dspy.Signature):
("""You are given some context (a premise) and a question (a hypothesis). """
"""You must indicate with Yes/No answer whether we can logically """
"""conclude the hypothesis from the premise.""")
context = dspy.InputField()
question = | dspy.InputField() | dspy.InputField |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat')
RUN_FROM_SCRATCH = False
get_ipython().system('git clone https://github.com/selenashe/ScoNe.git')
def load_scone(dirname):
dfs = []
for filename in glob.glob(dirname + "/*.csv"):
df = pd.read_csv(filename, index_col=0)
df['category'] = os.path.basename(filename).replace(".csv", "")
dfs.append(df)
data_df = pd.concat(dfs)
def as_example(row):
suffix = '' if row['category'] == 'one_scoped' else '_edited'
hkey = 'sentence2' + suffix
question = row[hkey][0].lower() + row[hkey][1: ].strip(".")
question = f"Can we logically conclude for sure that {question}?"
label = "Yes" if row['gold_label' + suffix] == 'entailment' else "No"
return dspy.Example({
"context": row['sentence1' + suffix],
"question": question,
"answer": label,
"category": row['category']
}).with_inputs("context", "question")
return list(data_df.apply(as_example, axis=1).values)
all_train = load_scone("ScoNe/scone_nli/train")
random.seed(1)
random.shuffle(all_train)
train, dev = all_train[: 200], all_train[200: 250]
len(train), len(dev)
random.seed(1)
test = load_scone(dirname=f"ScoNe/scone_nli/test")
test = [ex for ex in test if ex.category == "one_scoped"]
pd.Series([ex.answer for ex in test]).value_counts()
scone_accuracy = dspy.evaluate.metrics.answer_exact_match
evaluator = Evaluate(devset=test, num_threads=1, display_progress=True, display_table=0)
class ScoNeSignature(dspy.Signature):
("""You are given some context (a premise) and a question (a hypothesis). """
"""You must indicate with Yes/No answer whether we can logically """
"""conclude the hypothesis from the premise.""")
context = dspy.InputField()
question = dspy.InputField()
answer = | dspy.OutputField(desc="Yes or No") | dspy.OutputField |
import glob
import os
import pandas as pd
import random
import dspy
from dspy.evaluate import Evaluate
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join('.', 'cache')
turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=250, model_type='chat')
dspy.settings.configure(lm=turbo)
gpt4T = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=350, model_type='chat')
RUN_FROM_SCRATCH = False
get_ipython().system('git clone https://github.com/selenashe/ScoNe.git')
def load_scone(dirname):
dfs = []
for filename in glob.glob(dirname + "/*.csv"):
df = pd.read_csv(filename, index_col=0)
df['category'] = os.path.basename(filename).replace(".csv", "")
dfs.append(df)
data_df = pd.concat(dfs)
def as_example(row):
suffix = '' if row['category'] == 'one_scoped' else '_edited'
hkey = 'sentence2' + suffix
question = row[hkey][0].lower() + row[hkey][1: ].strip(".")
question = f"Can we logically conclude for sure that {question}?"
label = "Yes" if row['gold_label' + suffix] == 'entailment' else "No"
return dspy.Example({
"context": row['sentence1' + suffix],
"question": question,
"answer": label,
"category": row['category']
}).with_inputs("context", "question")
return list(data_df.apply(as_example, axis=1).values)
all_train = load_scone("ScoNe/scone_nli/train")
random.seed(1)
random.shuffle(all_train)
train, dev = all_train[: 200], all_train[200: 250]
len(train), len(dev)
random.seed(1)
test = load_scone(dirname=f"ScoNe/scone_nli/test")
test = [ex for ex in test if ex.category == "one_scoped"]
pd.Series([ex.answer for ex in test]).value_counts()
scone_accuracy = dspy.evaluate.metrics.answer_exact_match
evaluator = Evaluate(devset=test, num_threads=1, display_progress=True, display_table=0)
class ScoNeSignature(dspy.Signature):
("""You are given some context (a premise) and a question (a hypothesis). """
"""You must indicate with Yes/No answer whether we can logically """
"""conclude the hypothesis from the premise.""")
context = dspy.InputField()
question = dspy.InputField()
answer = dspy.OutputField(desc="Yes or No")
class ScoNeCoT(dspy.Module):
def __init__(self):
super().__init__()
self.generate_answer = | dspy.ChainOfThought(ScoNeSignature) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = | dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') | dspy.ColBERTv2 |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
| dspy.settings.configure(rm=colbertv2_wiki17_abstracts) | dspy.settings.configure |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = | dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500) | dspy.OpenAI |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
| dspy.settings.configure(lm=turbo, trace=[], temperature=0.7) | dspy.settings.configure |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = | HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True) | dspy.datasets.HotPotQA |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_tweeter = teleprompter.compile(student = tweeter, teacher = tweeter, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_tweeter)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_tweeter = teleprompter.compile(student = tweeter, teacher = tweeter, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_tweeter)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_tweeter = teleprompter.compile(student=tweeter, teacher = tweeter_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_with_assertions_tweeter)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6, num_threads=1) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = | dspy.InputField(desc="may contain relevant facts") | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = | dspy.OutputField() | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = | dspy.InputField(desc='ignore if N/A') | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = | dspy.OutputField(desc="Yes or No") | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_tweeter = teleprompter.compile(student = tweeter, teacher = tweeter, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_tweeter = teleprompter.compile(student = tweeter, teacher = tweeter, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_tweeter)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_tweeter = teleprompter.compile(student=tweeter, teacher = tweeter_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter_with_assertions = assert_transform_module(TweeterWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
example = devset[10]
tweet = tweeter_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_tweeter = teleprompter.compile(student = tweeter, teacher = tweeter, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_tweeter)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_tweeter = teleprompter.compile(student=tweeter, teacher = tweeter_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_with_assertions_tweeter)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6, num_threads=1)
compiled_tweeter_with_assertions = teleprompter.compile(student=tweeter_with_assertions, teacher = tweeter_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = | dspy.ChainOfThought(GenerateTweet) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = | dspy.Retrieve(k=passages_per_hop) | dspy.Retrieve |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return | dspy.Prediction(generated_tweet=generated_tweet, context=context) | dspy.Prediction |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = | dspy.ChainOfThought(GenerateTweet) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = | dspy.Retrieve(k=passages_per_hop) | dspy.Retrieve |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = dspy.Predict(AssessTweet)(context='N/A', assessed_text=generated_tweet, assessment_question=faithful_question)
dspy.Suggest(is_assessment_yes(faithful_assessment.assessment_answer), "The text contains unfaithful elements or significant facts not in the context. Please revise for accuracy.", target_module=GenerateTweet)
return | dspy.Prediction(generated_tweet=generated_tweet, context=context) | dspy.Prediction |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [ | dspy.ChainOfThought(GenerateSearchQuery) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = | deduplicate(context + passages) | dsp.utils.deduplicate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [ | dspy.ChainOfThought(GenerateSearchQuery) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = | deduplicate(context + passages) | dsp.utils.deduplicate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_TweetGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_TweetGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_TweetGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_TweetGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dsp.utils import deduplicate
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
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()
class GenerateTweet(dspy.Signature):
"""Generate an engaging tweet that effectively answers a question staying faithful to the context, is less than 280 characters, and has no hashtags."""
question = dspy.InputField()
context = dspy.InputField(desc="may contain relevant facts")
tweet = dspy.OutputField()
class Tweeter(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
return dspy.Prediction(generated_tweet=generated_tweet, context=context)
tweeter = Tweeter()
def has_no_hashtags(text):
return len(re.findall(r"#\w+", text)) == 0
def is_within_length_limit(text, length_limit=280):
return len(text) <= length_limit
def is_assessment_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
def has_correct_answer(text, answer):
return answer in text
class AssessTweet(dspy.Signature):
"""Assess the quality of a tweet along the specified dimension."""
context = dspy.InputField(desc='ignore if N/A')
assessed_text = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def no_hashtags_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
score = no_hashtags
return score
def is_correct_metric(gold, pred, trace=None):
answer, tweet = gold.answer, pred.generated_tweet
correct = has_correct_answer(tweet, answer)
score = correct
return score
def within_length_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
within_length_limit = is_within_length_limit(tweet, 280)
score = within_length_limit
return score
def engaging_metric(gold, pred, trace=None):
tweet = pred.generated_tweet
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging = engaging.assessment_answer.split()[0].lower() == 'yes'
score = engaging
return score
def faithful_metric(gold, pred, trace=None):
context, tweet = pred.context, pred.generated_tweet
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
faithful = faithful.assessment_answer.split()[0].lower() == 'yes'
score = faithful
return score
def overall_metric(gold, pred, trace=None):
answer, context, tweet = gold.answer, pred.context, pred.generated_tweet
no_hashtags = has_no_hashtags(tweet)
within_length_limit = is_within_length_limit(tweet, 280)
correct = has_correct_answer(tweet, answer)
engaging = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful = dspy.Predict(AssessTweet)(context=context, assessed_text=tweet, assessment_question=faithful)
engaging = dspy.Predict(AssessTweet)(context='N/A', assessed_text=tweet, assessment_question=engaging)
engaging, faithful = [m.assessment_answer.split()[0].lower() == 'yes' for m in [engaging, faithful]]
score = (correct + engaging + faithful + no_hashtags + within_length_limit) if correct and within_length_limit else 0
return score / 5.0
metrics = [no_hashtags_metric, is_correct_metric, within_length_metric, engaging_metric, faithful_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
example = devset[10]
tweet = tweeter(question=example.question, answer = example.answer)
print(f'Generated Tweet: ', tweet.generated_tweet)
tweet.context
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[10:11], num_threads=1, display_progress=True, display_table=5)
evaluate(tweeter)
class TweeterWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_tweet = dspy.ChainOfThought(GenerateTweet)
def forward(self, question, answer):
context = []
max_hops=2
passages_per_hop=3
generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]
retrieve = dspy.Retrieve(k=passages_per_hop)
for hop in range(max_hops):
query = generate_query[hop](context=context, question=question).query
passages = retrieve(query).passages
context = deduplicate(context + passages)
generated_tweet = self.generate_tweet(question=question, context=context).tweet
dspy.Suggest(has_no_hashtags(generated_tweet), f"Please revise the tweet to remove hashtag phrases following it.", target_module=GenerateTweet)
dspy.Suggest(is_within_length_limit(generated_tweet, 280), f"Please ensure the tweet is within {280} characters.", target_module=GenerateTweet)
dspy.Suggest(has_correct_answer(generated_tweet, answer), "The tweet does not include the correct answer to the question. Please revise accordingly.", target_module=GenerateTweet)
engaging_question = "Does the assessed text make for a self-contained, engaging tweet? Say no if it is not engaging."
engaging_assessment = dspy.Predict(AssessTweet)(context=context, assessed_text=generated_tweet, assessment_question=engaging_question)
dspy.Suggest(is_assessment_yes(engaging_assessment.assessment_answer), "The text is not engaging enough. Please revise to make it more captivating.", target_module=GenerateTweet)
faithful_question = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context."
faithful_assessment = | dspy.Predict(AssessTweet) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = | dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') | dspy.ColBERTv2 |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
| dspy.settings.configure(rm=colbertv2_wiki17_abstracts) | dspy.settings.configure |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = | dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500) | dspy.OpenAI |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
| dspy.settings.configure(lm=turbo, trace=[], temperature=0.7) | dspy.settings.configure |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = | HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True) | dspy.datasets.HotPotQA |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator = teleprompter.compile(student = quiz_generator, teacher = quiz_generator, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_quiz_generator)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator = teleprompter.compile(student = quiz_generator, teacher = quiz_generator, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_quiz_generator)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_quiz_generator = teleprompter.compile(student=quiz_generator, teacher = quiz_generator_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_with_assertions_quiz_generator)
teleprompter = | BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6) | dspy.teleprompt.BootstrapFewShotWithRandomSearch |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = | dspy.OutputField(desc='JSON key-value pairs') | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = | dspy.InputField() | dspy.InputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = | dspy.OutputField(desc="Yes or No") | dspy.OutputField |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator = teleprompter.compile(student = quiz_generator, teacher = quiz_generator, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator = teleprompter.compile(student = quiz_generator, teacher = quiz_generator, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_quiz_generator)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_quiz_generator = teleprompter.compile(student=quiz_generator, teacher = quiz_generator_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=choice_string, assessment_question=plausibility_question)
dspy.Suggest(is_plausibility_yes(plausibility_assessment.assessment_answer), "The answer choices are not plausible distractors or are too easily identifiable as incorrect. Please revise to provide more challenging and plausible distractors.", target_module=GenerateAnswerChoices)
return dspy.Prediction(choices = choice_string)
number_of_choices = '4'
quiz_generator_with_assertions = assert_transform_module(QuizAnswerGeneratorWithAssertions().map_named_predictors(Retry), backtrack_handler)
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator_with_assertions)
example = devset[38]
quiz_choices = quiz_generator_with_assertions(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=30)
evaluate(quiz_generator_with_assertions)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator = teleprompter.compile(student = quiz_generator, teacher = quiz_generator, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_quiz_generator)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_with_assertions_quiz_generator = teleprompter.compile(student=quiz_generator, teacher = quiz_generator_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(compiled_with_assertions_quiz_generator)
teleprompter = BootstrapFewShotWithRandomSearch(metric = overall_metric, max_bootstrapped_demos=2, num_candidate_programs=6)
compiled_quiz_generator_with_assertions = teleprompter.compile(student=quiz_generator_with_assertions, teacher = quiz_generator_with_assertions, trainset=trainset, valset=devset[:100])
for metric in metrics:
evaluate = | Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5) | dspy.evaluate.evaluate.Evaluate |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = | dspy.ChainOfThought(GenerateAnswerChoices) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = | dspy.Predict(AssessQuizChoices) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = | dspy.Predict(AssessQuizChoices) | dspy.Predict |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = | dspy.ChainOfThought(GenerateAnswerChoices) | dspy.ChainOfThought |
get_ipython().system('git clone https://huggingface.co/arnavs11/DSPy_QuizGen_Cache')
get_ipython().run_line_magic('cd', 'DSPy_QuizGen_Cache/')
get_ipython().system('git checkout master')
get_ipython().run_line_magic('cd', '..')
import os
repo_clone_path = '/content/DSPy_QuizGen_Cache'
if not os.access('/content', os.W_OK):
repo_clone_path = os.path.join(os.getcwd(), 'DSPy_QuizGen_Cache')
os.environ["DSP_NOTEBOOK_CACHEDIR"] = repo_clone_path
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
import sys
import os
import regex as re
import json
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)
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')
get_ipython().system('pip install -e $repo_path')
import dspy
from dspy.predict import Retry
from dspy.datasets import HotPotQA
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=500)
dspy.settings.configure(lm=turbo, trace=[], temperature=0.7)
dataset = HotPotQA(train_seed=1, train_size=300, eval_seed=2023, dev_size=300, test_size=0, keep_details=True)
trainset = [x.with_inputs('question', 'answer') for x in dataset.train]
devset = [x.with_inputs('question', 'answer') for x in dataset.dev]
class GenerateAnswerChoices(dspy.Signature):
"""Generate answer choices in JSON format that include the correct answer and plausible distractors for the specified question."""
question = dspy.InputField()
correct_answer = dspy.InputField()
number_of_choices = dspy.InputField()
answer_choices = dspy.OutputField(desc='JSON key-value pairs')
class QuizAnswerGenerator(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choices = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
return dspy.Prediction(choices = choices)
number_of_choices = '4'
quiz_generator = QuizAnswerGenerator()
def format_checker(choice_string):
try:
choices = json.loads(choice_string)
if isinstance(choices, dict) and all(isinstance(key, str) and isinstance(value, str) for key, value in choices.items()):
return True
except json.JSONDecodeError:
return False
return False
def is_correct_answer_included(correct_answer, generated_choices):
try:
choices_dict = json.loads(generated_choices)
return correct_answer in choices_dict.values()
except json.JSONDecodeError:
return False
def is_plausibility_yes(assessment_answer):
"""Check if the first word of the assessment answer is 'yes'."""
return assessment_answer.split()[0].lower() == 'yes'
class AssessQuizChoices(dspy.Signature):
"""Assess the quality of quiz answer choices along specified dimensions."""
question = dspy.InputField()
answer_choices = dspy.InputField()
assessment_question = dspy.InputField()
assessment_answer = dspy.OutputField(desc="Yes or No")
def format_valid_metric(gold, pred, trace=None):
generated_choices = pred.choices
format_valid = format_checker(generated_choices)
score = format_valid
return score
def is_correct_metric(gold, pred, trace=None):
correct_answer, generated_choices = gold.answer, pred.choices
correct_included = is_correct_answer_included(correct_answer, generated_choices)
score = correct_included
return score
def plausibility_metric(gold, pred, trace=None):
question, generated_choices = gold.question, pred.choices
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = plausibility_result
return score
def overall_metric(gold, pred, trace=None):
question, correct_answer, generated_choices = gold.question, gold.answer, pred.choices
format_valid = format_checker(generated_choices)
correct_included = is_correct_answer_included(correct_answer, generated_choices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = dspy.Predict(AssessQuizChoices)(question=question, answer_choices=generated_choices, assessment_question=plausibility_question)
plausibility_result = plausibility_assessment.assessment_answer.split()[0].lower() == 'yes'
score = (format_valid + correct_included + plausibility_result) / 3.0 if correct_included and format_valid else 0
return score
metrics = [format_valid_metric, is_correct_metric, plausibility_metric, overall_metric]
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset, num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
example = devset[38]
quiz_choices = quiz_generator(question=example.question, answer = example.answer)
print(f'Generated Quiz Choices: ', quiz_choices.choices)
for metric in metrics:
evaluate = Evaluate(metric=metric, devset=devset[38:39], num_threads=1, display_progress=True, display_table=5)
evaluate(quiz_generator)
class QuizAnswerGeneratorWithAssertions(dspy.Module):
def __init__(self):
super().__init__()
self.generate_choices = dspy.ChainOfThought(GenerateAnswerChoices)
def forward(self, question, answer):
choice_string = self.generate_choices(question=question, correct_answer=answer, number_of_choices=number_of_choices).answer_choices
dspy.Suggest(format_checker(choice_string), "The format of the answer choices should be in JSON format. Please revise accordingly.", target_module=GenerateAnswerChoices)
dspy.Suggest(is_correct_answer_included(answer, choice_string), "The answer choices do not include the correct answer to the question. Please revise accordingly.", target_module=GenerateAnswerChoices)
plausibility_question = "Are the distractors in the answer choices plausible and not easily identifiable as incorrect?"
plausibility_assessment = | dspy.Predict(AssessQuizChoices) | dspy.Predict |
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.Pyserini |