Skip to main content

fm_rs/
lib.rs

1//! Rust bindings for Apple's FoundationModels.framework
2//!
3//! This crate provides safe, idiomatic Rust bindings to Apple's `FoundationModels` framework,
4//! which enables on-device AI capabilities powered by Apple Intelligence.
5//!
6//! # Platform Requirements
7//!
8//! - **Minimum OS**: macOS 26.0+ or iOS/iPadOS 26.0+
9//! - **Apple Intelligence**: Must be enabled on the device
10//! - **Device**: Apple Silicon / Apple Intelligence-capable device
11//! - **Private Cloud Compute**: macOS/iOS/iPadOS 27.0+, network access, and
12//!   Apple's managed `com.apple.developer.private-cloud-compute` entitlement,
13//!   authorized by the app's provisioning profile
14//!
15//! # Quick Start
16//!
17//! ```rust,no_run
18//! use fm_rs::{SystemLanguageModel, Session, GenerationOptions};
19//!
20//! // Create the default system language model
21//! let model = SystemLanguageModel::new()?;
22//!
23//! // Check availability
24//! if !model.is_available() {
25//!     println!("FoundationModels is not available on this device");
26//!     return Ok(());
27//! }
28//!
29//! // Create a session with instructions
30//! let session = Session::with_instructions(&model, "You are a helpful assistant.")?;
31//!
32//! // Send a prompt
33//! let options = GenerationOptions::builder()
34//!     .temperature(0.7)
35//!     .build();
36//! let response = session.respond("What is the capital of France?", &options)?;
37//!
38//! println!("Response: {}", response.content());
39//! # Ok::<(), fm_rs::Error>(())
40//! ```
41//!
42//! # Streaming Responses
43//!
44//! ```rust,no_run
45//! use fm_rs::{SystemLanguageModel, Session, GenerationOptions};
46//!
47//! let model = SystemLanguageModel::new()?;
48//! let session = Session::new(&model)?;
49//!
50//! session.stream_response("Tell me a story", &GenerationOptions::default(), |chunk| {
51//!     print!("{}", chunk);
52//! })?;
53//! # Ok::<(), fm_rs::Error>(())
54//! ```
55//!
56//! # Tool Calling
57//!
58//! ```rust,no_run
59//! use fm_rs::{SystemLanguageModel, Session, Tool, ToolOutput, GenerationOptions};
60//! use serde_json::{json, Value};
61//! use std::sync::Arc;
62//!
63//! struct WeatherTool;
64//!
65//! impl Tool for WeatherTool {
66//!     fn name(&self) -> &str { "get_weather" }
67//!     fn description(&self) -> &str { "Gets the current weather for a location" }
68//!     fn arguments_schema(&self) -> Value {
69//!         json!({
70//!             "type": "object",
71//!             "properties": {
72//!                 "location": { "type": "string" }
73//!             },
74//!             "required": ["location"]
75//!         })
76//!     }
77//!     fn call(&self, args: Value) -> fm_rs::Result<ToolOutput> {
78//!         let location = args["location"].as_str().unwrap_or("Unknown");
79//!         Ok(ToolOutput::new(format!("Sunny, 72°F in {location}")))
80//!     }
81//! }
82//!
83//! let model = SystemLanguageModel::new()?;
84//! let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(WeatherTool)];
85//! let session = Session::with_tools(&model, &tools)?;
86//!
87//! let response = session.respond("What's the weather in Paris?", &GenerationOptions::default())?;
88//! # Ok::<(), fm_rs::Error>(())
89//! ```
90//!
91//! # Resource Management
92//!
93//! ## Session Lifecycle
94//!
95//! - **Ownership**: [`Session`] owns its underlying Swift `LanguageModelSession`. When
96//!   a `Session` is dropped, the Swift session is freed.
97//! - **Thread Safety**: Both [`SystemLanguageModel`] and [`Session`] are `Send + Sync`.
98//!   They can be shared across threads, though concurrent calls to the same session
99//!   may block waiting for the model.
100//! - **Drop Behavior**: Dropping a `Session` with active tool callbacks will wait
101//!   (up to 1 second) for in-flight callbacks to complete before freeing resources.
102//!
103//! ## Memory Considerations
104//!
105//! - Sessions maintain conversation history in memory. Long conversations can consume
106//!   significant memory. Use [`Session::transcript_json()`] to persist and
107//!   [`Session::from_transcript()`] to restore conversations.
108//! - Monitor context usage with [`context_usage_from_transcript()`] and implement
109//!   compaction strategies using [`compact_transcript()`] when approaching limits.
110//! - The default context window is approximately [`DEFAULT_CONTEXT_TOKENS`] tokens,
111//!   though this may vary by device and model version.
112//!
113//! ## Blocking Operations
114//!
115//! - [`Session::respond()`] blocks until generation completes. For long generations,
116//!   consider using [`Session::respond_with_timeout()`] or [`Session::stream_response()`].
117//! - Tool callbacks are invoked synchronously during generation. Long-running tools
118//!   will block the generation pipeline.
119//!
120//! ## No Persistence Across Restarts
121//!
122//! Sessions do not persist across process restarts. To resume a conversation:
123//! 1. Save the transcript with [`Session::transcript_json()`] before shutdown
124//! 2. Restore with [`Session::from_transcript()`] on next launch
125//!
126//! ## Error Recovery
127//!
128//! - If a session enters an error state, create a new session rather than retrying.
129//! - Tool errors are reported via [`Error::ToolCall`] with context about which tool
130//!   failed and the arguments that were passed.
131
132#![warn(missing_docs)]
133#![warn(clippy::all)]
134
135mod context;
136mod error;
137mod ffi;
138mod model;
139mod options;
140mod session;
141mod tool;
142
143/// Trait for types that can provide a JSON Schema for structured generation.
144pub trait Generable {
145    /// Returns a JSON Schema describing the type.
146    fn schema() -> serde_json::Value;
147}
148
149/// Re-export the derive macro when the `derive` feature is enabled.
150#[cfg(feature = "derive")]
151pub use fm_rs_derive::Generable;
152
153/// Re-export `serde_json` so derive macro output doesn't require a direct dependency.
154///
155/// Named `__serde_json` to avoid namespace conflicts with serde's internal derive paths.
156#[doc(hidden)]
157pub use serde_json as __serde_json;
158
159// Re-export public API
160pub use crate::context::{
161    CompactedSession, CompactionConfig, ContextLimit, ContextUsage, DEFAULT_CONTEXT_TOKENS,
162    compact_session_if_needed, compact_transcript, compacted_instructions,
163    context_usage_from_transcript, estimate_tokens, session_from_summary, transcript_to_text,
164};
165pub use crate::error::{Error, Result, ToolCallError};
166pub use crate::model::{LanguageModel, ModelAvailability, SystemLanguageModel, TokenUsage};
167#[cfg(feature = "private-cloud-compute")]
168pub use crate::model::{PrivateCloudComputeLanguageModel, QuotaStatus, QuotaUsage};
169pub use crate::options::{
170    GenerationOptions, GenerationOptionsBuilder, ReasoningLevel, Sampling, ToolCallingMode,
171};
172pub use crate::session::{
173    Attachment, CancellationHandle, Response, Session, SessionBuilder, SessionUsage, SystemTool,
174    TranscriptErrorHandlingPolicy,
175};
176pub use crate::tool::{Tool, ToolOutput};
177
178// FFI exports for Swift to call back into Rust
179
180/// Frees a string allocated by Rust (via `CString::into_raw`).
181///
182/// This function must be called by Swift to properly deallocate strings
183/// returned from Rust callbacks (e.g., tool callback results).
184///
185/// # Safety
186///
187/// The pointer must have been allocated by Rust using `CString::into_raw()`.
188/// Passing a pointer from any other source (e.g., Swift's strdup) is undefined behavior.
189///
190/// This function is called from Swift via FFI. The clippy `not_unsafe_ptr_arg_deref`
191/// lint is allowed because the unsafety contract is on the FFI caller side (Swift).
192#[unsafe(no_mangle)]
193#[allow(clippy::not_unsafe_ptr_arg_deref)]
194pub extern "C" fn fm_rust_string_free(s: *mut std::ffi::c_char) {
195    if !s.is_null() {
196        // SAFETY: The pointer was created by CString::into_raw() in Rust,
197        // as documented in the function contract.
198        unsafe {
199            drop(std::ffi::CString::from_raw(s));
200        }
201    }
202}