Skip to content

Commit

Permalink
parse string to json
Browse files Browse the repository at this point in the history
  • Loading branch information
OlivierDehaene committed Feb 20, 2024
1 parent bada345 commit 19dd0a8
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions router/src/validation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/// Payload validation logic
use crate::validation::ValidationError::{BestOfSampling, BestOfSeed, EmptyInput};
use crate::{GenerateParameters, GenerateRequest, GrammarType};
use jsonschema::{Draft, JSONSchema};
use rand::{thread_rng, Rng};
use serde_json::Value;
use text_generation_client::{
GrammarType as ProtoGrammarType, NextTokenChooserParameters, StoppingCriteriaParameters,
};
Expand Down Expand Up @@ -313,14 +315,24 @@ impl Validation {
return Err(ValidationError::Grammar);
}
match grammar {
// currently both are handled the same way since compilation is done in Python
GrammarType::Json(json) => {
// JSONSchema::options()
// .with_draft(Draft::Draft202012)
// .compile(&json)
// .map_err(|e| ValidationError::InvalidGrammar(e.to_string()))?;
let json = match json {
// if value is a string, we need to parse it again to make sure its
// a valid json
Value::String(s) => serde_json::from_str(&s)
.map_err(|e| ValidationError::InvalidGrammar(e.to_string())),
Value::Object(_) => Ok(json),
_ => Err(ValidationError::Grammar),
}?;

// Check if the json is a valid JSONSchema
JSONSchema::options()
.with_draft(Draft::Draft202012)
.compile(&json)
.map_err(|e| ValidationError::InvalidGrammar(e.to_string()))?;

(
// Serialize json to string
serde_json::to_string(&json)
.map_err(|e| ValidationError::InvalidGrammar(e.to_string()))?,
ProtoGrammarType::Json.into(),
Expand Down Expand Up @@ -497,7 +509,7 @@ pub enum ValidationError {
Tokenizer(String),
#[error("grammar is not supported")]
Grammar,
#[error("grammar is not a valid JSONSchema: {0}")]
#[error("grammar is not valid: {0}")]
InvalidGrammar(String),
}

Expand Down

0 comments on commit 19dd0a8

Please sign in to comment.