scouter-types 0.25.0

Client and server contract for scouter
Documentation
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
use crate::error::TypeError;
use crate::EvalRecord;
use crate::PyHelperFuncs;
use opentelemetry::StringValue;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyFloat, PyInt, PyList, PyString};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use tracing::error;

#[pyclass]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum EntityType {
    Feature,
    Metric,
    GenAI,
}

impl From<EntityType> for opentelemetry::Value {
    fn from(val: EntityType) -> Self {
        match val {
            EntityType::Feature => opentelemetry::Value::String(StringValue::from("Feature")),
            EntityType::Metric => opentelemetry::Value::String(StringValue::from("Metric")),
            EntityType::GenAI => opentelemetry::Value::String(StringValue::from("GenAI")),
        }
    }
}

impl Display for EntityType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            EntityType::Feature => write!(f, "Feature"),
            EntityType::Metric => write!(f, "Metric"),
            EntityType::GenAI => write!(f, "GenAI"),
        }
    }
}

#[pyclass]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct IntFeature {
    pub name: String,
    pub value: i64,
}

#[pymethods]
impl IntFeature {
    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl IntFeature {
    pub fn to_float(&self) -> f64 {
        self.value as f64
    }
}

#[pyclass]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct FloatFeature {
    pub name: String,
    pub value: f64,
}

#[pymethods]
impl FloatFeature {
    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

#[pyclass]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct StringFeature {
    pub name: String,
    pub value: String,
}

#[pymethods]
impl StringFeature {
    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl StringFeature {
    /// Generic conversion function that maps string feature values to numeric types
    /// via the feature map lookup. Falls back to "missing" key if the specific value
    /// is not found in the map.
    fn to_numeric<T>(&self, feature_map: &FeatureMap) -> Result<T, TypeError>
    where
        T: From<i32>,
    {
        feature_map
            .features
            .get(&self.name)
            .and_then(|feat_map| {
                feat_map
                    .get(&self.value)
                    .or_else(|| feat_map.get("missing"))
            })
            .copied()
            .map(T::from)
            .ok_or(TypeError::MissingStringValueError)
    }

    pub fn to_float(&self, feature_map: &FeatureMap) -> Result<f64, TypeError> {
        self.to_numeric::<i32>(feature_map).map(|v| v as f64)
    }

    pub fn to_i32(&self, feature_map: &FeatureMap) -> Result<i32, TypeError> {
        self.to_numeric::<i32>(feature_map)
    }
}
#[pyclass(name = "QueueFeature")]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum Feature {
    Int(IntFeature),
    Float(FloatFeature),
    String(StringFeature),
}

#[pymethods]
impl Feature {
    #[new]
    /// Parses a value to it's corresponding feature type.
    /// PyFLoat -> FloatFeature
    /// PyInt -> IntFeature
    /// PyString -> StringFeature
    /// # Arguments
    /// * `name` - The name of the feature.
    /// * `feature` - The value of the feature, which can be a PyFloat
    /// # Returns
    /// * `Feature` - The corresponding feature type.
    /// # Errors
    /// * `TypeError` - If the feature type is not supported.
    pub fn new(name: &str, feature: Bound<'_, PyAny>) -> Result<Self, TypeError> {
        // check python type
        if feature.is_instance_of::<PyFloat>() {
            let value: f64 = feature.extract().unwrap();
            Ok(Feature::Float(FloatFeature {
                name: name.into(),
                value,
            }))
        } else if feature.is_instance_of::<PyInt>() {
            let value: i64 = feature.extract().unwrap();
            Ok(Feature::Int(IntFeature {
                name: name.into(),
                value,
            }))
        } else if feature.is_instance_of::<PyString>() {
            let value: String = feature.extract().unwrap();
            Ok(Feature::String(StringFeature {
                name: name.into(),
                value,
            }))
        } else {
            Err(TypeError::UnsupportedFeatureTypeError(
                feature.get_type().name()?.to_string(),
            ))
        }
    }

    #[staticmethod]
    pub fn int(name: String, value: i64) -> Self {
        Feature::Int(IntFeature { name, value })
    }

    #[staticmethod]
    pub fn float(name: String, value: f64) -> Self {
        Feature::Float(FloatFeature { name, value })
    }

