ai-sdk-core 0.3.0

High-level APIs for AI SDK - text generation, embeddings, and tool execution
Documentation
//! # AI SDK Core
//!
//! High-level, ergonomic APIs for building applications with large language models.
//!
//! This crate provides production-ready abstractions over the provider specification
//! layer, offering builder-based APIs, automatic tool execution, structured output
//! generation, and comprehensive error handling.
//!
//! ## Core Features
//!
//! - **Text Generation**: `generate_text()` and `stream_text()` for chat completion
//! - **Tool Execution**: Automatic multi-step tool calling with custom functions
//! - **Embeddings**: `embed()` and `embed_many()` for semantic vector generation
//! - **Structured Output**: `generate_object()` for schema-validated JSON
//! - **Middleware**: Extensible hooks for logging, caching, and custom behavior
//! - **Multi-Provider**: Registry system for managing multiple provider configurations
//!
//! ## Example: Text Generation
//!
//! Generate text using a simple builder pattern with provider-agnostic configuration:
//!
//! ```rust,ignore
//! use ai_sdk_core::generate_text;
//! use ai_sdk_openai::openai;
//!
//! let result = generate_text()
//!     .model(openai("gpt-4").api_key(api_key))
//!     .prompt("Explain the fundamentals of quantum computing")
//!     .temperature(0.7)
//!     .max_tokens(500)
//!     .execute()
//!     .await?;
//!
//! println!("Response: {}", result.text());
//! println!("Tokens used: {}", result.usage.total_tokens);
//! ```
//!
//! ## Example: Tool Calling
//!
//! Implement custom tools that the model can call during generation. The framework
//! handles the execution loop automatically:
//!
//! ```rust,ignore
//! use ai_sdk_core::{generate_text, Tool, ToolContext};
//! use ai_sdk_openai::openai;
//! use async_trait::async_trait;
//! use std::sync::Arc;
//!
//! struct WeatherTool;
//!
//! #[async_trait]
//! impl Tool for WeatherTool {
//!     fn name(&self) -> &str { "get_weather" }
//!
//!     fn description(&self) -> &str {
//!         "Retrieves current weather conditions for a specified location"
//!     }
//!
//!     fn input_schema(&self) -> serde_json::Value {
//!         serde_json::json!({
//!             "type": "object",
//!             "properties": {
//!                 "location": {
//!                     "type": "string",
//!                     "description": "City name or coordinates"
//!                 }
//!             },
//!             "required": ["location"]
//!         })
//!     }
//!
//!     async fn execute(&self, input: serde_json::Value, _ctx: &ToolContext)
//!         -> Result<serde_json::Value, ai_sdk_core::ToolError> {
//!         let location = input["location"].as_str().unwrap_or("unknown");
//!         Ok(serde_json::json!({
//!             "location": location,
//!             "temperature": 72,
//!             "conditions": "sunny"
//!         }))
//!     }
//! }
//!
//! let result = generate_text()
//!     .model(openai("gpt-4").api_key(api_key))
//!     .prompt("What's the weather like in Tokyo?")
//!     .tools(vec![Arc::new(WeatherTool)])
//!     .max_steps(5)
//!     .execute()
//!     .await?;
//! ```
//!
//! ## Example: Streaming
//!
//! Process responses incrementally as they arrive for real-time user feedback:
//!
//! ```rust,ignore
//! use ai_sdk_core::stream_text;
//! use tokio_stream::StreamExt;
//!
//! let result = stream_text()
//!     .model(openai("gpt-4").api_key(api_key))
//!     .prompt("Write a creative short story about time travel")
//!     .temperature(0.9)
//!     .execute()
//!     .await?;
//!
//! let mut stream = result.into_stream();
//! while let Some(part) = stream.next().await {
//!     match part? {
//!         TextStreamPart::TextDelta(delta) => print!("{}", delta),
//!         TextStreamPart::FinishReason(reason) => {
//!             println!("\nFinished: {:?}", reason);
//!         }
//!         _ => {}
//!     }
//! }
//! ```

#![warn(missing_docs)]
#![warn(rustdoc::broken_intra_doc_links)]

/// Internal module for embedding functionality
#[path = "embed/mod.rs"]
mod embeddings;
/// Error definitions for the crate.
pub mod error;
// mod generate_text;
mod retry;
mod stop_condition;
// mod stream_text;
mod text;
mod tool;

/// Utility functions for media type detection, file download, and base64 encoding
pub mod util;

/// Generate structured objects with schema validation
pub mod generate_object;

/// Middleware system for customizing language model behavior
pub mod middleware;

/// Provider registry system for multi-provider management
pub mod registry;

// Re-export commonly used types from ai-sdk-provider
pub use ai_sdk_provider::language_model::{
    CallOptions, Content, FinishReason, LanguageModel, Message, ToolCallPart, ToolResultPart, Usage,
};
pub use ai_sdk_provider::{EmbeddingModel, EmbeddingUsage, JsonValue};

// Re-export core functionality
pub use embeddings::{
    embed, embed_many, EmbedBuilder, EmbedManyBuilder, EmbedManyResult, EmbedResult,
};
pub use error::{EmbedError, Error, GenerateError, Result, ToolError};
pub use retry::RetryPolicy;
pub use stop_condition::{stop_after_steps, stop_on_finish, StopCondition};
pub use text::{generate_text, GenerateTextBuilder, GenerateTextResult, StepResult};
pub use text::{stream_text, StreamTextBuilder, StreamTextResult, TextStreamPart};
pub use tool::{Tool, ToolContext, ToolExecutor, ToolOutput};