prompt
stringlengths
131
11.8k
completion
stringlengths
7
173
api
stringlengths
11
48
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') colbertv2_wiki17_abstracts =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2_wiki17_abstracts)
dspy.settings.configure
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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)
dspy.datasets.HotPotQA
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query dspy.Suggest( len(query) <= 100, "Query should be short and less than 100 characters", ) dspy.Suggest( validate_query_distinction_local(prev_queries, query), "Query should be distinct from: " + "; ".join(f"{i+1}) {q}" for i, q in enumerate(prev_queries)), ) prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred evaluate_on_hotpotqa =
Evaluate(devset=devset, num_threads=10, display_progress=True, display_table=False)
dspy.evaluate.evaluate.Evaluate
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if
dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8)
dspy.evaluate.answer_exact_match_str
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context =
dspy.InputField(desc="may contain relevant facts")
dspy.InputField
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question =
dspy.InputField()
dspy.InputField
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer =
dspy.OutputField(desc="often between 1 and 5 words")
dspy.OutputField
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not
dspy.evaluate.answer_exact_match(example, pred)
dspy.evaluate.answer_exact_match
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not
dspy.evaluate.answer_passage_match(example, pred)
dspy.evaluate.answer_passage_match
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer =
dspy.ChainOfThought(GenerateAnswer)
dspy.ChainOfThought
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred =
dspy.Prediction(context=context, answer=pred.answer)
dspy.Prediction
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, 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
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer =
dspy.ChainOfThought(GenerateAnswer)
dspy.ChainOfThought
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query dspy.Suggest( len(query) <= 100, "Query should be short and less than 100 characters", ) dspy.Suggest( validate_query_distinction_local(prev_queries, query), "Query should be distinct from: " + "; ".join(f"{i+1}) {q}" for i, q in enumerate(prev_queries)), ) prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred =
dspy.Prediction(context=context, answer=pred.answer)
dspy.Prediction
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [
dspy.ChainOfThought(GenerateSearchQuery)
dspy.ChainOfThought
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context =
deduplicate(context + passages)
dsp.utils.deduplicate
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [
dspy.ChainOfThought(GenerateSearchQuery)
dspy.ChainOfThought
import dspy from dsp.utils import deduplicate from dspy.datasets import HotPotQA from dspy.predict.retry import Retry from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch from dspy.evaluate.evaluate import Evaluate from dspy.primitives.assertions import assert_transform_module, backtrack_handler import os import openai openai.api_key = os.getenv('OPENAI_API_KEY') 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) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] def validate_query_distinction_local(previous_queries, query): """check if query is distinct from previous queries""" if previous_queries == []: return True if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8): return False return True def validate_context_and_answer_and_hops(example, pred, trace=None): if not dspy.evaluate.answer_exact_match(example, pred): return False if not dspy.evaluate.answer_passage_match(example, pred): return False return True def gold_passages_retrieved(example, pred, trace=None): gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles'])) found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context])) return gold_titles.issubset(found_titles) class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") class 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() def all_queries_distinct(prev_queries): query_distinct = True for i, query in enumerate(prev_queries): if validate_query_distinction_local(prev_queries[:i], query) == False: query_distinct = False break return query_distinct class SimplifiedBaleen(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query prev_queries.append(query) passages = self.retrieve(query).passages context = deduplicate(context + passages) if all_queries_distinct(prev_queries): self.passed_suggestions += 1 pred = self.generate_answer(context=context, question=question) pred = dspy.Prediction(context=context, answer=pred.answer) return pred class SimplifiedBaleenAssertions(dspy.Module): def __init__(self, passages_per_hop=2, max_hops=2): super().__init__() self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)] self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_answer = dspy.ChainOfThought(GenerateAnswer) self.max_hops = max_hops self.passed_suggestions = 0 def forward(self, question): context = [] prev_queries = [question] for hop in range(self.max_hops): query = self.generate_query[hop](context=context, question=question).query dspy.Suggest( len(query) <= 100, "Query should be short and less than 100 characters", ) dspy.Suggest( validate_query_distinction_local(prev_queries, query), "Query should be distinct from: " + "; ".join(f"{i+1}) {q}" for i, q in enumerate(prev_queries)), ) prev_queries.append(query) passages = self.retrieve(query).passages context =
deduplicate(context + passages)
dsp.utils.deduplicate
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.configure(rm=colbertv2)
dspy.configure
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.configure(rm=colbertv2) from langchain_openai import OpenAI from langchain.globals import set_llm_cache from langchain.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) retrieve = lambda x: dspy.Retrieve(k=5)(x["question"]).passages from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough prompt = PromptTemplate.from_template("Given {context}, answer the question `{question}` as a tweet.") vanilla_chain = RunnablePassthrough.assign(context=retrieve) | prompt | llm | StrOutputParser() from dspy.predict.langchain import LangChainPredict, LangChainModule zeroshot_chain = RunnablePassthrough.assign(context=retrieve) | LangChainPredict(prompt, llm) | StrOutputParser() zeroshot_chain =
LangChainModule(zeroshot_chain)
dspy.predict.langchain.LangChainModule
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.configure(rm=colbertv2) from langchain_openai import OpenAI from langchain.globals import set_llm_cache from langchain.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) retrieve = lambda x: dspy.Retrieve(k=5)(x["question"]).passages from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough prompt = PromptTemplate.from_template("Given {context}, answer the question `{question}` as a tweet.") vanilla_chain = RunnablePassthrough.assign(context=retrieve) | prompt | llm | StrOutputParser() from dspy.predict.langchain import LangChainPredict, LangChainModule zeroshot_chain = RunnablePassthrough.assign(context=retrieve) | LangChainPredict(prompt, llm) | StrOutputParser() zeroshot_chain = LangChainModule(zeroshot_chain) # then wrap the chain in a DSPy module. question = "In what region was Eddy Mazzoleni born?" zeroshot_chain.invoke({"question": question}) from tweet_metric import metric, trainset, valset, devset len(trainset), len(valset), len(devset) evaluate =
Evaluate(metric=metric, devset=devset, num_threads=8, display_progress=True, display_table=5)
dspy.evaluate.evaluate.Evaluate
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.configure(rm=colbertv2) from langchain_openai import OpenAI from langchain.globals import set_llm_cache from langchain.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) retrieve = lambda x: dspy.Retrieve(k=5)(x["question"]).passages from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough prompt = PromptTemplate.from_template("Given {context}, answer the question `{question}` as a tweet.") vanilla_chain = RunnablePassthrough.assign(context=retrieve) | prompt | llm | StrOutputParser() from dspy.predict.langchain import LangChainPredict, LangChainModule zeroshot_chain = RunnablePassthrough.assign(context=retrieve) | LangChainPredict(prompt, llm) | StrOutputParser() zeroshot_chain = LangChainModule(zeroshot_chain) # then wrap the chain in a DSPy module. question = "In what region was Eddy Mazzoleni born?" zeroshot_chain.invoke({"question": question}) from tweet_metric import metric, trainset, valset, devset len(trainset), len(valset), len(devset) evaluate = Evaluate(metric=metric, devset=devset, num_threads=8, display_progress=True, display_table=5) evaluate(zeroshot_chain) optimizer =
BootstrapFewShotWithRandomSearch(metric=metric, max_bootstrapped_demos=3, num_candidate_programs=3)
dspy.teleprompt.BootstrapFewShotWithRandomSearch
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.configure(rm=colbertv2) from langchain_openai import OpenAI from langchain.globals import set_llm_cache from langchain.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) retrieve = lambda x: dspy.Retrieve(k=5)(x["question"]).passages from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough prompt = PromptTemplate.from_template("Given {context}, answer the question `{question}` as a tweet.") vanilla_chain = RunnablePassthrough.assign(context=retrieve) | prompt | llm | StrOutputParser() from dspy.predict.langchain import LangChainPredict, LangChainModule zeroshot_chain = RunnablePassthrough.assign(context=retrieve) |
LangChainPredict(prompt, llm)
dspy.predict.langchain.LangChainPredict
import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShotWithRandomSearch colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.configure(rm=colbertv2) from langchain_openai import OpenAI from langchain.globals import set_llm_cache from langchain.cache import SQLiteCache set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) retrieve = lambda x:
dspy.Retrieve(k=5)
dspy.Retrieve
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k =
GSM8K()
dspy.datasets.gsm8k.GSM8K
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k = GSM8K() turbo =
dspy.OpenAI(model='gpt-3.5-turbo-instruct', max_tokens=250)
dspy.OpenAI
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k = GSM8K() turbo = dspy.OpenAI(model='gpt-3.5-turbo-instruct', max_tokens=250) trainset, devset = gms8k.train, gms8k.dev
dspy.settings.configure(lm=turbo)
dspy.settings.configure
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k = GSM8K() turbo = dspy.OpenAI(model='gpt-3.5-turbo-instruct', max_tokens=250) trainset, devset = gms8k.train, gms8k.dev dspy.settings.configure(lm=turbo) NUM_THREADS = 4 evaluate =
Evaluate(devset=devset[:], metric=gsm8k_metric, num_threads=NUM_THREADS, display_progress=True, display_table=0)
dspy.evaluate.Evaluate
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k = GSM8K() turbo = dspy.OpenAI(model='gpt-3.5-turbo-instruct', max_tokens=250) trainset, devset = gms8k.train, gms8k.dev dspy.settings.configure(lm=turbo) NUM_THREADS = 4 evaluate = Evaluate(devset=devset[:], metric=gsm8k_metric, num_threads=NUM_THREADS, display_progress=True, display_table=0) class CoT(dspy.Module): def __init__(self): super().__init__() self.prog = dspy.ChainOfThought("question -> answer") def forward(self, question): return self.prog(question=question) RUN_FROM_SCRATCH = False if RUN_FROM_SCRATCH: config = dict(max_bootstrapped_demos=8, max_labeled_demos=8, num_candidate_programs=10, num_threads=NUM_THREADS) teleprompter =
BootstrapFewShotWithRandomSearch(metric=gsm8k_metric, **config)
dspy.teleprompt.BootstrapFewShotWithRandomSearch
import dspy from dspy.evaluate import Evaluate from dspy.datasets.gsm8k import GSM8K, gsm8k_metric from dspy.teleprompt import BootstrapFewShotWithRandomSearch gms8k = GSM8K() turbo = dspy.OpenAI(model='gpt-3.5-turbo-instruct', max_tokens=250) trainset, devset = gms8k.train, gms8k.dev dspy.settings.configure(lm=turbo) NUM_THREADS = 4 evaluate = Evaluate(devset=devset[:], metric=gsm8k_metric, num_threads=NUM_THREADS, display_progress=True, display_table=0) class CoT(dspy.Module): def __init__(self): super().__init__() self.prog =
dspy.ChainOfThought("question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm =
dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000)
dspy.OpenAI
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000)
dspy.settings.configure(lm=lm)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor =
dspy.Predict("question -> answer")
dspy.Predict
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor = dspy.Predict("question -> answer") print(predictor(question="What is the capital of France?")) from dspy import InputField, OutputField, Signature from dspy.functional import TypedPredictor import pydantic class PythonCode(pydantic.BaseModel): code: str @pydantic.field_validator('code') def check_syntax(cls, v): try: compile(v, "<string>", "exec") except SyntaxError as e: raise ValueError(f"Code is not syntactically valid: {e}") return v class CodeSignature(Signature): prompt: str = InputField() test: PythonCode = InputField() entry_point: str = InputField() solution: PythonCode = OutputField() predictor =
TypedPredictor(CodeSignature)
dspy.functional.TypedPredictor
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor = dspy.Predict("question -> answer") print(predictor(question="What is the capital of France?")) from dspy import InputField, OutputField, Signature from dspy.functional import TypedPredictor import pydantic class PythonCode(pydantic.BaseModel): code: str @pydantic.field_validator('code') def check_syntax(cls, v): try: compile(v, "<string>", "exec") except SyntaxError as e: raise ValueError(f"Code is not syntactically valid: {e}") return v class CodeSignature(Signature): prompt: str =
InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor = dspy.Predict("question -> answer") print(predictor(question="What is the capital of France?")) from dspy import InputField, OutputField, Signature from dspy.functional import TypedPredictor import pydantic class PythonCode(pydantic.BaseModel): code: str @pydantic.field_validator('code') def check_syntax(cls, v): try: compile(v, "<string>", "exec") except SyntaxError as e: raise ValueError(f"Code is not syntactically valid: {e}") return v class CodeSignature(Signature): prompt: str = InputField() test: PythonCode =
InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor = dspy.Predict("question -> answer") print(predictor(question="What is the capital of France?")) from dspy import InputField, OutputField, Signature from dspy.functional import TypedPredictor import pydantic class PythonCode(pydantic.BaseModel): code: str @pydantic.field_validator('code') def check_syntax(cls, v): try: compile(v, "<string>", "exec") except SyntaxError as e: raise ValueError(f"Code is not syntactically valid: {e}") return v class CodeSignature(Signature): prompt: str = InputField() test: PythonCode = InputField() entry_point: str =
InputField()
dspy.InputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('pip', 'install datasets') import datasets ds = datasets.load_dataset("openai_humaneval") ds['test'][0] import dspy, dotenv, os dotenv.load_dotenv(os.path.expanduser("~/.env")) # load OpenAI API key from .env file lm = dspy.OpenAI(model="gpt-3.5-turbo", max_tokens=4000) dspy.settings.configure(lm=lm) predictor = dspy.Predict("question -> answer") print(predictor(question="What is the capital of France?")) from dspy import InputField, OutputField, Signature from dspy.functional import TypedPredictor import pydantic class PythonCode(pydantic.BaseModel): code: str @pydantic.field_validator('code') def check_syntax(cls, v): try: compile(v, "<string>", "exec") except SyntaxError as e: raise ValueError(f"Code is not syntactically valid: {e}") return v class CodeSignature(Signature): prompt: str = InputField() test: PythonCode = InputField() entry_point: str = InputField() solution: PythonCode =
OutputField()
dspy.OutputField
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import pkg_resources # Install the package if it's not installed if not "dspy-ai" in {pkg.key for pkg in pkg_resources.working_set}: get_ipython().system('pip install -U pip') get_ipython().system('pip install -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama =
dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150)
dspy.HFClientTGI
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2, lm=llama)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict =
dspy.Predict('question -> answer')
dspy.Predict
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter =
BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2)
dspy.teleprompt.BootstrapFewShot
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot =
Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15)
dspy.evaluate.Evaluate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 =
BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS)
dspy.teleprompt.BootstrapFewShotWithRandomSearch
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer =
dspy.ChainOfThought('question -> answer')
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve =
dspy.Retrieve(k=num_passages)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query =
dspy.ChainOfThought("question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer =
dspy.ChainOfThought("context, question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve =
dspy.Retrieve(k=num_passages)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query =
dspy.ChainOfThought("question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_query_from_context = None self.generate_answer =
dspy.ChainOfThought("context, question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [
dspy.Example(question=question, answer=answer)
dspy.Example
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [
dspy.Example(question=question, answer=answer)
dspy.Example
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import sys import os try: # When on google Colab, let's clone the notebook so we download the cache. import google.colab repo_path = 'dspy' get_ipython().system('git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path') except: repo_path = '.' if repo_path not in sys.path: sys.path.append(repo_path) os.environ["DSP_NOTEBOOK_CACHEDIR"] = os.path.join(repo_path, 'cache') import 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 -e $repo_path') get_ipython().system('pip install transformers') import dspy from dspy.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot, BootstrapFewShotWithRandomSearch, BootstrapFinetune llama = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=[7140, 7141, 7142, 7143], max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llama) train = [('Who was the director of the 2009 movie featuring Peter Outerbridge as William Easton?', 'Kevin Greutert'), ('The heir to the Du Pont family fortune sponsored what wrestling team?', 'Foxcatcher'), ('In what year was the star of To Hell and Back born?', '1925'), ('Which award did the first book of Gary Zukav receive?', 'U.S. National Book Award'), ('What documentary about the Gilgo Beach Killer debuted on A&E?', 'The Killing Season'), ('Which author is English: John Braine or Studs Terkel?', 'John Braine'), ('Who produced the album that included a re-recording of "Lithium"?', 'Butch Vig')] train = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in train] dev = [('Who has a broader scope of profession: E. L. Doctorow or Julia Peterkin?', 'E. L. Doctorow'), ('Right Back At It Again contains lyrics co-written by the singer born in what city?', 'Gainesville, Florida'), ('What year was the party of the winner of the 1971 San Francisco mayoral election founded?', '1828'), ('Anthony Dirrell is the brother of which super middleweight title holder?', 'Andre Dirrell'), ('The sports nutrition business established by Oliver Cookson is based in which county in the UK?', 'Cheshire'), ('Find the birth date of the actor who played roles in First Wives Club and Searching for the Elephant.', 'February 13, 1980'), ('Kyle Moran was born in the town on what river?', 'Castletown River'), ("The actress who played the niece in the Priest film was born in what city, country?", 'Surrey, England'), ('Name the movie in which the daughter of Noel Harrison plays Violet Trefusis.', 'Portrait of a Marriage'), ('What year was the father of the Princes in the Tower born?', '1442'), ('What river is near the Crichton Collegiate Church?', 'the River Tyne'), ('Who purchased the team Michael Schumacher raced for in the 1995 Monaco Grand Prix in 2000?', 'Renault'), ('André Zucca was a French photographer who worked with a German propaganda magazine published by what Nazi organization?', 'the Wehrmacht')] dev = [dspy.Example(question=question, answer=answer).with_inputs('question') for question, answer in dev] predict = dspy.Predict('question -> answer') predict(question="What is the capital of Germany?") class CoT(dspy.Module): # let's define a new module def __init__(self): super().__init__() self.generate_answer = dspy.ChainOfThought('question -> answer') def forward(self, question): return self.generate_answer(question=question) # here we use the module metric_EM = dspy.evaluate.answer_exact_match teleprompter = BootstrapFewShot(metric=metric_EM, max_bootstrapped_demos=2) cot_compiled = teleprompter.compile(CoT(), trainset=train) cot_compiled("What is the capital of Germany?") llama.inspect_history(n=1) NUM_THREADS = 32 evaluate_hotpot = Evaluate(devset=dev, metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=15) evaluate_hotpot(cot_compiled) class RAG(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): search_query = self.generate_query(question=question).search_query passages = self.retrieve(search_query).passages return self.generate_answer(context=passages, question=question) evaluate_hotpot(RAG(), display_table=0) teleprompter2 = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_candidate_programs=8, num_threads=NUM_THREADS) rag_compiled = teleprompter2.compile(RAG(), trainset=train, valset=dev) evaluate_hotpot(rag_compiled) rag_compiled("What year was the party of the winner of the 1971 San Francisco mayoral election founded?") llama.inspect_history(n=1) from dsp.utils.utils import deduplicate class MultiHop(dspy.Module): def __init__(self, num_passages=3): super().__init__() self.retrieve = dspy.Retrieve(k=num_passages) self.generate_query = dspy.ChainOfThought("question -> search_query") self.generate_query_from_context = None self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): passages = [] search_query = self.generate_query(question=question).search_query passages += self.retrieve(search_query).passages search_query2 = None passages += None return self.generate_answer(context=
deduplicate(passages)
dsp.utils.utils.deduplicate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat =
dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150)
dspy.HFClientTGI
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 =
dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.ColBERTv2
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
dspy.settings.configure(rm=colbertv2, lm=llamaChat)
dspy.settings.configure
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset =
HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0)
dspy.datasets.hotpotqa.HotPotQA
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS) basicmh_bs = tp.compile(BasicMH(), trainset=trainset[:50], valset=trainset[50:200]) ensemble = [prog for *_, prog in basicmh_bs.candidate_programs[:4]] for idx, prog in enumerate(ensemble): pass if not RECOMPILE_INTO_LLAMA_FROM_SCRATCH: ensemble = [] for idx in range(4): prog = BasicMH() prog.load(f'multihop_llama213b_{idx}.json') ensemble.append(prog) llama_program = ensemble[0] evaluate_hotpot =
Evaluate(devset=devset[:1000], metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=0)
dspy.evaluate.Evaluate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp =
BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS)
dspy.teleprompt.BootstrapFewShotWithRandomSearch
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS) basicmh_bs = tp.compile(BasicMH(), trainset=trainset[:50], valset=trainset[50:200]) ensemble = [prog for *_, prog in basicmh_bs.candidate_programs[:4]] for idx, prog in enumerate(ensemble): pass if not RECOMPILE_INTO_LLAMA_FROM_SCRATCH: ensemble = [] for idx in range(4): prog = BasicMH() prog.load(f'multihop_llama213b_{idx}.json') ensemble.append(prog) llama_program = ensemble[0] evaluate_hotpot = Evaluate(devset=devset[:1000], metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=0) evaluate_hotpot(llama_program) llama_program(question="How many storeys are in the castle that David Gregory inherited?") llamaChat.inspect_history(n=3) unlabeled_train =
HotPotQA(train_seed=1, train_size=3000, eval_seed=2023, dev_size=0, test_size=0)
dspy.datasets.hotpotqa.HotPotQA
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS) basicmh_bs = tp.compile(BasicMH(), trainset=trainset[:50], valset=trainset[50:200]) ensemble = [prog for *_, prog in basicmh_bs.candidate_programs[:4]] for idx, prog in enumerate(ensemble): pass if not RECOMPILE_INTO_LLAMA_FROM_SCRATCH: ensemble = [] for idx in range(4): prog = BasicMH() prog.load(f'multihop_llama213b_{idx}.json') ensemble.append(prog) llama_program = ensemble[0] evaluate_hotpot = Evaluate(devset=devset[:1000], metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=0) evaluate_hotpot(llama_program) llama_program(question="How many storeys are in the castle that David Gregory inherited?") llamaChat.inspect_history(n=3) unlabeled_train = HotPotQA(train_seed=1, train_size=3000, eval_seed=2023, dev_size=0, test_size=0).train unlabeled_train = [dspy.Example(question=x.question).with_inputs('question') for x in unlabeled_train] len(unlabeled_train) always_true = lambda g, p, trace=None: True for prog_ in ensemble: evaluate_hotpot(prog_, devset=unlabeled_train[:3000], metric=always_true) RECOMPILE_INTO_T5_FROM_SCRATCH = False if RECOMPILE_INTO_T5_FROM_SCRATCH: config = dict(target='t5-large', epochs=2, bf16=True, bsize=6, accumsteps=2, lr=5e-5) tp =
BootstrapFinetune(metric=None)
dspy.teleprompt.BootstrapFinetune
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS) basicmh_bs = tp.compile(BasicMH(), trainset=trainset[:50], valset=trainset[50:200]) ensemble = [prog for *_, prog in basicmh_bs.candidate_programs[:4]] for idx, prog in enumerate(ensemble): pass if not RECOMPILE_INTO_LLAMA_FROM_SCRATCH: ensemble = [] for idx in range(4): prog = BasicMH() prog.load(f'multihop_llama213b_{idx}.json') ensemble.append(prog) llama_program = ensemble[0] evaluate_hotpot = Evaluate(devset=devset[:1000], metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=0) evaluate_hotpot(llama_program) llama_program(question="How many storeys are in the castle that David Gregory inherited?") llamaChat.inspect_history(n=3) unlabeled_train = HotPotQA(train_seed=1, train_size=3000, eval_seed=2023, dev_size=0, test_size=0).train unlabeled_train = [dspy.Example(question=x.question).with_inputs('question') for x in unlabeled_train] len(unlabeled_train) always_true = lambda g, p, trace=None: True for prog_ in ensemble: evaluate_hotpot(prog_, devset=unlabeled_train[:3000], metric=always_true) RECOMPILE_INTO_T5_FROM_SCRATCH = False if RECOMPILE_INTO_T5_FROM_SCRATCH: config = dict(target='t5-large', epochs=2, bf16=True, bsize=6, accumsteps=2, lr=5e-5) tp = BootstrapFinetune(metric=None) t5_program = tp.compile(BasicMH(), teacher=ensemble, trainset=unlabeled_train[:3000], **config) for p in t5_program.predictors(): p.activated = False if not RECOMPILE_INTO_T5_FROM_SCRATCH: t5_program = BasicMH() ckpt_path = "colbert-ir/dspy-Oct11-T5-Large-MH-3k-v1" LM =
dspy.HFModel(checkpoint=ckpt_path, model='t5-large')
dspy.HFModel
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve =
dspy.Retrieve(k=passages_per_hop)
dspy.Retrieve
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer =
dspy.ChainOfThought("context, question -> answer")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [
dspy.ChainOfThought("context, question -> search_query")
dspy.ChainOfThought
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context =
deduplicate(context + passages)
dsp.utils.utils.deduplicate
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import dspy from dspy.evaluate import Evaluate from dspy.datasets.hotpotqa import HotPotQA from dspy.teleprompt import BootstrapFewShotWithRandomSearch, BootstrapFinetune ports = [7140, 7141, 7142, 7143, 7144, 7145] llamaChat = dspy.HFClientTGI(model="meta-llama/Llama-2-13b-chat-hf", port=ports, max_tokens=150) colbertv2 = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts') dspy.settings.configure(rm=colbertv2, lm=llamaChat) dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=1000, test_size=0) trainset = [x.with_inputs('question') for x in dataset.train] devset = [x.with_inputs('question') for x in dataset.dev] testset = [x.with_inputs('question') for x in dataset.test] len(trainset), len(devset), len(testset) trainset[0] from dsp.utils.utils import deduplicate class BasicMH(dspy.Module): def __init__(self, passages_per_hop=3): super().__init__() self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = [dspy.ChainOfThought("context, question -> search_query") for _ in range(2)] self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): search_query = self.generate_query[hop](context=context, question=question).search_query passages = self.retrieve(search_query).passages context = deduplicate(context + passages) return self.generate_answer(context=context, question=question).copy(context=context) RECOMPILE_INTO_LLAMA_FROM_SCRATCH = False NUM_THREADS = 24 metric_EM = dspy.evaluate.answer_exact_match if RECOMPILE_INTO_LLAMA_FROM_SCRATCH: tp = BootstrapFewShotWithRandomSearch(metric=metric_EM, max_bootstrapped_demos=2, num_threads=NUM_THREADS) basicmh_bs = tp.compile(BasicMH(), trainset=trainset[:50], valset=trainset[50:200]) ensemble = [prog for *_, prog in basicmh_bs.candidate_programs[:4]] for idx, prog in enumerate(ensemble): pass if not RECOMPILE_INTO_LLAMA_FROM_SCRATCH: ensemble = [] for idx in range(4): prog = BasicMH() prog.load(f'multihop_llama213b_{idx}.json') ensemble.append(prog) llama_program = ensemble[0] evaluate_hotpot = Evaluate(devset=devset[:1000], metric=metric_EM, num_threads=NUM_THREADS, display_progress=True, display_table=0) evaluate_hotpot(llama_program) llama_program(question="How many storeys are in the castle that David Gregory inherited?") llamaChat.inspect_history(n=3) unlabeled_train = HotPotQA(train_seed=1, train_size=3000, eval_seed=2023, dev_size=0, test_size=0).train unlabeled_train = [
dspy.Example(question=x.question)
dspy.Example
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=
dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6})
dspy.Clarifai
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=
ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2)
dspy.retrieve.clarifai_rm.ClarifaiRM
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2)
dspy.settings.configure(lm=llm, rm=retriever_model)
dspy.settings.configure
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2) dspy.settings.configure(lm=llm, rm=retriever_model) sentence = "disney again ransacks its archives for a quick-buck sequel ." # example from the SST-2 dataset. classify =
dspy.Predict('sentence -> sentiment')
dspy.Predict
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2) dspy.settings.configure(lm=llm, rm=retriever_model) sentence = "disney again ransacks its archives for a quick-buck sequel ." # example from the SST-2 dataset. classify = dspy.Predict('sentence -> sentiment') print(classify(sentence=sentence).sentiment) retrieve =
dspy.Retrieve()
dspy.Retrieve
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2) dspy.settings.configure(lm=llm, rm=retriever_model) sentence = "disney again ransacks its archives for a quick-buck sequel ." # example from the SST-2 dataset. classify = dspy.Predict('sentence -> sentiment') print(classify(sentence=sentence).sentiment) retrieve = dspy.Retrieve() topK_passages = retrieve("can I test my vehicle engine in pit?").passages print(topK_passages) class GenerateAnswer(dspy.Signature): """Think and Answer questions based on the context provided.""" context = dspy.InputField(desc="may contain relevant facts about user query") question = dspy.InputField(desc="User query") answer = dspy.OutputField(desc="Answer in one or two lines") class RAG(dspy.Module): def __init__(self): super().__init__() self.retrieve = dspy.Retrieve() self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) my_question = "can I test my vehicle engine in pit before inspection?" Rag_obj= RAG() predict_response_llama70b=Rag_obj(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {predict_response_llama70b.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in predict_response_llama70b.context]}") mistral_lm =
dspy.Clarifai(model="https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct", api_key=PAT, n=2, inference_params={'temperature':0.6})
dspy.Clarifai
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2) dspy.settings.configure(lm=llm, rm=retriever_model) sentence = "disney again ransacks its archives for a quick-buck sequel ." # example from the SST-2 dataset. classify = dspy.Predict('sentence -> sentiment') print(classify(sentence=sentence).sentiment) retrieve = dspy.Retrieve() topK_passages = retrieve("can I test my vehicle engine in pit?").passages print(topK_passages) class GenerateAnswer(dspy.Signature): """Think and Answer questions based on the context provided.""" context = dspy.InputField(desc="may contain relevant facts about user query") question = dspy.InputField(desc="User query") answer = dspy.OutputField(desc="Answer in one or two lines") class RAG(dspy.Module): def __init__(self): super().__init__() self.retrieve = dspy.Retrieve() self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) my_question = "can I test my vehicle engine in pit before inspection?" Rag_obj= RAG() predict_response_llama70b=Rag_obj(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {predict_response_llama70b.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in predict_response_llama70b.context]}") mistral_lm = dspy.Clarifai(model="https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct", api_key=PAT, n=2, inference_params={'temperature':0.6})
dspy.settings.configure(lm=mistral_lm, rm=retriever_model)
dspy.settings.configure
get_ipython().system('pip install clarifai') get_ipython().system('pip install dspy-ai') import dspy from dspy.retrieve.clarifai_rm import ClarifaiRM MODEL_URL = "https://clarifai.com/meta/Llama-2/models/llama2-70b-chat" PAT = "CLARIFAI_PAT" USER_ID = "YOUR_ID" APP_ID = "YOUR_APP" from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader from langchain.vectorstores import Clarifai as clarifaivectorstore loader = TextLoader("YOUR_TEXT_FILE") #replace with your file path documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=200) docs = text_splitter.split_documents(documents) clarifai_vector_db = clarifaivectorstore.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=PAT ) llm=dspy.Clarifai(model=MODEL_URL, api_key=PAT, n=2, inference_params={"max_tokens":100,'temperature':0.6}) retriever_model=ClarifaiRM(clarifai_user_id=USER_ID, clarfiai_app_id=APP_ID, clarifai_pat=PAT, k=2) dspy.settings.configure(lm=llm, rm=retriever_model) sentence = "disney again ransacks its archives for a quick-buck sequel ." # example from the SST-2 dataset. classify = dspy.Predict('sentence -> sentiment') print(classify(sentence=sentence).sentiment) retrieve = dspy.Retrieve() topK_passages = retrieve("can I test my vehicle engine in pit?").passages print(topK_passages) class GenerateAnswer(dspy.Signature): """Think and Answer questions based on the context provided.""" context = dspy.InputField(desc="may contain relevant facts about user query") question = dspy.InputField(desc="User query") answer = dspy.OutputField(desc="Answer in one or two lines") class RAG(dspy.Module): def __init__(self): super().__init__() self.retrieve = dspy.Retrieve() self.generate_answer = dspy.ChainOfThought(GenerateAnswer) def forward(self, question): context = self.retrieve(question).passages prediction = self.generate_answer(context=context, question=question) return dspy.Prediction(context=context, answer=prediction.answer) my_question = "can I test my vehicle engine in pit before inspection?" Rag_obj= RAG() predict_response_llama70b=Rag_obj(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {predict_response_llama70b.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in predict_response_llama70b.context]}") mistral_lm = dspy.Clarifai(model="https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct", api_key=PAT, n=2, inference_params={'temperature':0.6}) dspy.settings.configure(lm=mistral_lm, rm=retriever_model) my_question = "can I test my vehicle engine in pit before inspection?" Rag_obj= RAG() predict_response_mistral=Rag_obj(my_question) print(f"Question: {my_question}") print(f"Predicted Answer: {predict_response_mistral.answer}") print(f"Retrieved Contexts (truncated): {[c[:200] + '...' for c in predict_response_mistral.context]}") gemini_lm =
dspy.Clarifai(model="https://clarifai.com/gcp/generate/models/gemini-pro", api_key=PAT, n=2)
dspy.Clarifai
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card