8000 GitHub - bbrangeo/apple_ai: apple_ai · GitHub
[go: up one dir, main page]

Skip to content
bbrangeoPublic

About

apple_ai

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

apple_ai

Safe Rust bindings for Apple Intelligence (FoundationModels framework) on macOS. This crate provides a high-level API to use the on-device language model via a Swift bridge. Apple's default model guardrails apply.

macOS only. Requires macOS 26 (Tahoe) and Xcode 26.

Prerequisites

  • macOS 26 (Tahoe) or later
  • Xcode 26 with swiftc in your PATH
  • Apple Silicon Mac with Apple Intelligence enabled in System Settings

Installation

Add to your Cargo.toml:

[dependencies]
apple_ai = "0.2.0"

The crate enables the async feature by default (Tokio): generate().await runs the blocking Swift FFI call via tokio::task::spawn_blocking, so it requires a Tokio runtime. With async disabled the same async signature is retained for compatibility, but polling it executes FFI synchronously on the caller thread. To disable this offload:

apple_ai = { version = "0.2", default-features = false }

When building a consuming application, set the macOS deployment target to 26.0 or later so the Swift runtime is linked from the system location:

MACOSX_DEPLOYMENT_TARGET=26.0 cargo run

If the application was previously built with a lower deployment target, run cargo clean before rebuilding. This setting is required for each Cargo build command, or it can be configured in the consuming project's .cargo/config.toml:

[env]
MACOSX_DEPLOYMENT_TARGET = "26.0"

Quick start

The example also requires anyhow and tokio (with the macros and rt-multi-thread features) in your dependencies.

use apple_ai::{AppleAiClient, Message};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = AppleAiClient::new()?;
    let messages = vec![Message::user("Explain FoundationModels in one sentence.")];
    let resp = client.generate(messages, Default::default()).await?;
    println!("{}", resp.text);
    Ok(())
}

Features

  • Text generation — Non-streaming and async via AppleAiClient::generate() with GenerationOptions (temperature, max tokens).
  • Streaming — Token-by-token streaming with generate_stream() (callback) or generate_stream_async() (async stream, feature stream).
  • Tool calling — Define tools (JSON Schema), register a Rust callback with set_tool_callback(), and submit results with submit_tool_result().
  • Structured output — generate_structured<T>() for schema-guided responses deserialized into a type T.
  • Chat session — ChatSession keeps conversation state; use push_*, generate(), and append_response() for multi-turn and tool flows.
  • Retry — generate_with_retry() with RetryConfig for automatic retries on ModelNotReady.
  • Validation — validate_messages() to check roles and tool_call_id consistency before sending.
  • Availability — check_availability(), availability_reason(), and supported_languages().

Messages use an OpenAI-style format (Message::system(), Message::user(), Message::assistant(), Message::tool_result()).

Initial system messages supply model instructions; user/assistant history is preserved, and the latest user prompt is not duplicated in history. System messages after the conversation starts are rejected. All generation entry points validate messages and options before FFI (finite temperature in [0, 2], nonnegative max_tokens; zero uses the default token limit).

Tool execution

The registered tool callback must execute or schedule the tool and call AppleAiClient::submit_tool_result(tool_id, &result) while generation is in progress, not after awaiting generate. FoundationModels awaits that result before continuing its response. A missing result fails after 30 seconds rather than returning placeholder text and repeatedly calling the tool. The response contains both the collected tool_calls and the final text based on the results. Serialize tool-enabled generations: tool registration/collection are global and only one pending call per tool ID is supported. Text-only v2 streams do not use this global tool mechanism.

See examples/tool_calling.rs for a complete round-trip with demonstration weather data (not a live weather API).

Options builder

GenerationOptions supports fluent builders: .temperature(0.7), .max_tokens(256), .tools(tools), .schema(schema), .stop_after_tool_calls(true).

Async stream (feature stream)

apple_ai = { version = "0.2", features = ["stream"] }
# Also supported: default-features = false, features = ["stream"]

The stream feature enables Tokio independently of async. The new recommended text-only API is:

pub fn generate_stream_result_async(
    &self,
    messages: Vec<Message>,
    options: GenerationOptions,
) -> Result<impl Stream<Item = Result<String, AppleAiError>> + Send + 'static, AppleAiError>

Despite its name, this method is not an async fn: it starts the request immediately and returns an owned stream without borrowing the client. Setup/validation failures are returned directly; inference failures arrive as Err items followed by EOF.

use apple_ai::{AppleAiClient, GenerationOptions, Message};
use tokio_stream::StreamExt;

