ai_lib/
lib.rs

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