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
/*!
The Tangram crate makes it easy to make predictions with your Tangram machine learning model from Rust.

## Usage

```toml
[dependencies]
tangram = "*"
```

```rust no_run
let model: tangram::Model = tangram::Model::from_path("heart_disease.tangram", None).unwrap();

let input = tangram::predict_input! {
  "age": 63.0,
  "gender": "male",
  // ...
};

let output = model.predict_one(input, None);
```

For more information, [read the docs](https://www.tangram.dev/docs).
*/

use anyhow::Result;
use memmap::Mmap;
use std::path::Path;
use std::{collections::BTreeMap, marker::PhantomData};
pub use tangram_macro::{
	predict_input, ClassificationOutputValue, PredictInput, PredictInputValue,
};
use url::Url;

/// Use this struct to load a model, make predictions, and log events to the app.
pub struct Model<Input = PredictInput, Output = PredictOutput>
where
	Input: Into<PredictInput>,
	Output: From<PredictOutput> + Into<PredictOutput>,
{
	model: tangram_core::predict::Model,
	log_queue: Vec<Event>,
	tangram_url: Url,
	input_marker: PhantomData<Input>,
	output_marker: PhantomData<Output>,
}

/// These are the options passed when loading a [`Model`].
pub struct LoadModelOptions {
	/// If you are running the app locally or on your own server, use this field to provide a url that points to it. If not specified, the default value is `https://app.tangram.dev`.
	pub tangram_url: Option<Url>,
}

/// This is the input type of [`Model::predict`]. A predict input is a map whose keys are the same as the column names in the CSV the model was trained with, and whose values match the type for each column.
#[derive(Clone, Debug, serde::Serialize)]
pub struct PredictInput(pub BTreeMap<String, PredictInputValue>);

impl From<PredictInput> for tangram_core::predict::PredictInput {
	fn from(value: PredictInput) -> tangram_core::predict::PredictInput {
		tangram_core::predict::PredictInput(
			value
				.0
				.into_iter()
				.map(|(key, value)| (key, value.into()))
				.collect(),
		)
	}
}

#[derive(Clone, Debug, serde::Serialize)]
#[serde(untagged)]
pub enum PredictInputValue {
	Number(f64),
	String(String),
}

impl From<PredictInputValue> for tangram_core::predict::PredictInputValue {
	fn from(value: PredictInputValue) -> tangram_core::predict::PredictInputValue {
		match value {
			PredictInputValue::Number(value) => {
				tangram_core::predict::PredictInputValue::Number(value)
			}
			PredictInputValue::String(value) => {
				tangram_core::predict::PredictInputValue::String(value)
			}
		}
	}
}

impl From<f64> for PredictInputValue {
	fn from(value: f64) -> Self {
		PredictInputValue::Number(value)
	}
}

impl From<f32> for PredictInputValue {
	fn from(value: f32) -> Self {
		PredictInputValue::Number(value as f64)
	}
}

impl From<String> for PredictInputValue {
	fn from(value: String) -> Self {
		PredictInputValue::String(value)
	}
}

impl From<&str> for PredictInputValue {
	fn from(value: &str) -> Self {
		PredictInputValue::String(value.to_owned())
	}
}

/// These are the options passed to [`Model::predict`].
#[derive(Clone, Debug, serde::Serialize)]
pub struct PredictOptions {
	/// If your model is a binary classifier, use this field to make predictions using a threshold chosen on the tuning page of the app. The default value is `0.5`.
	pub threshold: Option<f32>,
	/// Computing feature contributions is disabled by default. If you set this field to `true`, you will be able to access the feature contributions with the `feature_contributions` field of the predict output.
	pub compute_feature_contributions: Option<bool>,
}

impl From<PredictOptions> for tangram_core::predict::PredictOptions {
	fn from(value: PredictOptions) -> tangram_core::predict::PredictOptions {
		let mut options = tangram_core::predict::PredictOptions::default();
		if let Some(threshold) = value.threshold {
			options.threshold = threshold;
		}
		if let Some(compute_feature_contributions) = value.compute_feature_contributions {
			options.compute_feature_contributions = compute_feature_contributions;
		}
		options
	}
}

