schema_utils.go
Overview
The schema_utils.go file provides utility functions to validate data structures against JSON schemas defined by the genai.Schema type. Its core functionality revolves around type checking and schema validation for inputs and outputs, ensuring data conforms to expected formats, types, and required properties.
This file is critical for runtime verification of data consistency with schemas, preventing type mismatches or missing required fields when processing input arguments or interpreting output JSON payloads. It supports primary JSON schema types such as string, integer, boolean, number, array, and object, with recursive validation for nested structures.
The validation logic is primarily used in contexts where inputs or outputs must conform strictly to predefined API or model schemas, aligning with schema-driven data handling patterns found in LLM Integration and Agents.
Functions and Methods
matchType(value any, schema *genai.Schema, isInput bool) (bool, error)
Checks whether a given value matches the type definition specified by the schema. Recursively validates arrays and objects using their respective subschemas.
Parameters:
value any: The data value to be validated.schema *genai.Schema: The schema describing the expected type and structure.isInput bool: Flag indicating if the validation is for input (true) or output (false). Currently used for error message context.
Returns:
bool:trueif the value matches the schema type,falseotherwise.error: Non-nil if an error occurs during validation (e.g., unsupported type, missing schema items).
Details:
Validates primitive types (
string,integer, boolean,number) directly.For
integer, checks that the float64 value has no fractional part.For array, uses reflection to ensure the value is a slice and recursively validates each item against the schema's
Items.For
object, asserts the value tomap[string]anyand delegates toValidateMapOnSchema.Returns errors when schema definitions are incomplete or unsupported types are encountered.
Usage Example:
ok, err := matchType(myValue, mySchema, true) if err != nil { // handle error } if !ok { // handle type mismatch }
ValidateMapOnSchema(args map[string]any, schema *genai.Schema, isInput bool) error
Validates a map (args) against an object schema, checking each property for existence and type correctness, as well as ensuring all required keys are present.
Parameters:
args map[string]any: The map to validate, typically representing JSON object decoded data.schema *genai.Schema: Object schema withPropertiesandRequiredfields.isInput bool: Indicates whether validation is for input or output, affects error message wording.
Returns:
error:nilif validation passes; otherwise, descriptive error indicating missing keys or type mismatches.
Details:
Iterates over each key-value pair in
args.Checks if the key exists in the schema's
Properties.Uses
matchTypeto validate the value against its property's schema.Verifies presence of all required keys defined in
schema.Required.Assumes strict schema compliance (additional properties not allowed).
Usage Example:
err := ValidateMapOnSchema(myMap, myObjectSchema, true) if err != nil { // handle validation failure }
ValidateOutputSchema(output string, schema *genai.Schema) (map[string]any, error)
Parses a JSON string output and validates the resulting map against the provided schema, intended for validating output data.
Parameters:
output string: JSON string representing the output data to validate.schema *genai.Schema: Schema to validate against.
Returns:
map[string]any: Decoded and validated map if successful.error: Parsing or validation errors.
Details:
Unmarshals the JSON string into a map.
Calls
ValidateMapOnSchemawithisInput=falseto validate the output.Returns detailed errors on JSON parsing or schema validation failure.
Usage Example:
validatedMap, err := ValidateOutputSchema(jsonOutput, outputSchema) if err != nil { // handle invalid output }
Implementation Details and Algorithms
Type Matching:
Uses Go's type assertions and reflection to verify runtime types.
Integer validation is done by checking if a
float64value equals its truncated integer value, accommodating JSON number representation.Array validation applies recursion per element, ensuring homogeneous conformity.
Object validation recursively checks all properties and required fields.
Error Handling:
Returns descriptive error messages indicating the exact property and nature of validation failures.
Differentiates between input and output validation in error messages for clarity.
Schema Assumptions:
Schemas are expected to be non-nil and well-formed.
Array schemas must specify
Items.Object schemas include
PropertiesandRequiredfields.Additional properties beyond those defined are disallowed in this strict validation.
Dependency:
Relies on
genai.Schemaand associatedTypeconstants (e.g.,genai.TypeString).Uses standard encoding/json for output JSON unmarshalling.
Interaction with Other Components
This file's utilities are foundational for validating data exchanged between agents and LLMs, ensuring adherence to schema contracts described in LLM Integration and Agents.
Validations occur during input processing before invoking models or tools, and during output processing before further handling or response generation.
The strict validation logic supports reliable agent workflows by enforcing data integrity in Agent Workflow Management and Function Tools which may require precise input/output schema adherence.
The schema validation functions may be invoked by agent runners or API controllers when deserializing and validating user or model inputs/outputs, possibly integrated with REST API and Web Launchers.
Visual Flowchart of Main Functions and Relationships
flowchart TD
A[matchType] --> B[ValidateMapOnSchema]
C[ValidateOutputSchema] --> D[json.Unmarshal to map]
D --> B
B --> E["matchType (recursive)"]
A --> E
Explanation:
ValidateOutputSchemastarts by unmarshalling JSON output to a map, then callsValidateMapOnSchema.ValidateMapOnSchemavalidates each key's value by invokingmatchType.matchTypemay recursively call itself for array items or delegate toValidateMapOnSchemafor objects.This recursive interplay ensures deep validation of nested data structures.