ai-sdk-core 0.3.0

High-level APIs for AI SDK - text generation, embeddings, and tool execution
Documentation
//! Generate structured objects from language models.
//!
//! This module provides functionality for generating validated, schema-based outputs
//! from language models, with support for:
//! - Single structured objects
//! - Arrays of elements
//! - Enum values
//! - Streaming with partial results
//!
//! # Examples
//!
//! ## Basic Object Generation
//!
//! ```rust,ignore
//! use ai_sdk_core::generate_object::{generate_object, ObjectOutputStrategy};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct Recipe {
//!     name: String,
//!     ingredients: Vec<String>,
//!     steps: Vec<String>,
//! }
//!
//! let result = generate_object()
//!     .model(model)
//!     .prompt("Generate a recipe for chocolate chip cookies")
//!     .output_strategy(ObjectOutputStrategy::new(recipe_schema))
//!     .execute()
//!     .await?;
//!
//! println!("Recipe: {:?}", result.object);
//! ```
//!
//! ## Streaming Object Generation
//!
//! ```rust,ignore
//! use ai_sdk_core::generate_object::{stream_object, ObjectOutputStrategy, ObjectStreamPart};
//! use tokio_stream::StreamExt;
//!
//! let mut result = stream_object()
//!     .model(model)
//!     .prompt("Generate a recipe for chocolate chip cookies")
//!     .output_strategy(ObjectOutputStrategy::new(recipe_schema))
//!     .execute()
//!     .await?;
//!
//! // Process streaming updates
//! while let Some(part) = result.partial_object_stream.next().await {
//!     match part {
//!         ObjectStreamPart::Object { object } => {
//!             println!("Partial recipe: {:?}", object);
//!         }
//!         ObjectStreamPart::Finish { .. } => break,
//!         _ => {}
//!     }
//! }
//! ```

mod builder;
mod output_strategy;
mod stream_object;

pub use crate::error::{GenerateObjectError, StreamObjectError};
pub use builder::{generate_object, GenerateObjectBuilder, GenerateObjectResult};
pub use output_strategy::{
    ArrayOutputStrategy, EnumOutputStrategy, NoSchemaOutputStrategy, ObjectOutputStrategy,
    OutputStrategy, OutputType, PartialValidation, ValidationContext, ValidationError,
    ValidationResult,
};
pub use stream_object::{stream_object, ObjectStreamPart, StreamObjectBuilder, StreamObjectResult};

use crate::retry::RetryPolicy;

/// Configuration parameters for structured object generation.
///
/// This structure holds configuration options specific to generating structured
/// objects (schemas) from language models. It extends basic generation options
/// with schema-specific settings for JSON mode and validation.
#[derive(Clone, Default)]
pub struct GenerationObjectConfig {
    /// Name of the schema being generated.
    ///
    /// Used by some providers to identify the schema in JSON mode prompting.
    /// This helps the model understand what type of object it should generate.
    /// May be used in the model's internal prompting for improved accuracy.
    pub schema_name: Option<String>,
    /// Human-readable description of the schema structure.
    ///
    /// Provides the language model with context about what the schema represents
    /// and what fields mean. A clear description improves the quality of generated
    /// objects by helping the model understand the intended structure and semantics.
    /// Used alongside the schema name in model prompting.
    pub schema_description: Option<String>,
    /// Sampling temperature controlling output randomness.
    ///
    /// Valid range is typically 0.0 to 2.0, with 0.0 being deterministic
    /// and higher values producing more diverse output. For structured generation,
    /// lower temperatures (closer to 0.0) are often preferred to ensure the model
    /// follows the schema constraints accurately.
    pub temperature: Option<f32>,
    /// Maximum number of tokens to generate in the output.
    ///
    /// This controls the maximum length of the model's response. If the model
    /// reaches this limit before finishing the object, generation will be truncated.
    /// Ensure this is large enough to accommodate your expected object size.
    pub max_tokens: Option<u32>,
    /// Policy for retrying failed API requests.
    ///
    /// Defines automatic retry behavior for transient failures such as rate limits
    /// or temporary service unavailability. Permanent errors or validation failures
    /// are not retried.
    pub retry_policy: RetryPolicy,
}