Skip to content

Commit

Permalink
Add constraints via Jinja expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
imalsogreg committed Oct 14, 2024
1 parent 66f6341 commit 74fd792
Show file tree
Hide file tree
Showing 94 changed files with 3,400 additions and 259 deletions.
11 changes: 11 additions & 0 deletions engine/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,8 @@ impl ScopeStack {
pub fn push_error(&mut self, error: String) {
self.scopes.last_mut().unwrap().errors.push(error);
}

pub fn push_warning(&mut self, warning: String) {
self.scopes.last_mut().unwrap().warnings.push(warning);
}
}
35 changes: 34 additions & 1 deletion engine/baml-lib/baml-core/src/ir/ir_helpers/to_baml_arg.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use baml_types::{BamlMap, BamlMediaType, BamlValue, FieldType, LiteralValue, TypeValue};
use baml_types::{
BamlMap, BamlValue, Constraint, ConstraintLevel, FieldType, LiteralValue, TypeValue
};
use core::result::Result;
use std::path::PathBuf;

use crate::ir::IntermediateRepr;

use super::{scope_diagnostics::ScopeStack, IRHelper};
use internal_baml_jinja::evaluate_predicate;

#[derive(Default)]
pub struct ParameterError {
Expand Down Expand Up @@ -325,6 +328,36 @@ impl ArgCoercer {
}
}
}
FieldType::Constrained { base, constraints } => {
let val = self.coerce_arg(ir, base, value, scope)?;
for c@Constraint {
level,
expression,
label,
} in constraints.iter()
{
let constraint_ok =
evaluate_predicate(&val, &expression).unwrap_or_else(|err| {
scope.push_error(format!(
"Error while evaluating check {c:?}: {:?}",
err
));
false
});
if !constraint_ok {
let msg = label.as_ref().unwrap_or(&expression.0);
match level {
ConstraintLevel::Check => {
scope.push_warning(format!("Failed check: {msg}"));
}
ConstraintLevel::Assert => {
scope.push_error(format!("Failed assert: {msg}"));
}
}
}
}
Ok(val)
}
}
}
}
1 change: 1 addition & 0 deletions engine/baml-lib/baml-core/src/ir/json_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ impl<'db> WithJsonSchema for FieldType {
}
}
}
FieldType::Constrained { base, .. } => base.json_schema(),
}
}
}
Loading

0 comments on commit 74fd792

Please sign in to comment.