# async fn example() -> Result<(), apple_ai::AppleAiError> {
let mut stream = {
    let client = AppleAiClient::new()?;
    client.generate_stream_result_async(
        vec![Message::system("Answer in French."), Message::user("Hello!")],
        GenerationOptions::default().max_tokens(128),
    )?
}; // stream does not borrow client
while let Some(delta) = stream.next().await {
    print!("{}", delta?);
}
# Ok(()) }

Each v2 request has its own callback context, so streams can run concurrently. Chunks are copied from borrowed Swift strings and forwarded through a bounded Tokio channel (64 items). blocking_send on Swift's background task applies lossless backpressure; a slow consumer pauses that producer rather than discarding deltas. Consume the stream concurrently; do not wait for inference to complete before reading it.

Dropping the stream closes the receiver and unblocks a pending send. The callback returns false when the receiver is closed or sending fails, requesting cooperative cancellation at a delta boundary. It cannot interrupt SDK inference immediately, and no further delta means cancellation cannot be requested yet. The request context is retained until Swift's unique terminal NULL callback, including after cancellation or errors; only that callback releases it. Callback panics are caught at the FFI boundary (not with panic = "abort").

V2 rejects options.tools = Some(...) (even an empty list) and options.schema = Some(...). For tools/schema use generate, generate_structured, or the legacy stream APIs. V2 does not replace or modify the tool bridge.

Legacy compatibility: generate_stream still calls Fn(Option<&str>), with STX-prefixed raw error chunks and None at termination. generate_stream_async still yields String (including raw STX errors), now with bounded, lossless forwarding. The context-free legacy ABI supports one active stream globally: another request returns AppleAiError::Busy until the previous terminal callback. A slow/abandoned legacy consumer cannot cooperatively cancel Swift inference; use v2 for cancellation and concurrent requests.

Errors and migration from 0.1

Version 0.2.0 is intentionally breaking: adding variants to the existing exhaustive AppleAiError enum breaks downstream exhaustive match expressions. Update those matches to handle:

  • ContextLengthExceeded(String) — reduce conversation/context size.
  • InvalidOptions(String) — fix options, including v2 tools/schema restrictions.
  • Busy — wait for the active legacy stream to terminate, or use v2 for text.

Both non-streaming responses and v2 error chunks decode STX + JSON { "code", "message" }: context_length_exceeded → ContextLengthExceeded, invalid_options → InvalidOptions, model_unavailable → Unavailable, invalid_messages → InvalidMessages, generation_error and unknown codes → Bridge. The original message is preserved. Legacy plain-text or malformed error payloads fall back to Bridge(payload). Normal text/JSON without leading STX is not interpreted as an error. AppleAiClient now implements Debug.

Debug logging

Set the environment variable APPLE_AI_SWIFT_DEBUG_LOGS (any value) before running to get verbose transcript and parsing logs from the Swift bridge.

Examples

Run from the repo:

# Simple one-shot generation
cargo run --example basic

# Token-by-token streaming
cargo run --features stream --example streaming

# Tool calling (model calls get_weather, then summarizes the result)
cargo run --example tool_calling

# ChatSession (stateful conversation: push_*, generate, append_response)
cargo run --example chat_session

Testing

Default tests do not require an available model: they cover validation, error decoding, borrowed Unicode chunks, independent request contexts, terminal cleanup, legacy Busy, callback panics, and backpressure/drop behavior.

From this clone, use --target-dir target to override any parent Cargo target directory:

rustfmt --edition 2021 src/lib.rs tests/*.rs examples/streaming.rs
cargo test --target-dir target --all-features
cargo test --target-dir target --no-default-features --features stream
cargo test --target-dir target --no-default-features
cargo clippy --target-dir target --all-targets --all-features -- -D warnings
cargo doc --target-dir target --all-features --no-deps

Model-dependent tests (generation, system instructions, history, v2 text and generation errors (context overflow or native safety guardrails)) are ignored by default. They need an available Apple Intelligence model and use 60-second per-operation timeouts; semantic assertions can vary with the native model. Run them serially with an external process timeout as well, since a timed-out blocking native call cannot be forcibly stopped by Tokio:

MACOSX_DEPLOYMENT_TARGET=26.0 cargo test --target-dir target --all-features --test basic_generation -- --ignored --test-threads=1

To format only Rust sources without formatting the existing build script, run rustfmt --edition 2021 src/lib.rs tests/*.rs examples/streaming.rs.

License

MIT. See LICENSE for details.

About

apple_ai

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0