    #[staticmethod]
    pub fn string(name: String, value: String) -> Self {
        Feature::String(StringFeature { name, value })
    }

    #[staticmethod]
    pub fn categorical(name: String, value: String) -> Self {
        Feature::String(StringFeature { name, value })
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl Feature {
    pub fn to_float(&self, feature_map: &FeatureMap) -> Result<f64, TypeError> {
        match self {
            Feature::Int(feature) => Ok(feature.to_float()),
            Feature::Float(feature) => Ok(feature.value),
            Feature::String(feature) => feature.to_float(feature_map),
        }
    }

    pub fn name(&self) -> &str {
        match self {
            Feature::Int(feature) => &feature.name,
            Feature::Float(feature) => &feature.name,
            Feature::String(feature) => &feature.name,
        }
    }

    pub fn to_usize(&self, feature_map: &FeatureMap) -> Result<usize, TypeError> {
        match self {
            Feature::Int(f) => Ok(f.value as usize),
            Feature::Float(f) => Ok(f.value as usize),
            Feature::String(f) => Ok(f.to_float(feature_map)? as usize),
        }
    }

    pub fn to_i32(&self, feature_map: &FeatureMap) -> Result<i32, TypeError> {
        match self {
            Feature::Int(f) => Ok(f.value as i32),
            Feature::Float(f) => Ok(f.value as i32),
            Feature::String(f) => Ok(f.to_i32(feature_map)?),
        }
    }
}

impl Display for Feature {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Feature::Int(feature) => write!(f, "{}", feature.value),
            Feature::Float(feature) => write!(f, "{}", feature.value),
            Feature::String(feature) => write!(f, "{}", feature.value),
        }
    }
}

#[pyclass]
#[derive(Clone, Debug, Serialize)]
pub struct Features {
    #[pyo3(get)]
    pub features: Vec<Feature>,

    #[pyo3(get)]
    pub entity_type: EntityType,
}

