-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmodels.py
394 lines (328 loc) · 10.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
173
174
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
from enum import Enum
import os
from typing import Any
from langchain_openai import (
ChatOpenAI,
OpenAI,
OpenAIEmbeddings,
AzureChatOpenAI,
AzureOpenAIEmbeddings,
AzureOpenAI,
)
from langchain_community.llms.ollama import Ollama
from langchain_ollama import ChatOllama
from langchain_community.embeddings import OllamaEmbeddings
from langchain_anthropic import ChatAnthropic
from langchain_groq import ChatGroq
from langchain_huggingface import (
HuggingFaceEmbeddings,
ChatHuggingFace,
HuggingFaceEndpoint,
)
from langchain_google_genai import (
GoogleGenerativeAI,
HarmBlockThreshold,
HarmCategory,
embeddings as google_embeddings,
)
from langchain_mistralai import ChatMistralAI
from pydantic.v1.types import SecretStr
from python.helpers import dotenv, runtime
from python.helpers.dotenv import load_dotenv
from python.helpers.rate_limiter import RateLimiter
# environment variables
load_dotenv()
# Configuration
DEFAULT_TEMPERATURE = 0.0
class ModelType(Enum):
CHAT = "Chat"
EMBEDDING = "Embedding"
class ModelProvider(Enum):
ANTHROPIC = "Anthropic"
HUGGINGFACE = "HuggingFace"
GOOGLE = "Google"
GROQ = "Groq"
LMSTUDIO = "LM Studio"
MISTRALAI = "Mistral AI"
OLLAMA = "Ollama"
OPENAI = "OpenAI"
OPENAI_AZURE = "OpenAI Azure"
OPENROUTER = "OpenRouter"
SAMBANOVA = "Sambanova"
OTHER = "Other"
rate_limiters: dict[str, RateLimiter] = {}
# Utility function to get API keys from environment variables
def get_api_key(service):
return (
dotenv.get_dotenv_value(f"API_KEY_{service.upper()}")
or dotenv.get_dotenv_value(f"{service.upper()}_API_KEY")
or "None"
)
def get_model(type: ModelType, provider: ModelProvider, name: str, **kwargs):
fnc_name = f"get_{provider.name.lower()}_{type.name.lower()}" # function name of model getter
model = globals()[fnc_name](name, **kwargs) # call function by name
return model
def get_rate_limiter(
provider: ModelProvider, name: str, requests: int, input: int, output: int
) -> RateLimiter:
# get or create
key = f"{provider.name}\\{name}"
rate_limiters[key] = limiter = rate_limiters.get(key, RateLimiter(seconds=60))
# always update
limiter.limits["requests"] = requests or 0
limiter.limits["input"] = input or 0
limiter.limits["output"] = output or 0
return limiter
def parse_chunk(chunk: Any):
if isinstance(chunk, str):
content = chunk
elif hasattr(chunk, "content"):
content = str(chunk.content)
else:
content = str(chunk)
return content
# Ollama models
def get_ollama_base_url():
return (
dotenv.get_dotenv_value("OLLAMA_BASE_URL")
or f"http://{runtime.get_local_url()}:11434"
)
def get_ollama_chat(
model_name: str,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
num_ctx=8192,
**kwargs,
):
if not base_url:
base_url = get_ollama_base_url()
return ChatOllama(
model=model_name,
temperature=temperature,
base_url=base_url,
num_ctx=num_ctx,
**kwargs,
)
def get_ollama_embedding(
model_name: str,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
**kwargs,
):
if not base_url:
base_url = get_ollama_base_url()
return OllamaEmbeddings(
model=model_name, temperature=temperature, base_url=base_url, **kwargs
)
# HuggingFace models
def get_huggingface_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
# different naming convention here
if not api_key:
api_key = get_api_key("huggingface") or os.environ["HUGGINGFACEHUB_API_TOKEN"]
# Initialize the HuggingFaceEndpoint with the specified model and parameters
llm = HuggingFaceEndpoint(
repo_id=model_name,
task="text-generation",
do_sample=True,
temperature=temperature,
**kwargs,
)
# Initialize the ChatHuggingFace with the configured llm
return ChatHuggingFace(llm=llm)
def get_huggingface_embedding(model_name: str, **kwargs):
return HuggingFaceEmbeddings(model_name=model_name, **kwargs)
# LM Studio and other OpenAI compatible interfaces
def get_lmstudio_base_url():
return (
dotenv.get_dotenv_value("LM_STUDIO_BASE_URL")
or f"http://{runtime.get_local_url()}:1234/v1"
)
def get_lmstudio_chat(
model_name: str,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
**kwargs,
):
if not base_url:
base_url = get_lmstudio_base_url()
return ChatOpenAI(model_name=model_name, base_url=base_url, temperature=temperature, api_key="none", **kwargs) # type: ignore
def get_lmstudio_embedding(
model_name: str,
base_url=None,
**kwargs,
):
if not base_url:
base_url = get_lmstudio_base_url()
return OpenAIEmbeddings(model=model_name, api_key="none", base_url=base_url, check_embedding_ctx_length=False, **kwargs) # type: ignore
# Anthropic models
def get_anthropic_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
if not api_key:
api_key = get_api_key("anthropic")
return ChatAnthropic(model_name=model_name, temperature=temperature, api_key=api_key, **kwargs) # type: ignore
# right now anthropic does not have embedding models, but that might change
def get_anthropic_embedding(
model_name: str,
api_key=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("anthropic")
return OpenAIEmbeddings(model=model_name, api_key=api_key, **kwargs) # type: ignore
# OpenAI models
def get_openai_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
if not api_key:
api_key = get_api_key("openai")
return ChatOpenAI(model_name=model_name, temperature=temperature, api_key=api_key, **kwargs) # type: ignore
def get_openai_embedding(model_name: str, api_key=None, **kwargs):
if not api_key:
api_key = get_api_key("openai")
return OpenAIEmbeddings(model=model_name, api_key=api_key, **kwargs) # type: ignore
def get_openai_azure_chat(
deployment_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
azure_endpoint=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("openai_azure")
if not azure_endpoint:
azure_endpoint = dotenv.get_dotenv_value("OPENAI_AZURE_ENDPOINT")
return AzureChatOpenAI(deployment_name=deployment_name, temperature=temperature, api_key=api_key, azure_endpoint=azure_endpoint, **kwargs) # type: ignore
def get_openai_azure_embedding(
deployment_name: str,
api_key=None,
azure_endpoint=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("openai_azure")
if not azure_endpoint:
azure_endpoint = dotenv.get_dotenv_value("OPENAI_AZURE_ENDPOINT")
return AzureOpenAIEmbeddings(deployment_name=deployment_name, api_key=api_key, azure_endpoint=azure_endpoint, **kwargs) # type: ignore
# Google models
def get_google_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
if not api_key:
api_key = get_api_key("google")
return GoogleGenerativeAI(model=model_name, temperature=temperature, google_api_key=api_key, safety_settings={HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE}, **kwargs) # type: ignore
def get_google_embedding(
model_name: str,
api_key=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("google")
return google_embeddings.GoogleGenerativeAIEmbeddings(model=model_name, api_key=api_key, **kwargs) # type: ignore
# Mistral models
def get_mistralai_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
if not api_key:
api_key = get_api_key("mistral")
return ChatMistralAI(model=model_name, temperature=temperature, api_key=api_key, **kwargs) # type: ignore
# Groq models
def get_groq_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
**kwargs,
):
if not api_key:
api_key = get_api_key("groq")
return ChatGroq(model_name=model_name, temperature=temperature, api_key=api_key, **kwargs) # type: ignore
# OpenRouter models
def get_openrouter_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("openrouter")
if not base_url:
base_url = (
dotenv.get_dotenv_value("OPEN_ROUTER_BASE_URL")
or "https://openrouter.ai/api/v1"
)
return ChatOpenAI(api_key=api_key, model=model_name, temperature=temperature, base_url=base_url, **kwargs) # type: ignore
def get_openrouter_embedding(
model_name: str,
api_key=None,
base_url=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("openrouter")
if not base_url:
base_url = (
dotenv.get_dotenv_value("OPEN_ROUTER_BASE_URL")
or "https://openrouter.ai/api/v1"
)
return OpenAIEmbeddings(model=model_name, api_key=api_key, base_url=base_url, **kwargs) # type: ignore
# Sambanova models
def get_sambanova_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
max_tokens=1024,
**kwargs,
):
if not api_key:
api_key = get_api_key("sambanova")
if not base_url:
base_url = (
dotenv.get_dotenv_value("SAMBANOVA_BASE_URL")
or "https://fast-api.snova.ai/v1"
)
return ChatOpenAI(api_key=api_key, model=model_name, temperature=temperature, base_url=base_url, max_tokens=max_tokens, **kwargs) # type: ignore
# right now sambanova does not have embedding models, but that might change
def get_sambanova_embedding(
model_name: str,
api_key=None,
base_url=None,
**kwargs,
):
if not api_key:
api_key = get_api_key("sambanova")
if not base_url:
base_url = (
dotenv.get_dotenv_value("SAMBANOVA_BASE_URL")
or "https://fast-api.snova.ai/v1"
)
return OpenAIEmbeddings(model=model_name, api_key=api_key, base_url=base_url, **kwargs) # type: ignore
# Other OpenAI compatible models
def get_other_chat(
model_name: str,
api_key=None,
temperature=DEFAULT_TEMPERATURE,
base_url=None,
**kwargs,
):
return ChatOpenAI(api_key=api_key, model=model_name, temperature=temperature, base_url=base_url, **kwargs) # type: ignore
def get_other_embedding(model_name: str, api_key=None, base_url=None, **kwargs):
return OpenAIEmbeddings(model=model_name, api_key=api_key, base_url=base_url, **kwargs) # type: ignore