forked from sambanova/ai-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
293 lines (283 loc) · 8.74 KB
/
config.ts
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
//SambaNova Cloud usage
const sambanova_api_key = "your-SambaNovaCloud-api-key";
const sambanova_model = "llama3-8b";
//SambaStudio usage
const sambastudio_base_url = "your-sambastudio-base-url";
const sambastudio_project_id = "your-sambastudio-project-id";
const sambastudio_endpoint_id = "your-sambastudio-endpoint-id";
const sambastudio_api_key = "your-sambastudio-api-key";
const sambastudio_use_coe = true;
const sambastudio_coe_expert_name = "Meta-Llama-3-70B-Instruct-4096";
/**
* Llama3 template structure
*
* Generates a template for Llama3 messages.
*
* @param {ChatMessage[]} msgs - An array of chat messages.
* @returns {string} A formatted prompt string for Llama3.
*/
function templateLlama3Messages(msgs: ChatMessage[]): string {
let prompt = "<|begin_of_text|><|start_header_id|>system<|end_header_id|> You are an assistant for question-answering tasks.\n";
if (msgs[0].role === "system") {
prompt += `${msgs[0].content}\n`;
msgs.shift();
}
prompt += "<|eot_id|><|start_header_id|>user<|end_header_id|>"
prompt += "Instruction:\n";
for (let msg of msgs) {
prompt += `${msg.content}\n`;
}
prompt += "Response:<|eot_id|><|start_header_id|>assistant<|end_header_id|> \n";
return prompt;
}
/**
* sambaStudioEndpoint handler
*
* This function is an asynchronous generator that handles Streaming API calls to a SambaNova endpoint.
*
* The function sends a POST request to the specified `url` with the provided `body` and `extraHeaders`.
* The function then reads the response body as a stream and decodes it as text.
* It splits the text into lines and yields each line as a JSON object.
*
* The yielded objects contain a `result` property with a `responses` property, which contains a `stream_token` property.
*
* @param {string} url - The URL of the SambaNova endpoint
* @param {string} key - The API key
* @param {string} body - The request body
* @param {Object} [extraHeaders] - Additional headers to include in the request
* @returns {IterableIterator<string>} An iterable iterator yielding stream tokens
*/
async function* sambaStudioEndpointHandler(
url: string,
key: string,
body: string,
extraHeaders: { [key: string]: string } | null = null
) {
let headers = {
'Content-Type': 'application/json',
'key': key,
};
if (extraHeaders !== null) {
headers = Object.assign({}, headers, extraHeaders);
}
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: body,
});
if (!response.ok) {
const responseBody = await response.text();
console.error('API call failed with status:', response.status);
console.error('Response body:', responseBody);
throw new Error(`API call failed with status ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('Failed to get reader from response body');
}
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let lines = buffer.split('\n');
buffer = lines.pop()!;
for (const line of lines) {
if (line.trim()) {
try {
const json_line = JSON.parse(line);
yield json_line.result.responses[0].stream_token;
} catch (error) {
console.error('failed to parse JSON: ', line)
}
}
}
}
}
/**
* SambaStudio model
*/
let SambaStudioModel = {
options: {
title: "SambaStudio",
model: sambastudio_coe_expert_name,
contextLength: 2048,
templateMessages: templateLlama3Messages,
},
/**
* Stream completion function for SambaStudio
*
* @param {string} prompt - The prompt to generate text for
* @param {CompletionOptions} options - Options for the completion
*/
streamCompletion: async function* (
prompt: string,
options: CompletionOptions,
) {
const url = `${sambastudio_base_url}/api/predict/generic/stream/${sambastudio_project_id}/${sambastudio_endpoint_id}`;
let body = ""
if(sambastudio_use_coe){
body = JSON.stringify({
instance: prompt,
params: {
select_expert: {
type: "string",
value: options.model
},
process_prompt: {
type: "bool",
value: "false"
},
max_tokens_to_generate: {
type: "int",
value: "1024"
}
}
});
}
else{
body = JSON.stringify({
instance: prompt,
params: {
do_sample:{
type:"bool",
value:"true",
},
max_tokens_to_generate: {
type: "int",
value: "1024",
},
temperature:{
type:"float",
value:"0.7",
},
}
});
}
yield* sambaStudioEndpointHandler(url, sambastudio_api_key, body);
}
};
/**
* sambaNovaCloudEndpoint handler
*
* This function is an asynchronous generator that handles Streaming API calls to a SambaNova endpoint.
*
* The function sends a POST request to the specified `url` with the provided `body` and `extraHeaders`.
* The function then reads the response body as a stream and decodes it as text.
* It splits the text into lines and yields each line as a JSON object.
*
* The yielded objects contain a `result` property with a `responses` property, which contains a `stream_token` property.
*
* @param {string} url - The URL of the SambaNova endpoint
* @param {string} key - The API key
* @param {string} body - The request body
* @param {Object} [extraHeaders] - Additional headers to include in the request
* @returns {IterableIterator<string>} An iterable iterator yielding stream tokens
*/
async function* sambaNovaCloudEndpointHandler(
url: string,
key: string,
body: string,
extraHeaders: { [key: string]: string } | null = null
) {
let headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${key}`,
};
if (extraHeaders !== null) {
headers = Object.assign({}, headers, extraHeaders);
}
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: body,
});
if (!response.ok) {
const responseBody = await response.text();
console.error('API call failed with status:', response.status);
console.error('Response body:', responseBody);
throw new Error(`API call failed with status ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('Failed to get reader from response body');
}
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let lines = buffer.split('\n');
buffer = lines.pop()!;
for (const line of lines) {
let str_line = line.trim();
if (str_line) {
if (str_line === "data: [DONE]"){
break;
}
else {
str_line = str_line.replace(/^data: /, '')
try {
const json_line = JSON.parse(str_line);
yield json_line.choices[0].delta.content;
} catch (error) {
console.error('failed to parse JSON: ', line)
}
}
}
}
}
}
/**
* SambaNova Cloud model
*/
let SambaNovaCloudModel = {
options: {
title: "SambaNovaCloud",
model: sambanova_model,
contextLength: 2048,
templateMessages: templateLlama3Messages,
},
/**
* Stream completion function for SambaNovaCloud
*
* @param {string} prompt - The prompt to generate text for
* @param {CompletionOptions} options - Options for the completion
*/
streamCompletion: async function* (
prompt: string,
options: CompletionOptions,
) {
const url = 'https://api.sambanova.ai/v1/chat/completions';
const extraHeaders = {
};
const body = JSON.stringify({
messages:[
{
role: "user",
content: prompt
}
],
model: options.model,
stop: ["<|eot_id|>"],
stream: true,
max_tokens: 1024,
});
yield* sambaNovaCloudEndpointHandler(url, sambanova_api_key, body, extraHeaders);
},
};
/**
* Modifies the given configuration by adding SambaStudioModel and SambaNovaCloudModel to the models array.
*
* @param {Config} config - The configuration object to be modified.
* @returns {Config} The modified configuration object.
*/
export function modifyConfig(config: Config): Config {
config.models.push(SambaStudioModel)
config.models.push(SambaNovaCloudModel)
//config.tabAutocompleteModel=SambaStudioModel;
//config.tabAutocompleteModel=SambaNovaCloudModel;
return config;
}