policyai 0.4.0

PolicyAI provides a mechanism for unstructured, composable policies that transform unstructured text into structured outputs.
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
#![deny(missing_docs)]

//! PolicyAI: A framework for turning unstructured data into structured data via composable policies.
//!
//! PolicyAI provides a mechanism for writing policies that transform unstructured text into
//! structured outputs. Policies are composable, meaning multiple policies can be applied together
//! with configurable conflict resolution strategies.
//!
//! # Core Concepts
//!
//! - **PolicyType**: Defines the structure of data that policies will work with
//! - **Policy**: A semantic injection coupled with structured actions
//! - **Field**: A typed field in a policy with default values and conflict resolution
//! - **Manager**: Coordinates the application of multiple policies to unstructured data
//! - **Report**: The result of applying policies, including the structured output
//!
//! # Example
//!
//! ```
//! use policyai::{PolicyType, Field, OnConflict, Manager};
//!
//! let policy_type = PolicyType {
//!     name: "EmailPolicy".to_string(),
//!     fields: vec![
//!         Field::Bool {
//!             name: "unread".to_string(),
//!             default: Some(true),
//!             on_conflict: OnConflict::Default,
//!         },
//!         Field::StringEnum {
//!             name: "priority".to_string(),
//!             values: vec!["low".to_string(), "high".to_string()],
//!             default: None,
//!             on_conflict: OnConflict::LargestValue,
//!         },
//!     ],
//! };
//! ```

use std::cmp::Ordering;

/// Data structures and utilities for test data
pub mod data;

/// Analysis tools for evaluation metrics
pub mod analysis;

mod errors;
mod field;
mod manager;
mod masks;
mod on_conflict;
mod parser;
mod policy;
mod policy_type;
mod report;
mod report_builder;
mod usage;

pub use errors::{ApplyError, Conflict, PolicyError};
pub use field::Field;
pub use manager::Manager;
pub use masks::{BoolMask, NumberMask, StringArrayMask, StringEnumMask, StringMask};
pub use on_conflict::OnConflict;
pub use parser::ParseError;
pub use policy::Policy;
pub use policy_type::PolicyType;
pub use report::Report;
pub use report_builder::ReportBuilder;
pub use usage::Usage;

//////////////////////////////////////////////// t64 ///////////////////////////////////////////////

/// A totally-ordered 64-bit floating point number.
///
/// This type implements `Ord` and `Eq` for f64 values by using total ordering,
/// which means NaN values are considered equal to themselves and greater than
/// all other values, including positive infinity.
#[derive(Clone, Copy, Debug, Default, serde::Deserialize, serde::Serialize)]
#[allow(non_camel_case_types)]
#[repr(transparent)]
pub struct t64(pub f64);

impl Eq for t64 {}

impl PartialEq for t64 {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other).is_eq()
    }
}

impl Ord for t64 {
    fn cmp(&self, other: &Self) -> Ordering {
        f64::total_cmp(&self.0, &other.0)
    }
}

impl PartialOrd for t64 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl From<t64> for serde_json::Value {
    fn from(x: t64) -> Self {
        serde_json::Number::from_f64(x.0)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null)
    }
}

//////////////////////////////////////////// Number Helpers ///////////////////////////////////////

pub(crate) fn number_is_equal(lhs: &serde_json::Number, rhs: &serde_json::Number) -> bool {
    if lhs.is_f64() && rhs.is_f64() {
        lhs.as_f64() == rhs.as_f64()
    } else if lhs.is_u64() && rhs.is_u64() {
        lhs.as_u64() == rhs.as_u64()
    } else if lhs.is_i64() && rhs.is_i64() {
        lhs.as_i64() == rhs.as_i64()
    } else {
        // Compare across different number types by converting to f64
        match (lhs.as_f64(), rhs.as_f64()) {
            (Some(l), Some(r)) => l == r,
            _ => false,
        }
    }
}

pub(crate) fn number_less_than(lhs: &serde_json::Number, rhs: &serde_json::Number) -> bool {
    if lhs.is_f64() && rhs.is_f64() {
        lhs.as_f64() < rhs.as_f64()
    } else if lhs.is_u64() && rhs.is_u64() {
        lhs.as_u64() < rhs.as_u64()
    } else if lhs.is_i64() && rhs.is_i64() {
        lhs.as_i64() < rhs.as_i64()
    } else {
        // Compare across different number types by converting to f64
        match (lhs.as_f64(), rhs.as_f64()) {
            (Some(l), Some(r)) => l < r,
            _ => false,
        }
    }
}

