|
| 1 | +import os |
| 2 | +from typing import Any, Optional |
| 3 | + |
| 4 | +import backoff |
| 5 | + |
| 6 | +from dsp.modules.lm import LM |
| 7 | + |
| 8 | +try: |
| 9 | + import premai |
| 10 | + |
| 11 | + premai_api_error = premai.errors.UnexpectedStatus |
| 12 | +except ImportError: |
| 13 | + premai_api_error = Exception |
| 14 | +except AttributeError: |
| 15 | + premai_api_error = Exception |
| 16 | + |
| 17 | + |
| 18 | +def backoff_hdlr(details) -> None: |
| 19 | + """Handler for the backoff package. |
| 20 | +
|
| 21 | + See more at: https://pypi.org/project/backoff/ |
| 22 | + """ |
| 23 | + print( |
| 24 | + "Backing off {wait:0.1f} seconds after {tries} tries calling function {target} with kwargs {kwargs}".format( |
| 25 | + **details, |
| 26 | + ), |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def giveup_hdlr(details) -> bool: |
| 31 | + """Wrapper function that decides when to give up on retry.""" |
| 32 | + if "rate limits" in details.message: |
| 33 | + return False |
| 34 | + return True |
| 35 | + |
| 36 | + |
| 37 | +def get_premai_api_key(api_key: Optional[str] = None) -> str: |
| 38 | + """Retrieve the PreMAI API key from a passed argument or environment variable.""" |
| 39 | + api_key = api_key or os.environ.get("PREMAI_API_KEY") |
| 40 | + if api_key is None: |
| 41 | + raise RuntimeError( |
| 42 | + "No API key found. See the quick start guide at https://docs.premai.io/introduction to get your API key.", |
| 43 | + ) |
| 44 | + return api_key |
| 45 | + |
| 46 | + |
| 47 | +class PremAI(LM): |
| 48 | + """Wrapper around Prem AI's API.""" |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + project_id: int, |
| 53 | + model: Optional[str] = None, |
| 54 | + api_key: Optional[str] = None, |
| 55 | + session_id: Optional[int] = None, |
| 56 | + **kwargs, |
| 57 | + ) -> None: |
| 58 | + """Parameters |
| 59 | +
|
| 60 | + project_id: int |
| 61 | + "The project ID in which the experiments or deployments are carried out. can find all your projects here: https://app.premai.io/projects/" |
| 62 | + model: Optional[str] |
| 63 | + The name of model deployed on launchpad. When None, it will show 'default' |
| 64 | + api_key: Optional[str] |
| 65 | + Prem AI API key, to connect with the API. If not provided then it will check from env var by the name |
| 66 | + PREMAI_API_KEY |
| 67 | + session_id: Optional[int] |
| 68 | + The ID of the session to use. It helps to track the chat history. |
| 69 | + **kwargs: dict |
| 70 | + Additional arguments to pass to the API provider |
| 71 | + """ |
| 72 | + model = "default" if model is None else model |
| 73 | + super().__init__(model) |
| 74 | + if premai_api_error == Exception: |
| 75 | + raise ImportError( |
| 76 | + "Not loading Prem AI because it is not installed. Install it with `pip install premai`.", |
| 77 | + ) |
| 78 | + self.kwargs = kwargs if kwargs == {} else self.kwargs |
| 79 | + |
| 80 | + self.project_id = project_id |
| 81 | + self.session_id = session_id |
| 82 | + |
| 83 | + api_key = get_premai_api_key(api_key=api_key) |
| 84 | + self.client = premai.Prem(api_key=api_key) |
| 85 | + self.provider = "premai" |
| 86 | + self.history: list[dict[str, Any]] = [] |
| 87 | + |
| 88 | + self.kwargs = { |
| 89 | + "temperature": 0.17, |
| 90 | + "max_tokens": 150, |
| 91 | + **kwargs, |
| 92 | + } |
| 93 | + if session_id is not None: |
| 94 | + self.kwargs["session_id"] = session_id |
| 95 | + |
| 96 | + # However this is not recommended to change the model once |
| 97 | + # deployed from launchpad |
| 98 | + |
| 99 | + if model != "default": |
| 100 | + self.kwargs["model"] = model |
| 101 | + |
| 102 | + def _get_all_kwargs(self, **kwargs) -> dict: |
| 103 | + other_kwargs = { |
| 104 | + "seed": None, |
| 105 | + "logit_bias": None, |
| 106 | + "tools": None, |
| 107 | + "system_prompt": None, |
| 108 | + } |
| 109 | + all_kwargs = { |
| 110 | + **self.kwargs, |
| 111 | + **other_kwargs, |
| 112 | + **kwargs, |
| 113 | + } |
| 114 | + |
| 115 | + _keys_that_cannot_be_none = [ |
| 116 | + "system_prompt", |
| 117 | + "frequency_penalty", |
| 118 | + "presence_penalty", |
| 119 | + "tools", |
| 120 | + ] |
| 121 | + |
| 122 | + for key in _keys_that_cannot_be_none: |
| 123 | + if all_kwargs.get(key) is None: |
| 124 | + all_kwargs.pop(key, None) |
| 125 | + return all_kwargs |
| 126 | + |
| 127 | + def basic_request(self, prompt, **kwargs) -> str: |
| 128 | + """Handles retrieval of completions from Prem AI whilst handling API errors.""" |
| 129 | + all_kwargs = self._get_all_kwargs(**kwargs) |
| 130 | + messages = [] |
| 131 | + |
| 132 | + if "system_prompt" in all_kwargs: |
| 133 | + messages.append({"role": "system", "content": all_kwargs["system_prompt"]}) |
| 134 | + messages.append({"role": "user", "content": prompt}) |
| 135 | + |
| 136 | + response = self.client.chat.completions.create( |
| 137 | + project_id=self.project_id, |
| 138 | + messages=messages, |
| 139 | + **all_kwargs, |
| 140 | + ) |
| 141 | + if not response.choices: |
| 142 | + raise premai_api_error("ChatResponse must have at least one candidate") |
| 143 | + |
| 144 | + content = response.choices[0].message.content |
| 145 | + if not content: |
| 146 | + raise premai_api_error("ChatResponse is none") |
| 147 | + |
| 148 | + output_text = content or "" |
| 149 | + |
| 150 | + self.history.append( |
| 151 | + { |
| 152 | + "prompt": prompt, |
| 153 | + "response": content, |
| 154 | + "kwargs": all_kwargs, |
| 155 | + "raw_kwargs": kwargs, |
| 156 | + }, |
| 157 | + ) |
| 158 | + |
| 159 | + return output_text |
| 160 | + |
| 161 | + @backoff.on_exception( |
| 162 | + backoff.expo, |
| 163 | + (premai_api_error), |
| 164 | + max_time=1000, |
| 165 | + on_backoff=backoff_hdlr, |
| 166 | + giveup=giveup_hdlr, |
| 167 | + ) |
| 168 | + def request(self, prompt, **kwargs) -> str: |
| 169 | + """Handles retrieval of completions from Prem AI whilst handling API errors.""" |
| 170 | + return self.basic_request(prompt=prompt, **kwargs) |
| 171 | + |
| 172 | + def __call__(self, prompt, **kwargs): |
| 173 | + return self.request(prompt, **kwargs) |
0 commit comments