ai_lib/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! AI-lib: A Unified AI SDK for Rust
3//!
4//! This library provides a single, consistent interface for interacting with multiple AI model providers.
5//!
6//! # Quick Start
7//!
8//! ```rust
9//! use ai_lib::{AiClient, Provider, ChatCompletionRequest, Message, Role, Content};
10//! // Or in applications, prefer the minimal prelude:
11//! // use ai_lib::prelude::*;
12//!
13//! #[tokio::main]
14//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
15//!     // Switch provider by changing Provider:: value
16//!     let client = AiClient::new(Provider::Groq)?;
17//!
18//!     let request = ChatCompletionRequest::new(
19//!         "llama3-8b-8192".to_string(),
20//!         vec![Message {
21//!             role: Role::User,
22//!             content: Content::Text("Hello, how are you?".to_string()),
23//!             function_call: None,
24//!         }],
25//!     );
26//!
27//!     println!("Client created successfully with provider: {:?}", client.current_provider());
28//!     println!("Request prepared for model: {}", request.model);
29//!
30//!     Ok(())
31//! }
32//! ```
33//!
34//! ## Import guidance
35//! - For application code, prefer `use ai_lib::prelude::*;` to get the minimal common set.
36//! - Library authors can import explicitly from domain modules for fine-grained control.
37//!
38//! See the module tree and import patterns guide for details: [docs/MODULE_TREE_AND_IMPORTS.md](docs/MODULE_TREE_AND_IMPORTS.md)
39//!
40//! # Proxy Support
41//!
42//! AI-lib supports proxy configuration via environment variables:
43//!
44//! ```bash
45//! # Set proxy server
46//! export AI_PROXY_URL=http://proxy.example.com:8080
47//!
48//! # Proxy with authentication
49//! export AI_PROXY_URL=http://username:password@proxy.example.com:8080
50//!
51//! # HTTPS proxy
52//! export AI_PROXY_URL=https://proxy.example.com:8080
53//! ```
54//!
55//! All AI provider requests will automatically use the specified proxy server.
56//!
57//! Optional environment variables for feature-gated capabilities:
58//! - cost_metrics feature:
59//!   - `COST_INPUT_PER_1K`: USD per 1000 input tokens
60//!   - `COST_OUTPUT_PER_1K`: USD per 1000 output tokens
61//!
62//! These cost metrics are read from environment variables for simplicity.
63//! 
64//! Note: In ai-lib-pro, these can be centrally configured and hot-reloaded
65//! via external configuration providers for enterprise deployments.
66
67pub mod api;
68pub mod client;
69pub mod config;
70pub mod metrics;
71pub mod provider;
72pub mod transport;
73pub mod types;
74pub mod utils; // minimal explicit configuration entrypoint
75
76// Feature-gated modules (OSS progressive complexity)
77#[cfg(feature = "interceptors")]
78pub mod interceptors;
79
80#[cfg(feature = "unified_sse")]
81pub mod sse;
82
83#[cfg(feature = "unified_transport")]
84pub mod net { pub use crate::transport::client_factory; }
85
86#[cfg(feature = "observability")]
87pub mod observability;
88
89#[cfg(feature = "config_hot_reload")]
90pub mod config_hot_reload;
91
92// Resilience modules
93pub mod circuit_breaker;
94pub mod rate_limiter;
95pub mod error_handling;
96
97// Re-export main types for user convenience
98pub use api::ChatApi;
99pub use client::{AiClient, AiClientBuilder, ModelOptions, Provider};
100pub use types::{
101    AiLibError, ChatCompletionRequest, ChatCompletionResponse, Choice, Message, Role,
102    FunctionCall, FunctionCallPolicy, Tool,
103};
104// Convenience re-exports: make the most-used types available from the crate root so
105// users don't need deep imports for common flows.
106pub use api::ChatCompletionChunk;
107pub use client::CancelHandle;
108pub use metrics::{Metrics, MetricsExt, NoopMetrics, NoopTimer, Timer};
109pub use transport::{
110    DynHttpTransport, DynHttpTransportRef, HttpClient, HttpTransport, TransportError,
111};
112// Re-export minimal configuration type
113pub use config::ConnectionOptions;
114// Export response metadata (Usage/UsageStatus) and common Content from canonical modules
115pub use types::response::{Usage, UsageStatus};
116pub use types::common::Content;
117
118// Re-export configuration types
119pub use provider::config::{FieldMapping, ProviderConfig};
120pub use provider::configs::ProviderConfigs;
121
122// Re-export model management tools (feature-gated)
123#[cfg_attr(docsrs, doc(cfg(feature = "routing_mvp")))]
124#[cfg(feature = "routing_mvp")]
125pub use provider::models::{
126    CustomModelManager, LoadBalancingStrategy, ModelArray, ModelCapabilities, ModelEndpoint,
127    ModelInfo, ModelSelectionStrategy, PerformanceMetrics, PricingInfo, QualityTier, SpeedTier,
128};
129
130// Re-export batch processing functionality
131pub use api::chat::{batch_utils, BatchResult};
132
133// Re-export enhanced file utilities
134pub use utils::file::{
135    create_temp_dir, get_file_extension, get_file_size, guess_mime_from_path, is_audio_file,
136    is_file_size_acceptable, is_image_file, is_text_file, is_video_file, read_file, remove_file,
137    save_temp_file, validate_file,
138};
139
140
141/// Prelude with the minimal commonly used items for applications.
142///
143/// Prefer `use ai_lib::prelude::*;` in application code for better ergonomics.
144/// Library authors may prefer importing explicit items from their modules.
145pub mod prelude {
146    pub use crate::{AiClient, AiClientBuilder, Provider};
147    pub use crate::types::{ChatCompletionRequest, ChatCompletionResponse, Choice};
148    pub use crate::types::common::{Content, Message, Role};
149    pub use crate::types::response::{Usage, UsageStatus};
150    pub use crate::types::error::AiLibError;
151}
152
153// Module tree and import guidance:
154// - Prefer the `prelude` for the minimal usable set in apps
155// - Top-level re-exports expose the most common types
156// - Provider-specific modules are internal in OSS; use `Provider` enum and `AiClient` to select providers