Function validate_responses

Source
pub fn validate_responses(
    workflow: Arc<dyn WorkflowLike>,
    context: &mut dyn ContextLike,
    responses: HashMap<String, Response>,
) -> Result<usize>
Expand description

Validates inference responses and assigns them to matching assignment rules in an AIM structure.

This function processes a collection of parsed inference responses and assigns them to corresponding assignment rules in the AIM structure. Assignment rules are identified by their underscore prefix (e.g., _example) which gets converted to an uppercase identifier (e.g., EXAMPLE) for matching with responses.

§Process

The validation follows a systematic workflow:

  1. Rule Enumeration - Iterates through all rules in the AIM structure
  2. Assignment Detection - Identifies rules with underscore prefixes (_)
  3. Identifier Conversion - Converts rule identifiers to uppercase for matching
  4. Response Matching - Finds responses with matching uppercase identifiers
  5. Type Validation - Validates responses against rule type definitions
  6. Value Assignment - Assigns validated values through the execution context

§Fault Tolerance

The validation process is intentionally fault-tolerant to handle the probabilistic nature of AI model responses:

  • Non-matching Responses: Silently ignores responses without matching assignment rules
  • Type Validation Failures: Silently ignores responses that fail type conversion
  • Partial Success: Returns success if at least one response is validated

This design ensures that workflows continue even when some inference responses are malformed or unexpected.

§Parameters

  • workflow - An Arc reference to the workflow containing assignment rules
  • context - A mutable reference to the execution context for value assignment
  • responses - A HashMap of parsed responses, keyed by uppercase identifiers

§Returns

  • Ok(usize) - Number of successfully validated and assigned responses
  • Err(anyhow::Error) - If no responses were validated, containing the last error

§Example

use aimx::{
    inference::{validate_responses, Response, Item},
    Context, Workflow, Rule, Typedef, Expression, Value, Literal, Prefix
};
use std::collections::HashMap;
use std::sync::Arc;

// Create a workflow with an assignment rule
let mut workflow = Workflow::new();
let rule = Rule::new(
    "_answer".to_string(), 
    Typedef::Number, 
    Expression::Empty, 
    Value::Empty
);
workflow.append_or_update(Some(rule));
 
// Create a context
let mut context = Context::new();
 
// Create a response map with a matching response
let mut responses = HashMap::new();
let item = Item::Value(Prefix::None, "42".to_string());
responses.insert("ANSWER".to_string(), Response::Single(item));
 
// Validate responses (this would assign 42 to the _answer rule)
let result = validate_responses(Arc::new(workflow), &mut context, responses);
// Note: In a real scenario, this would succeed if the context could properly set the value