-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathlib.rs
1594 lines (1450 loc) · 48.1 KB
/
lib.rs
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// LoRAX Webserver
mod adapter;
mod batch;
mod block_allocator;
pub mod config;
mod health;
mod infer;
mod loader;
mod queue;
mod radix;
mod scheduler;
pub mod server;
mod tool_grammar;
mod validation;
use lorax_client::{AdapterParameters as AdapterParametersMessage, Entity as EntityMessage};
use lorax_client::{MajoritySignMethod, MergeStrategy};
use batch::Entry;
use infer::{Infer, InferError};
use loader::AdapterLoader;
use serde::{Deserialize, Serialize};
use serde_json::json;
use server::prepare_chat_input;
use utoipa::ToSchema;
use validation::Validation;
/// Hub type
#[derive(Clone, Debug, Deserialize)]
pub struct HubModelInfo {
#[serde(rename(deserialize = "id"))]
pub model_id: String,
pub sha: Option<String>,
pub pipeline_tag: Option<String>,
}
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
/// Model info
#[schema(example = "bigscience/blomm-560m")]
pub model_id: String,
#[schema(nullable = true, example = "e985a63cdc139290c5f700ff1929f0b5942cced2")]
pub model_sha: Option<String>,
#[schema(example = "torch.float16")]
pub model_dtype: String,
#[schema(example = "cuda")]
pub model_device_type: String,
#[schema(nullable = true, example = "lorax")]
pub model_pipeline_tag: Option<String>,
/// Router Parameters
#[schema(example = "128")]
pub max_concurrent_requests: usize,
#[schema(example = "2")]
pub max_best_of: usize,
#[schema(example = "4")]
pub max_stop_sequences: usize,
#[schema(example = "1024")]
pub max_input_length: usize,
#[schema(example = "2048")]
pub max_total_tokens: usize,
#[schema(example = "1.2")]
pub waiting_served_ratio: f32,
#[schema(example = "32000")]
pub max_batch_total_tokens: u32,
#[schema(example = "20")]
pub max_waiting_tokens: usize,
#[schema(example = "2")]
pub validation_workers: usize,
#[schema(example = false)]
pub eager_prefill: bool,
/// Router Info
#[schema(example = "0.5.0")]
pub version: &'static str,
#[schema(nullable = true, example = "null")]
pub sha: Option<&'static str>,
#[schema(nullable = true, example = "null")]
pub docker_label: Option<&'static str>,
#[schema(nullable = true, example = "http://localhost:8899")]
pub request_logger_url: Option<String>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
pub(crate) struct AdapterParameters {
#[serde(rename(deserialize = "ids"))]
#[schema(inline, example = json ! (["arnavgrg/codealpaca-qlora"]))]
pub adapter_ids: Vec<String>,
#[serde(default)]
#[schema(inline, example = json ! ([0.25, 0.75]))]
pub weights: Vec<f32>,
#[serde(default)]
#[schema(nullable = true, default = "null", example = "linear")]
pub merge_strategy: Option<String>,
#[serde(default)]
#[schema(nullable = false, default = 0.0, example = 0.5)]
pub density: f32,
#[serde(default)]
#[schema(nullable = true, default = "null", example = "total")]
pub majority_sign_method: Option<String>,
}
impl Into<AdapterParametersMessage> for AdapterParameters {
fn into(self) -> AdapterParametersMessage {
AdapterParametersMessage {
adapter_ids: self.adapter_ids,
weights: self.weights,
merge_strategy: MergeStrategy::from_str_name(
self.merge_strategy
.unwrap_or("linear".to_string())
.to_uppercase()
.as_str(),
)
.unwrap()
.into(),
density: self.density,
majority_sign_method: MajoritySignMethod::from_str_name(
self.majority_sign_method
.unwrap_or("total".to_string())
.to_uppercase()
.as_str(),
)
.unwrap()
.into(),
}
}
}
impl std::hash::Hash for AdapterParameters {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
if self.adapter_ids.len() == 1 {
self.adapter_ids[0].hash(state);
return;
}
self.adapter_ids.hash(state);
// Convert weights vec into vec of u32 bits
let weights: Vec<u32> = self.weights.iter().map(|x| x.to_bits()).collect();
weights.hash(state);
self.merge_strategy.hash(state);
// Hash the raw bits of the float, acknowledging that this
// can cause issues with different representations of the same value.
self.density.to_bits().hash(state);
self.majority_sign_method.hash(state);
}
}
impl PartialEq for AdapterParameters {
fn eq(&self, other: &Self) -> bool {
if self.adapter_ids.len() == 1 {
return self.adapter_ids[0] == other.adapter_ids[0];
}
// In this implementation, we assume that adapter order matters
self.adapter_ids == other.adapter_ids
&& self.weights == other.weights
&& self.merge_strategy == other.merge_strategy
&& self.density == other.density // direct comparison of f32
&& self.majority_sign_method == other.majority_sign_method
}
}
impl Eq for AdapterParameters {}
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct GenerateParameters {
#[serde(default)]
#[schema(
nullable = true,
default = "null",
example = "arnavgrg/codealpaca-qlora"
)]
pub adapter_id: Option<String>,
#[serde(default)]
#[schema(nullable = true, default = "null", example = "hub")]
pub adapter_source: Option<String>,
#[serde(rename(deserialize = "merged_adapters"))]
#[schema(nullable = true, default = "null")]
pub adapter_parameters: Option<AdapterParameters>,
#[serde(default)]
#[schema(
nullable = true,
default = "null",
example = "<token for private adapters>"
)]
pub api_token: Option<String>,
#[serde(default)]
#[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
pub best_of: Option<usize>,
#[serde(default)]
#[schema(
exclusive_minimum = 0.0,
nullable = true,
default = "null",
example = 0.5
)]
pub temperature: Option<f32>,
#[serde(default)]
#[schema(
exclusive_minimum = 0.0,
nullable = true,
default = "null",
example = 1.03
)]
pub repetition_penalty: Option<f32>,
#[serde(default)]
#[schema(
exclusive_minimum = -2.0,
exclusive_maximum = 2.0,
nullable = true,
default = "null",
example = 0.1
)]
pub frequency_penalty: Option<f32>,
#[serde(default)]
#[schema(
exclusive_minimum = -2.0,
exclusive_maximum = 2.0,
nullable = true,
default = "null",
example = 0.1
)]
pub presence_penalty: Option<f32>,
#[serde(default)]
#[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 10)]
pub top_k: Option<i32>,
#[serde(default)]
#[schema(
exclusive_minimum = 0.0,
maximum = 1.0,
nullable = true,
default = "null",
example = 0.95
)]
pub top_p: Option<f32>,
#[serde(default)]
#[schema(
exclusive_minimum = 0.0,
maximum = 1.0,
nullable = true,
default = "null",
example = 0.95
)]
pub typical_p: Option<f32>,
#[serde(default)]
#[schema(default = "false", example = true)]
pub do_sample: bool,
#[serde(default)]
#[schema(exclusive_minimum = 0, default = "null")]
pub max_new_tokens: Option<u32>,
#[serde(default)]
#[schema(default = "false", example = true)]
pub ignore_eos_token: bool,
#[serde(default)]
#[schema(nullable = true, default = "null", example = false)]
pub return_full_text: Option<bool>,
#[serde(default)]
#[schema(inline, max_items = 4, example = json ! (["photographer"]))]
pub stop: Vec<String>,
#[serde(default)]
#[schema(nullable = true, default = "null", example = "null")]
pub truncate: Option<usize>,
#[serde(default)]
#[schema(default = "false", example = true)]
pub watermark: bool,
#[serde(default)]
#[schema(default = "true")]
pub details: bool,
#[serde(default)]
#[schema(default = "true")]
pub decoder_input_details: bool,
#[serde(default)]
#[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 10)]
pub return_k_alternatives: Option<i32>,
#[serde(default)]
#[schema(default = "false")]
#[allow(dead_code)] // For now allow this field even though it is unused
pub apply_chat_template: bool,
#[serde(default)]
#[schema(
exclusive_minimum = 0,
nullable = true,
default = "null",
example = "null"
)]
pub seed: Option<u64>,
#[serde(default)]
#[schema(
nullable = true,
default = "null",
example = json!(r#"{"type": "json_object", "schema": {type": "string", "title": "response"}}"#)
)]
pub response_format: Option<ResponseFormat>,
}
fn default_parameters() -> GenerateParameters {
GenerateParameters {
adapter_id: None,
adapter_source: None,
adapter_parameters: None,
api_token: None,
best_of: None,
temperature: None,
repetition_penalty: None,
frequency_penalty: None,
presence_penalty: None,
top_k: None,
top_p: None,
typical_p: None,
do_sample: false,
max_new_tokens: None,
ignore_eos_token: false,
return_full_text: None,
stop: Vec::new(),
truncate: None,
watermark: false,
details: false,
decoder_input_details: false,
return_k_alternatives: None,
apply_chat_template: false,
seed: None,
response_format: None,
}
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct GenerateRequest {
#[schema(example = "My name is Olivier and I")]
pub inputs: String,
#[serde(default = "default_parameters")]
pub parameters: GenerateParameters,
/// This is used internally because some requests
/// already contain the templated input therefore
/// we shouldn't add the special tokens.
#[serde(default = "default_true", skip)]
pub add_special_tokens: bool,
}
fn default_true() -> bool {
true
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct CompatGenerateRequest {
#[schema(example = "My name is Olivier and I")]
pub inputs: String,
#[serde(default = "default_parameters")]
pub parameters: GenerateParameters,
#[serde(default)]
#[schema(default = "false")]
pub stream: bool,
/// This is used internally because some requests
/// already contain the templated input therefore
/// we shouldn't add the special tokens.
#[serde(default = "default_true", skip)]
pub add_special_tokens: bool,
}
impl From<CompatGenerateRequest> for GenerateRequest {
fn from(req: CompatGenerateRequest) -> Self {
Self {
inputs: req.inputs,
parameters: req.parameters,
add_special_tokens: req.add_special_tokens,
}
}
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct TokenizeRequest {
#[schema(example = "My name is Olivier and I")]
pub inputs: String,
#[schema(nullable = true, example = true)]
pub add_special_tokens: Option<bool>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
#[schema(example = 0)]
id: u32,
#[schema(example = "test")]
text: String,
#[schema(nullable = true, example = - 0.34)]
logprob: f32,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct AlternativeToken {
#[schema(example = 0)]
id: u32,
#[schema(example = "test")]
text: String,
#[schema(nullable = true, example = - 0.34)]
logprob: f32,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct Token {
#[schema(example = 0)]
id: u32,
#[schema(example = "test")]
text: String,
#[schema(nullable = true, example = - 0.34)]
logprob: f32,
#[schema(example = "false")]
special: bool,
#[schema(nullable = true)]
#[serde(skip_serializing_if = "Option::is_none")]
alternative_tokens: Option<Vec<AlternativeToken>>,
#[schema(example = "false")]
skipped: bool,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct SimpleToken {
#[schema(example = 0)]
id: u32,
#[schema(example = "test")]
text: String,
#[schema(example = 0)]
start: usize,
#[schema(example = 2)]
stop: usize,
}
#[derive(Serialize, ToSchema, Clone)]
#[serde(rename_all(serialize = "snake_case"))]
pub(crate) enum FinishReason {
#[schema(rename = "length")]
Length,
#[serde(rename = "eos_token")]
#[schema(rename = "eos_token")]
EndOfSequenceToken,
#[schema(rename = "stop_sequence")]
StopSequence,
}
#[derive(Serialize, ToSchema)]
pub(crate) struct BestOfSequence {
#[schema(example = "test")]
pub generated_text: String,
#[schema(example = "length")]
pub finish_reason: FinishReason,
#[schema(example = 1)]
pub generated_tokens: u32,
#[schema(nullable = true, example = 42)]
pub seed: Option<u64>,
pub prefill: Vec<PrefillToken>,
pub tokens: Vec<Token>,
}
#[derive(Serialize, ToSchema)]
pub(crate) struct Details {
#[schema(example = "length")]
pub finish_reason: FinishReason,
#[schema(example = 1)]
pub prompt_tokens: u32,
#[schema(example = 1)]
pub generated_tokens: u32,
#[schema(example = 1)]
pub skipped_tokens: u32,
#[schema(nullable = true, example = 42)]
pub seed: Option<u64>,
pub prefill: Vec<PrefillToken>,
pub tokens: Vec<Token>,
#[serde(skip_serializing_if = "Option::is_none")]
pub best_of_sequences: Option<Vec<BestOfSequence>>,
}
#[derive(Serialize, ToSchema)]
pub(crate) struct GenerateResponse {
#[schema(example = "test")]
pub generated_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<Details>,
}
#[derive(Serialize, ToSchema)]
#[serde(transparent)]
pub(crate) struct TokenizeResponse(Vec<SimpleToken>);
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
#[schema(example = "length")]
pub finish_reason: FinishReason,
#[schema(example = 1)]
pub prompt_tokens: u32,
#[schema(example = 1)]
pub generated_tokens: u32,
#[schema(nullable = true, example = 42)]
pub seed: Option<u64>,
}
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamResponse {
pub token: Token,
#[schema(nullable = true, default = "null", example = "test")]
pub generated_text: Option<String>,
#[schema(nullable = true, default = "null")]
pub details: Option<StreamDetails>,
}
#[derive(Serialize, ToSchema)]
pub(crate) struct ErrorResponse {
pub error: String,
pub error_type: String,
}
// OpenAI compatible structs
#[derive(Serialize, ToSchema)]
struct UsageInfo {
prompt_tokens: u32,
total_tokens: u32,
completion_tokens: Option<u32>,
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
enum ResponseFormatType {
#[serde(alias = "text")]
Text,
#[serde(alias = "json_object")]
JsonObject,
#[serde(alias = "json_schema")]
JsonSchema,
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
struct ResponseFormat {
#[allow(dead_code)] // For now allow this field even though it is unused
r#type: ResponseFormatType,
#[serde(default = "default_json_schema")]
schema: Option<serde_json::Value>,
}
// Default schema to be used when no value is provided
fn default_json_schema() -> Option<serde_json::Value> {
Some(serde_json::json!({
"additionalProperties": {
"type": ["object", "string", "integer", "number", "boolean", "null"]
},
"title": "ArbitraryJsonModel",
"type": "object"
}))
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
struct JsonSchema {
#[allow(dead_code)] // For now allow this field even though it is unused
description: Option<String>,
#[allow(dead_code)] // For now allow this field even though it is unused
name: String,
schema: Option<serde_json::Value>,
#[allow(dead_code)] // For now allow this field even though it is unused
strict: Option<bool>,
}
// TODO check if json_schema field is required if type is json_schema
#[derive(Clone, Debug, Deserialize, ToSchema)]
struct OpenAiResponseFormat {
#[serde(rename(deserialize = "type"))]
response_format_type: ResponseFormatType,
json_schema: Option<JsonSchema>,
// For backwards compatibility
#[serde(default = "default_json_schema")]
schema: Option<serde_json::Value>,
}
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct Url {
url: String,
}
#[derive(Clone, Deserialize, Serialize, ToSchema, Default, Debug, PartialEq)]
pub(crate) struct ToolCall {
pub id: String,
pub r#type: String,
pub function: ReturnFunctionDefinition,
}
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum MessageChunk {
Text { text: String },
ImageUrl { image_url: Url },
}
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct Message {
#[schema(example = "user")]
role: String,
#[serde(default)]
#[schema(example = "My name is David and I")]
pub content: Option<MessageContent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schema(example = "\"David\"")]
name: Option<String>,
}
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
#[serde(untagged)]
pub enum MessageContent {
SingleText(String),
MultipleChunks(Vec<MessageChunk>),
}
// Manual implementation of Default instead of using #[default] attribute
impl Default for MessageContent {
fn default() -> Self {
MessageContent::SingleText(String::new())
}
}
// Pushing a chunk to a single text message will convert it to a multiple chunks message
impl MessageContent {
pub fn push(&mut self, chunk: MessageChunk) {
match self {
MessageContent::SingleText(text) => {
*self =
MessageContent::MultipleChunks(vec![MessageChunk::Text { text: text.clone() }]);
}
MessageContent::MultipleChunks(chunks) => {
chunks.push(chunk);
}
}
}
}
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct TextMessage {
#[schema(example = "user")]
pub role: String,
#[schema(example = "My name is David and I")]
pub content: String,
}
impl From<Message> for TextMessage {
fn from(value: Message) -> Self {
TextMessage {
role: value.role,
content: match value.content {
Some(MessageContent::SingleText(text)) => text,
Some(MessageContent::MultipleChunks(chunks)) => chunks
.into_iter()
.map(|chunk| match chunk {
MessageChunk::Text { text } => text,
MessageChunk::ImageUrl { image_url } => format!("", image_url.url),
})
.collect::<Vec<_>>()
.join(""),
None => String::new(),
},
}
}
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
struct ChatCompletionRequest {
model: String,
messages: Vec<Message>,
temperature: Option<f32>,
top_p: Option<f32>,
n: Option<i32>,
max_tokens: Option<i32>,
#[serde(default)]
stop: Vec<String>,
stream: Option<bool>,
#[allow(dead_code)] // For now allow this field even though it is unused
presence_penalty: Option<f32>,
#[allow(dead_code)] // For now allow this field even though it is unused
frequency_penalty: Option<f32>,
#[allow(dead_code)] // For now allow this field even though it is unused
logit_bias: Option<std::collections::HashMap<String, f32>>,
#[allow(dead_code)] // For now allow this field even though it is unused
user: Option<String>,
seed: Option<u64>,
response_format: Option<OpenAiResponseFormat>,
/// A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of
/// functions the model may generate JSON inputs for.
#[serde(default)]
#[schema(nullable = true, example = "null")]
pub tools: Option<Vec<Tool>>,
/// A specific tool to use. If not provided, the model will default to use any of the tools provided in the tools parameter.
/// A specific tool to use. If not provided, the model will default to use any of the tools provided in the tools parameter.
#[serde(default)]
#[schema(nullable = true, example = "null")]
pub tool_choice: ToolChoice,
// Additional parameters
// TODO(travis): add other LoRAX params here
repetition_penalty: Option<f32>,
top_k: Option<i32>,
ignore_eos_token: Option<bool>,
adapter_source: Option<String>,
api_token: Option<String>,
/// A prompt to be appended before the tools
#[serde(default)]
#[schema(
nullable = true,
example = "Given the functions available, please respond with a JSON for a function call with its proper arguments that best answers the given prompt. Respond in the format {name: function name, parameters: dictionary of argument name and its value}.Do not use variables."
)]
pub tool_prompt: Option<String>,
/// A guideline to be used in the chat_template
#[serde(default)]
#[schema(nullable = true, default = "null", example = "null")]
pub guideline: Option<String>,
}
impl ChatCompletionRequest {
fn try_into_generate(self, infer: &Infer) -> Result<(CompatGenerateRequest, bool), InferError> {
let ChatCompletionRequest {
model,
max_tokens,
messages,
seed,
stop,
stream,
tools,
tool_choice,
tool_prompt,
temperature,
response_format,
guideline,
repetition_penalty,
presence_penalty,
frequency_penalty,
top_p,
top_k,
n,
adapter_source,
api_token,
ignore_eos_token,
..
} = self;
let mut adapter_id = Some(model.clone());
if model == "" {
adapter_id = None;
}
// Modify input values to ResponseFormat to be OpenAI API compatible
let response_format: Option<ResponseFormat> = match response_format {
None => None,
Some(openai_format) => {
let response_format_type = openai_format.response_format_type.clone();
match response_format_type {
// Ignore when type is text
ResponseFormatType::Text => None,
// For json_object, use the fixed schema.
// For backwards compatibility, also support non-standard `schema` field
ResponseFormatType::JsonObject => openai_format.schema.map_or_else(
|| {
Some(ResponseFormat {
r#type: response_format_type.clone(),
schema: default_json_schema(),
})
},
|schema_value: serde_json::Value| {
Some(ResponseFormat {
r#type: response_format_type.clone(),
schema: Some(schema_value),
})
},
),
// For json_schema, use schema_value if available, otherwise fallback to the fixed schema
ResponseFormatType::JsonSchema => openai_format
.json_schema
.and_then(|schema| schema.schema)
.map_or_else(
|| {
Some(ResponseFormat {
r#type: response_format_type.clone(),
schema: default_json_schema(),
})
},
|schema_value: serde_json::Value| {
Some(ResponseFormat {
r#type: response_format_type.clone(),
schema: Some(schema_value),
})
},
),
}
}
};
let tool_prompt = tool_prompt
.filter(|s| !s.is_empty())
.unwrap_or_else(default_tool_prompt);
// enable greedy only when temperature is 0
let (do_sample, temperature) = match temperature {
Some(temperature) if temperature == 0.0 => (false, None),
other => (true, other),
};
let (inputs, response_format, using_tools) = prepare_chat_input(
&infer,
response_format,
tools,
tool_choice,
&tool_prompt,
guideline,
messages,
)?;
Ok((
CompatGenerateRequest {
inputs: inputs.to_string(),
add_special_tokens: false,
parameters: GenerateParameters {
adapter_id,
adapter_source,
adapter_parameters: None,
api_token,
best_of: n.map(|x| x as usize),
temperature,
repetition_penalty,
frequency_penalty,
presence_penalty,
top_k,
top_p,
typical_p: None,
do_sample,
max_new_tokens: max_tokens.map(|x| x as u32),
return_full_text: None,
stop,
truncate: None,
watermark: false,
details: true,
decoder_input_details: false,
seed,
ignore_eos_token: ignore_eos_token.unwrap_or(false),
return_k_alternatives: None,
apply_chat_template: false,
response_format,
},
stream: stream.unwrap_or(false),
},
using_tools,
))
}
}
pub fn default_tool_prompt() -> String {
"\nGiven the functions available, please respond with a JSON for a function call with its proper arguments that best answers the given prompt. Respond in the format {name: function name, parameters: dictionary of argument name and its value}.Do not use variables.\n".to_string()
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
#[schema(example = "auto")]
/// Controls which (if any) tool is called by the model.
pub enum ToolType {
/// Means the model can pick between generating a message or calling one or more tools.
#[schema(rename = "auto")]
OneOf,
/// Means the model will not call any tool and instead generates a message.
#[schema(rename = "none")]
NoTool,
/// Forces the model to call a specific tool.
#[schema(rename = "function")]
Function(FunctionName),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct FunctionName {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, ToSchema)]
#[serde(from = "ToolTypeDeserializer")]
pub struct ToolChoice(pub Option<ToolType>);
#[derive(Deserialize)]
#[serde(untagged)]
enum ToolTypeDeserializer {
Null,
String(String),
ToolType(ToolType),
}
impl From<ToolTypeDeserializer> for ToolChoice {
fn from(value: ToolTypeDeserializer) -> Self {
match value {
ToolTypeDeserializer::Null => ToolChoice(None),
ToolTypeDeserializer::String(s) => match s.as_str() {
"none" => ToolChoice(Some(ToolType::NoTool)),
"auto" => ToolChoice(Some(ToolType::OneOf)),
_ => ToolChoice(Some(ToolType::Function(FunctionName { name: s }))),
},
ToolTypeDeserializer::ToolType(tool_type) => ToolChoice(Some(tool_type)),
}
}
}
#[derive(Debug, Deserialize, Serialize, ToSchema, PartialEq)]
pub struct JsonSchemaTool {
#[serde(flatten)]
functions_map: FunctionsMap,
properties: Properties,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct FunctionsMap {
#[serde(rename = "$functions")]
functions: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct FunctionRef {
#[serde(rename = "$ref")]
ref_path: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Properties {
#[serde(serialize_with = "serialize_function")]
function: Vec<FunctionRef>,
}
fn serialize_function<S>(functions: &Vec<FunctionRef>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("Function", 1)?;
state.serialize_field("anyOf", functions)?;
state.end()
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
pub(crate) struct FunctionDefinition {
#[serde(default)]
pub description: Option<String>,
pub name: String,
pub parameters: serde_json::Value,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
pub(crate) struct ReturnFunctionDefinition {
#[serde(default)]
pub description: Option<String>,
pub name: String,
pub arguments: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct Tool {
// The type of the tool. Currently, only 'function' is supported.
#[schema(example = "function")]
pub r#type: String,
// Grab the tool as generic JSON for debugging purposes.
pub function: FunctionDefinition,
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
struct CompletionRequest {
model: String,
prompt: String,
#[allow(dead_code)] // For now allow this field even though it is unused
suffix: Option<String>,
max_tokens: Option<i32>,
temperature: Option<f32>,
top_p: Option<f32>,
n: Option<i32>,
stream: Option<bool>,
logprobs: Option<i32>,
echo: Option<bool>,
#[serde(default)]
stop: Vec<String>,
#[allow(dead_code)] // For now allow this field even though it is unused
presence_penalty: Option<f32>,
#[allow(dead_code)] // For now allow this field even though it is unused
frequency_penalty: Option<f32>,
best_of: Option<i32>,
#[allow(dead_code)] // For now allow this field even though it is unused
logit_bias: Option<std::collections::HashMap<String, f32>>,
#[allow(dead_code)] // For now allow this field even though it is unused
user: Option<String>,
seed: Option<u64>,
// Additional parameters
// TODO(travis): add other LoRAX params here
repetition_penalty: Option<f32>,
top_k: Option<i32>,
ignore_eos_token: Option<bool>,