/// This is the output of [`Model::predict`].
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum PredictOutput {
	Regression(RegressionPredictOutput),
	BinaryClassification(BinaryClassificationPredictOutput),
	MulticlassClassification(MulticlassClassificationPredictOutput),
}

impl From<RegressionPredictOutput> for PredictOutput {
	fn from(value: RegressionPredictOutput) -> Self {
		PredictOutput::Regression(value)
	}
}

impl<T> From<BinaryClassificationPredictOutput<T>> for PredictOutput
where
	T: ClassificationOutputValue,
{
	fn from(value: BinaryClassificationPredictOutput<T>) -> Self {
		PredictOutput::BinaryClassification(BinaryClassificationPredictOutput {
			class_name: value.class_name.as_str().to_owned(),
			probability: value.probability,
			feature_contributions: value.feature_contributions,
		})
	}
}

impl<T> From<MulticlassClassificationPredictOutput<T>> for PredictOutput
where
	T: ClassificationOutputValue,
{
	fn from(value: MulticlassClassificationPredictOutput<T>) -> Self {
		PredictOutput::MulticlassClassification(MulticlassClassificationPredictOutput {
			class_name: value.class_name.as_str().to_owned(),
			probability: value.probability,
			probabilities: value.probabilities,
			feature_contributions: value.feature_contributions,
		})
	}
}

impl From<tangram_core::predict::PredictOutput> for PredictOutput {
	fn from(value: tangram_core::predict::PredictOutput) -> Self {
		match value {
			tangram_core::predict::PredictOutput::Regression(value) => {
				PredictOutput::Regression(value.into())
			}
			tangram_core::predict::PredictOutput::BinaryClassification(value) => {
				PredictOutput::BinaryClassification(value.into())
			}
			tangram_core::predict::PredictOutput::MulticlassClassification(value) => {
				PredictOutput::MulticlassClassification(value.into())
			}
		}
	}
}

/// This is the output of calling [`Model::predict`] on a `Model` whose task is regression.
#[derive(Debug, serde::Serialize)]
pub struct RegressionPredictOutput {
	/// This is the predicted value.
	pub value: f32,
	/// If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output.
	pub feature_contributions: Option<FeatureContributions>,
}

impl From<tangram_core::predict::RegressionPredictOutput> for RegressionPredictOutput {
	fn from(value: tangram_core::predict::RegressionPredictOutput) -> Self {
		RegressionPredictOutput {
			value: value.value,
			feature_contributions: value.feature_contributions.map(Into::into),
		}
	}
}

impl From<PredictOutput> for RegressionPredictOutput {
	fn from(value: PredictOutput) -> Self {
		match value {
			PredictOutput::Regression(value) => value,
			_ => panic!("expected regression predict output"),
		}
	}
}

impl<T> From<PredictOutput> for MulticlassClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: PredictOutput) -> Self {
		match value {
			PredictOutput::MulticlassClassification(value) => {
				MulticlassClassificationPredictOutput {
					class_name: T::from_str(&value.class_name),
					probability: value.probability,
					probabilities: value.probabilities,
					feature_contributions: value.feature_contributions,
				}
			}
			_ => panic!("expected multiclass classification predict output"),
		}
	}
}

pub trait ClassificationOutputValue {
	fn from_str(value: &str) -> Self;
	fn as_str(&self) -> &str;
}

impl ClassificationOutputValue for String {
	fn from_str(value: &str) -> Self {
		value.to_owned()
	}
	fn as_str(&self) -> &str {
		self
	}
}

