|
| 1 | +use schemars::{schema_for, JsonSchema}; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use anyhow::{Result, bail}; |
| 4 | +use jsonschema::JSONSchema; |
| 5 | + |
| 6 | +#[derive(Serialize, Deserialize, JsonSchema, Debug)] |
| 7 | +pub struct DexterResponse { |
| 8 | + pub revenue_impact: String, |
| 9 | + pub primary_catalyst: String, |
| 10 | + #[validate(range(min = -1.0, max = 1.0))] |
| 11 | + pub sentiment_score: f64, |
| 12 | + pub recommended_action: String, // BUY, SELL, HOLD |
| 13 | +} |
| 14 | + |
| 15 | +pub struct SchemaValidator { |
| 16 | + compiled_schema: JSONSchema, |
| 17 | +} |
| 18 | + |
| 19 | +impl SchemaValidator { |
| 20 | + pub fn new() -> Result<Self> { |
| 21 | + let schema = schema_for!(DexterResponse); |
| 22 | + let schema_value = serde_json::to_value(&schema)?; |
| 23 | + let compiled = JSONSchema::compile(&schema_value).map_err(|e| anyhow::anyhow!("Schema compilation failed: {}", e))?; |
| 24 | + Ok(Self { |
| 25 | + compiled_schema: compiled, |
| 26 | + }) |
| 27 | + } |
| 28 | + |
| 29 | + pub fn validate_and_parse(&self, llm_json_str: &str) -> Result<DexterResponse> { |
| 30 | + let value: serde_json::Value = serde_json::from_str(llm_json_str)?; |
| 31 | + |
| 32 | + if let Err(errors) = self.compiled_schema.validate(&value) { |
| 33 | + let error_msgs: Vec<String> = errors.map(|e| e.to_string()).collect(); |
| 34 | + tracing::error!("Claude returned invalid JSON schema: {:?}", error_msgs); |
| 35 | + bail!("Schema validation failed: {:?}", error_msgs); |
| 36 | + } |
| 37 | + |
| 38 | + let response: DexterResponse = serde_json::from_value(value)?; |
| 39 | + Ok(response) |
| 40 | + } |
| 41 | +} |
0 commit comments