|
| 1 | +"""Module for interacting with Snowflake Cortex.""" |
| 2 | +import json |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import backoff |
| 6 | +from pydantic_core import PydanticCustomError |
| 7 | + |
| 8 | +from dsp.modules.lm import LM |
| 9 | + |
| 10 | +try: |
| 11 | + from snowflake.snowpark import Session |
| 12 | + from snowflake.snowpark import functions as snow_func |
| 13 | + |
| 14 | +except ImportError: |
| 15 | + pass |
| 16 | + |
| 17 | + |
| 18 | +def backoff_hdlr(details) -> None: |
| 19 | + """Handler from https://pypi.org/project/backoff .""" |
| 20 | + print( |
| 21 | + f"Backing off {details['wait']:0.1f} seconds after {details['tries']} tries ", |
| 22 | + f"calling function {details['target']} with kwargs", |
| 23 | + f"{details['kwargs']}", |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +def giveup_hdlr(details) -> bool: |
| 28 | + """Wrapper function that decides when to give up on retry.""" |
| 29 | + if "rate limits" in str(details): |
| 30 | + return False |
| 31 | + return True |
| 32 | + |
| 33 | + |
| 34 | +class Snowflake(LM): |
| 35 | + """Wrapper around Snowflake's CortexAPI. |
| 36 | +
|
| 37 | + Currently supported models include 'snowflake-arctic','mistral-large','reka-flash','mixtral-8x7b', |
| 38 | + 'llama2-70b-chat','mistral-7b','gemma-7b','llama3-8b','llama3-70b','reka-core'. |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, model: str = "mixtral-8x7b", credentials=None, **kwargs): |
| 42 | + """Parameters |
| 43 | +
|
| 44 | + ---------- |
| 45 | + model : str |
| 46 | + Which pre-trained model from Snowflake to use? |
| 47 | + Choices are 'snowflake-arctic','mistral-large','reka-flash','mixtral-8x7b','llama2-70b-chat','mistral-7b','gemma-7b' |
| 48 | + Full list of supported models is available here: https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions#complete |
| 49 | + credentials: dict |
| 50 | + Snowflake credentials required to initialize the session. |
| 51 | + Full list of requirements can be found here: https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/latest/api/snowflake.snowpark.Session |
| 52 | + **kwargs: dict |
| 53 | + Additional arguments to pass to the API provider. |
| 54 | + """ |
| 55 | + super().__init__(model) |
| 56 | + |
| 57 | + self.model = model |
| 58 | + cortex_models = [ |
| 59 | + "llama3-8b", |
| 60 | + "llama3-70b", |
| 61 | + "reka-core", |
| 62 | + "snowflake-arctic", |
| 63 | + "mistral-large", |
| 64 | + "reka-flash", |
| 65 | + "mixtral-8x7b", |
| 66 | + "llama2-70b-chat", |
| 67 | + "mistral-7b", |
| 68 | + "gemma-7b", |
| 69 | + ] |
| 70 | + |
| 71 | + if model in cortex_models: |
| 72 | + self.available_args = { |
| 73 | + "max_tokens", |
| 74 | + "temperature", |
| 75 | + "top_p", |
| 76 | + } |
| 77 | + else: |
| 78 | + raise PydanticCustomError( |
| 79 | + "model", |
| 80 | + 'model name is not valid, got "{model_name}"', |
| 81 | + ) |
| 82 | + |
| 83 | + self.client = self._init_cortex(credentials=credentials) |
| 84 | + self.provider = "Snowflake" |
| 85 | + self.history: list[dict[str, Any]] = [] |
| 86 | + self.kwargs = { |
| 87 | + **self.kwargs, |
| 88 | + "temperature": 0.7, |
| 89 | + "max_output_tokens": 1024, |
| 90 | + "top_p": 1.0, |
| 91 | + "top_k": 1, |
| 92 | + **kwargs, |
| 93 | + } |
| 94 | + |
| 95 | + @classmethod |
| 96 | + def _init_cortex(cls, credentials: dict) -> None: |
| 97 | + session = Session.builder.configs(credentials).create() |
| 98 | + session.query_tag = {"origin": "sf_sit", "name": "dspy", "version": {"major": 1, "minor": 0}} |
| 99 | + |
| 100 | + return session |
| 101 | + |
| 102 | + def _prepare_params( |
| 103 | + self, |
| 104 | + parameters: Any, |
| 105 | + ) -> dict: |
| 106 | + params_mapping = {"n": "candidate_count", "max_tokens": "max_output_tokens"} |
| 107 | + params = {params_mapping.get(k, k): v for k, v in parameters.items()} |
| 108 | + params = {**self.kwargs, **params} |
| 109 | + return {k: params[k] for k in set(params.keys()) & self.available_args} |
| 110 | + |
| 111 | + def _cortex_complete_request(self, prompt: str, **kwargs) -> dict: |
| 112 | + complete = snow_func.builtin("snowflake.cortex.complete") |
| 113 | + cortex_complete_args = complete( |
| 114 | + snow_func.lit(self.model), |
| 115 | + snow_func.lit([{"role": "user", "content": prompt}]), |
| 116 | + snow_func.lit(kwargs), |
| 117 | + ) |
| 118 | + raw_response = self.client.range(1).withColumn("complete_cal", cortex_complete_args).collect() |
| 119 | + |
| 120 | + if len(raw_response) > 0: |
| 121 | + return json.loads(raw_response[0].COMPLETE_CAL) |
| 122 | + |
| 123 | + else: |
| 124 | + return json.loads('{"choices": [{"messages": "None"}]}') |
| 125 | + |
| 126 | + def basic_request(self, prompt: str, **kwargs) -> list: |
| 127 | + raw_kwargs = kwargs |
| 128 | + kwargs = self._prepare_params(raw_kwargs) |
| 129 | + |
| 130 | + response = self._cortex_complete_request(prompt, **kwargs) |
| 131 | + |
| 132 | + history = { |
| 133 | + "prompt": prompt, |
| 134 | + "response": { |
| 135 | + "prompt": prompt, |
| 136 | + "choices": [{"text": c} for c in response["choices"]], |
| 137 | + }, |
| 138 | + "kwargs": kwargs, |
| 139 | + "raw_kwargs": raw_kwargs, |
| 140 | + } |
| 141 | + |
| 142 | + self.history.append(history) |
| 143 | + |
| 144 | + return [i["text"]["messages"] for i in history["response"]["choices"]] |
| 145 | + |
| 146 | + @backoff.on_exception( |
| 147 | + backoff.expo, |
| 148 | + (Exception), |
| 149 | + max_time=1000, |
| 150 | + on_backoff=backoff_hdlr, |
| 151 | + giveup=giveup_hdlr, |
| 152 | + ) |
| 153 | + def _request(self, prompt: str, **kwargs): |
| 154 | + """Handles retrieval of completions from Snowflake Cortex whilst handling API errors.""" |
| 155 | + return self.basic_request(prompt, **kwargs) |
| 156 | + |
| 157 | + def __call__( |
| 158 | + self, |
| 159 | + prompt: str, |
| 160 | + only_completed: bool = True, |
| 161 | + return_sorted: bool = False, |
| 162 | + **kwargs, |
| 163 | + ): |
| 164 | + return self._request(prompt, **kwargs) |
0 commit comments