/// This is the output of calling [`Model::predict`] on a `Model` whose task is binary classification.
#[derive(Debug, serde::Serialize)]
pub struct BinaryClassificationPredictOutput<T = String>
where
	T: ClassificationOutputValue,
{
	/// This is the name of the predicted class.
	pub class_name: T,
	/// This is the probability the model assigned to the predicted class.
	pub probability: f32,
	/// If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output.
	pub feature_contributions: Option<FeatureContributions>,
}

impl<T> From<tangram_core::predict::BinaryClassificationPredictOutput>
	for BinaryClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: tangram_core::predict::BinaryClassificationPredictOutput) -> Self {
		BinaryClassificationPredictOutput {
			class_name: T::from_str(&value.class_name),
			probability: value.probability,
			feature_contributions: value.feature_contributions.map(Into::into),
		}
	}
}

impl<T> From<tangram_core::predict::PredictOutput> for BinaryClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: tangram_core::predict::PredictOutput) -> Self {
		match value {
			tangram_core::predict::PredictOutput::BinaryClassification(value) => value.into(),
			_ => panic!("expected binary classification predict output"),
		}
	}
}

impl<T> From<PredictOutput> for BinaryClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: PredictOutput) -> Self {
		match value {
			PredictOutput::BinaryClassification(value) => BinaryClassificationPredictOutput {
				class_name: T::from_str(&value.class_name),
				probability: value.probability,
				feature_contributions: value.feature_contributions,
			},
			_ => panic!("expected binary classification predict output"),
		}
	}
}

/// This is the output of calling [`Model::predict`] on a `Model` whose task is multiclass classification.
#[derive(Debug, serde::Serialize)]
pub struct MulticlassClassificationPredictOutput<T = String>
where
	T: ClassificationOutputValue,
{
	/// This is the name of the predicted class.
	pub class_name: T,
	/// This is the probability the model assigned to the predicted class.
	pub probability: f32,
	/// This value maps from class names to the probability the model assigned to each class.
	pub probabilities: BTreeMap<String, f32>,
	/// If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output. This value maps from class names to `FeatureContributions` values for each class. The class with the `FeatureContributions` value with the highest `output_value` is the predicted class.
	pub feature_contributions: Option<BTreeMap<String, FeatureContributions>>,
}

impl<T> From<tangram_core::predict::MulticlassClassificationPredictOutput>
	for MulticlassClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: tangram_core::predict::MulticlassClassificationPredictOutput) -> Self {
		MulticlassClassificationPredictOutput {
			class_name: T::from_str(&value.class_name),
			probability: value.probability,
			probabilities: value.probabilities,
			feature_contributions: value.feature_contributions.map(|feature_contributions| {
				feature_contributions
					.into_iter()
					.map(|(key, value)| (key, value.into()))
					.collect()
			}),
		}
	}
}

impl<T> From<tangram_core::predict::PredictOutput> for MulticlassClassificationPredictOutput<T>
where
	T: ClassificationOutputValue,
{
	fn from(value: tangram_core::predict::PredictOutput) -> Self {
		match value {
			tangram_core::predict::PredictOutput::MulticlassClassification(value) => value.into(),
			_ => panic!("expected multiclass classification predict output"),
		}
	}
}

/// This is a description of the feature contributions for the prediction if the task is regression or binary classification, or for a single class if the task is multiclass classification.
#[derive(Debug, serde::Serialize)]
pub struct FeatureContributions {
	/// This is the value the model would output if all features had baseline values.
	pub baseline_value: f32,
	/// This is the value the model output. Any difference from the `baseline_value` is because of the deviation of the features from their baseline values.
	pub output_value: f32,
	/// This vec will contain one entry for each of the model's features. Note that features are computed from columns, so there will likely be more features than columns.
	pub entries: Vec<FeatureContributionEntry>,
}

impl From<tangram_core::predict::FeatureContributions> for FeatureContributions {
	fn from(value: tangram_core::predict::FeatureContributions) -> Self {
		FeatureContributions {
			baseline_value: value.baseline_value,
			output_value: value.output_value,
			entries: value.entries.into_iter().map(Into::into).collect(),
		}
	}
}

