forked from sambanova/ai-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_gateway.py
309 lines (280 loc) · 13 KB
/
api_gateway.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
import logging
import os
import sys
from typing import Any, Dict, Optional
from langchain_community.embeddings import HuggingFaceInstructEmbeddings
from langchain_core.embeddings import Embeddings
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.language_models.llms import LLM
current_dir = os.path.dirname(os.path.abspath(__file__))
utils_dir = os.path.abspath(os.path.join(current_dir, '..'))
repo_dir = os.path.abspath(os.path.join(utils_dir, '..'))
sys.path.append(utils_dir)
sys.path.append(repo_dir)
from utils.model_wrappers.langchain_chat_models import ChatSambaNovaCloud, ChatSambaStudio
from utils.model_wrappers.langchain_embeddings import SambaStudioEmbeddings
from utils.model_wrappers.langchain_llms import SambaNovaCloud, SambaStudio
EMBEDDING_MODEL = 'intfloat/e5-large-v2'
NORMALIZE_EMBEDDINGS = True
# Configure the logger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] - %(message)s',
handlers=[
logging.StreamHandler(),
],
)
logger = logging.getLogger(__name__)
class APIGateway:
@staticmethod
def load_embedding_model(
type: str = 'cpu',
batch_size: Optional[int] = None,
coe: bool = False,
select_expert: Optional[str] = None,
sambastudio_embeddings_base_url: Optional[str] = None,
sambastudio_embeddings_base_uri: Optional[str] = None,
sambastudio_embeddings_project_id: Optional[str] = None,
sambastudio_embeddings_endpoint_id: Optional[str] = None,
sambastudio_embeddings_api_key: Optional[str] = None,
) -> Embeddings:
"""Loads a langchain embedding model given a type and parameters
Args:
type (str): wether to use sambastudio embedding model or in local cpu model
batch_size (int, optional): batch size for sambastudio model. Defaults to None.
coe (bool, optional): whether to use coe model. Defaults to False. only for sambastudio models
select_expert (str, optional): expert model to be used when coe selected. Defaults to None.
only for sambastudio models.
sambastudio_embeddings_base_url (str, optional): base url for sambastudio model. Defaults to None.
sambastudio_embeddings_base_uri (str, optional): endpoint base uri for sambastudio model. Defaults to None.
sambastudio_embeddings_project_id (str, optional): project id for sambastudio model. Defaults to None.
sambastudio_embeddings_endpoint_id (str, optional): endpoint id for sambastudio model. Defaults to None.
sambastudio_embeddings_api_key (str, optional): api key for sambastudio model. Defaults to None.
Returns:
langchain embedding model
"""
if type == 'sambastudio':
envs = {
'sambastudio_embeddings_base_url': sambastudio_embeddings_base_url,
'sambastudio_embeddings_base_uri': sambastudio_embeddings_base_uri,
'sambastudio_embeddings_project_id': sambastudio_embeddings_project_id,
'sambastudio_embeddings_endpoint_id': sambastudio_embeddings_endpoint_id,
'sambastudio_embeddings_api_key': sambastudio_embeddings_api_key,
}
envs = {k: v for k, v in envs.items() if v is not None}
if coe:
if batch_size is None:
batch_size = 1
embeddings = SambaStudioEmbeddings(
**envs, batch_size=batch_size, model_kwargs={'select_expert': select_expert}
)
else:
if batch_size is None:
batch_size = 32
embeddings = SambaStudioEmbeddings(**envs, batch_size=batch_size)
elif type == 'cpu':
encode_kwargs = {'normalize_embeddings': NORMALIZE_EMBEDDINGS}
embedding_model = EMBEDDING_MODEL
embeddings = HuggingFaceInstructEmbeddings(
model_name=embedding_model,
embed_instruction='', # no instruction is needed for candidate passages
query_instruction='Represent this sentence for searching relevant passages: ',
encode_kwargs=encode_kwargs,
)
else:
raise ValueError(f'{type} is not a valid embedding model type')
return embeddings
@staticmethod
def load_llm(
type: str,
streaming: bool = False,
coe: bool = False,
do_sample: Optional[bool] = None,
max_tokens_to_generate: Optional[int] = None,
temperature: Optional[float] = None,
select_expert: Optional[str] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
repetition_penalty: Optional[float] = None,
stop_sequences: Optional[str] = None,
process_prompt: Optional[bool] = False,
sambastudio_base_url: Optional[str] = None,
sambastudio_base_uri: Optional[str] = None,
sambastudio_project_id: Optional[str] = None,
sambastudio_endpoint_id: Optional[str] = None,
sambastudio_api_key: Optional[str] = None,
sambanova_url: Optional[str] = None,
sambanova_api_key: Optional[str] = None,
) -> LLM:
"""Loads a langchain Sambanova llm model given a type and parameters
Args:
type (str): whether to use sambastudio, or SambaNova Cloud model "sncloud"
streaming (bool): whether to use streaming method. Defaults to False.
coe (bool): whether to use coe model. Defaults to False.
do_sample (bool) : Optional whether to do sample.
max_tokens_to_generate (int) : Optional max number of tokens to generate.
temperature (float) : Optional model temperature.
select_expert (str) : Optional expert to use when using CoE models.
top_p (float) : Optional model top_p.
top_k (int) : Optional model top_k.
repetition_penalty (float) : Optional model repetition penalty.
stop_sequences (str) : Optional model stop sequences.
process_prompt (bool) : Optional default to false.
sambastudio_base_url (str): Optional SambaStudio environment URL".
sambastudio_base_uri (str): Optional SambaStudio-base-URI".
sambastudio_project_id (str): Optional SambaStudio project ID.
sambastudio_endpoint_id (str): Optional SambaStudio endpoint ID.
sambastudio_api_token (str): Optional SambaStudio endpoint API key.
sambanova_url (str): Optional SambaNova Cloud URL",
sambanova_api_key (str): Optional SambaNovaCloud API key.
Returns:
langchain llm model
"""
if type == 'sambastudio':
envs = {
'sambastudio_base_url': sambastudio_base_url,
'sambastudio_base_uri': sambastudio_base_uri,
'sambastudio_project_id': sambastudio_project_id,
'sambastudio_endpoint_id': sambastudio_endpoint_id,
'sambastudio_api_key': sambastudio_api_key,
}
envs = {k: v for k, v in envs.items() if v is not None}
if coe:
model_kwargs = {
'do_sample': do_sample,
'max_tokens_to_generate': max_tokens_to_generate,
'temperature': temperature,
'select_expert': select_expert,
'top_p': top_p,
'top_k': top_k,
'repetition_penalty': repetition_penalty,
'stop_sequences': stop_sequences,
'process_prompt': process_prompt,
}
model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None}
llm = SambaStudio(
**envs,
streaming=streaming,
model_kwargs=model_kwargs,
)
else:
model_kwargs = {
'do_sample': do_sample,
'max_tokens_to_generate': max_tokens_to_generate,
'temperature': temperature,
'top_p': top_p,
'top_k': top_k,
'repetition_penalty': repetition_penalty,
'stop_sequences': stop_sequences,
}
model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None}
llm = SambaStudio(
**envs,
streaming=streaming,
model_kwargs=model_kwargs,
)
elif type == 'sncloud':
envs = {
'sambanova_url': sambanova_url,
'sambanova_api_key': sambanova_api_key,
}
envs = {k: v for k, v in envs.items() if v is not None}
llm = SambaNovaCloud(
**envs,
max_tokens=max_tokens_to_generate,
model=select_expert,
temperature=temperature,
top_k=top_k,
top_p=top_p,
)
else:
raise ValueError(f"Invalid LLM API: {type}, only 'sncloud' and 'sambastudio' are supported.")
return llm
@staticmethod
def load_chat(
type: str,
model: str,
streaming: bool = False,
max_tokens: int = 1024,
temperature: Optional[float] = 0.0,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
do_sample: Optional[bool] = False,
process_prompt: Optional[bool] = False,
stream_options: Optional[Dict[str, bool]] = {"include_usage": True},
special_tokens: Optional[Dict[str, str]] = {
'start': '<|begin_of_text|>',
'start_role': '<|begin_of_text|><|start_header_id|>{role}<|end_header_id|>',
'end_role': '<|eot_id|>',
'end': '<|start_header_id|>assistant<|end_header_id|>\n',
},
model_kwargs: Optional[Dict[str, Any]] = None,
sambanova_url: Optional[str] = None,
sambanova_api_key: Optional[str] = None,
sambastudio_url: Optional[str] = None,
sambastudio_api_key: Optional[str] = None
) -> BaseChatModel:
"""
Loads a langchain Sambanova chat model given some parameters
Args:
type (str): whether to use sambastudio, or SambaNova Cloud chat model "sncloud"
model (str): The name of the model to use, e.g., llama3-8b.
streaming (bool): whether to use streaming method. Defaults to False.
max_tokens (int): Optional max number of tokens to generate.
temperature (float): Optional model temperature.
top_p (float): Optional model top_p.
top_k (int): Optional model top_k.
do_sample (bool): whether to do sampling
process_prompt (bool): whether process prompt (for CoE generic v1 and v2 endpoints)
stream_options (dict): stream options, include usage to get generation metrics
special_tokens (dict): start, start_role, end_role and end special tokens
(set for CoE generic v1 and v2 endpoints when process prompt set to false
or for StandAlone v1 and v2 endpoints)
default to llama3 special tokens
model_kwargs (dict): Key word arguments to pass to the model.
sambanova_url (str): Optional SambaNova Cloud URL",
sambanova_api_key (str): Optional SambaNovaCloud API key.
sambastudio_url (str): Optional SambaStudio URL",
sambastudio_api_key (str): Optional SambaStudio API key.
Returns:
langchain BaseChatModel
"""
if type == 'sambastudio':
envs = {
'sambastudio_url': sambastudio_url,
'sambastudio_api_key': sambastudio_api_key,
}
envs = {k: v for k, v in envs.items() if v is not None}
model = ChatSambaStudio(
**envs,
model=model,
streaming=streaming,
max_tokens=max_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
do_sample=do_sample,
process_prompt=process_prompt,
stream_options=stream_options,
special_tokens=special_tokens,
model_kwargs=model_kwargs
)
elif type == 'sncloud':
envs = {
'sambanova_url': sambanova_url,
'sambanova_api_key': sambanova_api_key,
}
envs = {k: v for k, v in envs.items() if v is not None}
model = ChatSambaNovaCloud(
**envs,
model= model,
streaming=streaming,
max_tokens=max_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
stream_options=stream_options
)
else:
raise ValueError(f"Invalid LLM API: {type}, only 'sncloud' and 'sambastudio' are supported.")
return model