DSPy: The framework for programming—not prompting—language models
Python
Merge branch 'main' into hf_models
Omar Khattab4354556873c3
diff --cc dsp/modules/gpt3.pyindex 8f828a31c,78bd63c5c..5caeb6ed1--- a/dsp/modules/gpt3.py+++ b/dsp/modules/gpt3.py@@@ -1,50 -1,134 +1,137 @@@+ import functools+ import json+ from typing import Optional, Any, castimport openaiimport openai.error+ from openai.openai_object import OpenAIObjectimport backoff- import functools+from dsp.modules.lm import LMfrom 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 kwargs "+ "{kwargs}".format(**details)+ )-class GPT3:+class GPT3(LM):- def __init__(self, model='text-davinci-002', api_key=None, **kwargs):+ """Wrapper around OpenAI's GPT-3 API.++ Currently supported models include `davinci`, `curie`, `babbage`, `ada`, `gpt-3.5-turbo`, and `gpt-3.5-turbo-0301`.+ """++ def __init__(+ self, model: str = "text-davinci-002", api_key: Optional[str] = None, **kwargs+ ):+ super().__init__(model)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- self.history = []+ 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>- def basic_request(self, prompt, **kwargs):+ self.history: list[dict[str, Any]] = []++ def _basic_request(self, prompt: str, **kwargs) -> OpenAIObject:raw_kwargs = kwargs- kwargs = {**self.kwargs, 'prompt': prompt, **kwargs}- response = cached_gpt3_request(**kwargs)- history = {'prompt': prompt, 'response': response,- 'kwargs': kwargs, 'raw_kwargs': raw_kwargs}+ kwargs = {**self.kwargs, **kwargs}+ if kwargs["model"] in ("gpt-3.5-turbo", "gpt-3.5-turbo-0301"):+ # caching mechanism requires hashable kwargs+ kwargs["messages"] = json.dumps([{"role": "user", "content": prompt}])+ response = cached_gpt3_turbo_request(**kwargs)+ else:+ kwargs["prompt"] = prompt+ response = cached_gpt3_request(**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 super().request(prompt, **kwargs)-- def __call__(self, prompt, only_completed=True, return_sorted=False, **kwargs):+ @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: str, end: str = "\n"):+ print("\x1b[31m" + str(text) + "\x1b[0m", end=end)++ def inspect_history(self, n: int = 1):+ """Prints the last n prompts and their completions.+ TODO: print the valid choice that contains filled output field instead of the first+ """+ last_prompt = None+ printed = []++ for x in reversed(self.history[-100:]):+ prompt = x["prompt"]++ if prompt != last_prompt:+ printed.append((prompt, x["response"]["choices"]))++ last_prompt = prompt++ if len(printed) >= n:+ break++ for prompt, choices in reversed(printed):+ print("\n\n\n")+ print(prompt, end="")+ self.print_green(self._get_choice_text(choices[0]), end="")+ if len(choices) > 1:+ self.print_red(f" \t (and {len(choices)-1} other completions)", end="")+ print("\n\n\n")++ def _get_choice_text(self, choice: dict[str, Any]) -> str:+ if self.kwargs["model"] in ("gpt-3.5-turbo", "gpt-3.5-turbo-0301"):+ return choice["message"]["content"]+ return choice["text"]++ 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"