/// This identifies the type of a feature contribution.
#[derive(Debug, serde::Serialize)]
#[serde(tag = "type")]
pub enum FeatureContributionEntry {
	#[serde(rename = "identity")]
	Identity(IdentityFeatureContribution),
	#[serde(rename = "normalized")]
	Normalized(NormalizedFeatureContribution),
	#[serde(rename = "one_hot_encoded")]
	OneHotEncoded(OneHotEncodedFeatureContribution),
	#[serde(rename = "bag_of_words")]
	BagOfWords(BagOfWordsFeatureContribution),
	#[serde(rename = "bag_of_words_cosine_similarity")]
	BagOfWordsCosineSimilarity(BagOfWordsCosineSimilarityFeatureContribution),
	#[serde(rename = "word_embedding")]
	WordEmbedding(WordEmbeddingFeatureContribution),
}

impl From<tangram_core::predict::FeatureContributionEntry> for FeatureContributionEntry {
	fn from(value: tangram_core::predict::FeatureContributionEntry) -> Self {
		match value {
			tangram_core::predict::FeatureContributionEntry::Identity(value) => {
				FeatureContributionEntry::Identity(value.into())
			}
			tangram_core::predict::FeatureContributionEntry::Normalized(value) => {
				FeatureContributionEntry::Normalized(value.into())
			}
			tangram_core::predict::FeatureContributionEntry::OneHotEncoded(value) => {
				FeatureContributionEntry::OneHotEncoded(value.into())
			}
			tangram_core::predict::FeatureContributionEntry::BagOfWords(value) => {
				FeatureContributionEntry::BagOfWords(value.into())
			}
			tangram_core::predict::FeatureContributionEntry::BagOfWordsCosineSimilarity(value) => {
				FeatureContributionEntry::BagOfWordsCosineSimilarity(value.into())
			}
			tangram_core::predict::FeatureContributionEntry::WordEmbedding(value) => {
				FeatureContributionEntry::WordEmbedding(value.into())
			}
		}
	}
}