/////////////////////////////////////////////// tests //////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use claudius::{Anthropic, MessageCreateParams};

    use super::*;

    #[test]
    fn t64_equality() {
        assert_eq!(t64(1.0), t64(1.0));
        assert_ne!(t64(1.0), t64(2.0));
        assert_eq!(t64(f64::NAN), t64(f64::NAN)); // NaN equals itself in total ordering
    }

    #[test]
    fn t64_ordering() {
        assert!(t64(1.0) < t64(2.0));
        assert!(t64(2.0) > t64(1.0));
        assert!(t64(1.0) <= t64(1.0));
        assert!(t64(1.0) >= t64(1.0));

        // Test NaN handling
        assert!(t64(f64::NEG_INFINITY) < t64(f64::NAN));
        assert!(t64(f64::NAN) > t64(f64::INFINITY));
    }

    #[test]
    fn t64_serialization() {
        let value = t64(42.5);
        let serialized = serde_json::to_string(&value).unwrap();
        assert_eq!(serialized, "42.5");
        let deserialized: t64 = serde_json::from_str(&serialized).unwrap();
        assert_eq!(value, deserialized);
    }

    #[test]
    fn t64_to_json_value() {
        let value = t64(3.25);
        let json_value: serde_json::Value = value.into();
        assert_eq!(json_value, serde_json::json!(3.25));
    }

    #[test]
    fn t64_whole_number_serialization() {
        let value = t64(42.0);
        let json_value: serde_json::Value = value.into();
        let serialized = serde_json::to_string(&json_value).unwrap();
        let deserialized: serde_json::Value = serde_json::from_str(&serialized).unwrap();
        let as_t64: t64 = serde_json::from_value(deserialized).unwrap();
        assert_eq!(value, as_t64);
    }

    #[test]
    fn t64_integer_deserialization() {
        let json_str = "42";
        let value: t64 = serde_json::from_str(json_str).unwrap();
        assert_eq!(value, t64(42.0));
    }

    #[test]
    fn number_is_equal() {
        let n1 = serde_json::Number::from(42);
        let n2 = serde_json::Number::from(42);
        assert!(super::number_is_equal(&n1, &n2));

        let n1 = serde_json::Number::from_f64(3.25).unwrap();
        let n2 = serde_json::Number::from_f64(3.25).unwrap();
        assert!(super::number_is_equal(&n1, &n2));

        let n1 = serde_json::Number::from(42);
        let n2 = serde_json::Number::from(43);
        assert!(!super::number_is_equal(&n1, &n2));
    }

    #[test]
    fn number_less_than() {
        let n1 = serde_json::Number::from(41);
        let n2 = serde_json::Number::from(42);
        assert!(super::number_less_than(&n1, &n2));
        assert!(!super::number_less_than(&n2, &n1));

        let n1 = serde_json::Number::from_f64(3.24).unwrap();
        let n2 = serde_json::Number::from_f64(3.25).unwrap();
        assert!(super::number_less_than(&n1, &n2));
        assert!(!super::number_less_than(&n2, &n1));
    }

    #[test]
    fn readme() {
        let policy = PolicyType {
            name: "policyai::EmailPolicy".to_string(),
            fields: vec![
                Field::Bool {
                    name: "unread".to_string(),
                    default: Some(true),
                    on_conflict: OnConflict::Default,
                },
                Field::StringEnum {
                    name: "priority".to_string(),
                    values: vec!["low".to_string(), "medium".to_string(), "high".to_string()],
                    default: None,
                    on_conflict: OnConflict::LargestValue,
                },
                Field::StringEnum {
                    name: "category".to_string(),
                    values: vec![
                        "ai".to_string(),
                        "distributed systems".to_string(),
                        "other".to_string(),
                    ],
                    default: Some("other".to_string()),
                    on_conflict: OnConflict::Agreement,
                },
                Field::String {
                    name: "template".to_string(),
                    default: None,
                    on_conflict: OnConflict::Agreement,
                },
                Field::StringArray {
                    name: "labels".to_string(),
                },
            ],
        };
        assert_eq!(
            r#"type policyai::EmailPolicy {
    unread: bool = true,
    priority: ["low", "medium", "high"] @ highest wins,
    category: ["ai", "distributed systems", "other"] @ agreement = "other",
    template: string @ agreement,
    labels: [string],
}"#,
            format!("{policy}")
        );
    }

    #[tokio::test]
    async fn with_semantic_injection() {
        let client = Anthropic::new(None).unwrap();
        let policy = PolicyType {
            name: "policyai::EmailPolicy".to_string(),
            fields: vec![
                Field::Bool {
                    name: "unread".to_string(),
                    default: Some(true),
                    on_conflict: OnConflict::Default,
                },
                Field::StringEnum {
                    name: "priority".to_string(),
                    values: vec!["low".to_string(), "medium".to_string(), "high".to_string()],
                    default: None,
                    on_conflict: OnConflict::LargestValue,
                },
                Field::StringEnum {
                    name: "category".to_string(),
                    values: vec![
                        "ai".to_string(),
                        "distributed systems".to_string(),
                        "other".to_string(),
                    ],
                    default: Some("other".to_string()),
                    on_conflict: OnConflict::Agreement,
                },
                Field::String {
                    name: "template".to_string(),
                    default: None,
                    on_conflict: OnConflict::Agreement,
                },
                Field::StringArray {
                    name: "labels".to_string(),
                },
            ],
        };
        let policy = policy
            .with_semantic_injection(
                &client,
                "If the user talks about Paxos, set \"category\" to \"distributed systems\".",
            )
            .await
            .unwrap();
        assert_eq!(
            serde_json::json! {{
                "category": "distributed systems",
            }},
            policy.action,
        );
    }

    #[tokio::test]
    async fn numeric_semantic_injection() {
        let client = Anthropic::new(None).unwrap();
        let policy = PolicyType {
            name: "policyai::EmailPolicy".to_string(),
            fields: vec![Field::Number {
                name: "weight".to_string(),
                default: None,
                on_conflict: OnConflict::Default,
            }],
        };
        let policy = policy
            .with_semantic_injection(&client, "Assign weight to the email.")
            .await
            .unwrap();
        assert!(matches!(
            policy.action.get("weight"),
            Some(serde_json::Value::Number(_))
        ));
    }

    #[tokio::test]
    async fn apply_readme_policy() {
        let client = Anthropic::new(None).unwrap();
        let policy = PolicyType {
            name: "policyai::EmailPolicy".to_string(),
            fields: vec![
                Field::Bool {
                    name: "unread".to_string(),
                    default: Some(true),
                    on_conflict: OnConflict::Default,
                },
                Field::StringEnum {
                    name: "priority".to_string(),
                    values: vec!["low".to_string(), "medium".to_string(), "high".to_string()],
                    default: None,
                    on_conflict: OnConflict::LargestValue,
                },
                Field::String {
                    name: "template".to_string(),
                    default: None,
                    on_conflict: OnConflict::Agreement,
                },
                Field::StringEnum {
                    name: "category".to_string(),
                    values: vec![
                        "ai".to_string(),
                        "distributed systems".to_string(),
                        "other".to_string(),
                    ],
                    default: Some("other".to_string()),
                    on_conflict: OnConflict::Agreement,
                },
                Field::StringArray {
                    name: "labels".to_string(),
                },
            ],
        };
        let policy = policy
            .with_semantic_injection(
                &client,
                "When the email is about AI:  Set \"priority\" to \"low\" and \"unread\" to \"true\".",
            )
            .await
            .unwrap();
        assert_eq!(
            serde_json::json! {{"priority": "low", "unread": true}},
            policy.action
        );
        let mut manager = Manager::default();
        manager.add(policy);
        let report = manager
            .apply(
                &Anthropic::new(None).unwrap(),
                MessageCreateParams {
                    max_tokens: 2048,
                    ..Default::default()
                },
                r#"From: robert@example.org
To: jeff@example.org

This is an email about AI.
        "#,
                None,
            )
            .await
            .expect("manager should produce a JSON value");
        println!("{report}");
        assert_eq!(
            serde_json::json! {{"category": "other", "priority": "low", "unread": true}},
            report.value()
        );
    }
}