#[pymethods]
impl Features {
    #[new]
    /// Creates a new Features instance.
    /// A user may supply either a list of features or a single feature.
    /// Extract features into a Vec<Feature>
    /// Extraction follows the following rules:
    /// 1. Check if Pylist, if so, extract to Vec<Feature>
    /// 2. Check if PyDict, if so, iterate over each key-value pair and create a Feature
    /// 3. If neither, return an error
    /// # Arguments
    /// * `features` - A Python object that can be a list of Feature instances or
    ///               a dictionary of key-value pairs where keys are feature names
    /// # Returns
    /// * `Features` - A new Features instance containing the extracted features.
    pub fn new(features: Bound<'_, PyAny>) -> Result<Self, TypeError> {
        let features = if features.is_instance_of::<PyList>() {
            let feature_list = features.cast::<PyList>()?;
            let mut result = Vec::with_capacity(feature_list.len());
            for item in feature_list.iter() {
                result.push(item.extract::<Feature>()?);
            }
            result
        } else if features.is_instance_of::<PyDict>() {
            let dict = features.cast::<PyDict>()?;
            let mut result = Vec::with_capacity(dict.len());
            for (key, value) in dict.iter() {
                let name = key.extract::<String>()?;
                result.push(Feature::new(&name, value)?);
            }
            result
        } else {
            return Err(TypeError::UnsupportedFeaturesTypeError(
                features.get_type().name()?.to_string(),
            ));
        };

        Ok(Features {
            features,
            entity_type: EntityType::Feature,
        })
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl Features {
    pub fn iter(&self) -> std::slice::Iter<'_, Feature> {
        self.features.iter()
    }
}

#[pyclass]
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct FeatureMap {
    #[pyo3(get)]
    pub features: HashMap<String, HashMap<String, i32>>,
}

#[pymethods]
impl FeatureMap {
    pub fn __str__(&self) -> String {
        // serialize the struct to a string
        PyHelperFuncs::__str__(self)
    }
}

#[pyclass]
#[derive(Clone, Serialize, Debug)]
pub struct Metric {
    pub name: String,
    pub value: f64,
}

#[pymethods]
impl Metric {
    #[new]
    pub fn new(name: String, value: Bound<'_, PyAny>) -> Self {
        let value = if value.is_instance_of::<PyFloat>() {
            value.extract::<f64>().unwrap()
        } else if value.is_instance_of::<PyInt>() {
            value.extract::<i64>().unwrap() as f64
        } else {
            panic!(
                "Unsupported metric type: {}",
                value.get_type().name().unwrap()
            );
        };
        let lowercase_name = name.to_lowercase();
        Metric {
            name: lowercase_name,
            value,
        }
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl Metric {
    pub fn new_rs(name: String, value: f64) -> Self {
        Metric { name, value }
    }
}

#[pyclass]
#[derive(Clone, Serialize, Debug)]
pub struct Metrics {
    #[pyo3(get)]
    pub metrics: Vec<Metric>,

    #[pyo3(get)]
    pub entity_type: EntityType,
}

#[pymethods]
impl Metrics {
    #[new]
    pub fn new(metrics: Bound<'_, PyAny>) -> Result<Self, TypeError> {
        let metrics = if metrics.is_instance_of::<PyList>() {
            let list = metrics.cast::<PyList>()?;
            let mut result = Vec::with_capacity(list.len());
            for item in list.iter() {
                result.push(item.extract::<Metric>()?);
            }
            result
        } else if metrics.is_instance_of::<PyDict>() {
            let dict = metrics.cast::<PyDict>()?;
            let mut result = Vec::with_capacity(dict.len());
            for (key, value) in dict.iter() {
                let name = key.extract::<String>()?;
                result.push(Metric::new(name, value));
            }
            result
        } else {
            return Err(TypeError::UnsupportedMetricsTypeError(
                metrics.get_type().name()?.to_string(),
            ));
        };

        Ok(Metrics {
            metrics,
            entity_type: EntityType::Metric,
        })
    }
    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl Metrics {
    pub fn iter(&self) -> std::slice::Iter<'_, Metric> {
        self.metrics.iter()
    }
}

#[derive(Debug)]
pub enum QueueItem {
    Features(Features),
    Metrics(Metrics),
    GenAI(Box<EvalRecord>),
}

impl QueueItem {
    /// Helper for extracting an Entity from a Python object
    pub fn from_py_entity(entity: &Bound<'_, PyAny>) -> Result<Self, TypeError> {
        let entity_type = entity
            .getattr("entity_type")?
            .extract::<EntityType>()
            .inspect_err(|e| error!("Failed to extract entity type: {}", e))?;

        match entity_type {
            EntityType::Feature => {
                let features = entity.extract::<Features>()?;
                Ok(QueueItem::Features(features))
            }
            EntityType::Metric => {
                let metrics = entity.extract::<Metrics>()?;
                Ok(QueueItem::Metrics(metrics))
            }
            EntityType::GenAI => {
                // LLM is not supported in this context
                let genai = entity.extract::<EvalRecord>()?;
                Ok(QueueItem::GenAI(Box::new(genai)))
            }
        }
    }
}

pub trait QueueExt: Send + Sync {
    fn metrics(&self) -> &Vec<Metric>;
    fn features(&self) -> &Vec<Feature>;
    fn into_genai_record(self) -> Option<EvalRecord>;
}

impl QueueExt for Features {
    fn metrics(&self) -> &Vec<Metric> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        static EMPTY: Vec<Metric> = Vec::new();
        &EMPTY
    }

    fn features(&self) -> &Vec<Feature> {
        &self.features
    }

    fn into_genai_record(self) -> Option<EvalRecord> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        None
    }
}

impl QueueExt for Metrics {
    fn metrics(&self) -> &Vec<Metric> {
        &self.metrics
    }

    fn features(&self) -> &Vec<Feature> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        static EMPTY: Vec<Feature> = Vec::new();
        &EMPTY
    }

    fn into_genai_record(self) -> Option<EvalRecord> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        None
    }
}

impl QueueExt for EvalRecord {
    fn metrics(&self) -> &Vec<Metric> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        static EMPTY: Vec<Metric> = Vec::new();
        &EMPTY
    }

    fn features(&self) -> &Vec<Feature> {
        // this is not a real implementation, just a placeholder
        // to satisfy the trait bound
        static EMPTY: Vec<Feature> = Vec::new();
        &EMPTY
    }

    fn into_genai_record(self) -> Option<EvalRecord> {
        Some(self)
    }
}