DSPy: The framework for programming—not prompting—language models
Python
clean-up: adding type hints and doc-strings (1/n)
Sri Vardhamananb2e89e35bd7e
diff --git a/dsp/modules/gpt3.py b/dsp/modules/gpt3.pyindex cf798e952..8eb24075a 100644--- a/dsp/modules/gpt3.py+++ b/dsp/modules/gpt3.py@@ -1,107 +1,150 @@+import functools+from typing import Optional, Any, castimport openaiimport openai.error+from openai.openai_object import OpenAIObjectimport backoff-import functoolsfrom dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory, cache_turn_ondef backoff_hdlr(details):- # Handler from https://pypi.org/project/backoff/- print("Backing off {wait:0.1f} seconds after {tries} tries "- "calling function {target} with args {args} and kwargs "- "{kwargs}".format(**details))+ """Handler from https://pypi.org/project/backoff/"""+ print(+ "Backing off {wait:0.1f} seconds after {tries} tries "+ "calling function {target} with args {args} and kwargs "+ "{kwargs}".format(**details)+ )class GPT3:- def __init__(self, model='text-davinci-002', api_key=None, **kwargs):+ """Wrapper around OpenAI's GPT-3 API."""++ def __init__(+ self, model: str = "text-davinci-002", api_key: Optional[str] = None, **kwargs+ ):if api_key:openai.api_key = api_key- self.kwargs = {'model': model, 'temperature': 0.0, 'max_tokens': 150, 'top_p': 1,- 'frequency_penalty': 0, 'presence_penalty': 0, 'n': 1, **kwargs} # TODO: add kwargs above for </s>+ self.kwargs = {+ "model": model,+ "temperature": 0.0,+ "max_tokens": 150,+ "top_p": 1,+ "frequency_penalty": 0,+ "presence_penalty": 0,+ "n": 1,+ **kwargs,+ } # TODO: add kwargs above for </s>- self.history = []+ self.history: list[dict[str, Any]] = []- def basic_request(self, prompt, **kwargs):+ def _basic_request(self, prompt: str, **kwargs) -> OpenAIObject:raw_kwargs = kwargs- kwargs = {**self.kwargs, 'prompt': prompt, **kwargs}+ kwargs = {**self.kwargs, "prompt": prompt, **kwargs}response = cached_gpt3_request(**kwargs)- history = {'prompt': prompt, 'response': response,- 'kwargs': kwargs, 'raw_kwargs': raw_kwargs}+ history = {+ "prompt": prompt,+ "response": response,+ "kwargs": kwargs,+ "raw_kwargs": raw_kwargs,+ }self.history.append(history)return response- @backoff.on_exception(backoff.expo,- (openai.error.RateLimitError,- openai.error.ServiceUnavailableError),- max_time=1000,- on_backoff=backoff_hdlr)- def request(self, prompt, **kwargs):- return self.basic_request(prompt, **kwargs)-- def print_green(self, text, end='\n'):+ @backoff.on_exception(+ backoff.expo,+ (openai.error.RateLimitError, openai.error.ServiceUnavailableError),+ max_time=1000,+ on_backoff=backoff_hdlr,+ )+ def request(self, prompt: str, **kwargs) -> OpenAIObject:+ """Handles retreival of GPT-3 completions whilst handling rate limiting and caching."""+ return self._basic_request(prompt, **kwargs)++ def print_green(self, text: str, end: str = "\n"):print("\x1b[32m" + str(text) + "\x1b[0m", end=end)-- def print_red(self, text, end='\n'):++ def print_red(self, text: str, end: str = "\n"):print("\x1b[31m" + str(text) + "\x1b[0m", end=end)- def inspect_history(self, n=1):+ def inspect_history(self, n: int = 1):+ """Prints the last n prompts and their completions.+ TODO: print the valid choice with all fields filled instead of the first+ """last_prompt = Noneprinted = []for x in reversed(self.history[-100:]):- prompt = x['prompt']+ prompt = x["prompt"]if prompt != last_prompt:- printed.append((prompt, x['response']['choices']))-+ printed.append((prompt, x["response"]["choices"]))+last_prompt = promptif len(printed) >= n:break-+for prompt, choices in reversed(printed):- print('\n\n\n')- print(prompt, end='')- self.print_green(choices[0]['text'], end='')+ print("\n\n\n")+ print(prompt, end="")+ self.print_green(choices[0]["text"], end="")if len(choices) > 1:- self.print_red(f" \t (and {len(choices)-1} other completions)", end='')- print('\n\n\n')--- def __call__(self, prompt, only_completed=True, return_sorted=False, **kwargs):+ self.print_red(f" \t (and {len(choices)-1} other completions)", end="")+ print("\n\n\n")++ def __call__(+ self,+ prompt: str,+ only_completed: bool = True,+ return_sorted: bool = False,+ **kwargs,+ ) -> list[dict[str, Any]]:+ """Retrieves completions from GPT-3.++ Args:+ prompt (str): prompt to send to GPT-3+ only_completed (bool, optional): return only completed responses and ignores completion due to length. Defaults to True.+ return_sorted (bool, optional): sort the completion choices using the returned probabilities. Defaults to False.++ Returns:+ list[dict[str, Any]]: list of completion choices+ """assert only_completed, "for now"assert return_sorted is False, "for now"- if kwargs.get('n', 1) > 1:- kwargs = {**kwargs, 'logprobs': 5}+ if kwargs.get("n", 1) > 1:+ kwargs = {**kwargs, "logprobs": 5}response = self.request(prompt, **kwargs)- choices = response['choices']+ choices = response["choices"]- completed_choices = [c for c in choices if c['finish_reason'] != 'length']+ completed_choices = [c for c in choices if c["finish_reason"] != "length"]if only_completed and len(completed_choices):choices = completed_choices- completions = [c['text'] for c in choices]+ completions = [c["text"] for c in choices]- if return_sorted and kwargs.get('n', 1) > 1:+ if return_sorted and kwargs.get("n", 1) > 1:scored_completions = []for c in choices:- tokens, logprobs = c['logprobs']['tokens'], c['logprobs']['token_logprobs']+ tokens, logprobs = (+ c["logprobs"]["tokens"],+ c["logprobs"]["token_logprobs"],+ )- if '<|endoftext|>' in tokens:- index = tokens.index('<|endoftext|>') + 1+ if "<|endoftext|>" in tokens:+ index = tokens.index("<|endoftext|>") + 1tokens, logprobs = tokens[:index], logprobs[:index]avglog = sum(logprobs) / len(logprobs)- scored_completions.append((avglog, c['text']))+ scored_completions.append((avglog, c["text"]))scored_completions = sorted(scored_completions, reverse=True)completions = [c for _, c in scored_completions]@@ -110,13 +153,13 @@ class GPT3:@CacheMemory.cache-def cached_gpt3_request_v2(**kwargs):- return openai.Completion.create(**kwargs)+def cached_gpt3_request_v2(**kwargs) -> OpenAIObject:+ return cast(OpenAIObject, openai.Completion.create(**kwargs))@functools.lru_cache(maxsize=None if cache_turn_on else 0)@NotebookCacheMemory.cache-def cached_gpt3_request_v2_wrapped(**kwargs):+def cached_gpt3_request_v2_wrapped(**kwargs) -> OpenAIObject:return cached_gpt3_request_v2(**kwargs)diff --git a/dsp/primitives/demonstrate.py b/dsp/primitives/demonstrate.pyindex a5086828c..e0770330e 100644--- a/dsp/primitives/demonstrate.py+++ b/dsp/primitives/demonstrate.py@@ -1,5 +1,5 @@import random-from typing import Callable, List+from typing import Callable, Anyimport numpy as np@@ -7,13 +7,15 @@ import dspfrom dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text-class Example(dotdict):+ """A primitive datatype for representing an example"""++ demos: list[Any]+def __init__(self, *args, **kwargs):- assert len(args) <= 1super().__init__()- if len(args):+ if args:assert len(args) == 1self.update(args[0])@@ -25,29 +27,31 @@ class Example(dotdict):return the_copydef without(self, *keys):+ """Removes the provided keys from the example and returns a copy"""keys = set(keys)return Example({k: v for k, v in self.items() if k not in keys})def demos_at(self, fn):- def at(d):+ """Returns a copy of the example with the demos stage transformed by the provided function"""++ def at(example):try:- return fn(d).without('augmented')- except:+ return fn(example).without("augmented")+ except Exception:return {}- demos = [d.copy(**at(d)) for d in self.demos]+ demos = [example.copy(**at(example)) for example in self.demos]return self.copy(demos=demos)- # def __str__(self):- # return self.get('question', self.get('query'))-def annotate(*transformations):+ """Returns an Augment function that applies the provided transformations to the Examples"""+def do_augment(train, k=None, return_all=False):rdemos = []ademos = []- for example in (train): # tqdm.tqdm+ for example in train: # tqdm.tqdmraw_example = dsp.Example(example)if k and len(ademos) >= k:@@ -74,85 +78,78 @@ def annotate(*transformations):return do_augment-def sample(train, k: int):- branch_idx = (- hasattr(dsp.settings, 'branch_idx')- and isinstance(dsp.settings.branch_idx, int)- and dsp.settings.branch_idx- )- branch_idx = branch_idx or 0- # print(f"branch_idx = {branch_idx}")-- rng = random.Random(branch_idx)- shuffled_train = list(train)+def sample(train: list[Example], k: int):+ """Sample k examples from train."""+ rng = random.Random(dsp.settings.branch_idx)+ shuffled_train = [example.copy() for example in train]rng.shuffle(shuffled_train)- subset = shuffled_train[:k]- subset = [dsp.Example(x) for x in subset] # augmented=False+ return shuffled_train[:k]- return subset--def all_but(train, x):- # output = [y for y in train if y.question != x.question]+def all_but(train: list[Example], x: Example) -> list[Example]:+ """Removes the example x from the train set by comparing the question and history."""output = [- y for y in train+ y+ for y in trainif not set.intersection(- set(x.get('history', []) + [x.question]),- set(y.get('history', []) + [y.question])+ set(x.get("history", []) + [x.question]),+ set(y.get("history", []) + [y.question]),)]- # print(len(output))return output-def passage_match(passages, answers):- # passages = example.passages- # answers = example.answers+def passage_match(passages: list[str], answers: str) -> bool:+ """Returns True if any of the passages contains the answer."""return any(passage_has_answers(psg, answers) for psg in passages)+def answer_match(prediction, answers, frac=1.0):# pred = example.prediction# answers = example.answersif frac >= 1.0:return EM(prediction, answers)-+return F1(prediction, answers) >= frac-def passage_has_answers(passage, answers):+def passage_has_answers(passage: str, answers: str) -> bool:+ """Returns True if the passage contains the answer."""return has_answer(tokenized_answers=[DPR_normalize(normalize_text(ans)) for ans in answers],- text=normalize_text(passage)+ text=normalize_text(passage),)def cast_naive_get_only_question_text(inp_example: Example) -> Example:- '''+ """Extracts question as a field to vectorize with Vectorizer object. `question` field is used.- '''+ """return inp_example.copy(text_to_vectorize=inp_example.question)def cast_naive_get_question_and_answer(inp_example: Example) -> Example:- '''+ """Extracts question and answer as fields to vectorize with Vectorizer object.`question` and `answer` fields are used. They will be concatenated with the word "Answer"between.- '''- text_to_vectorize = inp_example.question.strip() + " Answer: " + inp_example.answer.strip()+ """+ text_to_vectorize = (+ inp_example.question.strip() + " Answer: " + inp_example.answer.strip()+ )return inp_example.copy(text_to_vectorize=text_to_vectorize)def knn(- train: List[Example],+ train: list[Example],cast: Callable[[Example], Example] = cast_naive_get_only_question_text,**knn_args-) -> Callable[[Example, int], List[Example]]:- '''+) -> Callable[[Example, int], list[Example]]:+ """A function that vectorizes train data using `dsm.settings.vectorizer`, then build an ANN/KNNindex to search similar questions among `train` samples.@@ -164,18 +161,21 @@ def knn(Doesn't affect bruteforce-based search.knn_args: check `create_faiss_index` function for details on ANN/KNN arguments.Returns: function to search similar Examples from `train` in FAISS-index.- '''+ """from dsp.utils.ann_utils import create_faiss_index+train_casted_to_vectorize = [cast(cur_elem) for cur_elem in train]vectorizer: "BaseSentenceVectorizer" = dsp.settings.vectorizerall_vectors = vectorizer(train_casted_to_vectorize).astype(np.float32)- index = create_faiss_index(emb_dim=all_vectors.shape[1], n_objects=len(train), **knn_args)+ index = create_faiss_index(+ emb_dim=all_vectors.shape[1], n_objects=len(train), **knn_args+ )index.train(all_vectors)index.add(all_vectors)- def inner_knn_search(inp_example: Example, k: int) -> List[Example]:+ def inner_knn_search(inp_example: Example, k: int) -> list[Example]:inp_example_vector = vectorizer([cast(inp_example)])_, nearest_samples_idxs = index.search(inp_example_vector, k)train_sampled = [train[cur_idx] for cur_idx in nearest_samples_idxs[0]]diff --git a/dsp/primitives/predict.py b/dsp/primitives/predict.pyindex 2e5478f74..da18814f8 100644--- a/dsp/primitives/predict.py+++ b/dsp/primitives/predict.py@@ -1,11 +1,16 @@-import dspfrom collections import Counter+from typing import Callable, Any, Optional+import dspfrom dsp.utils import zipstar, normalize_textfrom dsp.utils.utils import dotdict+from dsp.templates.template_v3 import Template+from dsp.primitives.demonstrate import Exampleclass Completions:- def __init__(self, completions: list, template):+ """A state object that holds the valid LM completions for a given Template."""++ def __init__(self, completions: list[Example], template: Template):self.data = completionsself.template = template@@ -31,55 +36,74 @@ class Completions:if name in completion.keys():return getattr(completion, name)-- if name.endswith('s') and name[:-1] in completion.keys():++ if name.endswith("s") and name[:-1] in completion.keys():passassert False, name+def generate(template: Template, **kwargs) -> Callable:+ """Returns a callable function that generates completions for a given example using the provided template."""+ # todo: re-think this? doesn't seem like a good way to pass the template to nested function+ if not dsp.settings.lm:+ raise AssertionError("No LM is loaded.")-def generate(template, **kwargs):generator = dsp.settings.lm- def do_generate(example, stage, max_depth=2, original_example=None):+ def do_generate(+ example: Example, stage: str, max_depth: int = 2, original_example=None+ ):original_example = original_example or exampleassert stage is not None# Look up the appropriate fields in each demonstration.example = example.demos_at(lambda d: d[stage])-+# Generate and extract the fields.prompt = template(example)- completions = generator(prompt, **kwargs)- completions = [template.extract(example, p) for p in completions]+ completions: list[dict[str, Any]] = generator(prompt, **kwargs)+ completions: list[Example] = [template.extract(example, p) for p in completions]# Find the completions that are most complete.- field_names = [field.input_variable for field in template.fields]+ field_names: list[str] = [field.input_variable for field in template.fields]last_field_idx = 0for field_idx, key in enumerate(field_names):- completions_ = [c for c in completions if key in c.keys() and c[key] is not None]+ completions_ = [+ c for c in completions if key in c.keys() and c[key] is not None+ ]# Filter out completions that are missing fields that are present in at least one completion.if len(completions_):completions = completions_- last_field_idx = field_idx+1-+ last_field_idx = field_idx + 1+# If none of the completions is completed (i.e., none has the final field set).if last_field_idx < len(field_names):# Pick the first completion that has gone farthest.completion = completions[0]- completion[field_names[last_field_idx]] = ''+ completion[field_names[last_field_idx]] = ""# Recurse with greedy decoding and a shorter length.- max_tokens = kwargs.get('max_tokens', dsp.settings.lm.kwargs['max_tokens'])+ max_tokens = kwargs.get("max_tokens", dsp.settings.lm.kwargs["max_tokens"])max_tokens = min(max(75, max_tokens // 2), max_tokens)- new_kwargs = {**kwargs, 'max_tokens': max_tokens, 'n': 1, 'temperature': 0.0}+ new_kwargs = {+ **kwargs,+ "max_tokens": max_tokens,+ "n": 1,+ "temperature": 0.0,+ }assert max_depth > 0- return generate(template, **new_kwargs)(completion, stage=stage, max_depth=max_depth-1, original_example=original_example)-+ return generate(template, **new_kwargs)(+ completion,+ stage=stage,+ max_depth=max_depth - 1,+ original_example=original_example,+ )++ # print("completion found: {}".format(completions))completions = Completions(completions, template=template)example = example.copy(completions=completions)@@ -89,44 +113,76 @@ def generate(template, **kwargs):if dsp.settings.compiling:inputs_ = set(original_example.keys())- inputs = [f.input_variable for f in template.fields if f.input_variable in inputs_]- outputs = [f.output_variable for f in template.fields if f.input_variable not in inputs_]-- example.compiling_stages = example.get('compiling_stages', [])- example.compiling_stages.append({'name': stage, 'template': template, 'inputs': inputs, 'outputs': outputs})+ inputs = [+ f.input_variable+ for f in template.fields+ if f.input_variable in inputs_+ ]+ outputs = [+ f.output_variable+ for f in template.fields+ if f.input_variable not in inputs_+ ]++ example.compiling_stages = example.get("compiling_stages", [])+ example.compiling_stages.append(+ {+ "name": stage,+ "template": template,+ "inputs": inputs,+ "outputs": outputs,+ }+ )else:# assert not dsp.settings.compiling, "TODO: At this point, cannot compile n>1 generations"example[stage] = dotdict(completions=completions)return example, completions-+return do_generate-def generate_sc(example, prompt, normalize=True, extract=None, prediction_field=None, **kwargs):- kwargs = {'temperature': 0.7, 'max_tokens': 150, 'n': 20, **kwargs}+def generate_sc(+ example, prompt, normalize=True, extract=None, prediction_field=None, **kwargs+):+ kwargs = {"temperature": 0.7, "max_tokens": 150, "n": 20, **kwargs}completions = dsp.settings.lm(prompt, **kwargs)completions = extract_final_answer(example, completions, extract=extract)- return majority_vote_(completions, normalize=normalize, prediction_field=prediction_field)+ return majority_vote_(+ completions, normalize=normalize, prediction_field=prediction_field+ )+def extract_final_answer(example, completions, extract=None):if extract:completions = [extract(example, p) for p in completions]else:- completions = [p.strip().split('\n')[-1].split(':', 1)[-1].strip() for p in completions]+ completions = [+ p.strip().split("\n")[-1].split(":", 1)[-1].strip() for p in completions+ ]- dsp.settings.lm.history.append({**dsp.settings.lm.history[-1], 'completions': completions})+ dsp.settings.lm.history.append(+ {**dsp.settings.lm.history[-1], "completions": completions}+ )return completions-def majority(completions, normalize=True, field=None):++def majority(+ completions: Completions, normalize: bool = True, field: Optional[str] = None+):+ """Returns the most common completion for the target field or the last field in the template."""field = completions.template.fields[-1].output_variable if field is None else field- return Completions(majority_vote_(completions, normalize=normalize, prediction_field=field),- template=completions.template)+ return Completions(+ majority_vote_(completions, normalize=normalize, prediction_field=field),+ template=completions.template,+ )-def majority_vote_(completions, normalize: bool, prediction_field: str):+def majority_vote_(completions: Completions, normalize: bool, prediction_field: str):+ """Core logic for majority vote."""+ normalized_to_original = {}if normalize:original_completions = completionscompletions_ = []@@ -134,16 +190,14 @@ def majority_vote_(completions, normalize: bool, prediction_field: str):if prediction_field in pred:completions_.append(normalize_text(pred[prediction_field]))else:- completions_.append('')+ completions_.append("")completions = completions_- normalized_to_original = {}for completion, normalized_completion in zip(original_completions, completions):if normalized_completion not in normalized_to_original:normalized_to_original[normalized_completion] = completioncompletions_ = [x for x in completions if x]- # completions_ = [x for x in completions_ if len(x.split()) < 7]if completions_:completions = completions_@@ -154,8 +208,8 @@ def majority_vote_(completions, normalize: bool, prediction_field: str):if normalize:pred = normalized_to_original[pred]- dsp.settings.lm.history.append({**dsp.settings.lm.history[-1], 'topk': topk, 'completions': [pred]})+ dsp.settings.lm.history.append(+ {**dsp.settings.lm.history[-1], "topk": topk, "completions": [pred]}+ )return [pred]--diff --git a/dsp/primitives/primitives.py b/dsp/primitives/primitives.pyindex 51f4f6b4e..fd839dea2 100644--- a/dsp/primitives/primitives.py+++ b/dsp/primitives/primitives.py@@ -1,6 +1,5 @@import dspimport copy-from functools import wraps# applied right to left (innermost first, like function calls)diff --git a/dsp/primitives/search.py b/dsp/primitives/search.pyindex a080b6046..e27f574e5 100644--- a/dsp/primitives/search.py+++ b/dsp/primitives/search.py@@ -1,18 +1,23 @@import dsp-def retrieve(query: str, k):+def retrieve(query: str, k: int) -> list[str]:+ """Retrieves passages from the RM for the query and returns the top k passages."""passages = dsp.settings.rm(query, k=k)passages = [psg.long_text for psg in passages]return passages-def retrieveEnsemble(queries, k, by_prob=True):++def retrieveEnsemble(queries: list[str], k: int, by_prob: bool = True) -> list[str]:+ """Retrieves passages from the RM for each query in queries and returns the top k passages+ based on the probability or score.+ """queries = [q for q in queries if q]passages = {}for q in queries:- for psg in dsp.settings.rm(q, k=k*3):+ for psg in dsp.settings.rm(q, k=k * 3):if by_prob:passages[psg.long_text] = passages.get(psg.long_text, 0.0) + psg.probelse:diff --git a/dsp/templates/template_v2.py b/dsp/templates/template_v2.pyindex f9858aa42..0b0dcaf1a 100644--- a/dsp/templates/template_v2.py+++ b/dsp/templates/template_v2.py@@ -1,45 +1,32 @@from collections import namedtupleimport re-+from typing import Union, Anyimport dsp+from dsp.primitives.demonstrate import Example+from .utils import passages2text, format_answersField = namedtuple("Field", "name separator input_variable output_variable description")# TODO: de-duplicate with dsp/templates/template.py-def passages2text(passages):- if type(passages) is str:- return passages-- assert type(passages) in [list, tuple]-- if len(passages) == 1:- return f"«{passages[0]}»"-- return "\n".join([f"[{idx+1}] «{txt}»" for idx, txt in enumerate(passages)])---def format_answers(answers):- if isinstance(answers, list):- if len(answers) >= 1:- return str(answers[0]).strip()- elif len(answers) == 0:- raise ValueError(f"No answers found")- elif isinstance(answers, str):- return answers- else:- raise ValueError(f"Unable to parse answers of type {type(answers)}")--class TemplateV2:- def __init__(self, template, format_handlers={"passages": passages2text, "context": passages2text, "answer": format_answers, "answers": format_answers}):+ def __init__(+ self,+ template,+ format_handlers={+ "passages": passages2text,+ "context": passages2text,+ "answer": format_answers,+ "answers": format_answers,+ },+ ):self.format_handlers = format_handlerstemplate = template.strip()self.instructions = re.search("(.*)\n", template).group(1)- template = template[len(self.instructions):].strip()+ template = template[len(self.instructions) :].strip()self.fields = []while len(template) > 0:@@ -77,10 +64,11 @@ class TemplateV2:))- template = template[len(match.group(0)):].strip()+ template = template[len(match.group(0)) :].strip()- def query(self, example, is_demo=False):- result = []+ def query(self, example: Example, is_demo: bool = False) -> str:+ """Retrieves the input variables from the example and formats them into a query string."""+ result: list[str] = []if not is_demo:has_value = [@@ -96,22 +84,34 @@ class TemplateV2:breakfor field in self.fields:- if (field.input_variable in example and example[field.input_variable] is not None):+ if (+ field.input_variable in example+ and example[field.input_variable] is not None+ ):if field.input_variable in self.format_handlers:format_handler = self.format_handlers[field.input_variable]else:- def format_handler(x): return ' '.join(x.split())-- result.append(f"{field.name}{field.separator}{format_handler(example[field.input_variable])}")- if self._has_augmented_guidelines() and ("augmented" in example and example.augmented):+ def format_handler(x):+ return " ".join(x.split())++ result.append(+ f"{field.name}{field.separator}{format_handler(example[field.input_variable])}"+ )++ if self._has_augmented_guidelines() and (+ "augmented" in example and example.augmented+ ):return "\n\n".join(result)- else:- return "\n".join(result)+ return "\n".join(result)- def guidelines(self, show_guidelines=True):- if (not show_guidelines) or (hasattr(dsp.settings, 'show_guidelines') and not dsp.settings.show_guidelines):- return ''+ def guidelines(self, show_guidelines=True) -> str:+ """Returns the task guidelines as described in the lm prompt"""+ if (not show_guidelines) or (+ hasattr(dsp.settings, "show_guidelines")+ and not dsp.settings.show_guidelines+ ):+ return ""result = "Follow the following format.\n\n"@@ -124,54 +124,64 @@ class TemplateV2:return resultdef _has_augmented_guidelines(self):- return len(self.fields) > 3 or any(field.separator == "\n" for field in self.fields)-- def extract(self, example, raw_pred):+ return len(self.fields) > 3 or any(+ field.separator == "\n" for field in self.fields+ )++ def extract(+ self, example: Union[Example, dict[str, Any]], raw_pred: str+ ) -> Example:+ """Extracts the answer from the LM raw prediction using the template structure++ Args:+ example (Union[Example, dict[str, Any]]): Contains the input variables that raw_pred was completed on.+ raw_pred (str): LM generated string++ Returns:+ Example: The example with the output variables filled in+ """example = dsp.Example(example)raw_pred = raw_pred.strip()idx = 0while idx < len(self.fields):- if (self.fields[idx].input_variable not in example or example[self.fields[idx].input_variable] is None):+ if (+ self.fields[idx].input_variable not in example+ or example[self.fields[idx].input_variable] is None+ ):breakidx += 1-- idx = min(idx, len(self.fields) - 1)+ idx = min(idx, len(self.fields) - 1)while raw_pred != "" and idx < len(self.fields):- # print("HERE,", idx)if idx < len(self.fields) - 1:- next_field_name = '\n' + self.fields[idx + 1].name+ next_field_name = "\n" + self.fields[idx + 1].nameoffset = raw_pred.find(next_field_name)- # print(f"Looking for ```{next_field_name}```. Found it at {offset}")if offset >= 0:- example[self.fields[idx].output_variable] = raw_pred[:offset].strip()- raw_pred = raw_pred[offset + len(next_field_name):].strip()+ example[self.fields[idx].output_variable] = raw_pred[+ :offset+ ].strip()+ raw_pred = raw_pred[offset + len(next_field_name) :].strip()idx += 1else:example[self.fields[idx].output_variable] = raw_pred.strip()raw_pred = ""idx += 1- # print("Exiting")break- else: #if idx == len(self.fields) - 1:+ else:assert idx == len(self.fields) - 1, (idx, len(self.fields))example[self.fields[idx].output_variable] = raw_pred.strip()break- # offset = raw_pred.find(self.fields[idx].name)- # if offset < 0:- # else:- # raw_pred = raw_pred[offset + len(self.fields[idx].name):].strip()- # example[self.fields[idx].output_variable] = raw_predreturn example- def __call__(self, example, show_guidelines=True):+ def __call__(self, example, show_guidelines=True) -> str:example = dsp.Example(example)+ # The training data should not contain the output variableif self.fields[-1].input_variable in example:del example[self.fields[-1].input_variable]@@ -180,12 +190,13 @@ class TemplateV2:for demo in example.demosif (("augmented" not in demo or not demo.augmented)- and (+ and ( # validate that the training example has the same primitive input var as the templateself.fields[-1].input_variable in demoand demo[self.fields[-1].input_variable] is not None))]+ademos = [self.query(demo, is_demo=True)for demo in example.demos@@ -196,16 +207,29 @@ class TemplateV2:if long_query:example["augmented"] = Truequery = self.query(example)-rdemos = "\n\n".join(rdemos)if len(rdemos) >= 1 and len(ademos) == 0 and not long_query:rdemos_and_query = "\n\n".join([rdemos, query])- parts = [self.instructions, self.guidelines(show_guidelines), rdemos_and_query]+ parts = [+ self.instructions,+ self.guidelines(show_guidelines),+ rdemos_and_query,+ ]elif len(rdemos) == 0:- parts = [self.instructions, self.guidelines(show_guidelines), *ademos, query]+ parts = [+ self.instructions,+ self.guidelines(show_guidelines),+ *ademos,+ query,+ ]else:- parts = [self.instructions, rdemos,- self.guidelines(show_guidelines), *ademos, query]+ parts = [+ self.instructions,+ rdemos,+ self.guidelines(show_guidelines),+ *ademos,+ query,+ ]prompt = "\n\n---\n\n".join([p.strip() for p in parts if p])diff --git a/dsp/templates/template_v3.py b/dsp/templates/template_v3.pyindex 0e6a6b0f8..d0e67e250 100644--- a/dsp/templates/template_v3.py+++ b/dsp/templates/template_v3.py@@ -1,30 +1,49 @@+from typing import Callablefrom dsp.templates import TemplateV2, passages2text, format_answers, Field+class Type:- def __init__(self, prefix, desc, format=None, aliases=[]) -> None:+ """A primitive datatype that defines and represents a prompt label."""++ def __init__(self, prefix: str, desc: str, format=None, aliases=[]) -> None:self.prefix = prefixself.desc = descself.format = formatself.aliases = aliases- assert aliases == [], "TODO: If aliases is used, handling of input_variable in V2 needs to be richer."-+ assert (+ aliases == []+ ), "TODO: If aliases is used, handling of input_variable in V2 needs to be richer."+def __call__(self, **kwargs):kwargs = {**self.__dict__, **kwargs}return Type(**kwargs)+class Template(TemplateV2):- def __init__(self, instructions, **kwargs):+ """A template datatype that represents the structure of communicate with the LM."""++ def __init__(self, instructions: str, **kwargs):self.instructions = instructions- self.fields = []- self.format_handlers = {"context": passages2text, "answers": format_answers}+ self.fields: list[Field] = []+ self.format_handlers: dict[str, Callable] = {+ "context": passages2text,+ "answers": format_answers,+ }for key, value in kwargs.items():- prefix = value.prefix- separator = ' ' if prefix.rstrip() == prefix else prefix[len(prefix.rstrip()):]- field = Field(name=prefix.strip(), description=value.desc,- input_variable=key, output_variable=key, separator=separator)+ prefix: str = value.prefix+ separator: str = (+ " " if prefix.rstrip() == prefix else prefix[len(prefix.rstrip()) :]+ )+ field = Field(+ name=prefix.strip(),+ description=value.desc,+ input_variable=key,+ output_variable=key,+ separator=separator,+ )self.fields.append(field)if value.format:diff --git a/dsp/templates/utils.py b/dsp/templates/utils.pyindex 8c217d535..191a5356a 100644--- a/dsp/templates/utils.py+++ b/dsp/templates/utils.py@@ -1,5 +1,9 @@-def passages2text(passages):- if type(passages) is str:+from typing import Union, Optional+++def passages2text(passages: Union[str, list, tuple]) -> str:+ """Formats the given one or more passages into a single structured string."""+ if isinstance(passages, str):return passagesassert type(passages) in [list, tuple]@@ -7,4 +11,29 @@ def passages2text(passages):if len(passages) == 1:return f"«{passages[0]}»"- return '\n'.join([f"[{idx+1}] «{txt}»" for idx, txt in enumerate(passages)])+ return "\n".join([f"[{idx+1}] «{txt}»" for idx, txt in enumerate(passages)])+++def format_answers(answers: Union[str, list]) -> Optional[str]:+ """Parses the given answers and returns the appropriate answer string.++ Args:+ answers (Union[str, list]): The answers to parse.++ Raises:+ ValueError: when instance is of type list and has no answers+ ValueError: when is not of type list or str++ Returns:+ _type_: Optiona[str]+ """+ if isinstance(answers, list):+ # TODO: why can answer not have one value?+ if len(answers) >= 1:+ return str(answers[0]).strip()+ if len(answers) == 0:+ raise ValueError("No answers found")+ elif isinstance(answers, str):+ return answers+ else:+ raise ValueError(f"Unable to parse answers of type {type(answers)}")diff --git a/dsp/utils/settings.py b/dsp/utils/settings.pyindex 5c62d2914..1a69ca639 100644--- a/dsp/utils/settings.py+++ b/dsp/utils/settings.py@@ -1,20 +1,30 @@+from typing import Callable, Optionalfrom contextlib import contextmanagerfrom dsp.utils.utils import dotdictclass Settings(object):+ """DSP configuration settings."""+_instance = None+ branch_idx: int = 0def __new__(cls):"""Singleton Pattern. See https://python-patterns.guide/gang-of-four/singleton/"""-+if cls._instance is None:cls._instance = super().__new__(cls)cls._instance.stack = []- config = dotdict(lm=None, rm=None, compiled_lm=None, force_reuse_cached_compilation=False, compiling=False)+ config = dotdict(+ lm=None,+ rm=None,+ compiled_lm=None,+ force_reuse_cached_compilation=False,+ compiling=False,+ )cls._instance.__append(config)return cls._instance@@ -26,7 +36,7 @@ class Settings(object):def __getattr__(self, name):if hasattr(self.config, name):return getattr(self.config, name)-+if name in self.config:return self.config[name]@@ -37,10 +47,17 @@ class Settings(object):def __pop(self):self.stack.pop()-- def configure(self, inherit_config=True, **kwargs):++ def configure(self, inherit_config: bool = True, **kwargs):+ """Set configuration settings.++ Args:+ inherit_config (bool, optional): Set configurations for the given, and use existing configurations for the rest. Defaults to True.+ """if inherit_config:config = {**self.config, **kwargs}+ else:+ config = {**kwargs}self.__append(config)@@ -56,4 +73,5 @@ class Settings(object):def __repr__(self) -> str:return repr(self.config)+settings = Settings()diff --git a/dsp/utils/utils.py b/dsp/utils/utils.pyindex ec5978ffe..f4a738ce5 100644--- a/dsp/utils/utils.py+++ b/dsp/utils/utils.py@@ -7,14 +7,13 @@ from collections import defaultdictdef print_message(*s, condition=True, pad=False, sep=None):- s = ' '.join([str(x) for x in s])+ s = " ".join([str(x) for x in s])msg = "[{}] {}".format(datetime.datetime.now().strftime("%b %d, %H:%M:%S"), s)if condition:- msg = msg if not pad else f'\n{msg}\n'+ msg = msg if not pad else f"\n{msg}\n"print(msg, flush=True, sep=sep)-return msg@@ -27,7 +26,9 @@ def timestamp(daydir=False):def file_tqdm(file):print(f"#> Reading {file.name}")- with tqdm.tqdm(total=os.path.getsize(file.name) / 1024.0 / 1024.0, unit="MiB") as pbar:+ with tqdm.tqdm(+ total=os.path.getsize(file.name) / 1024.0 / 1024.0, unit="MiB"+ ) as pbar:for line in file:yield linepbar.update(len(line) / 1024.0 / 1024.0)@@ -37,15 +38,15 @@ def file_tqdm(file):def create_directory(path):if os.path.exists(path):- print('\n')- print_message("#> Note: Output directory", path, 'already exists\n\n')+ print("\n")+ print_message("#> Note: Output directory", path, "already exists\n\n")else:- print('\n')- print_message("#> Creating directory", path, '\n\n')+ print("\n")+ print_message("#> Creating directory", path, "\n\n")os.makedirs(path)-def deduplicate(seq):+def deduplicate(seq: list[str]) -> list[str]:"""Source: https://stackoverflow.com/a/480227/1493011"""@@ -57,7 +58,7 @@ def deduplicate(seq):def batch(group, bsize, provide_offset=False):offset = 0while offset < len(group):- L = group[offset: offset + bsize]+ L = group[offset : offset + bsize]yield ((offset, L) if provide_offset else L)offset += len(L)return@@ -68,6 +69,7 @@ class dotdict(dict):dot.notation access to dictionary attributesCredit: derek73 @ https://stackoverflow.com/questions/2352181"""+__getattr__ = dict.__getitem____setattr__ = dict.__setitem____delattr__ = dict.__delitem__@@ -119,9 +121,9 @@ def zip_first(L1, L2):def int_or_float(val):- if '.' in val:+ if "." in val:return float(val)-+return int(val)@@ -137,7 +139,7 @@ def groupby_first_item(lst):def process_grouped_by_first_item(lst):"""- Requires items in list to already be grouped by first item.+ Requires items in list to already be grouped by first item."""groups = defaultdict(list)@@ -150,7 +152,9 @@ def process_grouped_by_first_item(lst):if started and first != last_group:yield (last_group, groups[last_group])- assert first not in groups, f"{first} seen earlier --- violates precondition."+ assert (+ first not in groups+ ), f"{first} seen earlier --- violates precondition."groups[first].append(rest)@@ -185,8 +189,10 @@ def lengths2offsets(lengths):class NullContextManager(object):def __init__(self, dummy_resource=None):self.dummy_resource = dummy_resource+def __enter__(self):return self.dummy_resource+def __exit__(self, *args):pass@@ -203,9 +209,9 @@ def load_batch_backgrounds(args, qids):if len(back) and type(back[0]) == int:x = [args.collection[pid] for pid in back]else:- x = [args.collectionX.get(pid, '') for pid in back]+ x = [args.collectionX.get(pid, "") for pid in back]- x = ' [SEP] '.join(x)+ x = " [SEP] ".join(x)qbackgrounds.append(x)-+return qbackgrounds