Skip to content

Llm

EmbeddingLLMConfig

Bases: InferenceLLMConfig

Configuration for the embedding model.

Source code in src/ml/llm.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
class EmbeddingLLMConfig(InferenceLLMConfig):
    """Configuration for the embedding model."""

    model_name: str
    base_url: str
    api_key: SecretStr
    api_version: str = "2024-12-01-preview"  # used only if model is from azure openai
    model_config = ConfigDict(arbitrary_types_allowed=True)

    def load_model(self, prompt: str, schema: Type[BaseModel] = None, *args, **kwargs):
        pass

    def embed_text(self, text: str) -> list[float]:
        response = embedding(
            model=self.model_name,
            api_base=self.base_url,
            api_key=self.api_key.get_secret_value(),
            input=[text],
        )
        return response.data[0]["embedding"]

    def embed_texts(self, texts: list[str]) -> list[list[float]]:
        response = embedding(
            model=self.model_name,
            api_base=self.base_url,
            api_key=self.api_key.get_secret_value(),
            input=texts,
        )
        return [data.embedding for data in response.data]

    async def a_embed_text(self, text: str) -> list[float]:
        response = await aembedding(
            model=self.model_name,
            api_base=self.base_url,
            api_key=self.api_key.get_secret_value(),
            input=[text],
        )
        return response.data[0]["embedding"]

    async def a_embed_texts(self, texts: list[str]) -> list[list[float]]:
        response = await aembedding(
            model=self.model_name,
            api_base=self.base_url,
            api_key=self.api_key.get_secret_value(),
            input=texts,
        )
        return [data.embedding for data in response.data]

    def get_model_name(self):
        return self.model_name

InferenceLLMConfig

Bases: BaseModel

Configuration for the inference model.

Source code in src/ml/llm.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
class InferenceLLMConfig(BaseModel):
    """Configuration for the inference model."""

    model_name: str
    base_url: str
    api_key: SecretStr
    api_version: str = "2024-12-01-preview"  # used only if model is from azure openai
    model_config = ConfigDict(arbitrary_types_allowed=True)

    supports_response_schema: bool = False

    temperature: Optional[float] = None
    seed: int = 1729
    max_tokens: Optional[int] = None

    @model_validator(mode="after")
    def init_client(self) -> Self:
        try:
            # check if the model supports structured output
            self.supports_response_schema = supports_response_schema(self.model_name.split("/")[-1])
            logger.debug(
                f"\nModel: {self.model_name} Supports response schema: {self.supports_response_schema}"
            )
        except Exception as e:
            # logger.exception(f"Error in initializing the LLM : {self}")
            logger.error(f"Error in initializing the LLM : {e}")
            raise e

        return self

    def load_model(self, prompt: str, schema: Type[BaseModel] = None, *args, **kwargs):
        pass

    @observe(as_type="generation")
    async def a_generate(self, prompt: str, schema: Type[BaseModel] = None, *args, **kwargs):
        messages = [{"role": "user", "content": prompt}]
        return await self.a_generate_from_messages(
            messages=messages, schema=schema, *args, **kwargs
        )

    @observe(as_type="generation")
    @retry(
        wait=wait_fixed(60),
        stop=stop_after_attempt(6),
        retry=retry_if_exception_type(
            (litellm.exceptions.RateLimitError, instructor.exceptions.InstructorRetryException)
        ),
    )
    async def a_generate_from_messages(
        self, messages: list, schema: Type[BaseModel] = None, *args, **kwargs
    ):
        # check if model supports structured output
        if schema:
            if self.supports_response_schema:
                res = await litellm.acompletion(
                    model=self.model_name,
                    api_key=self.api_key.get_secret_value(),
                    base_url=self.base_url,
                    messages=messages,
                    response_format=schema,
                    api_version=self.api_version,
                )
                if res.choices[0].finish_reason == "content_filter":
                    raise ValueError(f"Response filtred by content filter")
                else:
                    dict_res = ast.literal_eval(res.choices[0].message.content)
                    return schema(**dict_res)

            else:
                client = instructor.from_litellm(acompletion, mode=instructor.Mode.JSON)
                res, raw_completion = await client.chat.completions.create_with_completion(
                    model=self.model_name,
                    api_key=self.api_key.get_secret_value(),
                    base_url=self.base_url,
                    messages=messages,
                    response_model=schema,
                    api_version=self.api_version,
                )
                return res
        else:
            res = await litellm.acompletion(
                model=self.model_name,
                api_key=self.api_key.get_secret_value(),
                base_url=self.base_url,
                messages=messages,
                api_version=self.api_version,
            )
            return res.choices[0].message.content

    @observe(as_type="generation")
    def generate(self, prompt: str, schema: Type[BaseModel] = None, *args, **kwargs):
        messages = [{"role": "user", "content": prompt}]
        return self.generate_from_messages(messages=messages, schema=schema, *args, **kwargs)

    @observe(as_type="generation")
    @retry(
        wait=wait_fixed(60),
        stop=stop_after_attempt(6),
        retry=retry_if_exception_type(
            (litellm.exceptions.RateLimitError, instructor.exceptions.InstructorRetryException)
        ),
    )
    def generate_from_messages(
        self, messages: list, schema: Type[BaseModel] = None, *args, **kwargs
    ):
        try:
            # check if model supports structured output
            if schema:
                if self.supports_response_schema:
                    res = litellm.completion(
                        model=self.model_name,
                        api_key=self.api_key.get_secret_value(),
                        base_url=self.base_url,
                        messages=messages,
                        response_format=schema,
                        api_version=self.api_version,
                    )
                    if res.choices[0].finish_reason == "content_filter":
                        raise ValueError(f"Response filtred by content filter")
                    else:
                        dict_res = ast.literal_eval(res.choices[0].message.content)
                        return schema(**dict_res)

                else:
                    client = instructor.from_litellm(completion, mode=instructor.Mode.JSON)
                    res, raw_completion = client.chat.completions.create_with_completion(
                        model=self.model_name,
                        api_key=self.api_key.get_secret_value(),
                        base_url=self.base_url,
                        messages=messages,
                        response_model=schema,
                        api_version=self.api_version,
                    )
                    return res
            else:
                res = litellm.completion(
                    model=self.model_name,
                    api_key=self.api_key.get_secret_value(),
                    base_url=self.base_url,
                    messages=messages,
                    api_version=self.api_version,
                )

                return res.choices[0].message.content
        except Exception as e:
            # todo handle cost if exception
            logger.error(f"Error in generating response from LLM: {e}")
            return None

    def get_model_name(self, *args, **kwargs) -> str:
        return self.model_name