/// This describes the contribution of a feature from an identity feature group.
#[derive(Debug, serde::Serialize)]
pub struct IdentityFeatureContribution {
	/// This is the name of the source column for the identity feature group.
	pub column_name: String,
	/// This is the value of the feature.
	pub feature_value: f32,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::IdentityFeatureContribution> for IdentityFeatureContribution {
	fn from(value: tangram_core::predict::IdentityFeatureContribution) -> Self {
		IdentityFeatureContribution {
			column_name: value.column_name,
			feature_value: value.feature_value,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

/// This describes the contribution of a feature from a normalized feature group.
#[derive(Debug, serde::Serialize)]
pub struct NormalizedFeatureContribution {
	/// This is the name of the source column for the feature group.
	pub column_name: String,
	/// This is the value of the feature.
	pub feature_value: f32,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::NormalizedFeatureContribution> for NormalizedFeatureContribution {
	fn from(value: tangram_core::predict::NormalizedFeatureContribution) -> Self {
		NormalizedFeatureContribution {
			column_name: value.column_name,
			feature_value: value.feature_value,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

#[derive(Debug, serde::Serialize)]
pub struct OneHotEncodedFeatureContribution {
	/// This is the name of the source column for the feature group.
	pub column_name: String,
	/// This is the enum variant the feature indicates the presence of.
	pub variant: Option<String>,
	/// This is the value of the feature.
	pub feature_value: bool,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::OneHotEncodedFeatureContribution>
	for OneHotEncodedFeatureContribution
{
	fn from(value: tangram_core::predict::OneHotEncodedFeatureContribution) -> Self {
		OneHotEncodedFeatureContribution {
			column_name: value.column_name,
			variant: value.variant,
			feature_value: value.feature_value,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

/// This describes the contribution of a feature from a bag of words feature group.
#[derive(Debug, serde::Serialize)]
pub struct BagOfWordsFeatureContribution {
	/// This is the name of the source column for the feature group.
	pub column_name: String,
	/// This is the ngram for the feature.
	pub ngram: NGram,
	/// This is the value of the feature.
	pub feature_value: f32,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::BagOfWordsFeatureContribution> for BagOfWordsFeatureContribution {
	fn from(value: tangram_core::predict::BagOfWordsFeatureContribution) -> Self {
		BagOfWordsFeatureContribution {
			column_name: value.column_name,
			ngram: value.ngram.into(),
			feature_value: value.feature_value,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

/// This is a sequence of `n` tokens. Tangram currently supports unigrams and bigrams.
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum NGram {
	Unigram(String),
	Bigram(String, String),
}

impl From<tangram_core::predict::NGram> for NGram {
	fn from(value: tangram_core::predict::NGram) -> Self {
		match value {
			tangram_core::predict::NGram::Unigram(token) => NGram::Unigram(token),
			tangram_core::predict::NGram::Bigram(token_a, token_b) => {
				NGram::Bigram(token_a, token_b)
			}
		}
	}
}

/// This describes the contribution of a feature from a bag of words cosine similarity feature group.
#[derive(Debug, serde::Serialize)]
pub struct BagOfWordsCosineSimilarityFeatureContribution {
	/// This is the name of the first source column for the feature group.
	pub column_name_a: String,
	/// This is the name of the second source column for the feature group.
	pub column_name_b: String,
	/// This is the value of the feature.
	pub feature_value: f32,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::BagOfWordsCosineSimilarityFeatureContribution>
	for BagOfWordsCosineSimilarityFeatureContribution
{
	fn from(value: tangram_core::predict::BagOfWordsCosineSimilarityFeatureContribution) -> Self {
		BagOfWordsCosineSimilarityFeatureContribution {
			column_name_a: value.column_name_a,
			column_name_b: value.column_name_b,
			feature_value: value.feature_value,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

/// This describes the contribution of a feature from a word vector feature group.
#[derive(Debug, serde::Serialize)]
pub struct WordEmbeddingFeatureContribution {
	/// This is the name of the source column for the feature group.
	pub column_name: String,
	/// This is the index of the feature in the word embedding.
	pub value_index: usize,
	/// This is the amount that the feature contributed to the output.
	pub feature_contribution_value: f32,
}

impl From<tangram_core::predict::WordEmbeddingFeatureContribution>
	for WordEmbeddingFeatureContribution
{
	fn from(value: tangram_core::predict::WordEmbeddingFeatureContribution) -> Self {
		WordEmbeddingFeatureContribution {
			column_name: value.column_name,
			value_index: value.value_index,
			feature_contribution_value: value.feature_contribution_value,
		}
	}
}

/// This is the type of the argument to [`Model::log_prediction`] and [`Model::enqueue_log_prediction`] which specifies the details of the prediction to log.
#[derive(Debug)]
pub struct LogPredictionArgs<Input, Output>
where
	Input: Into<PredictInput>,
	Output: From<PredictOutput> + Into<PredictOutput>,
{
	/// This is a unique identifier for the prediction, which will associate it with a true value event and allow you to look it up in the app.
	pub identifier: NumberOrString,
	/// This is the same [`struct@PredictInput`] value that you passed to [`Model::predict`].
	pub input: Input,
	/// This is the same `PredictOptions` value that you passed to [`Model::predict`].
	pub options: Option<PredictOptions>,
	/// This is the output returned by [`Model::predict`].
	pub output: Output,
}

/// This is the type of the argument to [`Model::log_true_value`] and [`Model::enqueue_log_true_value`] which specifies the details of the true value to log.
#[derive(Debug)]
pub struct LogTrueValueArgs {
	/// This is a unique identifier for the true value, which will associate it with a prediction event and allow you to look it up in the app.
	pub identifier: NumberOrString,
	/// This is the true value for the prediction.
	pub true_value: NumberOrString,
}

#[derive(serde::Serialize)]
#[serde(tag = "type")]
enum Event {
	#[serde(rename = "prediction")]
	Prediction(PredictionEvent),
	#[serde(rename = "true_value")]
	TrueValue(TrueValueEvent),
}

#[derive(Debug, serde::Serialize)]
struct PredictionEvent {
	date: chrono::DateTime<chrono::Utc>,
	identifier: NumberOrString,
	input: PredictInput,
	options: Option<PredictOptions>,
	output: PredictOutput,
	model_id: String,
}

#[derive(Debug, serde::Serialize)]
struct TrueValueEvent {
	date: chrono::DateTime<chrono::Utc>,
	identifier: NumberOrString,
	model_id: String,
	true_value: NumberOrString,
}

#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum NumberOrString {
	Number(f64),
	String(String),
}

impl From<f64> for NumberOrString {
	fn from(value: f64) -> Self {
		NumberOrString::Number(value)
	}
}

impl From<String> for NumberOrString {
	fn from(value: String) -> Self {
		NumberOrString::String(value)
	}
}

impl From<&str> for NumberOrString {
	fn from(value: &str) -> Self {
		NumberOrString::String(value.to_owned())
	}
}

/// Use this struct to load a model, make predictions, and log events to the app.
impl<Input, Output> Model<Input, Output>
where
	Input: Into<PredictInput>,
	Output: From<PredictOutput> + Into<PredictOutput>,
{
	/// Load a model from the `.tangram` file at `path`.
	pub fn from_path(
		path: impl AsRef<Path>,
		options: Option<LoadModelOptions>,
	) -> Result<Model<Input, Output>> {
		let file = std::fs::File::open(path)?;
		let bytes = unsafe { Mmap::map(&file)? };
		Model::from_bytes(&bytes, options)
	}

	/// Load a model from a byte slice. You should use this only if you already have a `.tangram` loaded into memory. Otherwise, use [`Model::from_path`], which is faster because it memory maps the file.
	pub fn from_bytes(
		bytes: &[u8],
		options: Option<LoadModelOptions>,
	) -> Result<Model<Input, Output>> {
		let model = tangram_model::from_bytes(bytes)?;
		let model = tangram_core::predict::Model::from(model);
		let tangram_url = options
			.and_then(|options| options.tangram_url)
			.unwrap_or_else(|| "https://app.tangram.dev".parse().unwrap());
		Ok(Model {
			model,
			log_queue: Vec::new(),
			tangram_url,
			input_marker: PhantomData,
			output_marker: PhantomData,
		})
	}

	/// Retrieve the model's id.
	pub fn id(&self) -> &str {
		self.model.id.as_str()
	}

	/// Make a prediction with a single input.
	pub fn predict_one(&self, input: Input, options: Option<PredictOptions>) -> Output {
		let model = &self.model;
		let options = options.map(Into::into).unwrap_or_default();
		let output = tangram_core::predict::predict(model, &[input.into().into()], &options);
		let output: PredictOutput = output.into_iter().next().unwrap().into();
		output.into()
	}

	/// Make a prediction with multiple inputs.
	pub fn predict(&self, input: Vec<Input>, options: Option<PredictOptions>) -> Vec<Output> {
		let model = &self.model;
		let options = options.map(Into::into).unwrap_or_default();
		let input = input
			.into_iter()
			.map(Into::into)
			.map(Into::into)
			.collect::<Vec<_>>();
		let output = tangram_core::predict::predict(model, &input, &options);
		output
			.into_iter()
			.map(|output| -> PredictOutput { output.into() })
			.map(Into::into)
			.collect()
	}

	/// Send a prediction event to the app. If you want to batch events, you can use [`Model::enqueue_log_true_value`] instead.
	#[cfg(not(feature = "tokio"))]
	pub fn log_prediction(&mut self, args: LogPredictionArgs<Input, Output>) -> Result<()> {
		let event = Event::Prediction(self.prediction_event(args));
		self.log_event(event)?;
		Ok(())
	}

	/// Send a prediction event to the app. If you want to batch events, you can use [`Model::enqueue_log_true_value`] instead.
	#[cfg(feature = "tokio")]
	pub async fn log_prediction(&mut self, args: LogPredictionArgs<Input, Output>) -> Result<()> {
		let event = Event::Prediction(self.prediction_event(args));
		self.log_event(event).await?;
		Ok(())
	}

	/// Send a true value event to the app. If you want to batch events, you can use [`Model::enqueue_log_true_value`] instead.
	#[cfg(not(feature = "tokio"))]
	pub fn log_true_value(&mut self, args: LogTrueValueArgs) -> Result<()> {
		let event = Event::TrueValue(self.true_value_event(args));
		self.log_event(event)?;
		Ok(())
	}

	/// Send a true value event to the app. If you want to batch events, you can use [`Model::enqueue_log_true_value`] instead.
	#[cfg(feature = "tokio")]
	pub async fn log_true_value(&mut self, args: LogTrueValueArgs) -> Result<()> {
		let event = Event::TrueValue(self.true_value_event(args));
		self.log_event(event).await?;
		Ok(())
	}

	/// Add a prediction event to the queue. Remember to call [`Model::flush_log_queue`] at a later point to send the event to the app.
	pub fn enqueue_log_prediction(&mut self, args: LogPredictionArgs<Input, Output>) {
		let event = Event::Prediction(self.prediction_event(args));
		self.log_queue.push(event);
	}

	/// Add a true value event to the queue. Remember to call [`Model::flush_log_queue`] at a later point to send the event to the app.
	pub fn enqueue_log_true_value(&mut self, args: LogTrueValueArgs) {
		let event = Event::TrueValue(self.true_value_event(args));
		self.log_queue.push(event);
	}

	/// Send all events in the queue to the app.
	#[cfg(not(feature = "tokio"))]
	pub fn flush_log_queue(&mut self) -> Result<()> {
		let events = self.log_queue.drain(0..self.log_queue.len()).collect();
		self.log_events(events)
	}

	/// Send all events in the queue to the app.
	#[cfg(feature = "tokio")]
	pub async fn flush_log_queue(&mut self) -> Result<()> {
		let events = self.log_queue.drain(0..self.log_queue.len()).collect();
		self.log_events(events)
	}

	#[cfg(not(feature = "tokio"))]
	fn log_event(&mut self, event: Event) -> Result<()> {
		self.log_events(vec![event])
	}

	#[cfg(feature = "tokio")]
	fn log_event(&mut self, event: Event) -> Result<()> {
		self.log_events(vec![event])
	}

	#[cfg(not(feature = "tokio"))]
	fn log_events(&mut self, events: Vec<Event>) -> Result<()> {
		let mut url = self.tangram_url.clone();
		url.set_path("/track");
		let body = serde_json::to_vec(&events)?;
		reqwest::blocking::Client::new()
			.post(url)
			.body(body)
			.send()?;
		Ok(())
	}

	#[cfg(feature = "tokio")]
	async fn log_events(&mut self, events: Vec<Event>) -> Result<()> {
		let mut url = self.tangram_url.clone();
		url.set_path("/track");
		let body = serde_json::to_vec(&events)?;
		reqwest::Client::new().post(url).body(body).send().await?;
		Ok(())
	}

	fn prediction_event(&self, args: LogPredictionArgs<Input, Output>) -> PredictionEvent {
		PredictionEvent {
			date: chrono::Utc::now(),
			identifier: args.identifier,
			input: args.input.into(),
			options: args.options,
			output: args.output.into(),
			model_id: self.id().to_owned(),
		}
	}

	fn true_value_event(&self, args: LogTrueValueArgs) -> TrueValueEvent {
		TrueValueEvent {
			date: chrono::Utc::now(),
			identifier: args.identifier,
			model_id: self.id().to_owned(),
			true_value: args.true_value,
		}
	}
}